I'm new to Java and find it hard to grasp the concept of objects. I wrote a simple guessing game to practice the concept of OO programming but I am not sure if I am doing it correctly.
The objective of the game is to guess a number from 0-9 with 3 players and the first player who guesses it correctly will win the game.
Player
public class Player {
private String playerName;
private int number;
public int getNumber() {
return number;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public void guessNumber(){
number = Integer.parseInt(JOptionPane.showInputDialog(playerName
+ "'s Turn\nGuess the Number"));
JOptionPane.showMessageDialog(null, playerName+ "'s GUESS is " + number);
}
}
GuessGame
public class GuessGame {
private int numberToGuess;
private Player p1;
private Player p2;
private Player p3;
public void startGame(){
numberToGuess = (int) (Math.random()*10);
p1 = new Player();
p2 = new Player();
p3 = new Player();
p1.setPlayerName(JOptionPane.showInputDialog("Enter Player 1 Name: "));
p2.setPlayerName(JOptionPane.showInputDialog("Enter Player 2 Name: "));
p3.setPlayerName(JOptionPane.showInputDialog("Enter Player 3 Name: "));
int flagWinner = 0;
while(0==flagWinner){
p1.guessNumber();
if (p1.getNumber()==numberToGuess){
flagWinner = 1;
break;
}
JOptionPane.showMessageDialog(null, p1.getPlayerName()
+ "'s Guess is Wrong!");
p2.guessNumber();
if (p2.getNumber()==numberToGuess){
flagWinner = 2;
break;
}
JOptionPane.showMessageDialog(null, p2.getPlayerName()
+ "'s Guess is Wrong!");
p3.guessNumber();
if (p3.getNumber()==numberToGuess){
flagWinner = 3;
break;
}
JOptionPane.showMessageDialog(null, p3.getPlayerName()
+ "'s Guess is Wrong!");
}
if (1 == flagWinner){
JOptionPane.showMessageDialog(null,p1.getPlayerName()+ " Wins!");
} else if (2 == flagWinner){
JOptionPane.showMessageDialog(null,p2.getPlayerName()+ " Wins!");
} else JOptionPane.showMessageDialog(null,p3.getPlayerName()+ " Wins!");
}
}
And I have a gameLauncher
where I have the main()
method which creates the game.
Am I doing it correctly especially in the Player
class where I created a method guessNumber()
instead of setter setNumber(int number)
?
Am I violating any object-oriented concepts in my code?
How can I improve my code?