初学者练习代码
贪吃蛇小游戏
#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define N 16
#define NUM 64
#define G 254
char GameDate[N][NUM];
char *p=&GameDate[7][31];
char *plong[G+1];
char *qf=NULL;
int count = 0,num = 0,ture = 1,game = 1;
int n=N/2,m=NUM/2;
void mapprintf();
void contrl(char ch);
void monster();
void map();
void food();
int main(int argc,char *argv[])
{
mapprintf();//初始化地图
system("stty -icanon");
while(1)
{
if(game)
{
system("clear");
map();
char ctl = getchar();
contrl(ctl);
monster();
}
else
{
if(count >100)
printf(" 胜利!分数:%d\n",count);
else if(count > 50)
printf("\n 游戏结束!分数:%d\n",count);
else
printf("\n 你得了%d分\n",count);
return 0;
}
}
}
void mapprintf()
{
//init 初始化
int i,j;
for(i=0;i<NUM;i++)
{
GameDate[0][i] = '#';
GameDate[N-1][i] = '#';
}
for(i=0;i<N;i++)
{
GameDate[i][0] = '#';
GameDate[i][NUM-1] = '#';
}
for(i=1;i<N-1;i++)
for(j=1;j<NUM-1;j++)
GameDate[i][j]=' ';
food();
}
void contrl(char ch)
{
int charg = 1;
if(ch =='w'&& *(p-NUM)!='#'&&*(p-NUM)!='@')
{
charg = 0;
p-=NUM;
}
else if(ch =='s'&&*(p+NUM)!='#'&&*(p+NUM)!='@')
{
charg = 0;
p+=NUM;
}
else if(ch =='a'&&*(p-1)!='#'&&*(p-1)!='@')
{
charg = 0;
p-=1;
}
else if(ch =='d'&&*(p+1)!='#'&&*(p+1)!='@')
{
charg = 0;
p+=1;
}
else if((ch>='a'&&ch<='z')&&(charg==1))
game = 0;
if(count >= 128)
game = 0;
plong[++num]=p;
if(*p == '*')
{
ture = 1;
count++;
}
}
void monster()
{
int i;
mapprintf();
if(num == G)
{
for(i=count;i>=0;i--)
{
plong[i]=plong[num];
num--;
}
num = count;
}
for(i=num;i>=num-count;i--)
*plong[i]='@';
}
void map()
{
int i,j;
printf("*****************************贪吃蛇****************************\n");
if(num == 0)
*p = '@';
for(i=0;i<N;i++)
{
for(j=0;j<NUM;j++)
putchar(GameDate[i][j]);
printf("\n");
}
printf(" 您的得分:%d\n",count);
}
void food()
{
srand(time(0));
if(ture == 1)
while(1)
{
n = rand()%(N-2)+1;
m = rand()%(NUM-2)+1;
if(GameDate[n][m] == ' ')
{
qf=&GameDate[n][m];
GameDate[n][m]='*';
ture = 0;
break;
}
}
else
{
*qf='*';
}
}