Reputation: 35
I am a beginner in Java and for some practise, I am creating a text based noughts and crosses. What I have so far is a Player class, a Board class and a Game class. In the Game class, I have one instance of Board and two instances of Player. I have managed to write code for a player to make a move and to determine whether the game is a win or draw. I now want to ensure that a player can only have one move at a time and not more than one consecutive move i.e Player A, Player B, Player A, Player B...... rather than Player A, Player A, Player A...
The way I thought of doing this was to create a boolean field in the Player class of myTurn and have a method along these lines :
public boolean isMyTurn (){
if (myTurn == true){
return false;
}
return true;
}
I then invoke this method in the game glass before I make a move, but for some reason it doesn't work. Maybe I've made a mistake somewhere but if anyone has any other ways/ideas I could write some code to determine if a payers turn is valid or not, please let me know. Would appreciate if you could provide some examples too as I'm still a beginner.
Upvotes: 0
Views: 977
Reputation: 1117
maybe I didn't understand well your problem, but:
Seems like this should be done by the same guy (a Game/GameManager class?). So why don't players just play given a description of the game, and you let the task of managing turns to another class?
Cheers
Upvotes: 0
Reputation: 93040
I would make the Game class responsible for that. E.g.:
class Game {
...
public void makeTurn(){
if(isFirst)
firstPlayer.makeTurn();
else
secondPlayer.makeTurn();
isFirst = !isFirst;
}
private bool isFirst = true;
private Player firstPlayer, secondPlayer;
}
It even makes sense logically. The player can make many moves one after the other. It's the game (the rules of the game) that prevents him from doing that.
Upvotes: 3