2048: Difference between revisions

Content deleted Content added
Steenslag (talk | contribs)
m →‎{{header|Ruby}}: shaved off a few lines in the "case input"
Thundergnat (talk | contribs)
m →‎{{header|Perl 6}}: minor tweaks, more idiomatic, DRY
Line 1,423: Line 1,423:
# set flags needed to emulate it manually
# set flags needed to emulate it manually
$termios.unset_iflags(<BRKINT ICRNL ISTRIP IXON>);
$termios.unset_iflags(<BRKINT ICRNL ISTRIP IXON>);
$termios.unset_lflags(<ECHO ICANON IEXTEN ISIG>);
$termios.unset_lflags(< ECHO ICANON IEXTEN ISIG>);
$termios.setattr(:DRAIN);
$termios.setattr(:DRAIN);


Line 1,457: Line 1,457:
my $pad = ' ' x ceiling($c/2);
my $pad = ' ' x ceiling($c/2);
my $tile = sprintf "%{cell}s", "$s$pad";
my $tile = sprintf "%{cell}s", "$s$pad";
my $idx = $s ?? $s.log(2) !! 1;
my $idx = $s ?? $s.log(2) !! 0;
ansi ?? "\e[{@ANSI[$idx]}m$tile\e[0m" !! $tile;
ansi ?? "\e[{@ANSI[$idx]}m$tile\e[0m" !! $tile;
}
}
Line 1,468: Line 1,468:
Press direction arrows to move.
Press direction arrows to move.


Press q to quit.
Press q to quit.


$top
$top
{ join "\n $mid\n ", map { $_.&row }, @board }
{ join "\n\t$mid\n\t", map { .&row }, @board }
$bot
$bot


Line 1,479: Line 1,479:
}
}


sub squash (@c) {
sub squash (@c) {
my @t = grep { .chars }, @c;
my @t = grep { .chars }, @c;
map { combine(@t[$_], @t[$_+1]) if @t[$_] && @t[$_+1] == @t[$_] }, ^@t-1;
map { combine(@t[$_], @t[$_+1]) if @t[$_] && @t[$_+1] == @t[$_] }, ^@t-1;
Line 1,490: Line 1,490:


multi sub move('up') {
multi sub move('up') {
map { @board[*]»[$_] = squash @board[*]»[$_] }, ^n;
map { @board[*;$_] = squash @board[*;$_] }, ^n;
}
}


multi sub move('down') {
multi sub move('down') {
map { @board[*]»[$_] = reverse squash reverse @board[*]»[$_] }, ^n;
map { @board[*;$_] = reverse squash reverse @board[*;$_] }, ^n;
}
}


multi sub move('left') {
multi sub move('left') {
map { @board[$_] = squash flat @board[$_]»[*] }, ^n;
map { @board[$_] = squash flat @board[$_;*] }, ^n;
}
}


multi sub move('right') {
multi sub move('right') {
map { @board[$_] = reverse squash reverse flat @board[$_]»[*] }, ^n;
map { @board[$_] = reverse squash reverse flat @board[$_;*] }, ^n;
}
}


Line 1,513: Line 1,513:
@board[$x; $y] = (flat 2 xx 9, 4).roll;
@board[$x; $y] = (flat 2 xx 9, 4).roll;
}
}

sub save () { join '|', flat @board».list }


loop {
loop {
another if $save ne join '|', flat @board».list;
another if $save ne save();
draw-board;
draw-board;
$save = save();

# Read up to 4 bytes from keyboard buffer.
# Page navigation keys are 3-4 bytes each.
# Specifically, arrow keys are 3.
my $key = $*IN.read(4).decode;


move %dir{$key} if so %dir{$key};
# Read up to 4 bytes from keyboard buffer.
# Page navigation keys are 3-4 bytes each.
last if $key eq 'q'; # (q)uit
# Specifically, arrow keys are 3.
my $char = $*IN.read(4).decode;
$save = join '|', flat @board».list;
move %dir{$char} if so %dir{$char};
last if $char eq 'q'; # (q)uit
}</lang>
}</lang>
Sample output:
Sample output: