2048小游戏c语言源代码
时间: 2023-08-25 12:05:46 浏览: 122
下面是一个简单的2048小游戏的C语言源代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 4
#define COLS 4
void init(int board[][COLS])
{
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j] = 0;
}
}
}
void print_board(int board[][COLS])
{
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%d\t", board[i][j]);
}
printf("\n");
}
}
void add_random_number(int board[][COLS])
{
int i, j, r;
do {
i = rand() % ROWS;
j = rand() % COLS;
} while (board[i][j] != 0);
r = (rand() % 2 + 1) * 2;
board[i][j] = r;
}
void move_up(int board[][COLS])
{
int i, j, k;
for (j = 0; j < COLS; j++) {
for (i = 1; i < ROWS; i++) {
if (board[i][j] != 0) {
k = i;
while (k > 0 && board[k-1][j] == 0) {
board[k-1][j] = board[k][j];
board[k][j] = 0;
k--;
}
if (k > 0 && board[k-1][j] == board[k][j]) {
board[k-1][j] *= 2;
board[k][j] = 0;
}
}
}
}
}
void move_down(int board[][COLS])
{
int i, j, k;
for (j = 0; j < COLS; j++) {
for (i = ROWS - 2; i >= 0; i--) {
if (board[i][j] != 0) {
k = i;
while (k < ROWS - 1 && board[k+1][j] == 0) {
board[k+1][j] = board[k][j];
board[k][j] = 0;
k++;
}
if (k < ROWS - 1 && board[k+1][j] == board[k][j]) {
board[k+1][j] *= 2;
board[k][j] = 0;
}
}
}
}
}
void move_left(int board[][COLS])
{
int i, j, k;
for (i = 0; i < ROWS; i++) {
for (j = 1; j < COLS; j++) {
if (board[i][j] != 0) {
k = j;
while (k > 0 && board[i][k-1] == 0) {
board[i][k-1] = board[i][k];
board[i][k] = 0;
k--;
}
if (k > 0 && board[i][k-1] == board[i][k]) {
board[i][k-1] *= 2;
board[i][k] = 0;
}
}
}
}
}
void move_right(int board[][COLS])
{
int i, j, k;
for (i = 0; i < ROWS; i++) {
for (j = COLS - 2; j >= 0; j--) {
if (board[i][j] != 0) {
k = j;
while (k < COLS - 1 && board[i][k+1] == 0) {
board[i][k+1] = board[i][k];
board[i][k] = 0;
k++;
}
if (k < COLS - 1 && board[i][k+1] == board[i][k]) {
board[i][k+1] *= 2;
board[i][k] = 0;
}
}
}
}
}
int game_over(int board[][COLS])
{
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (board[i][j] == 0) {
return 0;
}
if (i < ROWS - 1 && board[i][j] == board[i+1][j]) {
return 0;
}
if (j < COLS - 1 && board[i][j] == board[i][j+1]) {
return 0;
}
}
}
return 1;
}
int main()
{
int board[ROWS][COLS];
char input;
srand(time(NULL));
init(board);
add_random_number(board);
add_random_number(board);
while (1) {
printf("\n");
print_board(board);
if (game_over(board)) {
printf("Game over!\n");
break;
}
printf("Use arrow keys to move. Press q to quit.\n");
input = getchar();
if (input == 'q') {
break;
}
if (input == '\033') {
getchar(); // skip [
switch (getchar()) {
case 'A':
move_up(board);
break;
case 'B':
move_down(board);
break;
case 'C':
move_right(board);
break;
case 'D':
move_left(board);
break;
}
add_random_number(board);
}
}
return 0;
}
```
这是一个简化版的2048小游戏,只支持上下左右移动,不支持撤销和计分等功能。如果需要完整的游戏体验,还需要进行一些扩展。
阅读全文