随机的#

介绍#

Random provides access to Python’s urandom module, which is available by default in VEXcode V5. These methods let you generate random numbers, floats, and values from lists or ranges—useful for adding unpredictability to games, behaviors, and autonomous decision-making.

以下是可用方法列表:

  • randint – Returns a random integer between two values (inclusive).

  • uniform – Returns a random float between two values.

  • randrange – Returns a random integer from a range with an optional step.

  • seed – sets the starting value for urandom’s pseudo-random number generator.

随机变量#

randint returns a random integer between two values (inclusive), where both values are integers.

Usage:
urandom.randint(a, b)

范围

描述

a

表示范围下限的整数。

b

表示范围上限的整数。

# Generate a random integer between
# 1 and 10 (inclusive)
urandom_int = urandom.randint(1, 10)
brain.screen.print(urandom_int)

# urandom_int = (random integer between 1 and 10)

制服#

uniform returns a random float between two values, where both values are floats or integers.

Usage:
urandom.uniform(start, end)

范围

描述

start

表示范围下限的浮点数或整数。

end

表示范围上限的浮点数或整数。

# Generate a random float 
# between 5.0 and 10.0
urandom_uniform = urandom.uniform(5.0, 10.0)
brain.screen.print(urandom_uniform)

# urandom_uniform = (random float 
# between 5.0 and 10.0)

随机范围#

randrange returns a random integer from a range with an optional step, where both the start and stop values are integers.

Usage:
urandom.randrange(start, stop, step)

范围

描述

start

可选。表示范围起始值的整数。默认值为 0。

stop

表示范围的最后一个值(不包括最后一个值)的整数。

step

可选参数。一个整数,表示范围内每个数字之间的差值。默认值为 1。

# Generate a random integer from
# 0 to 9 (exclusive of 10)
urandom_range = urandom.randrange(10)
brain.screen.print(urandom_range)

# urandom_range = (random integer from 0 to 9)

# Generate a random integer from
# 5 to 15 (exclusive of 15)
urandom_range = urandom.randrange(5, 15)
brain.screen.print(urandom_range)

# urandom_range = (random integer from 5 to 14)

# Generate a random integer from
# 10 to 50, stepping by 5
urandom_range = urandom.randrange(10, 50, 5)
brain.screen.print(urandom_range)

# urandom_range = (random multiple of 5 between 10 and 45)

种子#

seed sets the starting value for urandom’s pseudo-random number generator.

如果不设置种子,你的项目每次启动时都可能生成相同的随机序列。

为了在每次运行中获得不同的结果,请在项目开始时设置一次种子,使用在运行之间会改变的值,例如电池读数、计时器值或两者的组合。

Usage:
urandom.seed(seed)

范围

描述

seed

用于启动伪随机序列的整数。

# Set a different seed each time the project starts
urandom.seed(int(brain.battery.current()))