我刚刚进入高级c ++编码,我在使用类和对象时遇到了麻烦。基本上我正在尝试从此完成编程练习 site,除了“Dungeon Crawl”。目标是创建一个使用charecter网格进行游戏的游戏。我正在尝试使用一个类来使玩家统计数据像x坐标和y坐标。还有一个错误'。''必须有class / struct / union。这是我的代码。谢谢你的帮助!
#include <iostream>
#include <Windows.h>
using namespace std;
class players {
public:
int y = 2; //Row
int x = 3; //Column
int health = 10;
int name = "player";
};
void move() {
switch (getchar()) {
case 67: //if right arrow pressed
player.x += 1;
gameBoard[player.y][player.x] = { 'P' };
break;
case 68: //if left arrow pressed
player.x -= 1;
gameBoard[player.y][player.x] = { 'P' };
break;
case 66: //if down arrow pressed
player.y -= 1;
gameBoard[player.y][player.x] = { 'P' };
break;
case 65: //if up arrow pressed
player.y += 1;
gameBoard[player.y][player.x] = { 'P' };
break;
}
}
bool hasWon = false;
const int boardRow = 5; //makes the games size
const int boardColumn = 7;
char gameBoard[boardRow][boardColumn] = //Defines starting gameboard
{
{'.','.','.','.','.','.','.'},
{'.','.','.','.','.','.','.'},
{'.','.','.','P','.','.','.'},
{'.','.','.','.','.','.','.'},
{'.','.','.','.','.','.','.'}
};
void displayBoard() { //Displays the board
for (int x = 0; x < boardRow; x++) { //Loop for the rows
int row = x;
for (int x = 0; x < boardColumn; x++) { //Loop through column
cout << gameBoard[row][x];
}
cout << endl; //New line after each row
}
}
int main() {
players player;
cout << "Please type your name: "; //Takes user name
cin >> player.name; //changes the name on the object
while (hasWon == false) { //keeps taking input until player wins
displayBoard(); //update board
move(); //check for keys and move
}
system("pause"); // pause
return 0;
}
答案 0 :(得分:0)
player
在main
中定义。在那之外,代码不知道它意味着什么。
最简单的解决方法是将players player;
行从main
移到move
之前的某个位置(最好是在顶部,其余的全局变量应该在其中)。全球通常是一个坏主意,但如果你已经收到了一大堆,呃......不妨跟它一起去。
稍微不那么明确的解决方案是通过引用player
来引用需要它的代码(此处为move
)。
(更好的方法是让你的players
课程知道如何移动,但这基本上会涉及重写。)
答案 1 :(得分:0)
player
超出了move()
的范围。作为快速更改,将其作为参数传递:
void move(players& player) {
...
move(player); //check for keys and move
下一步可以重新设计类,比如make move()是类Player的成员函数。
答案 2 :(得分:0)
我需要在函数'move'之前声明对象'player'。