2048: Difference between revisions

411 bytes removed ,  1 year ago
Line 5,687:
 
struct G2048 {
public void gameLoop() /*@safe @nogc*/ {
addTile;
while (true) {
Line 5,701:
 
private:
static struct Tile {
uint val = 0;
bool blocked = false;
Line 5,713:
uint score = 0;
 
void drawBoard() const /*@safe @nogc*/ {
writeln("SCORE: ", score, "\n");
foreach (immutable y; 0 .. side) {
write("+------+------+------+------+\n| ");
foreach (immutable x; 0 .. side) {
if (board[x][y].val)
writef("%4d", board[x][y].val);
Line 5,726:
writeln;
}
writeln("+------+------+------+------+\n".writeln);
}
 
void waitKey() /*@safe*/ {
moved = false;
write("(W)Up (S)Down (A)Left (D)Right (Q)Quit: ".write);
immutableauto c = readln.strip.toLower;
 
switch (c) {
Line 5,743:
}
 
foreach (immutable y; 0 .. side)
foreach (immutable x; 0 .. side)
board[x][y].blocked = false;
}
Line 5,753:
}
 
void addTile() /*nothrow*/ @safe /*@nogc*/ {
foreach (immutable y; 0 .. side) {
foreach (immutable x; 0 .. side) {
if (!board[x][y].val) {
uint a, b;
Line 5,772:
}
 
bool canMove() const pure nothrow @safe @nogc {
foreach (immutable y; 0 .. side)
foreach (immutable x; 0 .. side)
if (!board[x][y].val)
return true;
 
foreach (immutable y; 0 .. side) {
foreach (immutable x; 0 .. side) {
if (testAdd(x + 1, y, board[x][y].val) ||
testAdd(x - 1, y, board[x][y].val) ||
Line 5,790:
}
 
bool testAdd(in uint x, in uint y, in uint v) const pure nothrow @safe @nogc {
if (x > 3 || y > 3)
return false;
Line 5,796:
}
 
void moveVertically(in uint x, in uint y, in uint d) pure nothrow @safe @nogc {
if (board[x][y + d].val && board[x][y + d].val == board[x][y].val &&
!board[x][y].blocked && !board[x][y + d].blocked) {
Line 5,819:
}
 
void moveHorizontally(in uint x, in uint y, in uint d) pure nothrow @safe @nogc {
if (board[x + d][y].val && board[x + d][y].val == board[x][y].val &&
!board[x][y].blocked && !board[x + d][y].blocked) {
Line 5,842:
}
 
void move(in moveDir d) pure nothrow @safe @nogc {
final switch (d) with(moveDir) {
case up:
foreach (immutable x; 0 .. side)
foreach (immutable y; 1 .. side)
if (board[x][y].val)
moveVertically(x, y, -1);
break;
case down:
foreach (immutable x; 0 .. side)
foreach_reverse (immutable y; 0 .. 3)
if (board[x][y].val)
moveVertically(x, y, 1);
break;
case left:
foreach (immutable y; 0 .. side)
foreach (immutable x; 1 .. side)
if (board[x][y].val)
moveHorizontally(x, y, -1);
break;
case right:
foreach (immutable y; 0 .. side)
foreach_reverse (immutable x; 0 .. 3)
if (board[x][y].val)
moveHorizontally(x, y, 1);
Line 5,876:
}</syntaxhighlight>
The output is the same as the C++ version.
 
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
1

edit