【发布时间】:2014-05-03 21:56:03
【问题描述】:
您好,我正在为学校编写一个小型主机游戏。如果有的话,问题是推动'w'和'a'有效(它们将2d数组的行或col元素减去1)但'd'和's'不起作用(它们将1添加到行或col二维数组的元素)。如果您尝试该代码,您会注意到按 s 或 d 会使屏幕出现故障。
请参考CGame类的Move()和Update()。
TY
#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);
}
}
【问题讨论】:
标签: c++ arrays char switch-statement 2d