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