Fourteen Years of Service
Posts: 721
Threads: 49
RE: rock scissors paper 11-05-2013, 02:54 AM
#29
(11-04-2013, 02:05 PM)Deque Wrote: Using Math.random() is a bad idea in general if all you need is a choice of three, which is an integer range.
Definitely, I talked with him on the IRC as well and also suggested to use a switch with that (plus you can directly check for equality with integer, instead of using range comparison).
The way I do this kind of thing myself that I find neat (not in Java though since I don't use that much) is in combination with enums, where I put some "TERMINATOR" element at the end of the enum that stays the same (the name doesn't change) and when I need to select random element from the enum, initialize array based on it or run through a loop, I can do something like this:
Code:
enum Option
{ Option0, Option1, Option2, Option3, END };
// ....
// Random.Range(int min, int max) generates between min (including) and max (excluding)
Option randomOption = (Option)Random.Range(0, (int)Option.END);
That way I can keep altering, expanding and modifying the elements in the enum as needed and the code that works with it stays the same and takes all the new elements into account, so it saves a lot of work and keeps the code nicely organized and flexible.
@BlackEagle: I recommend looking at this:
http://docs.oracle.com/javase/tutorial/j.../enum.html
Essentially you'll do something like
Code:
public enum Choice { ROCK, PAPER, SCISSORS }
And then you use "Choice" as new "datatype" instead of "string" to store the choice.
For example modify the function to pick random choice like this:
Code:
public static Choice pcChoice() {
int random = (int) Math.random()*3;
if(random == 0) return Choice.ROCK;
if(random == 1) return Choice.PAPER;
if(random == 2) return Choice.SCISSORS;
}
I love creativity and creating, I love science and rational thought, I am an open atheist and avid self-learner.
•