我试图让一条小道出现在玩家自行车后面但由于某种原因而不是每次移动时玩家后面出现“x”,玩家实际上会复制自己。这听起来有点混乱,但你应该自己编译这个代码,看看我的意思。我想要做的就是在玩家后面留下一条“x”而不是玩家留下“P”的痕迹。感谢
#include <iostream>
#include "windows.h"
#include <conio.h>
#include <ctime>
using namespace std;
//prototype functions used
void DisplayMap();
void PlayerBike();
void setCursorTo();
void SetBike();
//global variables that will be used by different functions
int PlayerX = 10;
int PlayerY = 70;
bool GameOver = false;
const int H = 25; // const variable so it doesnt change size
const int W = 82;// const variable so it doesnt change size
char Map[H][W]; // char map with HxW
char trail = 'x'; // this is where the trail is initialized as a *
int main()
{
SetBike();
DisplayMap();
while (GameOver == false){
setCursorTo();
PlayerBike();
} // end while loop
return 0;
}//end main
void DisplayMap(){ // display map function
for(int i = 0; i < H; i++ ){
for(int j = 0; j < W; j++){
if(i == 0 || i == 24 || j == 0 || j == 81 ){ Map[i][j] = 'x';} // characters in row 24x81 are changed to x
cout << Map[i][j]; // output map
} // end for loop
cout << "\n"; // create new line to output the map correctly
} //end for loop
} // end DisplayMap function
void SetBike(){
Map[PlayerX] [PlayerY] = 'P';
}
void PlayerBike(){
Map[PlayerY][PlayerX]= trail; // I would like this trail to repeat behind the player but it does not appear at all.
if (kbhit()) {// get user key input
char GetCh = getch(); // GetCh equal to the button the user presses
if (GetCh == 'w'){PlayerX = PlayerX - 1; Trailx = Trailx -1;}
else if (GetCh == 's'){PlayerX = PlayerX +1; Trailx = Trailx +1;}
else if (GetCh == 'd'){PlayerY = PlayerY +1;}
else if (GetCh == 'a'){PlayerY = PlayerY - 1;}
}// end kbhit
}// end PlayerBike function
void setCursorTo() // stops constant flashing on the map
{
HANDLE handle;
COORD position;
handle = GetStdHandle(STD_OUTPUT_HANDLE);
position.X = 0;
position.Y = 0;
SetConsoleCursorPosition(handle, position);
}
答案 0 :(得分:1)
您的DisplayMap
功能存在缺陷。
首先,您似乎不仅显示地图,而且还在积极修改它。将绘图边框放入一个单独的initMap
函数中,该函数也会用空格将所有其他位置归零(看起来你还没有这样做,所以也许这就是它出错的地方)。您只需拨打initMap
一次。
接下来,请勿在{{1}}功能中绘制播放器P
。在进入游戏循环之前,先画一次 。然后:如果用户按下有效的移动键,
DisplayMap
x
P
可能的改进:在通过更新位置接受'move'命令之前,检查地图是否包含空格或其他内容。如果它包含空格,则可以执行移动;如果没有,播放爆炸动画(DisplayMap
)。另外,请考虑在您最喜欢的C引用中查找*oO*+.
语句,以避免无休止的switch
长序列。