pyxen.random
Générez des nombres aléatoires. Disponible globalement via 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
Méthodes
| Méthode | Retour | Description |
|---|---|---|
seed(n) | None | Définir la graine aléatoire pour des résultats reproductibles |
random() | float | Flottant aléatoire dans [0, 1) |
randint(a, b) | int | Entier aléatoire dans [a, b] inclus |
choice(seq) | élément | Élément aléatoire d’une séquence |
seed(n)
random.seed(42)
Définit l’état interne du générateur de nombres aléatoires. Utiliser la même graine produit la même séquence de nombres à chaque fois.
Utile pour :
- La génération procédurale reproductible
- Un comportement de jeu déterministe pour le débogage
- Des dispositions de niveaux cohérentes entre les parties
random()
value = random.random()
Renvoie un flottant aléatoire entre 0 (inclus) et 1 (exclus).
Exemple — vélocité aléatoire dans toutes les directions :
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)
Renvoie un entier aléatoire N tel que a <= N <= b. Les deux bornes sont incluses.
Exemple — 50% de chance :
if random.randint(0, 1) == 1:
spawn_coin()
Exemple — variante aléatoire de tuile :
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"])
Renvoie un élément aléatoire d’une séquence non vide (liste, tuple ou chaîne).
Lève une IndexError si la séquence est vide.
Exemple — position de spawn aléatoire :
spawns = [(10, 20), (50, 80), (120, 40)]
x, y = random.choice(spawns)