最近听说2048游戏挺好玩就上网找个玩,结果没有一个完整的所以我只好自己写一个了。
源代码:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<windows.h>
#include<time.h>
int null_count();//统计还有几个空格
void start_game();//开始游戏
void reset_game();//重置游戏,不清空记录
void move_left();//向左移动
void move_right();//向右移动
void move_up();//向上移动
void move_down();//向下移动
void refresh_show();//刷新显示屏
void add_rand_num();//添加随机数
void check_if_over();//检查游戏是否结束
int board[4][4];
int score = 0;
int best = 0;
int if_need_add_num;
int if_game_over;
int i;
int j;
int k;
int main() {
start_game();
}
void setColor(unsigned short ForeColor = 7, unsigned short BackGroundColor = 0)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(handle, ForeColor + BackGroundColor * 0x10);
}
void start_game() {
reset_game();
char fr;
while (1) {
fr = _getch();//从键盘读数
if (if_game_over) {
if (fr == 'y' || fr == 'Y') {
reset_game();
continue;
}
else if (fr == 'n' || fr == 'N') {
return;
}
else continue;
}
if_need_add_num = 0;
switch (fr) {
case 'a':
case 'A':
move_left();
break;
case 'd':
case 'D':
move_right();
break;
case 'w':
case 'W':
move_up();
break;
case 's':
case 'S':
move_down();
break;
}
if (score > best) {
best = score;
}
if (if_need_add_num) {
add_rand_num();
refresh_show();
}
}
}
int null_count() {
int n = 0;
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
if (board[i][j] == 0) {
n++;
}
}
}
return n;
}
void reset_game() {
score = 0;
if_need_add_num = 1;
if_game_over = 0;
srand(time(0));
int n =