Java

OOP GUIDE / WORK

 

GAME CLASS SOLUTIONS

 

 

TASK – PART 1 – SETUP – STUDYPRACTICE INTERFACE

 

No solution required.

 

 

TASK – PART 2 – WORK

 

Here is my code:

 

public class Game

{

     private Level levelOne;

     private Level levelTwo;

     private Level levelThree;

     private boolean isBonus;

    

     /** This constructor creates a random Game result. */

    

     public Game()

     {

           play(); 

     }

    

     /** This constructor creates a Game with provided parameters.

      *  This is required to test the getPoints results from the question.

      */   

    

     public Game(Level l1, Level l2, Level l3, boolean isBonus)

     {

           levelOne = l1;

           levelTwo = l2;

           levelThree = l3;

           this.isBonus = isBonus;

     }

    

     /** Returns true if this game is a bonus game and returns false otherwise. */

    

     public boolean isBonus()

     {

           return isBonus;

     }

    

     /** Simulates the play of this Game (consisting of three levels) and

      *  updates all relevant game data

      */

    

     public void play()

     {

           levelOne = new Level();

           levelTwo = new Level();

           levelThree = new Level();

           if (Math.random() <= 0.50)

                isBonus = true;

           else

                isBonus = false;

     }

    

     /** Returns the score earned in the most recently played game,

      *  as described in part (a)

      */

    

     public int getPoints()

     {

           int score = 0;

           if (levelOne.goalReached())

           {

                score += levelOne.getPoints();

                if (levelTwo.goalReached())

                {

                      score += levelTwo.getPoints();

                      if (levelThree.goalReached())

                           score += levelThree.getPoints();

                }

           }

           if (isBonus())

           {

                score = score * 3;

           }

           return score;

     }

    

     /** Simulates the play of num games and returns the highest

      *  score earned, as described in (b)

      *  Precondition: num > 0

      * 

      *  NOTE: Output statements can be used to help test the method.

      */

    

     public int playManyTimes(int num)

     {

           //Play first game

           play();

           int highScore = getPoints();

           //System.out.println("Game 1 score: " + getPoints());

          

           //Play other games

           for (int i=2; i<=num; i++)

           {

                play();

                //System.out.println("Game " + i + " score: " + getPoints());

                if (getPoints() > highScore)

                      highScore = getPoints();

           }

           return highScore;

     }

}

 

 

 

TASK – PART 3 – TESTING YOUR CLASS

 

No solution required.