summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/gates.rs8
-rw-r--r--src/main.rs3
-rw-r--r--src/rand.rs47
3 files changed, 54 insertions, 4 deletions
diff --git a/src/gates.rs b/src/gates.rs
index ebc2b69..1e3630f 100644
--- a/src/gates.rs
+++ b/src/gates.rs
@@ -1,4 +1,5 @@
use super::constants;
+use super::rand;
use super::state;
pub struct Gates {
@@ -57,8 +58,8 @@ impl state::Positioned for Gates {
fn random_position() -> (f64, f64) {
(
- rand::random::<f64>() * (constants::X_DIM - 200) as f64 + 100.,
- rand::random::<f64>() * 100.,
+ rand::random() * (constants::X_DIM - 200) as f64 + 100.,
+ rand::random() * 100.,
)
}
@@ -85,8 +86,7 @@ impl state::StraightBullet for GatesBullet {
fn random_bullet<T: state::Enemy<GatesBullet>>(enemy: &T) -> GatesBullet {
let multiplier = 2. + 3. * (1. - enemy.health());
- let theta: f64 =
- rand::random::<f64>() * 2. * std::f64::consts::PI / 3. + std::f64::consts::PI / 6.;
+ let theta: f64 = rand::random() * 2. * std::f64::consts::PI / 3. + std::f64::consts::PI / 6.;
let dx = f64::cos(theta) * multiplier;
let dy = f64::sin(theta) * multiplier;
GatesBullet::new(enemy.x(), dx, enemy.y(), dy)
diff --git a/src/main.rs b/src/main.rs
index 59913c0..25a4f3b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,6 +1,7 @@
mod constants;
mod gates;
mod player;
+mod rand;
mod state;
use state::Bullet;
@@ -221,6 +222,8 @@ fn victory(
}
fn main() {
+ rand::seed().expect("failed to seed random generator");
+
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
diff --git a/src/rand.rs b/src/rand.rs
new file mode 100644
index 0000000..404e115
--- /dev/null
+++ b/src/rand.rs
@@ -0,0 +1,47 @@
+use std::fs::File;
+use std::io::Read;
+use std::sync::Mutex;
+use std::time::SystemTime;
+
+static STATE: Mutex<u64> = Mutex::new(0);
+
+fn seed_urandom() -> Option<()> {
+ let mut f = File::open("/dev/urandom").ok()?;
+ let mut bytes = [0; 8];
+ f.read_exact(&mut bytes).ok()?;
+
+ *STATE.lock().unwrap() = u64::from_ne_bytes(bytes);
+ return Some(());
+}
+
+fn seed_time() -> Option<()> {
+ let n = SystemTime::now()
+ .duration_since(SystemTime::UNIX_EPOCH)
+ .ok()?;
+
+ *STATE.lock().unwrap() = n.as_nanos() as u64;
+ return Some(());
+}
+
+pub fn seed() -> Option<()> {
+ match seed_urandom() {
+ Some(()) => return Some(()),
+ None => (),
+ }
+ match seed_time() {
+ Some(()) => return Some(()),
+ None => (),
+ }
+ return None;
+}
+
+fn mix(s: &mut u64) {
+ // https://en.wikipedia.org/wiki/Linear_congruential_generator
+ *s = s.wrapping_mul(6364136223846793005).wrapping_add(1);
+}
+
+pub fn random() -> f64 {
+ let mut s = STATE.lock().unwrap();
+ mix(&mut s);
+ return (*s >> 32) as f64 / 4294967296.;
+}