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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With