Skip to content

Commit

Permalink
Changed random number generator to be reliable cross-platform.
Browse files Browse the repository at this point in the history
(I hope.)

Reference Issue #23.
  • Loading branch information
icculus committed Aug 14, 2023
1 parent 74d3e36 commit a51ed7a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 17 deletions.
28 changes: 15 additions & 13 deletions mojozork.c
Expand Up @@ -16,12 +16,6 @@
#include <stdint.h>
#include <time.h>

// oh well.
#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__) || defined(_WIN32)
#define random rand
#define srandom srand
#endif

#define MOJOZORK_DEBUGGING 0

static inline void dbg(const char *fmt, ...)
Expand Down Expand Up @@ -1139,19 +1133,27 @@ static void opcode_print_paddr(void)
print_zscii(unpackAddress(GState->operands[0]), 0);
} // opcode_print_paddr


static int random_seed = 0;
static int randomNumber(void)
{
// this is POSIX.1-2001's potentially bad suggestion, but we're not exactly doing cryptography here.
random_seed = random_seed * 1103515245 + 12345;
return (int) ((unsigned int) (random_seed / 65536) % 32768);
}

static uint16 doRandom(const sint16 range)
{
uint16 result = 0;
if (range == 0) // reseed in "most random way"
srandom((unsigned long) time(NULL));
random_seed = (int) time(NULL);
else if (range < 0) // reseed with specific value
srandom(-range);
random_seed = -range;
else
{
FIXME("this is sucky");
long r = random();
r = (r >> (sizeof (r) / 2) * 8) ^ r;
result = (uint16) ((((float) (r & 0xFFFF)) / 65535.0f) * ((float) range));
const uint16 lo = 1;
const uint16 hi = (uint16) range;
result = (((uint16) randomNumber()) % ((hi + 1) - lo)) + lo;
if (!result)
result = 1;
} // else
Expand Down Expand Up @@ -2137,7 +2139,7 @@ int main(int argc, char **argv)
GState->die = die;
GState->writestr = writestr_stdio;

srandom((unsigned long) time(NULL));
random_seed = (int) time(NULL);

loadStory(fname);

Expand Down
5 changes: 1 addition & 4 deletions zork1-script.txt
@@ -1,4 +1,4 @@
#random -2345
#random -2
open mailbox
read leaflet
drop leaflet
Expand Down Expand Up @@ -315,9 +315,6 @@ kill thief with sword
kill thief with sword
kill thief with sword
kill thief with sword
kill thief with sword
kill thief with sword
kill thief with sword
take all
drop stiletto
take chalice
Expand Down

0 comments on commit a51ed7a

Please sign in to comment.