2021-05-03
作者:互联网
#include
#include<windows.h>
#include<graphics.h>
#include<conio.h>
#include
using namespace std;
#define MAX 100
#define nodeSize 10
struct place {
int x;
int y;
};
struct Snack {
int Size;
place node[MAX];
char dir;
};
struct snackFood {
place food;
bool symbol;
};
Snack snack;//蛇
snackFood snackfood;//食物
//初始化蛇
void iniSnack() {
initgraph(640, 480);
srand((unsigned int)time(NULL));
snack.Size = 3;
snack.dir = ‘d’;
snack.node[0].x = 100;
snack.node[0].y = 100;
snack.node[1].x = 90;
snack.node[1].y = 100;
snack.node[2].x = 80;
snack.node[2].y = 100;
//给食物的初始化状态
snackfood.symbol = true;
}
//产生食物
void createFood() {
int flag;//蛇与食物重合的标志
while (1) {
flag = 0;
//1.食物必须在蛇的轨道上
snackfood.food.x = rand() % 64 * 10;
snackfood.food.y = rand() % 48 * 10;
//2.蛇的身体不能与食物重合
for (int i = 0; i < snack.Size; i++)
{
if (snack.node[i].x == snackfood.food.x && snack.node[i].y == snackfood.food.y) {
flag = 1;
break;
}
}
if (flag) {
continue;
}
else
{
snackfood.symbol = false;
break;
}
}
}
//吃食物
void eatFood() {
if (snack.node[0].x == snackfood.food.x && snack.node[0].y == snackfood.food.y) {
snack.Size++;
snackfood.symbol = true;
}
}
//判断是否撞墙
bool gameOver() {
if (snack.node[0].x < 0 || snack.node[0].x>640 || snack.node[0].y < 0 || snack.node[0].y>480) {
return true;
}
for (int i = snack.Size - 1; i > 0; i–)
{
if (snack.node[0].x == snack.node[i].x && snack.node[0].y == snack.node[i].y) {
return true;
}
}
}
//画蛇
void drawSnack() {
cleardevice();
for (int i = 0; i < snack.Size; i++) {
setfillcolor(RGB(rand() % 256 + i, rand() % 256 + i, rand() % 256 + i));
solidcircle(snack.node[i].x, snack.node[i].y, 5);
}
solidcircle(snackfood.food.x, snackfood.food.y, 5);
}
//移动蛇
void moveSnack() {
system(“cls”);
for (int i = snack.Size; i > 0; i–) {
snack.node[i].x = snack.node[i - 1].x;
snack.node[i].y = snack.node[i - 1].y;
}
switch (snack.dir) {
case ‘w’:snack.node[0].y -= nodeSize; break;
case ‘s’:snack.node[0].y += nodeSize; break;
case ‘a’:snack.node[0].x -= nodeSize; break;
case ‘d’:snack.node[0].x += nodeSize; break;
}
}
//改变方向
void changeSnackDir() {
int ch = _getch();
switch (ch) {
case ‘w’:if (snack.dir != ‘s’) { snack.dir = ‘w’; }break;
case ‘s’:if (snack.dir != ‘w’) { snack.dir = ‘s’; }break;
case ‘a’:if (snack.dir != ‘d’) { snack.dir = ‘a’; }break;
case ‘d’:if (snack.dir != ‘a’) { snack.dir = ‘d’; }break;
}
}
void main() {
iniSnack();
while (1) {
if (snackfood.symbol == true) {
createFood();
}
drawSnack();
moveSnack();
Sleep(2);
eatFood();
if (gameOver()) {
break;
}
if (_kbhit()) {
changeSnackDir();
}
}
}## c++贪吃蛇<有灵魂的蛇> 但是这个要用到图形界面graphics.h
标签:node,03,snack,05,int,snackfood,break,2021,dir 来源: https://blog.csdn.net/weixin_55109596/article/details/116381486