制作简单的蛇游戏

时间:2016-04-16 18:12:34

标签: c++ opencv

我有疑问,我正在通过opencv制作一个简单的蛇游戏。现在我只想让我的蛇移动,但事实并非如此。我的代码有什么问题?我认为我创造的snakemove()不适用于我的蛇。我怎么能解决这个问题?提前致谢。 这是我的代码

#include<opencv2\core\core.hpp>
    #include<opencv2\highgui\highgui.hpp>
    #include<opencv2\imgproc.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++;
        }
    }

1 个答案:

答案 0 :(得分:0)

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++;
    }
}
相关问题