c语言实现2048小游戏的代码
时间: 2023-08-28 22:04:47 浏览: 267
C语言实现2048游戏代码
以下是一个简单的 C 语言实现 2048 游戏的代码。注意,这只是一个简单的实现,仅供参考。
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 4
int board[SIZE][SIZE]; // 游戏面板
int score = 0; // 分数
// 初始化游戏面板
void init_board()
{
int i, j;
for (i = 0; i < SIZE; i++)
for (j = 0; j < SIZE; j++)
board[i][j] = 0;
}
// 在游戏面板上随机生成一个数字
void add_random()
{
int i, j, r;
int empty_count = 0;
int empty[SIZE * SIZE][2];
for (i = 0; i < SIZE; i++)
for (j = 0; j < SIZE; j++)
if (board[i][j] == 0) {
empty[empty_count][0] = i;
empty[empty_count][1] = j;
empty_count++;
}
if (empty_count == 0)
return;
r = rand() % empty_count;
board[empty[r][0]][empty[r][1]] = rand() % 10 == 0 ? 4 : 2;
}
// 在游戏面板上移动数字
void move(int dir)
{
int i, j, k;
int tmp[SIZE];
for (i = 0; i < SIZE; i++) {
// 将一行或一列复制到一个临时数组中
for (j = 0; j < SIZE; j++)
if (dir == 0)
tmp[j] = board[i][j];
else if (dir == 1)
tmp[j] = board[j][i];
else if (dir == 2)
tmp[j] = board[i][SIZE - 1 - j];
else
tmp[j] = board[SIZE - 1 - j][i];
// 合并相邻的相同数字
k = 0;
for (j = 0; j < SIZE; j++) {
if (tmp[j] != 0) {
if (k > 0 && tmp[k - 1] == tmp[j]) {
tmp[k - 1] *= 2;
score += tmp[k - 1];
tmp[j] = 0;
} else {
tmp[k] = tmp[j];
k++;
}
}
}
// 将合并后的数组复制回游戏面板
for (j = 0; j < SIZE; j++)
if (dir == 0)
board[i][j] = tmp[j];
else if (dir == 1)
board[j][i] = tmp[j];
else if (dir == 2)
board[i][SIZE - 1 - j] = tmp[j];
else
board[SIZE - 1 - j][i] = tmp[j];
}
}
// 绘制游戏面板
void draw_board()
{
int i, j;
printf("Score: %d\n", score);
printf("+------+------+------+------+");
for (i = 0; i < SIZE; i++) {
printf("\n");
for (j = 0; j < SIZE; j++)
printf("|%4d ", board[i][j]);
printf("|");
printf("\n");
printf("+------+------+------+------+\n");
}
}
// 判断游戏是否结束
int game_over()
{
int i, j;
for (i = 0; i < SIZE; i++)
for (j = 0; j < SIZE; j++)
if (board[i][j] == 0)
return 0;
for (i = 0; i < SIZE; i++)
for (j = 0; j < SIZE - 1; j++)
if (board[i][j] == board[i][j + 1])
return 0;
for (i = 0; i < SIZE - 1; i++)
for (j = 0; j < SIZE; j++)
if (board[i][j] == board[i + 1][j])
return 0;
return 1;
}
int main()
{
int dir;
char c;
srand(time(NULL));
init_board();
add_random();
add_random();
draw_board();
while (!game_over()) {
printf("Use wasd to move, q to quit: ");
scanf("%c", &c);
while (getchar() != '\n');
if (c == 'q')
break;
if (c == 'w')
dir = 0;
else if (c == 's')
dir = 1;
else if (c == 'a')
dir = 2;
else if (c == 'd')
dir = 3;
else
continue;
move(dir);
add_random();
draw_board();
}
printf("Game over! Your score is %d.\n", score);
return 0;
}
```
阅读全文