[英]Issues with rand() function
我的隨機生成的“蛇丸”有一些問題。 我希望將*
用作蛇的食物。 它不是在我用作游戲板的char
數組內部生成的。 我不確定; 我可能會說錯了或使用了該函數。
#include<iostream>
#include<Windows.h>
#include<stdlib.h>
#include<time.h>
#include<stdio.h>
using namespace std;
char Map[11][22] =
{
"---------------------",
"|S * |",
"| |",
"| |",
"| |",
"| |",
"| |",
"| |",
"| |",
"| |",
"---------------------"
};
int x = 1, y = 1;
bool GameRunning = true;
int main()
{
srand(time(NULL));
int pellet = rand();
while (GameRunning == true)
{
for (int pellet = 0; pellet % Map[11][22]; pellet++)
{
cout << '*';
}
system("cls");
for (int display = 0; display < 11; display++)
{
cout << Map[display] << endl;
}
system("pause>nul");
if (GetAsyncKeyState(VK_DOWN))
{
int y2 = y + 1;
if (Map[y2][x] == ' ')
{
Map[y][x] = ' ';
y++;
Map[y][x] = 'S';
}
}
if (GetAsyncKeyState(VK_UP))
{
int y2 = y - 1;
if (Map[y2][x] == ' ')
{
Map[y][x] = ' ';
y--;
Map[y][x] = 'S';
}
}
if (GetAsyncKeyState(VK_RIGHT))
{
int x2 = x+1;
if (Map[y][x2] == ' ')
{
Map[y][x] = ' ';
x++;
Map[y][x] = 'S';
}
}
if (GetAsyncKeyState(VK_LEFT))
{
int x2 = x - 1;
if (Map[y][x2] == ' ')
{
Map[y][x] = ' ';
x--;
Map[y][x] = 'S';
}
}
}
}
您在for循環中用0覆蓋了pellet
,所以它總是用0而不是rand()
初始化。 另外, rand()
會產生一個介於0到至少32767之間的隨機數,因此您需要對其進行修改以獲取所需的范圍。 例如,從0-20開始,您將執行pellet = rand() % 21
或4-16,而您可以進行pellet= (rand() % 13) + 4
(因為4-16可以重寫為范圍0-12加4)。 這是rand()
文檔: http : //www.cplusplus.com/reference/cstdlib/rand/
第二點,您真的需要for循環嗎? 真的應該出現在游戲循環中嗎? 在開始時設置一次似乎更有意義。
您可能希望使用Map[random_x_val][random_y_val] = '*'
在Map[random_x_val][random_y_val] = '*'
的開頭將隨機框設置為'*'
,其中random_x_val
和random_y_val
是矩陣的有效范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.