小游戏贪吃蛇,
#include <graphics.h>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <Windows.h>
#include <iostream>
#include <math.h>
#include <istream>
using std::cin;
using std::cout;
struct pos_xy
{
//坐标
int x;
int y;
};
struct snakeInfo
{
int num; //蛇的节数
struct pos_xy xy{ 100 }; //蛇的最大节数是100节
char position; //蛇的方向
}snake;
struct foodInfo
{
struct pos_xy xy; //蛇的坐标
int flag; //蛇的标记
int grade; //蛇自带的经验值
}food;
enum snakePosition{right,left,down,up};
void initSnake()
{
snake.xy[2].x = 0;
snake.xy[2].y = 0;
snake.xy[1].x = 10;
snake.xy[1].y = 0;
snake.xy[0].x = 20;
snake.xy[0].y = 0;
snake.num = 3;
snake.position = left; //蛇的初始方向
food.grade = 0;
}
void drawSnake()
{
for (int i = 0; i < snake.num; i++)
{
setfillcolor(RED);
fillrectangle(snake.xy.x, snake.xy.y, snake.xy.x + 10, snake.xy.y + 10);
}
};
void moveSnake()
{
for (int i = snake.num - 1; i > 0; i--)
{
snake.xy.x = snake.xy.x;
snake.xy.y = snake.xy.y;
}
switch (snake.position)
{
case right:
snake.xy.x -= 10;
break;
case left:
snake.xy.x += 10;
break;
case down:
snake.xy.y += 10;
break;
case up:
snake.xy.y -= 10;
break;
}
}
void keyDown()
{
char ch = 0;
ch = _getch();
switch(ch)
{
case 'w':
case 'W':
case 72:
if (snake.position != down)
{
snake.position = up;
}
break;
case 's':
case 'S':
case 80:
if (snake.position != up)
{
snake.position = down;
}
break;
case 'a':
case 'A':
case 75:
if (snake.position != left)
{
snake.position = right;
}
break;
case 'd':
case 'D':
case 77:
if (snake.position != right)
{
snake.position = left;
}
break;
}
}
void initFood()
{
srand((unsigned int)time(NULL));
food.xy.x = rand() % 80 * 10;
food.xy.y = rand() % 60 * 10;
food.flag = 1;
for (int i = 0;i < snake.num;i++)
{
if (food.xy.x == snake.xy.x && food.xy.y == snake.xy.y)
{
food.xy.x = rand() % 80 * 10;
food.xy.y = rand() % 60 * 10;
}
}
}
void drawFood()
{
fillrectangle(food.xy.x, food.xy.y, food.xy.x + 10, food.xy.y + 10);
}
void eatFood()
{
if (snake.xy.x == food.xy.x && snake.xy.y == food.xy.y)
{
snake.num++;
food.grade += 10;
food.flag = 0;
}
}
int main()
{
initgraph(900, 600);
setbkcolor(WHITE);
cleardevice();
initSnake();
while (1)
{
cleardevice();
if (food.flag == 0)
{
initFood;
}
drawFood();
drawSnake();
moveSnake();
eatFood();
if (_kbhit())
{
keyDown();
}
Sleep(50);
}
cout << "游戏结束!!!!";
closegraph();
return 0;
}
无法运行,错误E0349
void initSnake()
{
snake.xy[2].x = 0;
snake.xy[2].y = 0;
snake.xy[1].x = 10;
snake.xy[1].y = 0;
snake.xy[0].x = 20;
snake.xy[0].y = 0;
snake.num = 3;
snake.position = left; //蛇的初始方向
food.grade = 0;
}
此处的六个"[]"都出现了错误提示
贪吃蛇 cmd命令行
https://juejin.cn/user/2595295089934200
贪吃蛇 easyX
xy是个结构变量,不是数组啊
struct pos_xy xy{ 100 }; //蛇的最大节数是100节
改为 struct pos_xy xy[100];