This is a sample exercise tutorial that would be used to test understanding of how simple classes communicate/message and are designed.
Tester class
public class GuessingGameTester {
public static void main(String[] args){
//create a new game
GuessingGame g1 = new GuessingGame();
//call the start method
g1.startGame();
}
}
Player class
public class GuessingGamePlayer {
boolean areTheyRight = false;
//player random guess
int getPlayerGuess(){
return (int) (Math.random()* 20);
}
}
Game class
public class GuessingGame {
private int numberToGuess;
private boolean keepPlaying;
private int round;
//constructor
GuessingGame(){
//create a random number for players to guess
numberToGuess = (int) (Math.random() * 20);//cast to int
keepPlaying = true;
round = 1;
}
void startGame(){
//create 3 players to play
GuessingGamePlayer p1 = new GuessingGamePlayer();
GuessingGamePlayer p2 = new GuessingGamePlayer();
GuessingGamePlayer p3 = new GuessingGamePlayer();
System.out.println("The number to guess is : " + numberToGuess);
//giving 100 attemps for the computer to guess the correct number
while(keepPlaying && round <= 100){
//get their guess
int p1guess = p1.getPlayerGuess();
int p2guess = p2.getPlayerGuess();
int p3guess = p3.getPlayerGuess();
System.out.println("round " + round);
System.out.println("p1 guessed: " + p1guess);
System.out.println("p2 guessed: " + p2guess);
System.out.println("p3 guessed: " + p3guess);
System.out.println("\n");
if(p1guess == numberToGuess){
p1.areTheyRight = true;
keepPlaying = false;
}else if(p2guess == numberToGuess){
p2.areTheyRight = true;
keepPlaying = false;
}else if(p3guess == numberToGuess){
p3.areTheyRight = true;
keepPlaying = false;
}
round ++;
}//end while
//game over - echo who guessed the correct num and the round
System.out.println("\n");
if(p1.areTheyRight){
System.out.println("p1 guessed the correct number during round " + round);
}else if(p2.areTheyRight){
System.out.println("p2 guessed the correct number during round " + round);
}else{
System.out.println("p3 guessed the correct number during round " + round);
}
}//end startGame
}