陈道宁 • 1个月前
typedef struct{
int eat;
int ch=72;
int money=0;
int speed;
int length;
int x[SNAKESIZE];
int y[SNAKESIZE];
}SNAKE; SNAKE snake; typedef struct{
int x;
int y;
}FOOD; FOOD food; void settextcolor(int color){
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
} void gotoxy(int x,int y){
COORD c;
c.X=x;
c.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);
} void drawapple(){
gotoxy(food.x,food.y);
settextcolor(4);
printf("★");
settextcolor(7);
gotoxy(0,0);
} void eatfood(){
if(snake.x[0]==food.x&&snake.y[0]==food.y){
snake.length++;
snake.eat=1;
snake.speed-=10;
time_t t;
srand((unsigned)time(&t));
food.x=rand()%(LENGTH-4)/2*2+2;
food.y=rand()%(HEIGHT-2)/2*2+1;
snake.money+=10;
}
} void initgame(){
for(int i=0;i<=LENGTH;i+=2){
gotoxy(i,0);
printf("■");
gotoxy(i,HEIGHT);
printf("■");
}
for(int i=1;i<HEIGHT;i++){
gotoxy(0,i);
printf("■");
gotoxy(LENGTH,i);
printf("■");
}
snake.length=3;
snake.speed=200;
snake.x[0]=LENGTH/2+1;
snake.y[0]=HEIGHT/2;
gotoxy(snake.x[0],snake.y[0]);
settextcolor(6);
printf("■");
settextcolor(7);
for(int i=1;i<snake.length;i++){
snake.x[i]=snake.x[i-1]+2;
snake.y[i]=snake.y[i-1];
gotoxy(snake.x[i], snake.y[i]);
printf("■");
}
while(1){
bool flag=true;
food.x=rand()%(LENGTH-4)+2;
food.y=rand()%(HEIGHT-2)+1;
for(int i=0;i<snake.length;i++){
if(snake.x[i]==food.x&&snake.y[i]==food.y){
flag=false;
break;
}
}
if(flag&&food.x%2==0){
break;
}
}
drawapple();
} void turn(){
int pre_ch=snake.ch;
if(_kbhit()){
snake.ch=_getch();
if(snake.ch==224){
snake.ch=_getch();
}
else{
snake.ch=pre_ch;
}
}
if(snake.eat==0){
gotoxy(snake.x[snake.length-1],snake.y[snake.length-1]);
printf(" ");
}
for(int i=snake.length-1;i>0;i--){
snake.x[i]=snake.x[i-1];
snake.y[i]=snake.y[i-1];
}
if(pre_ch==72&&snake.ch==80){
snake.ch=72;
}
if(pre_ch==80&&snake.ch==72){
snake.ch=80;
}
if(pre_ch==75&&snake.ch==77){
snake.ch=75;
}
if(pre_ch==77&&snake.ch==75){
snake.ch=77;
}
if(snake.ch==77){
snake.x[0]+=2;
}
if(snake.ch==75){
snake.x[0]-=2;
}
if(snake.ch==80){
snake.y[0]++;
}
if(snake.ch==72){
snake.y[0]--;
}
gotoxy(snake.x[0],snake.y[0]);
settextcolor(6);
printf("■");
settextcolor(7);
gotoxy(0,0);
snake.eat=0;
} bool over(){
for(int i=1;i<snake.length;i++){
if(snake.x[0]==snake.x[i]&&snake.y[0]==snake.y[i]){
return true;
}
}
if(snake.x[0]<2|snake.x[0]>LENGTH-2||snake.y[0]<1||snake.y[0]>HEIGHT-1){
return true;
}
return false;
} int main(){
initgame();
while(1){
Sleep(200);
snake.money++;
turn();
if(over()){
break;
}
eatfood();
drawapple();
}
gotoxy(30,12);
printf("GAME OVER");
gotoxy(30,13);
printf("得分 : %d",snake.money);
getchar();
}
评论: