pyxen.random
生成随机数。通过 from pyxen import * 全局可用。
random.seed(42)
value = random.random() # float in [0, 1)
roll = random.randint(1, 6) # int in [1, 6]
pick = random.choice(items) # random element from sequence
方法
| 方法 | 返回值 | 描述 |
|---|---|---|
seed(n) | None | 设置随机种子以获得可复现的结果 |
random() | float | [0, 1) 范围内的随机浮点数 |
randint(a, b) | int | [a, b] 范围内的随机整数(含两端) |
choice(seq) | 元素 | 从序列中随机选取一个元素 |
seed(n)
random.seed(42)
设置随机数生成器的内部状态。使用相同的种子每次都会产生相同的数字序列。
适用于:
- 可复现的程序化生成
- 用于调试的确定性游戏行为
- 跨运行的一致关卡布局
random()
value = random.random()
返回一个介于 0(含)和 1(不含)之间的随机浮点数。
示例——任意方向的随机速度:
vx = (random.random() * 2.0) - 1.0 # range [-1, 1)
vy = (random.random() * 2.0) - 1.0
randint(a, b)
roll = random.randint(1, 6)
返回一个随机整数 N,满足 a <= N <= b。两端都包含。
示例——50% 概率:
if random.randint(0, 1) == 1:
spawn_coin()
示例——随机图块变体:
random.seed(42)
for col in range(COLS):
alt = random.randint(0, 99) <= 10 # 10% chance
tile = (1 if alt else 0, 4)
choice(seq)
color = random.choice(["red", "green", "blue"])
从非空序列(列表、元组或字符串)中返回一个随机元素。
如果序列为空,则抛出 IndexError。
示例——随机生成位置:
spawns = [(10, 20), (50, 80), (120, 40)]
x, y = random.choice(spawns)