【发布时间】:2021-06-05 00:36:07
【问题描述】:
我目前正在尝试通过实现蛇游戏来更新我的 c++ 技能。我创建了以下类 - 相关代码 sn-p:
snake_class.h
#include <string>
#include <vector>
#include <windows.h>
typedef struct coordinates {
int x;
int y;
};
class Snake {
public:
std::vector<coordinates> body;
Snake(const int MAX_HEIGHT, const int MAX_WIDTH, const int initLengthSnake);
void updateSnakeBody(coordinates newDirection, int startingPoint);
};
...以及.cpp文件的对应代码sn-p:
snake_class.cpp
#include <vector>
#include "snake_class.h"
Snake::Snake(const int MAX_HEIGHT, const int MAX_WIDTH, const int initLengthSnake) {
for (int snakeLength = 0; snakeLength < initLengthSnake; snakeLength++) {
coordinates currentBodyPoint = { (MAX_WIDTH + initLengthSnake) / 2 - snakeLength, (MAX_HEIGHT) / 2 };
body.push_back(currentBodyPoint);
}
}
void Snake::updateSnakeBody(coordinates newDirection, int startingPoint) {
coordinates currentBodyPoint = body[startingPoint];
body[startingPoint].x += newDirection.x;
body[startingPoint].y += newDirection.y;
if (startingPoint + 1 < body.size()) {
coordinates nextDirection = { currentBodyPoint.x - body[startingPoint + 1].x,
currentBodyPoint.y - body[startingPoint + 1].y };
updateSnakeBody(nextDirection, startingPoint + 1);
}
}
我的主要方法如下所示:
bool crashed = false;
int main()
{
//init-part for windows and snake length
const int windowHeight = 20;
const int windowWidth = 25;
const int initSnakeLength = 4;
//init part for snake game to move and some stock variables
coordinates direction = { 1, 0 };
bool initNeeded = false;
//snake init
Snake* snake = new Snake(windowWidth, windowHeight, initSnakeLength);
while (true) {
if (initNeeded) {
crashed = false;
Snake* snake = new Snake(windowWidth, windowHeight, initSnakeLength);
initNeeded = false;
}
if (!crashed) {
(*snake).updateSnakeBody(direction, 0);
crashed = true;
}
else {
delete snake;
initNeeded = true;
}
}
return 0;
}
构建成功,第一轮游戏按预期进行。当我向游戏反馈我想再玩一轮时,新的蛇类在if (initNeeded) {...}-条件中再次构建。向量在构造后也得到了4的大小。
但程序一进入行
(*snake).updateSnakeBody(direction, 0);
我检索了错误消息vector subsrictp out of range,不知何故向量得到了0的大小。
我知道,我不需要动态分配新类来让游戏按预期运行,但我想以这种方式进行尝试。
我真的不明白为什么新类会这样,希望你们中的一些人能帮助我解决这个问题!
提前致谢!
【问题讨论】:
-
感谢您指出这一点,我忘记了。我减少了代码部分。
标签: c++ class dynamic allocation