C語言實現的簡易貪吃蛇小遊戲

#include <stdio.h>
#include <windows.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include <malloc.h>
typedef struct SnakeGame{ int x;int y;struct SnakeGame *next
;}snake;

snake *front, *rear;
char map[20][42];//give the map//


 void ini();
 int Move();
 void insert(int x,int y);
 void clean();
 void print();

int main()
{   
 int res;
 res=1;

 ini();
  while(res!=0)
  {
  
   Move();//when this function ends,game over//
   res=0;  
  }

  printf("GAME OVER!!!\n");
  return 0;
}

void ini()//print the map ,food and snake//
{
   int i,j,a,b;
   front=rear=NULL;
   for(i=0;i<20;i++)
   {
   for(j=0;j<42;j++)
   {
    if(i==0||i==19||j==0||j==41)
    map[i][j]='*';
    else
    map[i][j]=' ';
   }
   }

   for(i=2;i<6;i++)
   map[2][i]='x';
   map[2][i]='H';

 a= rand()%19+1;      
 b= rand()%41+1;
 map[a][b] = '$';       
}

void insert(int x,int y)//insert the new head after every step//
{
 snake *p;
 p=(snake*)malloc(sizeof(snake));
 p->x=x;//the coordine of the body ,head and food//
 p->y=y;

 if(rear==NULL)
   rear=front=p;
 else
 {
  p->next=front;
  front=p;
 }

}

void clean()//if not eat food,clean the old rear//
{
 snake *q;
 q=front;

 while(q->next!=rear)
  q=q->next;

 free(rear);
 rear=q;
}

void gotoxy(int x,int y)//just find this online //
{ HANDLE hOutput;
   COORD loc;
   loc.X=x;
   loc.Y=y;
 hOutput = GetStdHandle(STD_OUTPUT_HANDLE); 
SetConsoleCursorPosition(hOutput, loc);  
}

void print()//print the picture in time//
{
	int i,j;
	gotoxy(0,0);
	for(i=0;i<20;i++)
	{
		for(j=0;j<42;j++)
		{
			
				printf("%c",map[i][j]);
			if(j>0&&j%41==0)
			     printf("\n");
		}
	}
}
int Move()//to tell how to move //
{
 char key='d';
 int a,b,rx,ry;
 int i;

rear = front = NULL;

for(i=2;i<7;i++)
insert(2,i);
print();

 while(1) 
 {	  
	  Sleep(200);
	  if(kbhit())
	   key=getch();

	switch(key)//the way to go in four directions//
	{
	case'a':{
            ry = (front->y)-1;
			rx = front->x;
			break;
			}
	case'd':{
		      ry=(front->y)+1;
              rx = front->x;
			  break;
			}
    case'w':{
			 ry=front->y;
			 rx=(front->x)-1;
			 break;
			}
    case's':{
		      ry=front->y;
			  rx=(front->x)+1;
			  break;
			}
	default:break;
	}


    map[front->x][front->y] = 'x';//replace the old head and insert the new head//
    insert(rx,ry);

	if(map[front->x][front->y]=='*' ||map[front->x][front->y]=='x') //judge the death//
      return 0;
    else
	{
     if(map[front->x][front->y]!='$')//judge the food//
		{
			map[rear->x][rear->y] = ' '; 
		    clean();
		}

	 else
	 {
         a= rand()%19+1;
	     b= rand()%41+1;
		while(map[a][b] != ' ')
			{
		    	a= rand()%19+1;
				b= rand()%41+1;
			}
	  	 map[a][b] = '$';
	 }

	 map[front->x][front->y]='H';
     print();
	}

 }

}
相關文章
相關標籤/搜索