Minecraft – What sources of randomness can be made with commands in Minecraft

minecraft-commandsminecraft-java-edition

I want to make a mini game in Minecraft were I need a random command generator for 9 commands. I need a random command to give the player a random item.

I can't do the command block in the dispenser any more because it will just drop out instead of being placed.

What different ways are there for generating randomness in commands, and which one would be best for my use?

This question is similar to the one about randomness in Redstone circuits, but I am specifically attempting to get randomness when using commands – the redstone solutions do not apply here.

Best Answer

Running score method: Primitive, simple, but not as good as others

Min Max
-2147483648 2147483647

Details

The simplest solution is not to use an actual random generator at all, because it's not really needed. The randomness can come from a user input instead.

What I mean by that is that you can have a rapidly changing scoreboard objective, and evaluate the score at the moment a button is pressed.

First set up your randomness objective using

scoreboard objectives add RNG dummy

There used to be a stat.playOneMinute which would automatically increase it by 1 every single game tick without another command needed, and it will not be the same for every player (if that is not desired, resetting it for everyone works). However, because updates have removed this statistic, we would need to implement our own commands to increase it by one tick.

1.13+ : scoreboard players add @a[scores={RNG=9..}] RNG 1
1.12- : scoreboard players add @a[score_RNG_min=9] RNG 1

Now create a fill/setblock clock and have it run

1.13+ : scoreboard players set @a[scores={RNG=9..}] RNG 0
1.12- : scoreboard players set @a[score_RNG_min=9] RNG 0

and you're done. To use your random numbers, make one command block for every single outcome and include [score_RNG=X,score_RNG_min=X] with your target selector arguments, where X is the score to use, running from 0 to 8(!). Trigger all of these at the same time. For example

...
/give @a[score_RNG=4,score_RNG_min=4,team=PlayingTheGame] diamond_sword 
/give @a[score_RNG=5,score_RNG_min=5,team=PlayingTheGame] dirt
...

If your command does not use a target selector argument, you can (ab)use execute for that, e.g.

/execute @a[score_RNG=4,score_RNG_min=4] ~ ~ ~ setblock 1 2 3 stone

Nowadays in 1.13+, it is advised not to use this as there are much better alternatives and it requires a running function. This is however the most easy way to generate random numbers.