PocketMine-MP 5.21.2 git-a6534ecbbbcf369264567d27e5ed70f7f5be9816
Loading...
Searching...
No Matches
Random.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\utils;
25
26use function time;
27
32class Random{
33 public const X = 123456789;
34 public const Y = 362436069;
35 public const Z = 521288629;
36 public const W = 88675123;
37
38 private int $x;
39 private int $y;
40 private int $z;
41 private int $w;
42
43 protected int $seed;
44
48 public function __construct(int $seed = -1){
49 if($seed === -1){
50 $seed = time();
51 }
52
53 $this->setSeed($seed);
54 }
55
59 public function setSeed(int $seed) : void{
60 $this->seed = $seed;
61 $this->x = self::X ^ $seed;
62 $this->y = self::Y ^ ($seed << 17) | (($seed >> 15) & 0x7fffffff) & 0xffffffff;
63 $this->z = self::Z ^ ($seed << 31) | (($seed >> 1) & 0x7fffffff) & 0xffffffff;
64 $this->w = self::W ^ ($seed << 18) | (($seed >> 14) & 0x7fffffff) & 0xffffffff;
65 }
66
67 public function getSeed() : int{
68 return $this->seed;
69 }
70
74 public function nextInt() : int{
75 return $this->nextSignedInt() & 0x7fffffff;
76 }
77
81 public function nextSignedInt() : int{
82 $t = ($this->x ^ ($this->x << 11)) & 0xffffffff;
83
84 $this->x = $this->y;
85 $this->y = $this->z;
86 $this->z = $this->w;
87 $this->w = ($this->w ^ (($this->w >> 19) & 0x7fffffff) ^ ($t ^ (($t >> 8) & 0x7fffffff))) & 0xffffffff;
88
89 return Binary::signInt($this->w);
90 }
91
95 public function nextFloat() : float{
96 return $this->nextInt() / 0x7fffffff;
97 }
98
102 public function nextSignedFloat() : float{
103 return $this->nextSignedInt() / 0x7fffffff;
104 }
105
109 public function nextBoolean() : bool{
110 return ($this->nextSignedInt() & 0x01) === 0;
111 }
112
119 public function nextRange(int $start = 0, int $end = 0x7fffffff) : int{
120 return $start + ($this->nextInt() % ($end + 1 - $start));
121 }
122
123 public function nextBoundedInt(int $bound) : int{
124 return $this->nextInt() % $bound;
125 }
126}
nextRange(int $start=0, int $end=0x7fffffff)
Definition Random.php:119
__construct(int $seed=-1)
Definition Random.php:48