您好!这是一个简单的版本的 2048 游戏的代码:
#include <stdio.h> #include <stdlib.h> #include <time.h>
#define SIZE 4
void printBoard(int board[SIZE][SIZE]); void addRandom(int board[SIZE][SIZE]); void shiftUp(int board[SIZE][SIZE]); void shiftDown(int board[SIZE][SIZE]); void shiftLeft(int board[SIZE][SIZE]); void shiftRight(int board[SIZE][SIZE]);
int main() { int board[SIZE][SIZE]; char move; int gameOver = 0;
// Initialize the board with all zeros for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { board[i][j] = 0; } }
// Add two initial random tiles addRandom(board); addRandom(board);
while (!gameOver) { printBoard(board);
printf("Enter a move (w/a/s/d): ");
scanf(" %c", &move);
switch (move) {
case 'w':
shiftUp(board);
break;
case 'a':
shiftLeft(board);
break;
case 's':
shiftDown(board);
break;
case 'd':
shiftRight(board);
break;
default:
printf("Invalid move.\n");
}
addRandom(board);
}
return 0; }
void printBoard(int board[SIZE][SIZE]) { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { printf("%d\t", board[i][j]); } printf("\n"); } }
void addRandom(int board[SIZE][SIZE]) { int emptyTiles = 0; int tileLocations[SIZE * SIZE][2];
// Find all empty tiles for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (board[i][j] == 0) { tileLocations[emptyTiles][0] = i; tileLocations[emptyTiles][1] = j; emptyTiles++; } } }
// Exit function if no empty tiles if (emptyTiles == 0) { return; }
// Choose a random empty tile srand(time(0)); int randomTile = rand() % emptyTiles; int row = tileLocations[randomTile][0]; int col = tileLocations[randomTile][1];
// Choose a random value for the tile (2 or 4) int value = (rand() % 2 + 1) * 2;
// Add the tile to the board board[row][col] = value; }
void shift