用C语言写一个2048游戏
时间: 2023-05-12 10:05:35 浏览: 104
非常感谢您的提问,以下是一个简单的用C语言实现的2048游戏:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 4
int board[SIZE][SIZE];
void init_board() {
int i, j;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
board[i][j] = 0;
}
}
}
void print_board() {
int i, j;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
printf("%d ", board[i][j]);
}
printf("\n");
}
}
int is_full() {
int i, j;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
if (board[i][j] == 0) {
return 0;
}
}
}
return 1;
}
void add_random() {
if (is_full()) {
return;
}
int i, j;
do {
i = rand() % SIZE;
j = rand() % SIZE;
} while (board[i][j] != 0);
board[i][j] = (rand() % 2 + 1) * 2;
}
void move_left() {
int i, j, k;
for (i = 0; i < SIZE; i++) {
k = 0;
for (j = 0; j < SIZE; j++) {
if (board[i][j] != 0) {
if (k != j) {
board[i][k] = board[i][j];
board[i][j] = 0;
}
k++;
}
}
for (j = 0; j < SIZE - 1; j++) {
if (board[i][j] == board[i][j + 1]) {
board[i][j] *= 2;
board[i][j + 1] = 0;
}
}
k = 0;
for (j = 0; j < SIZE; j++) {
if (board[i][j] != 0) {
if (k != j) {
board[i][k] = board[i][j];
board[i][j] = 0;
}
k++;
}
}
}
}
void move_right() {
int i, j, k;
for (i = 0; i < SIZE; i++) {
k = SIZE - 1;
for (j = SIZE - 1; j >= 0; j--) {
if (board[i][j] != 0) {
if (k != j) {
board[i][k] = board[i][j];
board[i][j] = 0;
}
k--;
}
}
for (j = SIZE - 1; j > 0; j--) {
if (board[i][j] == board[i][j - 1]) {
board[i][j] *= 2;
board[i][j - 1] = 0;
}
}
k = SIZE - 1;
for (j = SIZE - 1; j >= 0; j--) {
if (board[i][j] != 0) {
if (k != j) {
board[i][k] = board[i][j];
board[i][j] = 0;
}
k--;
}
}
}
}
void move_up() {
int i, j, k;
for (j = 0; j < SIZE; j++) {
k = 0;
for (i = 0; i < SIZE; i++) {
if (board[i][j] != 0) {
if (k != i) {
board[k][j] = board[i][j];
board[i][j] = 0;
}
k++;
}
}
for (i = 0; i < SIZE - 1; i++) {
if (board[i][j] == board[i + 1][j]) {
board[i][j] *= 2;
board[i + 1][j] = 0;
}
}
k = 0;
for (i = 0; i < SIZE; i++) {
if (board[i][j] != 0) {
if (k != i) {
board[k][j] = board[i][j];
board[i][j] = 0;
}
k++;
}
}
}
}
void move_down() {
int i, j, k;
for (j = 0; j < SIZE; j++) {
k = SIZE - 1;
for (i = SIZE - 1; i >= 0; i--) {
if (board[i][j] != 0) {
if (k != i) {
board[k][j] = board[i][j];
board[i][j] = 0;
}
k--;
}
}
for (i = SIZE - 1; i > 0; i--) {
if (board[i][j] == board[i - 1][j]) {
board[i][j] *= 2;
board[i - 1][j] = 0;
}
}
k = SIZE - 1;
for (i = SIZE - 1; i >= 0; i--) {
if (board[i][j] != 0) {
if (k != i) {
board[k][j] = board[i][j];
board[i][j] = 0;
}
k--;
}
}
}
}
int main() {
srand(time(NULL));
init_board();
add_random();
add_random();
print_board();
while (1) {
char c = getchar();
if (c == 'q') {
break;
} else if (c == 'a') {
move_left();
add_random();
print_board();
} else if (c == 'd') {
move_right();
add_random();
print_board();
} else if (c == 'w') {
move_up();
add_random();
print_board();
} else if (c == 's') {
move_down();
add_random();
print_board();
}
}
return 0;
}
```
希望这个程序能够帮助到您,如果您有任何问题,请随时问我。
阅读全文