Skip to content

Instantly share code, notes, and snippets.

@hikari-no-yume
Created January 12, 2015 01:59
Show Gist options
  • Save hikari-no-yume/0fe156a661f2c9ea6843 to your computer and use it in GitHub Desktop.
Save hikari-no-yume/0fe156a661f2c9ea6843 to your computer and use it in GitHub Desktop.
Lazy deterministic RNG for games
<?php
class ProceduralNumericSequenceGenerator {
private $algo, $state;
public function __construct($seed = NULL, $algo = "sha256") {
if ($seed === NULL) {
$seed = time();
}
if (array_search($algo, hash_algos()) === FALSE) {
throw new RuntimeException("Hashing algorithm \"$algo\" is not available.");
}
$this->state = $seed;
$this->algo = $algo;
}
public function getInt() {
return hexdec(substr($this->state, 0, PHP_INT_SIZE));
}
public function advance() {
$this->state = hash($this->algo, $this->state);
}
public function advanceNew() {
$new = clone $this;
$new->advance();
return $new;
}
public function advanceAndGetInt() {
$this->advance();
return $this->getInt();
}
public function advanceNewAndGetInt() {
$new = $this->advanceNew();
return [$new->getInt(), $new];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment