我正在嘗試創建一個小的 ascii 游戲,我可以在其中跑來跑去殺死敵人等。但是我是 C 新手,如果玩家位置在某個點,我想做點什么。
下面是一個更簡單的代碼版本和問題的圖片:
#include <iostream>
using namespace std;
struct Game
{
bool bGameOver = false;
int iWidth = 20;
int iHeight = 40;
void Draw() {
if (player.x == 5)
{
cout << "Hello"
}
}
};
struct Player
{
bool bGameOver = false;
int x = 0;
int y = 0;
};
void Setup()
{
}
int main()
{
Game game;
Player player;
while (!game.bGameOver)
{
Setup();
}
}
錯誤圖片
uj5u.com熱心網友回復:
該變數player在函式中是區域的main,因此在您嘗試使用它的地方不可見Game::Draw。
一種解決方案可能是創建player一個全域變數。您需要切換結構的順序:
struct Player
{
bool bGameOver = false;
int x = 0;
int y = 0;
};
Player player;
struct Game
{
bool bGameOver = false;
int iWidth = 20;
int iHeight = 40;
void Draw() {
if (player.x == 5)
{
cout << "Hello"
}
}
};
但我更愿意將事物建模為Game"has a" Player。所以做Player一個成員Game:
struct Player
{
bool bGameOver = false;
int x = 0;
int y = 0;
};
struct Game
{
Player player;
bool bGameOver = false;
int iWidth = 20;
int iHeight = 40;
void Draw() {
if (player.x == 5)
{
cout << "Hello"
}
}
};
(旁白:您可能不希望呼叫兩個不同的值bGameOver,因為使它們保持同步將是額外的作業。對我來說,這聽起來更像是游戲屬性而不是玩家屬性。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/496384.html
