为什么这里的贪吃蛇总是吃完第一次食物后就出现bug?

求解为什么这里蛇吃完第一次食物后会出现bug,

#include<stdio.h>
#include<easyx.h>
#include<conio.h>
#include<stdlib.h>
#define snake_num 5
struct snake
{
    int size;
    int dir;
    int speed;
    POINT coor[snake_num];
}snk;
struct food
{
    int x;
    int y;
    int r;
    bool flag;
    DWORD COLOR;
}food;
void game() 
{
    snk.size = snake_num;
    snk.speed = 20;
    for (int i = snk.size - 1; i >= 0; i--)
    {
        snk.coor[i].x = i * 20;
        snk.coor[i].y = 10;  
    }
}
void initgame()
{
    initgraph(800, 600, EW_SHOWCONSOLE);
    srand(GetTickCount());
    setfillcolor(RGB(128,128,128));
    setbkcolor(RGB(26,74,73));
    cleardevice();
    setlinecolor(RGB(26, 74, 73));
    food.x = rand() % 800;
    food.y = rand() % 600;
    food.COLOR = RGB(rand() % 256, rand() % 256, rand() % 256);
    food.r = rand() % 50 + 5;
    food.flag = true;
}
void drawgame()
{
    BeginBatchDraw();
    cleardevice();
    for (int i = 0; i < snk.size; i++)
     {
         fillcircle(snk.coor[i].x, snk.coor[i].y, 15);
     }
    if (food.flag)
    {
        solidcircle(food.x, food.y, food.r); 
    }
    EndBatchDraw();
}
void snakemove()
{
    for (int i = snk.size-1; i > 0; i--)
    {
        snk.coor[i] = snk.coor[i-1];
    }
}
void keycontrol()
{
    switch (_getch())
        {
        case'W':
        case'w':
            snk.coor[0].y -= snk.speed;
            if (snk.coor[0].y <= 0) 
            {
                snk.coor[0].y = 600;
            }
                break;
        case'S':
        case's':
                snk.coor[0].y += snk.speed;
                if (snk.coor[0].y >= 600)
                {
                    snk.coor[0].y = 0;
                }
                break;    
        case'A':
        case'a':
                snk.coor[0].x -= snk.speed;
                if (snk.coor[0].x <= 0)
                {
                    snk.coor[0].x = 800;
                }
                break;    
        case'D':
        case'd':    
                snk.coor[0].x += snk.speed;
                if (snk.coor[0].x >= 800)
                {
                    snk.coor[0].x =0;
                }
                break;
        }
}
void eatfood()
{
    if (food.flag && snk.coor[0].x >= food.x - food.r && snk.coor[0].x <= food.x + food.r &&
        snk.coor[0].y <= food.y + food.r && snk.coor[0].y >= food.y - food.r)
    {
        food.flag = false;
        snk.size++;
    }
    if (!food.flag)
    {
        food.x = rand() % 800;
        food.y = rand() % 600;
        food.COLOR = RGB(rand() % 256, rand() % 256, rand() % 256);
        food.r = rand() % 50 + 5;
        food.flag = true;
    }
}
int main()
{
    initgame();
    game();
    while (1)
    {
        drawgame();
        snakemove();
        keycontrol();
        eatfood();
    }
    getchar();
}
阅读 1k
1 个回答

size++ 之后, coor 数组就不够长了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进