#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#include<conio.h>
int score=0,move=0,a[4][4]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},temp[5],highest_score=0;
void print(void)
{
int i,j;
system("cls");
printf(" ___________________2048________________\n");
printf(" ------------how to play?----------\n");
printf(" A---left,D-right,W---up,S---down,0---exit\n");
printf(" ----------------------------------\n");
printf(" highest score:%d\n",highest_score);
printf(" ----------------------------------\n");
printf(" score:%d move:%d \n",score,move);
for(i=0;i<4;i++)
{
printf(" |-------------------|\n");
printf(" ");
for(j=0;j<4;j++)
{
if(a[i][j]==0)
printf("| ");
else
printf("|%-4d",a[i][j]);
if(j==3)
printf("|\n");
}
}
printf(" |-------------------|\n");
}
int add()
{
int i,j,t=1,change=0;
while(t<=3)
{
for(i=0;i<3;i++)
{
if(temp[i]==0)
{
if(temp[i]!=temp[i+1])
change=1;
temp[i]=temp[i+1];
temp[i+1]=0;
}
}
t++;
}
for(i=0;i<3;i++)
{
if(temp[i]==temp[i+1])
{
if(temp[i]!=0)
{
change=1;
score=score+temp[i];
}
temp[i]=temp[i]*2;
temp[i+1]=0;
}
}
t=1;
while(t<=3)
{
for(i=0;i<3;i++)
{
if(temp[i]==0)
{
temp[i]=temp[i+1];
temp[i+1]=0;
}
}
t++;
}
return change;
}
int main()
{
int change=1,gameover=0,i,j;
char input;
srand((unsigned)time(NULL));
while(gameover==0)
{
if(change>=1)
{
do
{
i=((unsigned)rand())%4;
j=((unsigned)rand())%4;
}while(a[i][j]!=0);
if(((unsigned)rand())%2==0)
a[i][j]=2;
else
a[i][j]=4;
}
print();
input=getch();
change=0;
if(input=='0')
{
printf("Do you really want to exit this game?Y/N\n");
input=getch();
if(input=='y'||input=='Y')
break;
}
else if(input=='w'||input=='W')
{
for(j=0;j<4;j++)
{
for(i=0;i<4;i++)
temp[i]=a[i][j];
temp[5]=0;
change+=add();
for(i=0;i<4;i++)
a[i][j]=temp[i];
}
move++;
}
else if(input=='s'||input=='S')
{
for(j=0;j<4;j++)
{
for(i=0;i<4;i++)
temp[i]=a[3-i][j];
temp[5]=0;
change+=add();
for(i=0;i<4;i++)
a[i][j]=temp[3-i];
}
move++;
}
else if(input=='a'||input=='A')
{
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
temp[j]=a[i][j];
temp[5]=0;
change+=add();
for(j=0;j<4;j++)
a[i][j]=temp[j] ;
}
move++;
}
else if(input=='d'||input=='D')
{
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
temp[j]=a[i][3-j];
temp[5]=0;
change+=add();
for(j=0;j<4;j++)
a[i][j]=temp[3-j];
}
move++;
}
gameover=1;
for(i=0;i<4;i++)
for(j=0;j<4;j++)
{
if(a[i][j]==0)
gameover=0;
}
if(gameover==1)
{
for(i=0;i<3;i++)
for(j=0;j<3;j++)
if(a[i][j]==a[i+1][j]||a[i][j]==a[i][j+1])
gameover=0;
for(i=0;i<3;i++)
if(a[3][i]==a[3][i+1]||a[i][3]==a[i+1][3])
gameover=0;
}
if(gameover==1)
{
printf("Do you want to try again?Y/N");
input=getch();
if(input=='Y'||input=='y')
{
gameover=0;
memset(a,0,sizeof(a));
change=1;
if(score>highest_score)
highest_score=score;
score=0;
move=0;
}
else if(input=='n'||input=='N')
gameover=1;
}
}
printf("\n Game over!\n");
getch();
return 0;
}
就是highest_score这个全局变量,为什么每次重新开始游戏的时候只在按过Y之后才会显示为score的值,之后一旦进行了一次操作,就右边为了0?而且我发现只要把它改为一个非零的数,就一切正常,这是为什么?