]> git.draconx.ca Git - rrace.git/blobdiff - src/game.c
Improve RNG compatibility with old compilers.
[rrace.git] / src / game.c
index eefafe5ac40e16d93df0581a51fc23a46539202b..801625103ab9ef09ae747a8a9b3c6447f36645a7 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Slide puzzle core game logic
- * Copyright © 2022 Nick Bowler
+ * Copyright © 2022-2024 Nick Bowler
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
 #include <config.h>
 #include <limits.h>
 #include <string.h>
+#include <unistd.h>
 #include <time.h>
-#include <gethrxtime.h>
 #include "game.h"
 
-#define B64(x) ((x) & 0xffffffffffffffff)
+#define B64(x) ((x) & 0xffffffffffffffffull)
 
 /* Rotate val left by n bits.  The behaviour is undefined if n is zero. */
 static unsigned long long rot_left64(unsigned long long val, int n)
@@ -56,9 +56,9 @@ static unsigned long long splitmix64(unsigned long long *state)
 {
        unsigned long long z;
 
-       z = B64(*state += 0x9e3779b97f4a7c15);
-       z = B64((z ^ (z >> 30)) * 0xbf58476d1ce4e5b9);
-       z = B64((z ^ (z >> 27)) * 0x94d049bb133111eb);
+       z = B64(*state += 0x9e3779b97f4a7c15ull);
+       z = B64((z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull);
+       z = B64((z ^ (z >> 27)) * 0x94d049bb133111ebull);
 
        return z ^ (z >> 31);
 }
@@ -133,8 +133,19 @@ void game_reset(struct board *board)
        if (!rng_is_seeded()) {
                unsigned long long seed;
 
-               seed = time(NULL);
-               seed += gethrxtime();
+               /*
+                * Try to get a reasonable initial seed.
+                *
+                * Reasonable in this context means:
+                *
+                * - roughly even distribution of 1/0 bits, and
+                * - unlikely to generate the same seed twice in succession.
+                */
+               game_begin(board);
+
+               seed  = time(NULL);
+               seed += board->time_start;
+               seed += (unsigned long long)getpid() << 16;
                seed += seed << 32;
 
                game_reseed(seed);
@@ -241,16 +252,6 @@ uint_fast32_t game_check_goal(struct board *board)
        return mask & GOAL_MASK;
 }
 
-void game_begin(struct board *board)
-{
-       board->time_start = gethrxtime();
-}
-
-int_fast32_t game_elapsed(struct board *board)
-{
-       return (gethrxtime() - board->time_start) / 1000000;
-}
-
 int_fast32_t game_finish(struct board *board)
 {
        int_fast32_t t = game_elapsed(board);