我开始使用 raylib 进行编程,并尝试制作一个贪吃蛇游戏。我想将发生的所有事情都放在 Game 类中。所以我包含了我的蛇类的头文件,然后尝试在我的游戏类中创建一个对象,但我随后收到错误:未知覆盖说明符。
#ifndef GAME_H
#define GAME_H
#include "food.h"
#include "snake.h"
class Game {
public:
void Draw();
void Update();
void MoveSnake();
private:
Snake snake = Snake(); // error here
Food food = Food(); // error here
};
#endif // GAME_H
两个类的问题是相同的。 蛇类示例:
#ifndef SNAKE_H
#define SNAKE_H
#include "header.h"
#define COLOR_R 43
#define COLOR_G 51
#define COLOR_B 24
#define COLOR_A 255
class Snake {
public:
int i;
void Draw();
void Update();
void Move();
private:
std::deque<Vector2> body = { Vector2{6, 9}, Vector2{5, 9}, Vector2{4, 9} };
Vector2 direction{ 1, 0 };
int j;
};
#endif
我知道如果我在同一个文件中实现该类,我不会收到错误,但我希望未来的项目和良好的实践将其放在单独的文件中。到目前为止我发现的所有内容都是嵌套类,但人们只是直接在另一个类中编写该类。希望你能帮助我(抱歉我的英语不好)。
其余文件:
#include "header.h"
Color green = Color{ 173, 204, 96, 255 };
double lastUpdateTime{};
bool eventTriggered(double interval) {
double currentTime = GetTime();
if (currentTime - lastUpdateTime >= interval) {
lastUpdateTime = currentTime;
return true;
}
return false;
}
int main() {
InitWindow(cellSize * cellCount, cellSize * cellCount, "Snake");
SetTargetFPS(60);
Game game = Game();
while (!WindowShouldClose()) {
BeginDrawing();
if (eventTriggered(0.2)) {
game.Update();
}
game.MoveSnake();
// Drawing
ClearBackground(green);
game.Draw();
EndDrawing();
}
CloseWindow();
return 0;
}
游戏cpp:
#include "game.h"
#include "snake.h"
void Game::Draw(void) {
this->snake.Draw();
this->food.Draw();
}
void Game::Update(void) {
this->snake.Update();
}
void Game::MoveSnake(void) {
this->snake.Move();
}
蛇cpp:
#include "snake.h"
Snake::Snake() {};
void Snake::Draw(void) {
for (size_t i{}; i < body.size(); ++i) {
Rectangle segment = Rectangle{ this->body[i].x * cellSize, this->body[i].y * cellSize, cellSize, cellSize };
DrawRectangleRounded(segment, 0.5f, 6, { COLOR_A, COLOR_G, COLOR_B, COLOR_A });
}
}
void Snake::Update(void) {
this->body.pop_back();
this->body.push_front(Vector2Add(this->body[0], this->direction));
}
void Snake::Move(void) {
if (IsKeyPressed(KEY_UP) && this->direction.y != 1) {
this->direction = Vector2{ 0, -1 };
}
if (IsKeyPressed(KEY_DOWN) && this->direction.y != -1) {
this->direction = Vector2{ 0, 1 };
}
if (IsKeyPressed(KEY_LEFT) && this->direction.x != 1) {
this->direction = Vector2{ -1, 0 };
}
if (IsKeyPressed(KEY_RIGHT) && this->direction.x != -1) {
this->direction = Vector2{ 1, 0 };
}
}
脚你可以把它从代码中取出来,它不是必需品 标题:
#ifndef HEADER_H
#define HEADER_H
#include <iostream>
#include <raylib.h>
#include <deque>
#include <raymath.h>
#include "game.h"
constexpr int cellSize{ 30 };
constexpr int cellCount{ 25 };
#endif
问题可能是没有在任何地方声明 Snake() 函数。您应该为每个类创建一个构造函数,并使用构造函数声明该类型的任何实例。
例如
class Snake
public:
//constructor for the class
snake()
{
//code to be executed upon object creation
}
int i;
void Draw();
void Update();
void Move();
然后像这样声明一个 Snake 类型的对象
Snake snake();
希望这有帮助。