Good day!
With regards to my previous post, to adapt to the concept of MVC as suggested, I changed my code and included an IO class as follows:
public class IO {
public void output(String msg) {
JOptionPane.showMessageDialog(null, msg);
}
public String input(String prompt) {
return JOptionPane.showInputDialog(prompt);
}
public int inputInt(String prompt) {
return Integer.parseInt(input(prompt));
}
}
public class GuessGame {
private int numberToGuess;
private ArrayList<Player> player;
private IO io = new IO ();
public void acceptPlayers(){
int num_players = io.inputInt("Enter number of players");
player = new ArrayList<Player>(num_players);
for (int i = 0; i < num_players; i++) {
player.add(new Player(io.input("Enter Player " + (i+1) + " Name: ")));
}
}
public void startGame() {
numberToGuess = (int) (Math.random() * 10);
while (true) {
for (Player curPlayer : player) {
if (curPlayer.guessNumber() == numberToGuess) {
declareWinner(curPlayer);
return;
}
io.output(curPlayer.getPlayerName() + "'s Guess is Wrong!");
}
}
}
private void declareWinner(Player player) {
io.output(player.getPlayerName() + " Wins!");
}
}
Is this correct? How can I improve my code? Thank you.
IO class rappresent your View in MVC model.
GuessGame class have to much responsability, this class is for you both the model and the controller, you have to split it.
You can create a Game class wich have as status numberToGuess and ArrayList player;
and for method addPlayer() and start()
Than you can have a class GameControlled that have for status IO class and a Game class.
and for method acceptPlayers(),*startGame()*,declareWinner(Player player).