参考文档
借助了这位大佬的开发思路, 开发过程中学到了很多
C语言实现《2048游戏》
技术点:
完整代码
/*********************************************************************
程序名: 贪吃蛇
*********************************************************************/
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_DEPRECATE
#include <iostream> // 对应c中的#include <stdio.h>
#include <cstdlib> // 对应C中的#include <stdlib.h>
#include <ctime> // 对应c中的#include <time.h>
#include <conio.h> // 使用getch()函数
#include <windows.h> //使用Sleep()函数
#include <iomanip> // C++ 输出对齐函数
#include <fstream> // 文件操作头函数
using namespace std;
void Menu();//菜单
void Rule_of_game();//游戏规则
void Begin(); //开始
void Table();//打印4×4方格
int Random_number1();//产生2或4的随机数
int Random_number2();//产生0、1、2、3的随机数
int Get(int *p_cnt, int score);//输入指令
void Move();//保留上一次的棋盘布局
int If_move();//判断是否移动
int Over();//判断是否结束
void Write_max(int score);//向2048游戏-最高记录写入最高分
int Read_max();//读出最高分记录的文件
void Write_file(int *p_cnt, int scort);//存档
int Read_file(int *p_cnt);//读档
void again();//是否继续游戏
int color(int c);//更改颜色
void box_color(int x);//不同数值对应不同颜色
int a[4][4] = {
0 };// 定义全局的二维数组
int A[4][4]; //保留上一步的棋局
char *name_max = "2048游戏-最高记录.txt";
char *name_file = "[山海]-2048游戏.txt";
int main()
{
system("mode con cols=90 lines=30"); //调整控制台大小
system("title 2048超级大大型游戏"); //程序标题
system("color F0");//F 表示背景颜色,0表示前景颜色
Menu();
system("PAUSE");
return 0;
}
void Menu() //菜单
{
cout << "\t\t║ 欢迎使用由[山海]制作的2048超级大大型游戏 ║\n";
cout << "\t\t╟──────────────────────────────────────────────╢\n";
cout << "\t\t║请输入选项: ║\n";
cout << "\t\t║ ┌───┐ ║\n";
cout << "\t\t║ │ 1 │ 游戏规则 ║\n";
cout << "\t\t║ └───┘ ║\n";
cout << "\t\t║ ┌───┐ ║\n";
cout << "\t\t║ │ 2 │ 开始游戏 ║\n";
cout << "\t\t║ └───┘ ║\n";
cout << "\t\t║ ┌───┐ ║\n";
cout << "\t\t║ │ 3 │ 继续游戏 ║\n";
cout << "\t\t║ └───┘ ║\n";
cout << "\t\t║ ┌───┐ ║\n";
cout << "\t\t║ │ 4 │ 退出游戏 ║\n";
cout << "\t\t║ └───┘ ║\n";
cout << "\t\t╚══════════════════════════════════════════════╝\n";
int x = 1, max = 0;
while (x)
{
switch (getch()) // getch()函数检测按键。
{
case '1':
x = 0;
Rule_of_game();//游戏规则
Menu();
break;
case '2':
x = 0;
system("cls");//清屏
int h, l;
for (h = 0; h < 4; h++)
{
for (l = 0; l < 4; l++)
{
a[h][l] = 0;
A[h][l] = 0;
}
}
Begin(); //开始游戏
break;
case '3':
x = 0;
system("cls");//清屏
max = Read_max();//读取之前的最高记录
Begin(); //开始游戏
break;
case '4':
exit(0);
default:
cout << "输入了非法选项,请重新选择!" << endl;
}
}
}
void Rule_of_game()
{
system("cls");//清屏
cout << "╔══════════════════════════════════════════════════════════════════════════════════╗" << endl;
cout << "║本游戏通过按键W、S、A、D(不区分大小写)四个键分别控制滑块上移、下移、左移和右移。 ║" << endl;
cout << "║滑块移动的过程中,如有相邻且相等数字的滑块将会相加,并获得相应的分数。 ║" << endl;
cout << "║当棋盘上的所有位置均有数字,且不能合成,则游戏结束。本游戏未设置游戏成功。 ║"<< endl;
cout << "║游戏过程中输入I即为存档并退出游戏,输入O即为读档,输入P则退出游戏。 ║"<< endl;
cout << "║“开始游戏”则清除最高记录及存档、“继续游戏”则保存之前的最高记录,且可以读档。 ║" << endl;
cout << "╚══════════════════════════════════════════════════════════════════════════════════╝" << endl;
system("pause");//暂停
system("cls");//清屏
}
void Begin()
{
int score = 0;
int sign = 1;
int h