Many games and game systems require dice. Let's start with the simple part: throw a six-sided dice. In fact, rolling a six-sided dice means selecting a random number from 1 to 6. In PHP, this is very simple.
Simple flipper
Many games and game systems require dice. Let's start with the simple part: throw a six-sided dice. In fact, rolling a six-sided dice means selecting a random number from 1 to 6. In PHP, this is very simple:
In many cases, this is basically simple. However, when dealing with probability games, we need some better implementations.
PHP provides a better random number generator:
Without in-depth research on the differences between the two, mt_rand can be considered as a faster and better random number generator:
If the random number generator is put into the function, the effect will be better.
List1. use the mt_rand () random number generator function
Function roll (){ Return mt_rand (1, 6 ); } Echo roll (); |
Then, you can pass the dice type to be rolled to the function as a parameter.
List2. pass the dice type as a parameter
Function roll ($ sides ){ Return mt_rand (1, $ sides ); } Echo roll (6); // roll a six-sided die Echo roll (10); // roll a ten-sided die Echo roll (20); // roll a twenty-sided die |
Starting from here, we can continue to scroll multiple dice at a time as needed and return an array of results. we can also scroll multiple different types of dice at a time. However, most tasks can use this simple script.