c++ - 蛇游戏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 之后)
解决方案
推荐阅读
- jquery-ui-slider - 有没有办法在 jquery-ui 范围滑块中显式设置选项,而不是使用“min”、“max”和“step”?
- c++ - 为什么我的 char 数组条件不起作用
- node.js - 接口中的计算属性名称必须引用类型为文字类型或“唯一符号”类型的表达式
- git - VSCode 不显示 GitHub 身份验证的密码对话框
- here-api - 直接序列中的航点
- c# - LINQ 顺序字符串列表,按起始字符,然后按整个字符串
- android - APK 的文件名不能包含(NUL、CR、LF)字符
- c - ASCII 与显示的结果 (a) 之间的关系是什么?
- google-apps-script - Function not running in GAS
- java - 活动不会在主页按钮后从广播接收器开始,而是在返回按钮后开始