2048: Difference between revisions

Content deleted Content added
Thundergnat (talk | contribs)
m →‎{{header|Perl 6}}: refactor a bit, style tweaks
Thundergnat (talk | contribs)
m →‎{{header|Perl 6}}: some more refactoring, DRY
Line 1,805: Line 1,805:


multi sub squash ('left', @c) {
multi sub squash ('left', @c) {
my @tiles = grep { .chars }, @c;
my @t = grep { .chars }, @c;
map { combine(@t[$_], @t[$_+1]) if @t[$_] && @t[$_+1] == @t[$_] }, ^@t-1;
@tiles.push: '' while @tiles < 4;
@tiles;
@t = grep { .chars }, @t;
@t.push: '' while @t < 4;
@t;
}
}


multi sub squash ('right', @c) {
multi sub squash ('right', @c) {
my @tiles = grep { .chars }, @c;
my @t = reverse grep { .chars }, @c;
map { combine(@t[$_], @t[$_+1]) if @t[$_] && @t[$_+1] == @t[$_] }, ^@t-1;
@tiles.unshift: '' while @tiles < 4;
@tiles;
@t = grep { .chars }, @t;
@t.push: '' while @t < 4;
reverse @t;
}
}


Line 1,819: Line 1,823:


multi sub move('up') {
multi sub move('up') {
map { @board[*]»[$_] = squash left, @board[*]»[$_] }, 0..3
for 0 .. 3 -> $y {
my @col = squash left, @board[*]»[$y];
for 0 .. 2 -> $x {
combine(@col[$x], @col[$x+1]) if @col[$x] && @col[$x+1] == @col[$x]
}
@board[*]»[$y] = squash left, @col;
}
}
}


multi sub move('down') {
multi sub move('down') {
map { @board[*]»[$_] = squash right, @board[*]»[$_] }, 0..3
for 0 .. 3 -> $y {
my @col = squash right, @board[*]»[$y];
for 3 ... 1 -> $x {
combine(@col[$x], @col[$x-1]) if @col[$x] && @col[$x-1] == @col[$x]
}
@board[*]»[$y] = squash right, @col;
}
}
}


multi sub move('left') {
multi sub move('left') {
map { @board[$_] = squash left, flat @board[$_]»[*] }, 0..3
for 0 .. 3 -> $y {
my @row = squash left, flat @board[$y]»[*];
for 0 .. 2 -> $x {
combine(@row[$x], @row[$x+1]) if @row[$x] && @row[$x+1] == @row[$x]
}
@board[$y] = squash left, @row;
}
}
}


multi sub move('right') {
multi sub move('right') {
map { @board[$_] = squash right, flat @board[$_]»[*] }, 0..3
for 0 .. 3 -> $y {
my @row = squash right, flat @board[$y]»[*];
for 3 ... 1 -> $x {
combine(@row[$x], @row[$x-1]) if @row[$x] && @row[$x-1] == @row[$x]
}
@board[$y] = squash right, @row;
}
}
}