制作简单的蛇游戏

making simple snake game

本文关键字:游戏 简单      更新时间:2023-10-16

我有问题,我正在用opencv制作一个简单的蛇游戏。现在我只想让我的蛇动,但它没有。我的代码怎么了?我认为我创建的snakemove()不适用于我的snake。我该怎么解决这个问题?提前谢谢。这是我的代码

#include<opencv2corecore.hpp>
    #include<opencv2highguihighgui.hpp>
    #include<opencv2imgproc.hpp>
    #include<stdio.h>
    #include<conio.h>
    #include<iostream>
    bool gameover;
    using namespace cv;
    const int width = 500;
    const int height = 500;
    int x, y;
    enum eDirection
    {
        STOP = 0,
        LEFT,
        RIGHT,
        UP,
        DOWN
    };
    eDirection dir;
    void Setup()
    {
        gameover = false;
        dir = STOP;
        x = width / 2;
        y =height / 2;
    }
    void DrawAsnake(Mat &img)
    {
        const int HEAD_SIZE = 10;
        const int BODY_SIZE = 10;
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                if (i == y && j == x)
                {
                    circle(img, Point(x, y), HEAD_SIZE, Scalar(255, 0, 0), 2);
                    rectangle(img, Point(x - 2 * HEAD_SIZE, y), Point(x - HEAD_SIZE, y + HEAD_SIZE / 2), Scalar(255, 0, 0), 2);
                }
                }
        }
    }
    void SnakeMove()
    {

            if (_kbhit()) 
            {

                switch (_getch())
                {
                case 'a'://75
                    dir = LEFT;
                    break;

                case'w' ://72
                    dir = UP;
                    break;

                case 'd'://77
                    dir = RIGHT;
                    break;

                case 's'://80
                    dir = DOWN;
                    break;

                }
            }
    }
    void GameLogic()
    {
        switch (dir)
        {
        case LEFT:

            x--;
            break;
        case RIGHT:
            x--;
            break;
        case UP:
            y--;
            break;
        case DOWN:
            y++;
        default:
            break;
        }
    }
    void main()
    {
        Mat img(500, 800, CV_32FC3);
        Setup();
        while(!gameover)
        {
            DrawAsnake(img);
            SnakeMove();
            GameLogic();
            imshow("main window", img);
            waitKey(20);
            img = Mat::zeros(img.rows, img.cols, CV_32FC3);
            imshow("main window", img);
            x++;
        }
    }
Try this. 
void main()
{
    Mat img(500, 800, CV_32FC3);
    Setup();
    while(!gameover)
    {

        imshow("main window", img);
        DrawAsnake(img);
        SnakeMove();
        GameLogic();
        waitKey(20);
        img = Mat::zeros(img.rows, img.cols, CV_32FC3);
        imshow("main window", img);
        x++;
    }
}