首页 > 解决方案 > 蛇游戏c++尾部类如何添加新对象

问题描述

我是 C++ 的初学者程序员,我想要一些帮助来继续我的蛇项目。为了对类进行一些练习,我决定在这个程序中使用它们,而不是养成使用数百个可以被集成的函数之类的坏习惯。

当我必须为我的蛇制作尾巴时,我的问题就来了,因为为了用类制作它,我需要一种命令,在程序中“召唤”一个新的尾巴对象。

例如:我的头刚刚与食物相撞,尾巴必须长出来,但是我怎样才能召唤一个新的尾巴对象呢?

这是代码(我将很快删除 system("cls") 以使程序运行更顺畅):

::::::::::::::::SNAKE.cpp::::::::::::::::::

#include <iostream>
#include <conio.h>
#include <Windows.h>

#include "Head.h"


int score = 0;


int main()
{
    HEAD head;


    while (1)
    {
        head.key();
        head.movement();
        head.show();

        if (GetKeyState(VK_ESCAPE) & 0x8000)
        {
            return 0;
        }

        Sleep(100);
        system("cls");
    }

}

:::::::::::::HEAD.h::::::::::::::

#include <iostream>

void gotoxy(int x, int y)
{
    COORD coord;
    coord.X = x;
    coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

class HEAD
{

private:
    int x = 20;
    int y = 20;
    int direction, lastdirection;


public:

    void show()
    {
        gotoxy(x, y); std::cout << "@";
    }

    void movement()
    {
        lastdirection = direction;

        switch (direction)
        {
        case 1:
            y--;
            break;
        case 2:
            x--;
            break;
        case 3:
            y++;
            break;
        case 4:
            x++;
            break;
        }

    }
    void key()
    {
        //------------directions-----------

        if (GetKeyState('W') & 0x8000)
        {
            direction = 1;
        }

        if (GetKeyState('A') & 0x8000)
        {
            direction = 2;
        }

        if (GetKeyState('S') & 0x8000)
        {
            direction = 3;
        }

        if (GetKeyState('D') & 0x8000)
        {
            direction = 4;
        }

        //-------specific direction changes--------

        if (lastdirection == 1 && direction == 3 || lastdirection == 3 && direction == 1)
        {
            direction = lastdirection;
        }

        if (lastdirection == 2 && direction == 4 || lastdirection == 4 && direction == 2)
        {
            direction = lastdirection;
        }


    }

};

我希望你能帮助我,因为这是一个需要完成的项目,因为对我来说,这是我用 C++ 编程过的最难的事情(在 pong 之后)

标签: c++classconsole

解决方案


推荐阅读