/*
* Empire - A multi-player, client/server Internet based war game.
- * Copyright (C) 1986-2011, Dave Pare, Jeff Bailey, Thomas Ruschak,
+ * Copyright (C) 1986-2013, Dave Pare, Jeff Bailey, Thomas Ruschak,
* Ken Stevens, Steve McClure, Markus Armbruster
*
* Empire is free software: you can redistribute it and/or modify
*
* ---
*
- * chance.c: return 1 if "roll" is under the chance.
+ * chance.c: Roll dice
*
* Known contributors to this file:
- *
+ * Markus Armbruster, 2006-2012
*/
#include <config.h>
#include <math.h>
-#include "prototypes.h"
+#include <stdlib.h>
+#include "chance.h"
+#include "mt19937ar.h"
+/*
+ * Return non-zero with probability D.
+ */
int
chance(double d)
{
- return d > (random() % 32768) / 32768.0;
+ return d > genrand_real2();
+}
+
+/*
+ * Return non-zero with probability PCT%.
+ */
+int
+pct_chance(int pct)
+{
+ return roll(100) <= pct;
+}
+
+static unsigned
+round_up_to_pow2(unsigned val)
+{
+ val--;
+ val |= val >> 1;
+ val |= val >> 2;
+ val |= val >> 4;
+ val |= val >> 8;
+ val |= val >> 16;
+ val++;
+ return val;
+}
+
+/*
+ * Return a random number in [0..N-1].
+ * N must be in [1..2^31-1].
+ */
+int
+roll0(int n)
+{
+ unsigned pow2 = round_up_to_pow2(n);
+ int r;
+
+ do
+ r = genrand_int32() & (pow2 - 1);
+ while (r >= n);
+ return r;
}
+/*
+ * Return a random number in [1..N].
+ * N must be in [0..2^31-1].
+ */
int
roll(int n)
{
- return 1 + random() % n;
+ return 1 + roll0(n);
}
/*
- * round value to nearest int (on the average). E.g. rounds up
- * with a chance proportional to the size of the fractional part.
+ * Round VAL to nearest integer (on the average).
+ * VAL's fractional part is chance to round up.
*/
int
roundavg(double val)
double flr = floor(val);
return (int)(flr + chance(val - flr));
}
+
+/*
+ * Seed the pseudo-random number generator with SEED.
+ * The sequence of pseudo-random numbers is repeatable by seeding it
+ * with the same value.
+ */
+void
+seed_prng(unsigned seed)
+{
+ init_genrand(seed);
+}