好玩的c语言代码_做游戏,学编程(C语言) 11 2048
时间: 2024-01-24 11:05:06 浏览: 59
2048小游戏C语言代码
以下是一个简单的 2048 游戏的 C 语言代码示例,供你参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define BOARD_SIZE 4
void print_board(int board[BOARD_SIZE][BOARD_SIZE]) {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
printf("%4d", board[i][j]);
}
printf("\n");
}
}
// 将所有数字向左移动
void move_left(int board[BOARD_SIZE][BOARD_SIZE]) {
for (int i = 0; i < BOARD_SIZE; i++) {
int k = 0;
for (int j = 1; j < BOARD_SIZE; j++) {
if (board[i][j] != 0) {
if (board[i][k] == 0) {
board[i][k] = board[i][j];
board[i][j] = 0;
} else if (board[i][k] == board[i][j]) {
board[i][k] *= 2;
board[i][j] = 0;
k++;
} else {
k++;
board[i][k] = board[i][j];
board[i][j] = 0;
}
}
}
}
}
// 将所有数字向右移动
void move_right(int board[BOARD_SIZE][BOARD_SIZE]) {
for (int i = 0; i < BOARD_SIZE; i++) {
int k = BOARD_SIZE - 1;
for (int j = BOARD_SIZE - 2; j >= 0; j--) {
if (board[i][j] != 0) {
if (board[i][k] == 0) {
board[i][k] = board[i][j];
board[i][j] = 0;
} else if (board[i][k] == board[i][j]) {
board[i][k] *= 2;
board[i][j] = 0;
k--;
} else {
k--;
board[i][k] = board[i][j];
board[i][j] = 0;
}
}
}
}
}
// 将所有数字向上移动
void move_up(int board[BOARD_SIZE][BOARD_SIZE]) {
for (int j = 0; j < BOARD_SIZE; j++) {
int k = 0;
for (int i = 1; i < BOARD_SIZE; i++) {
if (board[i][j] != 0) {
if (board[k][j] == 0) {
board[k][j] = board[i][j];
board[i][j] = 0;
} else if (board[k][j] == board[i][j]) {
board[k][j] *= 2;
board[i][j] = 0;
k++;
} else {
k++;
board[k][j] = board[i][j];
board[i][j] = 0;
}
}
}
}
}
// 将所有数字向下移动
void move_down(int board[BOARD_SIZE][BOARD_SIZE]) {
for (int j = 0; j < BOARD_SIZE; j++) {
int k = BOARD_SIZE - 1;
for (int i = BOARD_SIZE - 2; i >= 0; i--) {
if (board[i][j] != 0) {
if (board[k][j] == 0) {
board[k][j] = board[i][j];
board[i][j] = 0;
} else if (board[k][j] == board[i][j]) {
board[k][j] *= 2;
board[i][j] = 0;
k--;
} else {
k--;
board[k][j] = board[i][j];
board[i][j] = 0;
}
}
}
}
}
int main() {
int board[BOARD_SIZE][BOARD_SIZE] = {0};
srand(time(NULL));
int x, y;
x = rand() % BOARD_SIZE;
y = rand() % BOARD_SIZE;
board[x][y] = 2;
while (1) {
print_board(board);
char c = getchar();
system("clear");
switch (c) {
case 'a':
move_left(board);
break;
case 'd':
move_right(board);
break;
case 'w':
move_up(board);
break;
case 's':
move_down(board);
break;
default:
break;
}
x = rand() % BOARD_SIZE;
y = rand() % BOARD_SIZE;
if (board[x][y] == 0) {
board[x][y] = 2;
}
}
return 0;
}
```
这个程序使用了一个二维数组来表示游戏棋盘,然后定义了四个函数来处理向左、向右、向上和向下移动的逻辑。程序使用 `rand()` 函数来生成随机位置并添加一个新的数字。最后,使用一个无限循环来持续游戏,直到玩家退出。
阅读全文