Hi, I am new to Java and I am working through Big Java, 3rd Edition. I have also been reading Head First Java, Java docs, etc.
I am writing an exercise in Big Java coding the game of NIM. It's a turn based game where players take at least one but 1/2 or less of a pile of stones. The player picking up the last stone loses.
The exercise asks me to code three player classes. A Smart Player, a DumbPlayer, and a Human Player. There is also a class for the pile of stones and a class for the game itself. My question is the player class.
I wanted to create a tree so that I could add other types of players if I wanted. So I created an interface with one method that figures out how to determine the number of stones to take:
public interface Player {
public int takeTurn (int stones);
}
I chose an interface because I wanted every class that implements the method to have the same, well, interface. :)
Then I created my classes that implement Player and wrote the code to figure out how many stones to take, wrote a JUnit test for them and they all work. Yay.
So in my game class, I have the following:
public void playGame() {
Pile thePile = new Pile();
Random generator = new Random();
int turn = generator.nextInt(1);
HumanPlayer human = new HumanPlayer();
int computerSelect = 0;
boolean foundWinner = false;
// Select SmartPlayer or DumbPlayer
if (generator.nextInt(1) == 0){
SmartPlayer computer = new SmartPlayer();
} else {
DumbPlayer computer = new DumbPlayer();
}
while (!foundWinner) {
if (turn == 0) {
computerSelect = computer.takeTurn(thePile.getNumberOfStones());
} else {
human.takeTurn(thePile.getNumberOfStones());
}
//TODO do something here
}
}
What I want to do is that based on a random drawing, I want to instantiate a smart or dumb player class. However, when I do that, netBeans complains that the object referenced by "computer" doesn't exist.
Is there another way to do what I want?
I might try to change the Player Interface class to an Abstract class, and make takeTurn an Abstract method. Then create a Player reference, and assign SmartPlayer or DumbPlayer to that reference. But that seems akward to me but is it the right way?
Thanks.