贪吃蛇代码能在同学电脑上运行,在我的Devc++就运行不了,这是我的代码
#include<stdio.h>
#include <stdlib.h>
#include <graphics.h>
#include<conio.h>
#define SNAKE_NUM 500
enum DIR
{
UP,
DOWN,
LEFT,
RIGHT,
};
typedef struct Snake
{
int size;
int dir;
int speed;
POINT coor[SNAKE_NUM];
}snake;
typedef struct Food
{
int x;
int y;
int r;
int grade;
bool flag;
DWORD color;
}food;
//数据的初始化
void GameInit()
{
initgraph(640,480);
srand(GetTickCount());
snake.size=3;
snake.speed=10;
snake.dir=RIGHT;
for(int i=0;i<snake.size;i++)
{
snake.coor[i].x=40-10*i;
snake.coor[i].y=10;
}
food.x=rand()%640;
food.y=rand()%480;
food.color=RGB(rand()%256,rand()%256,rand()%256);
food.r=rand()%10+5;
food.flag=true;
}
void showGrade()
{
char grade[20]="";
sprintf(grade,"grade: %d",food.grade);
settextcolor(BLACK);
settextstyle(20,0,"楷体");
outtextxy(550,19,grade);
}
void GameDraw()
{
BeginBatchDraw();
setbkcolor(RGB(211,241,240));
cleardevice();
setfillcolor(YELLOW);
for(int i=0;i<snake.size;i++)
{
solidcircle(snake.coor[i].x,snake.coor[i].y,5);
}
if(food.flag)
{
solidcircle(food.x,food.y,food.r);
}
showGrade();
EndBatchDraw();
}
//移动蛇
void snakeMove()
{
for(int i=snake.size-1;i>0;i--)
{
snake.coor[i]=snake.coor[i-1];
}
switch(snake.dir)
{
case UP:
snake.coor[0].y-=snake.speed;
if(snake.coor[0].y+10<=0)
{
snake.coor[0].y=480;
}
break;
case DOWN:
snake.coor[0].y+=snake.speed;
if(snake.coor[0].y-10>=480)
{
snake.coor[0].y=0;
}
break;
case LEFT:
snake.coor[0].x-=snake.speed;
if(snake.coor[0].x+10<=0)
{
snake.coor[0].x=640;
}
break;
case RIGHT:
snake.coor[0].x+=snake.speed;
if(snake.coor[0].x-10>=640)
{
snake.coor[0].x=0;
}
break;
}
}
void keyControl()
{
if(_kbhit())
{
switch (_getch())
{
case 'w':
case 'W':
case 72:
if(snake.dir!=DOWN) //防止反向操作
{
snake.dir=UP;
}
break;
case 's':
case 'S':
case 80:
if(snake.dir!=UP)
{
snake.dir=DOWN;
}
break;
case 'a':
case 'A':
case 75:
if(snake.dir!=RIGHT)
{
snake.dir=LEFT;
}
break;
case 'd':
case 'D':
case 77:
if(snake.dir!=LEFT)
{
snake.dir=RIGHT;
}
break;
case ' ':
while(1)
{
if(_getch()==' ')
return;
}
break;
}
}
}
void EatFood()
{
if(food.flag && snake.coor[0].x>=food.x-food.r && snake.coor[0].x<=food.x+food.r&&
snake.coor[0].y>=food.y-food.r && snake.coor[0].y<=food.y+food.r)
{
food.flag=false;
snake.size++;
food.grade+=10;
}
if(!food.flag)
{
food.x=rand()%640;
food.y=rand()%480;
food.color=RGB(rand()%256,rand()%256,rand()%256);
food.r=rand()%10+5;
food.flag=true;
}
}
int main()
{
GameInit();
while(1)
{
snakeMove();
GameDraw();
keyControl();
EatFood();
Sleep(50);
}
return 0;
}