2048c语言
时间: 2023-07-07 20:12:59 浏览: 36
2048 游戏可以使用 C 语言进行开发。以下是一个简单的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 4
#define TARGET 2048
int board[SIZE][SIZE];
void init_board() {
srand(time(NULL));
int x1 = rand() % SIZE;
int y1 = rand() % SIZE;
int x2 = rand() % SIZE;
int y2 = rand() % SIZE;
while (x1 == x2 && y1 == y2) {
x2 = rand() % SIZE;
y2 = rand() % SIZE;
}
board[x1][y1] = 2;
board[x2][y2] = 2;
}
void print_board() {
printf("\n");
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
printf("%d\t", board[i][j]);
}
printf("\n");
}
}
int can_move(int x, int y, int dx, int dy) {
if (x + dx < 0 || x + dx >= SIZE || y + dy < 0 || y + dy >= SIZE) {
return 0;
}
if (board[x + dx][y + dy] == 0 || board[x + dx][y + dy] == board[x][y]) {
return 1;
}
return 0;
}
void move(int x, int y, int dx, int dy) {
if (can_move(x, y, dx, dy)) {
if (board[x + dx][y + dy] == 0) {
board[x + dx][y + dy] = board[x][y];
board[x][y] = 0;
} else if (board[x + dx][y + dy] == board[x][y]) {
board[x + dx][y + dy] *= 2;
board[x][y] = 0;
}
}
}
void move_left() {
for (int i = 0; i < SIZE; i++) {
for (int j = 1; j < SIZE; j++) {
move(i, j, 0, -1);
}
}
}
void move_right() {
for (int i = 0; i < SIZE; i++) {
for (int j = SIZE - 2; j >= 0; j--) {
move(i, j, 0, 1);
}
}
}
void move_up() {
for (int i = 1; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
move(i, j, -1, 0);
}
}
}
void move_down() {
for (int i = SIZE - 2; i >= 0; i--) {
for (int j = 0; j < SIZE; j++) {
move(i, j, 1, 0);
}
}
}
int game_over() {
int count = 0;
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (board[i][j] == 0) {
return 0;
}
if (board[i][j] == TARGET) {
return 1;
}
if (i > 0 && board[i][j] == board[i - 1][j]) {
count++;
}
if (j > 0 && board[i][j] == board[i][j - 1]) {
count++;
}
}
}
if (count == 0) {
return 1;
}
return 0;
}
int main() {
init_board();
print_board();
while (!game_over()) {
char c = getchar();
switch (c) {
case 'a':
move_left();
break;
case 'd':
move_right();
break;
case 'w':
move_up();
break;
case 's':
move_down();
break;
default:
break;
}
print_board();
}
printf("Game over!\n");
return 0;
}
```
该代码使用二维数组 `board` 来存储游戏棋盘,其中 0 表示空格,2 表示初始的两个方块。游戏的核心逻辑在 `move` 函数中,用于判断是否可以移动并更新棋盘状态。在 `main` 函数中,根据用户输入来调用相应的移动函数,并在每次移动后打印当前的棋盘状态。游戏结束的判断逻辑在 `game_over` 函数中,当棋盘上没有空格并且没有相邻的方块可以合并时,游戏结束。