Created
January 12, 2015 01:59
-
-
Save hikari-no-yume/0fe156a661f2c9ea6843 to your computer and use it in GitHub Desktop.
Lazy deterministic RNG for games
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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