Luckys-Yang 2021-12-09 19:11 采纳率: 50%
浏览 28
已结题

贪吃蛇代码食物生成次数问题已经是求解答

为什么每次生成大概5次的食物后就不生成了窗口啥都没只有一条蛇应该不是超出窗口问题因为食物应该设置坐标在窗口内,就是找不到问题所在


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<easyx.h>
#include<conio.h>
#include<mmsystem.h>
#include<time.h>
#pragma comment(lib,"winmm.lib")
#define USIZE 10
#define HEIGHT 640
#define WIDTH 500

int main()
{
    initgraph(HEIGHT,WIDTH);
    //定义蛇
    int len;//蛇的长度
    int dir;//蛇的方向 0上 1下 2左 3右
    int x[200];//蛇的x坐标
    int y[200];//蛇的y坐标

    //定义食物
    int fx, fy;

    //定义背景
    IMAGE backimg;
    loadimage(&backimg,"sky.jpg",HEIGHT,WIDTH);//加载图片
    
    //初始化(最开始的时候)
    len = 1;
    dir = 3;
    x[0] = 0;
    y[0] = 0;

    //初始化食物(注意)
    srand((unsigned int)time(NULL));
    fx =rand()%(WIDTH/USIZE)*USIZE;//要保证食物坐标是10的倍数因为蛇的坐标也是10的倍数
    fy =rand()%(HEIGHT/USIZE)*USIZE;
    while (1)
{
        int ch1=0;
        int ch2=0;
        //方向按键
        if (kbhit())
        {
            if (ch1 =getch())
            {
                ch2 =getch();//要调用两次getch()函数功能键才生效
                if (ch2 == 72)//键码
                    dir = 0;
                else if (ch2 == 80)
                    dir = 1;
                else if (ch2 == 75)
                    dir = 2;
                else if (ch2 == 77)
                    dir = 3;
            }
        }

        cleardevice();//刷新
        putimage(0, 0, &backimg);
    //数据可视化(绘制蛇)
    for (int i = 0; i < len; i++)
    {
        fillrectangle(x[i], y[i], x[i] + USIZE, y[i] + USIZE);//画一个矩形函数,fill填充,(矩形左上角x坐标,左上角y坐标,右下角x坐标,右下角y坐标) 
        setfillcolor(YELLOW);
    }
    //绘制食物
    for (int i=0; i<len;i++)
    {
        fillrectangle(fx, fy, fx + USIZE, fy + USIZE);
        setfillcolor(RED);

    }
    //蛇的移动
    for (int i = len - 1; i > 0; i--)
    {
        x[i] = x[i - 1];
        y[i] = y[i - 1];
    }
    switch (dir)
    {
    case 0:y[0] -= USIZE; break;//上
    case 1:y[0] += USIZE; break;//下
    case 2:x[0] -= USIZE; break;//左
    case 3:x[0] += USIZE; break;//右
    }
    if (x[0] == fx && y[0] == fy)
    {
        len++;//蛇节数加1
        fx = rand() % (WIDTH / USIZE) * USIZE;
        fy = rand() % (HEIGHT / USIZE) * USIZE;
    }
    Sleep(100);
    
}
    

    system("pause");
    return 0;
}

![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/658581840936142.png "#left")
就生成两次食物就没了

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 12月17日
    • 创建了问题 12月9日

    悬赏问题

    • ¥20 python忆阻器数字识别
    • ¥15 无法输出helloworld
    • ¥15 高通uboot 打印ubi init err 22
    • ¥20 PDF元数据中的XMP媒体管理属性
    • ¥15 R语言中lasso回归报错
    • ¥15 网站突然不能访问了,上午还好好的
    • ¥15 有没有dl可以帮弄”我去图书馆”秒选道具和积分
    • ¥15 semrush,SEO,内嵌网站,api
    • ¥15 Stata:为什么reghdfe后的因变量没有被发现识别啊
    • ¥15 振荡电路,ADS仿真