Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get a random value from 3 different enums

Tags:

java

enums

random

I am implementing a simple version of the Cluedo game. There are 3 types of cards in the game, Character, Weapon and Room. Since one card is nothing more than a String (i.e no functionality or information other than the name is stored in a card), I chose not to have a Card interface and each type extends Card. Rather I had three enums in my game which are:

public enum Character {Scarlett, Mustard, White, Green, Peacock, Plum;}
public enum Weapon {Candlestick, Dagger, LeadPipe, Revolver, Rope, Spanner;}
public enum Room {Kitchen, Ballroom, Conservatory, BilliardRoom, Library, Study, Hall;}

However there is one case where three types of cards are put together and dealt evenly to each player of the game. For example, one player may have a hand of 2 Characters, 2 Weapons and 1 Room, another player may have 3 Rooms and 2 Characters, so long the total number of cards are even it doesn't matter what type that is.

And that's why I wonder if there is a way to randomly choose one single value from all three enums in Java?

Or I shouldn't do this three enums thing in the first place? (Badly designed)

like image 901
Shenbo Avatar asked Jul 26 '15 10:07

Shenbo


2 Answers

A simple way is to collect all the enum members into a single Object[], then take a random element from it.

Note that an enum can also implement an interface, so you can even have some shared API across all the enums. Typically you'll find yourself writing a lot of switch statements on the value of the enum; those can mostly be replaced by dynamic dispatch against such interface methods. Further note that each enum member can provide its own method implementation.

like image 133
Marko Topolnik Avatar answered Sep 24 '22 05:09

Marko Topolnik


I think you should keep it like it is, but then put them all in the same list:

List<Enum> enums = new ArrayList<>();
enums.addAll(Arrays.asList(Character.values()));
enums.addAll(Arrays.asList(Weapon.values()));
enums.addAll(Arrays.asList(Room.values()));

And then you take random values of that list. More closely resembles what you do in real life.

like image 22
Oskar Kjellin Avatar answered Sep 23 '22 05:09

Oskar Kjellin