[英]How to generate random fruit for C++ 2D Snake game
我無法為我的 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)創建隨機值,然后將 append 放入我的游戲板。
但問題是:我只想用隨機的 X 和 Y 和 append 制作一個水果到我的游戲板中顯示它。 但我目前的代碼是這樣的:
bGameW.insert(fruitX, "F");
bGameL.insert(fruitY, "F");
此代碼生成 2 個水果,其中 1 個隨機 X 和 1 個隨機 Y。我想將這 2 個水果變成 1 個水果,1 個隨機 X 和 1 個隨機 Y。
有很多值得評論的事情。 開始:
\n
\n
后兩者都是 11)。 您的 RNG 正在生成 0 到 20 之間的數字……如果您曾經生成大於 11 的數字(並且您會),壞事將會發生(並且可能已經發生)。 就編程風格而言,您會發現所謂的“幻數”(如您的案例中的 21)會導致錯誤。 人們通常做的是定義一個具有適當值的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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.