C++贪吃蛇原码
#include <stdio.h>
#include <graphics.h>
#include <easyx.h>
#include <conio.h>
#include <time.h>
#define myHeight 10
#define width 600
#define height 400
#define speed 5
enum fangxiang
{
UP,DOWN,LEFT,RIGHT
};
struct pos
{
int x;
int y;
};
struct snake
{
pos position[50];
int length;
int direction;
}snake;
struct foods
{
pos position;
int flag;
}food;
void initSnake()
{
snake.length = 3;
snake.direction =RIGHT ;
snake.position[0].x = 2*myHeight;
snake.position[0].y = 0;
snake.position[1].x = myHeight;
snake.position[1].y = 0;
snake.position[2].x = 0;
snake.position[2].y = 0;
}
void drawSnake()
{
cleardevice();
BeginBatchDraw();
if (snake.position[0].x > width || snake.position[0].y > height ||
snake.position[0].x < 0 || snake.position[0].y < 0)
{
MessageBox(NULL, L"就这?\t就这?\n就这?\t就这?", L"信息框", MB_SYSTEMMODAL);
exit(0);
}
if (snake.position[0].x == food.position.x&&snake.position[0].y==food.position.y)
{
snake.length += 1;
srand(time(NULL));
int a = 0;
int b = width-myHeight;
int c = height-myHeight;
int r = rand() % (b - a + 1) + a;
food.position.x = r - r % 10;
int m = rand() % (c - a + 1) + a;
food.position.y = m - m % 10;
}
for (int i = 0; i < snake.length; i++)
{
setfillcolor(RED);
fillrectangle(snake.position[i].x, snake.position[i].y,
snake.position[i].x+myHeight, snake.position[i].y+myHeight);
fillrectangle(food.position.x, food.position.y, food.position.x+myHeight, food.position.y+ myHeight);
}
FlushBatchDraw();
}
void runSnake()
{
for (int i = snake.length-1 ; i >0; i--)
{
snake.position[i].x = snake.position[i - 1].x;
snake.position[i].y = snake.position[i - 1].y;
}
switch (snake.direction)
{
case UP:
snake.position[0].y -= myHeight;
break;
case DOWN:
snake.position[0].y += myHeight;
break;
case LEFT:
snake.position[0].x -= myHeight;
break;
case RIGHT:
snake.position[0].x += myHeight;
break;
default:
break;
}
}
int userkey()
{
if (_kbhit())
{
char ch = _getch();
switch (ch)
{
case 72:
if (snake.direction!=DOWN)
snake.direction = UP;
break;
case 80:
if (snake.direction!=UP)
snake.direction = DOWN;
return 1;
case 75:
if(snake.direction!=RIGHT)
snake.direction = LEFT;
break;
case 77:
if(snake.direction!=LEFT)
snake.direction = RIGHT;
break;
default:
break;
}
}
}
void startGame()
{
initgraph(width, height);
setbkcolor(RGB(210, 255, 200));
cleardevice();
initSnake();
}
int main()
{
startGame();
food.position.x = 100;
food.position.y = 100;
while (true)
{
BeginBatchDraw();
drawSnake();
runSnake();
for (int i = 0; i < 18-snake.length; i++)
{
if (userkey() != 1)
{
Sleep(speed);
}
else
break;
}
FlushBatchDraw();
}
EndBatchDraw();
closegraph();
return 0;
}