Skip to content

Instantly share code, notes, and snippets.

@JRiggles
Last active December 21, 2023 14:03
Show Gist options
  • Save JRiggles/0b7a899d8eb1173893052d33a01ddf02 to your computer and use it in GitHub Desktop.
Save JRiggles/0b7a899d8eb1173893052d33a01ddf02 to your computer and use it in GitHub Desktop.
SMB3 LFSR
from time import time # not 100% necessary, just used to seed the RNG
def nes_lfsr(seed: int) -> int:
"""
Implementation of the Linear-Feedback Shift Register RNG used by SMB3
RNG will repeat after 32,767 (0x7FFF) iterations (the maximum 15-bit
integer value) regardless of the seed
"""
if seed <= 0:
raise ValueError('seed value must be >= 1')
MASK = 0x7FFF
rand = seed & MASK # start with the seed value, masked to 15 bits
while True:
# XOR the 0th and 8th bits
xor = ((rand >> 8) & 1) ^ (rand & 1)
# shift the value over 1 bit, insert XOR value at MSB
rand = (rand >> 1 | xor << 14) & MASK
yield rand
seed = int(time())
rng = nes_lfsr(seed)
for _ in range(0x7FFF):
print(next(rng))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment