我在为我的Snake游戏生成随机水果时遇到了麻烦。(我是编程新手,这是我的第一门语言)。
当我运行我的代码时,到目前为止所有的工作都很好(除了一些小问题)。我在一个空项目中使用Visual Studio C++。以下是我的完整代码(我没有显示我的 #includes
):
using namespace std;
bool gameOver = false;
int gameScore;
int fruitX;
int fruitY;
string bGameW = "###########";
string bGameL = "# #\n";
class gameStart
{
public:
void start()
{
cout << bGameW;
cout << bGameL;
cout << bGameL;
cout << bGameL;
cout << bGameL;
cout << bGameL;
cout << bGameL;
cout << bGameL;
cout << bGameL;
cout << bGameW;
}
void generateFruit()
{
srand(time(NULL));
fruitX = rand() % 21;
fruitY = rand() % 21;
bGameW.insert(fruitX, "F");
bGameL.insert(fruitY, "F");
}
void clearscreen()
{
system("cls");
}
private:
};
int main ()
{
gameStart gameObj;
gameObj.generateFruit();
gameObj.clearscreen();
gameObj.start();
return 0;
}
生成随机的随机水果的字符串。我使用一个字符串来制作游戏板,然后我为水果创建随机值(X和Y),然后我把它们追加到我的游戏板中。
但问题是。我想只做一个随机X和Y的水果 然后把它追加到我的游戏板上显示出来。但我现在的代码是这样的。
bGameW.insert(fruitX, "F");
bGameL.insert(fruitY, "F");
这段代码产生了两个水果,其中一个是随机X,一个是随机Y 我想把这两个水果变成一个水果,一个随机X,一个随机Y。
有一大堆事情值得评论。 下面是这样的。
\n
\n
). 你的RNG正在生成0到20之间的数字......如果你曾经生成过一个数字> 11(你会的)。坏事 会发生(而且可能已经发生了)。至于编程风格,你会发现所谓的 "魔法数字"(比如你的案例中的21)会导致bug。 人们通常做的是定义一个 const
用适当的值,然后用这个const来定义事物。
// constants are often named in ALL_UPPER_CASE_WITH_UNDERSCORES
// to help you recognize them.
const int PLAY_AREA_HEIGHT = 10;
const int PLAY_AREA_WIDTH = 10;
const char EMPTY_PLAY_SQUARE = '.';
// have you learned about 2d arrays yet? Arrays at all?
char playAreaDisplay[PLAY_AREA_HEIGHT][PLAY_AREA_WIDTH];
void wipePlayArea()
{
for (int heightIdx = 0; heightIdx < PLAY_AREA_HEIGHT; ++heightIdx)
{
for (int widthIdx = 0; widthIdx < PLAY_AREA_WIDTH; ++widthIdx)
{
playAreaDisplay[heightIdx][widthIdx] = EMPTY_PLAY_SQUARE;
}
}
}