//2048
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<conio.h>
int code[4][4] =
{ 0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0 };//十六个格子
int temp[5];//中间变量
int score = 0;//分数
int move = 0;//移动次数
void print(void) //每进行一次大循环(输入方向键),清屏并显示表格
{
int i, j;
system("cls");//清屏
printf("W:上,S:下,A:左,D:右\n");
printf("SCORE:%d MOVE:%d\n", score, move);
printf("Made by lzp\n");
printf("--------------------\n");
for (i = 0; i <= 3; i++)
{
for (j = 0; j <= 3; j++)
if (code[i][j] == 0)
printf("| ");//若为0则显示四个空格
else printf("|%4d", code[i][j]);//显示数字和空格
printf("|\n|-------------------|\n");//横向分割线
}
}
int add(void)//中间变量的处理
{
int i, change = 0, t = 0;
while (t <= 3)//低顺位往高顺位挪动一位,低顺位变为0,高顺位变为低顺位的数
{
for (i = 0; i <= 3; i++)
if (temp[i] == 0)
{
temp[i] = temp[i + 1];
temp[i + 1] = 0;
if (temp[i] != temp[i + 1])
change = 1;//当0后面不是0时,数组有变化
}
t++;
}
for (i = 1; i < 4; i++)
{
if (temp[i] == temp[i - 1] && temp[i - 1] != 0)
{
change = 1;//两个非零数相加则数组有变化
score += temp[i];
temp[i - 1] *= 2;
temp[i] = 0;
}
} //如果低顺位的数和高顺位的数相等,则,有变化,高顺位为两数相加,并让低顺位变为0
while (t <= 3)
{
for (i = 0; i < 4; i++)
if (temp[i] == 0)
{
temp[i] = temp[i + 1];
temp[i + 1] == 0;
}
t++;//t的循环要遍历四遍。
} // 若为2 2 2 0,则完成第一二块的时候,为4 0 2 0.为了避免这种情况加了第三部分。
return change;
}
int main(void)
{
int gameover = 0;//判断游戏是否结束
int i, j;
int change = 1;
char input;
srand(time(NULL));//随机数初始化
while (gameover == 0)//若没有结束游戏则进入循环
{
if (change >= 1)//如果数发生变化则添加新的数
{
do
{
i = rand() % 4;
j = rand() % 4;
} while (code[i][j] != 0);
if (rand() % 4 == 0)
code[i][j] = 4;
else code[i][j] = 2;//随机选一个空格添加2或4
move++;
}
print(); //清屏并显示表格
input = getch();//输入方向
change = 0;
switch (input)
{
case'0':printf("Are you sure to exit?(y/n)");//退出
input = getchar();
if (input == 'y' || input == 'Y')
exit(0);break;
case'w':
case'W'://把一纵列赋给temp,从下到上为低顺位到高顺位
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
temp[i] = code[i][j];
temp[4] = 0;
change = change + add();
for (i = 0; i < 4; i++)
code[i][j] = temp[i];//把这列数从中间变量temp移回来
}break;
case'A':
case'a'://把每一行作为temp数组的数据,右底左高
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
temp[j] = code[i][j];
temp[4] = 0;
change = change + add();
for (j = 0; j < 4; j++)
code[i][j] = temp[j];
}break;
case'S':
case's'://类似w,但反向赋值,反向赋值就达成了高低顺位调换的作用
for (j = 0;j < 4; j++)
{
for (i = 0; i < 4; i++)
temp[i] = code[3 - i][j];
temp[4] = 0;
change = change + add();
for (i = 0; i <= 3; i++)
code[3 - i][j] = temp[i];
}
break;
case 'D':
case 'd'://类似a,反向赋值
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
temp[j] = code[i][3 - j];
temp[4] = 0;
change = change + add();
for (j = 0; j < 4; j++)
code[i][3 - j] = temp[j];
}
break;
}
gameover = 1;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
if (code[i][j] == 0)
gameover = 0; //格子都填满时就gameover
}
printf("GAMEVOER!\n");
getch();
return 0;
}
数组实现2048
最新推荐文章于 2023-06-25 15:59:04 发布