ruby - Pick two different items randomly from an array -
in fighting program, have 2 players in array:
players = [brad, josh]
i want randomly select 2 distinct players, 1 of attack other, schematically this:
random_player.attack(other_random_player)
i want make sure players never attack themselves. if do:
players[rand(0..1)].attack(players[rand(0..1)])
there chance 1 player fight itself. how make once first player chosen , fights remaining player(s) array?
you use .sample
:
match = players.sample(2); match[0].attack(match[1]);
this randomly pick 2 players array, have them fight each other. there no way same player picked both.
more cleanly:
p1, p2 = players.sample(2) p1.attack p2
Comments
Post a Comment