大家好,我正在为学校编写一个小型主机游戏。问题是推“w”和“a”有效(它们对二维数组的行或列元素减 1)但“d”和“s”不起作用(它们向行或列加 1二维数组的元素)。如果您尝试代码,您会注意到按 s 或 d 会使屏幕出现故障。
请引用CGame类的Move()和Update()
泰
#include <iostream>
#include <string>
#include <conio.h>
#include <ctime>
#include <cstdlib>
using namespace std;
const char PLAYER = 'H';
const char WALLS = '=';
const int ROWS = 20;
const int COLS = 50;
//Map class generates map, player and enemies
class CMap{
public:
char m_cMap[20][50];
//Map constructor
CMap(int _row, int _col){
//Spawn boarders
for (int i = 0; i < ROWS; i++){
for (int j = 0; j < COLS; j++){
if (i == 0 || i == ROWS - 1){
m_cMap[i][j] = WALLS;
}else if (j == 0 || j == COLS - 1){
m_cMap[i][j] = WALLS;
}else{
m_cMap[i][j] = ' ';
}
}
}
//Spawn player
m_cMap[_row][_col] = PLAYER;
}
};
class CGame{
private:
void Move(CMap& _map, char _move, int _i, int _j){
_map.m_cMap[_i][_j] = ' ';
switch (_move){
case 'w':
case 'W':
_i--;
break;
case 's':
case 'S':
_i++;
break;
case 'a':
case 'A':
_j--;
break;
case 'd':
case 'D':
_j++;
break;
default:
break;
}
_map.m_cMap[_i][_j] = PLAYER;
}
public:
//Functions for the main gameloop
void Update(CMap& _map, char _move){
for (int i = 0; i < ROWS; i++){
for (int j = 0; j < COLS; j++){
//Move Player
if (_map.m_cMap[i][j] == PLAYER){
Move(_map, _move, i, j);
}
//Move Enemies...
}
}
}
void Check(CMap _map){}
void Display(CMap _map){
system("CLS");
for (int i = 0; i < ROWS; i++){
for (int j = 0; j < COLS; j++){
cout << _map.m_cMap[i][j];
}
cout << endl;
}
}
};
int main(){
//Generate random numbers for player spawn
srand(time(0));
int randRow = (rand() % 17) + 1;
int randCol = randRow + 20;
//Instantiate the game and map objects
CGame game;
CMap map(randRow, randCol);
//Game loop
bool gg = false;
while (!gg){
//PlayerController
char move = 0;
if (_kbhit){
move = _getch();
}
game.Update(map, move);
//game.Check(map);
game.Display(map);
}
}
最佳答案
问题是,当您移动播放器时,您不会打破循环。由于再次检测到玩家,他们再次移动它。像这样修改您的更新功能:
//Functions for the main gameloop
void Update(CMap& _map, char _move){
bool moved = false;
for (int i = 0; i < ROWS; i++){
for (int j = 0; j < COLS; j++){
//Move Player
if (_map.m_cMap[i][j] == PLAYER){
Move(_map, _move, i, j);
moved = true;
break;
}
//Move Enemies...
}
if (moved)
break;
}
}
关于C++控制台游戏,故障重新切换语句以在二维数组中移动字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22645050/