![](/img/trans.png)
[英]Using C++ rand() to get random directions (up/down/left/right) - always getting up
[英]Select one of 4 random directions with rand()?
我想從4個方向中隨機選擇:
movePlayer(map, &positionPlayer, direction);
方向是UP
, DOWN
, LEFT
和RIGHT
。
我還沒有找到如何使用rand()
函數來做到這一點。
我怎樣才能做到這一點? 我是否需要為每個方向分配一個數字,然后在這些范圍內選擇一個隨機數?
謝謝您的幫助。
是的,您需要為每個方向分配一個數字。 即。 0 =向上1 =向下2 =向左3 =向右您需要如下代碼:
int direction = rand()%4;
最簡單的方法是對rand函數取模,以得到0到3(含3)之間的數字。
int x = rand() % 4;
然后,您只需執行switch語句即可選擇方向
switch(x)
{
case 0:
movePlayer(map, &positionPlayer, UP);
break;
case 1:
movePlayer(map, &positionPlayer, DOWN);
break;
case 2:
movePlayer(map, &positionPlayer, LEFT);
break;
case 3:
movePlayer(map, &positionPlayer, RIGHT);
break;
}
當然,具有完美的分布將不會是完全隨機的(模量有點小)。
如果您想使用實際分布獲得真正的隨機性,那么您可能需要研究Boost.Random。
如果direction
是一個枚舉:
enum Direction {
UP,
DOWN,
LEFT,
RIGHT
} direction;
在C / C ++中,枚舉常量表示為整數。 第一個值UP
對應於0, DOWN
為1,依此類推。
因此,您可以致電:
movePlayer(map, &positionPlayer, static_cast<Direction>(rand() % 4));
它將使用隨機選擇的方向值調用movePlayer
。
不總是建議僅使用模運算符來縮小rand()
的范圍。 如果您需要某種具有更均勻分布的東西,則應該考慮其他方法 。
rand()不一定很好。 <random>
可能是一個更好的選擇。
C ++ 11:
#include <random>
#include <iostream>
enum Direction : char {
north, east, south, west
};
std::ostream &operator<< (std::ostream &os, Direction d) {
switch (d) {
case Direction::north : return os << "North";
case Direction::east : return os << "East";
case Direction::south : return os << "South";
case Direction::west : return os << "West";
}
}
std::uniform_int_distribution<Direction> random_direction
{Direction::north, Direction::west};
int main() {
// you can use any of several different sources of random values depending on your needs
std::mt19937 eng;
for (int i=0;i<10;++i)
std::cout << random_direction(eng) << '\n';
}
如果您不希望將方向隱式轉換為int,則可以對random_direction
使用enum class
和其他定義:
template<typename Engine>
Direction random_direction(Engine &&eng) {
std::uniform_int_distribution<> dist
{int(Direction::north),int(Direction::west)};
return Direction(dist(std::forward<Engine>(eng)));
}
更好的方法是在rand()%4之前調用srand(time(0))。 這樣可以確保每次執行程序時,都會生成不同的隨機數集。 每次執行程序時,調用不帶srand()的rand()都會生成相同的隨機數集。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.