用c++写一个2048

您好!这是一个简单的版本的 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值