源码如下:
#include <iostream>
#include <conio.h>
#include <vector>
#include <Windows.h>
#include <time.h>
#include <easyx.h>
using namespace std;
struct node
{
int x, y, r;
};
char dir = 's';
vector<node> mv;
node foodNode = { 0, 0, 10 };
int x = 0;
void initSnake()
{
mv.push_back({ 30, 40, 10 });
mv.push_back({ 50, 40, 10 });
mv.push_back({ 70, 40, 10 });
}
void drawMap()
{
for (auto& i : mv)
{
circle(i.x, i.y, i.r);
}
circle(foodNode.x, foodNode.y, foodNode.r);
}
void move()
{
for (int i = mv.size() - 1; i > 0; i--)
{
mv[i] = mv[i - 1];
}
switch (dir)
{
case 'w':
mv[0].y -= 20;
break;
case 's':
mv[0].y += 20;
break;
case 'a':
mv[0].x -= 20;
break;
case 'd':
mv[0].x += 20;
break;
}
}
void play()
{
if (_kbhit())
switch (_getch())
{
case 'w':
if (dir != 's')
dir = 'w';
break;
case 's':
if (dir != 'w')
dir = 's';
break;
case 'a':
if (dir != 'd')
dir = 'a';
break;
case 'd':
if (dir != 'a')
dir = 'd';
break;
}
}
bool crash(node n, int x, int y)
{
int xx = abs(n.x - x);
int yy = abs(n.y - y);
return xx < 20 && yy < 20;
}
void initFood()
{
int x, y;
while (1)
{
x = rand() % 781 + 10;
y = rand() % 781 + 10;
for (auto& i : mv)
{
if (!crash(i, x, y))
goto a;
}
}
a:
foodNode.x = x;
foodNode.y = y;
}
void eat()
{
if (crash(mv[0], foodNode.x, foodNode.y))
{
mv.push_back(foodNode);
initFood();
x++;
}
}
void loser()
{
if (mv[0].x < 0 || mv[0].x>800 || mv[0].y < 0 || mv[0].y>800)
{
MessageBox(GetHWnd(), "游戏失败", "提示", MB_OK);
getchar();
exit(1);
}
for (int i = 1; i < mv.size(); i++)
{
if (crash(mv[0], mv[i].x, mv[i].y))
{
MessageBox(GetHWnd(), "游戏失败", "提示", MB_OK);
getchar();
exit(1);
}
}
}
int main()
{
srand((unsigned)time(NULL));
initgraph(800, 800);
initSnake();
char str[6] = { 0 };
initFood();
while (1)
{
sprintf(str, "%d", x);
outtext(str);
play();
eat();
move();
loser();
drawMap();
Sleep(100);
cleardevice();
}
system("pause");
closegraph();
return 0;
}