[英]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.