Randomness

From Terranigma Wiki
Jump to navigation Jump to search

The randomness is at 0x7E0408 and is 16 bytes. It is set to all zero on reset of the game.

Randomness Advancements

  • Ark idle animation
  • Ark gets hit
  • Enemy gets hit
  • Enemy logic calls the random function
  • NPC randomly walks around
  • Sprite animations

Manipulations

Since on reset the randomness has a known starting point and a predicable continuation of the values, it is possible in certain cases to manipulate it.

  • Ghost fight
  • Dragoon Castle guard pattern
  • Dark Gaia
  • Quintet Quiz

Code

Note: This is simply translated from the assembler code

typedef unsigned char u8;
typedef unsigned char u16;

u8 seed[16];

void random( u8 *seed )
{
	u8 x = 0xF;
	u8 a = 0;
	u8 b = 0;
	u8 c = 0;

loc_C68242:
	a = seed[x];

	u8 r = 0;

	if( a + c + seed[x-1] > 0xFF )
		r = 1;
	else
		r = 0;

	a += c + seed[x-1];

	c = r;

	seed[x-1] = a;
	x = x - 1;
	if( x > 0 )
		goto loc_C68242;

	x = 0x10;

loc_C68251: 
	if( seed[x-1] + 1 > 0xFF )
		r = 1;
	else
		r = 0;

	seed[x-1] += 1;
	if(r==0)
		goto loc_C68259;

	x = x - 1;
	if( x > 0 )
		goto loc_C68251;

loc_C68259:
;
}

example implementation in python3

#!/usr/bin/env python3
state = [0] * 16

def rng():
    carry = 0
    for i in range(15,0,-1):
        carry, state[i-1] = divmod(carry + state[i-1] + state[i], 256)

    for i in range(15,-1,-1):
        state[i] = (state[i] + 1) % 256
        if state[i] != 0:
            break
    return state[0]

for _ in range(20):
    print(hex(rng()))