Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

import java.util.ArrayList; import java.util.Collections; import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; import cmps251.homework3.Board; import cmps251.homework3.Game; import cmps251.homework3.Player; /** * DO NOT MODIFY THIS CODE * */

image text in transcribed
image text in transcribed
image text in transcribed
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
import cmps251.homework3.Board;
import cmps251.homework3.Game;
import cmps251.homework3.Player;
/**
* DO NOT MODIFY THIS CODE
*
*/
public class Runner {
public static void main(String[] args) {
Runner r = new Runner();
r.studentRunner();
}
private void studentRunner()
{
Scanner s = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = s.nextLine();
System.out.print("Enter your age: ");
int age = s.nextInt();
s.nextLine(); //clear buffer
Player player = new Player(name, age);
ArrayList list = new ArrayList();
for (int i = 0; i
list.add(new Integer(i));
Collections.shuffle(list, new Random(System.currentTimeMillis()));
int[] rabbitPositions = {pickIndexAtRandom(list), pickIndexAtRandom(list), pickIndexAtRandom(list)};
ArrayList gluePositionsArray = new ArrayList();
ArrayList thornPositionsArray = new ArrayList();
Random a = new Random(System.currentTimeMillis());
for (int i = 0; i
if(a.nextInt(2) == 1) //flip a coin (50/50 chance) for either a Thorn or a Glue
gluePositionsArray.add(pickIndexAtRandom(list));
else thornPositionsArray.add(pickIndexAtRandom(list));
}
Game myGame = new Game(rabbitPositions, //rabbit positions
gluePositionsArray, //glue positions
thornPositionsArray, //thorn positions
pickIndexAtRandom(list), //bull position
player); //player
myGame.printStartingGreeting();
int userInput;
int thorneNum = myGame.getBoard().getNumberOfThorns();
while (!myGame.getIsGameOver())
{
userInput = -1;
System.out.println("Current Play No: " + (myGame.getPlayCount()+1));
System.out.println("Number of rabbits caught so far: " + myGame.getRabbitsCaught());
System.out.println("Number of thornes: " + thorneNum);
System.out.println("Number of glues: " + (Game.MAX_PUNISHABLES-thorneNum) +" ");
myGame.getBoard().displayBoard();
System.out.print("Please select a position ('1'-'16'): ");
while(userInput == -1)
{
try{
userInput = s.nextInt(); //a trick to find the first character of the entered string
if (userInput 16) {
System.out.print("Not a correct input, please try again: ");
userInput = -1;
userInput = s.nextInt();
}
}catch(InputMismatchException e)
{
System.out.println("Illegal input, please try again: ");
s.next(); // clears the buffer
}
}
myGame.nextPlay(userInput);
System.out.println(" ");
}
System.out.println(" FINAL BOARD:");
myGame.getBoard().displayBoard();
System.out.println("You found all rabbits!");
System.out.println("It took you: " + myGame.getPlayCount() + " turns. Not bad for a " + myGame.getPlayer().getAge() + " year old!");
s.close();
}
private int pickIndexAtRandom(ArrayList list)
{
int out = list.get(0);
list.remove(0);
return out;
}
}
package cmps251.homework3;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import cmps251.homework3.interfaces.ResetBoard;
import cmps251.homework3.spacetypes.BullSpace;
import cmps251.homework3.spacetypes.EmptySpace;
import cmps251.homework3.spacetypes.GlueSpace;
import cmps251.homework3.spacetypes.RabbitSpace;
import cmps251.homework3.spacetypes.Space;
import cmps251.homework3.spacetypes.ThornSpace;
public class Board implements ResetBoard {
public static final int NUM_SPACES = 16;
private ArrayList mSpaces;
private Game mGame;
/**
* This constructor should initiate the state of the board with 16 different spaces
* Spaces could be RabbitSpace, BullSpace, EmptySpace, ThornSpace, or GlueSpace.
* To determine which spaces have rabbits, you should
* see the elements of the @param rabbitsPositions. So if rabbitPositions = {3, 5, 7},
* then space[3], space[5] and space[7] have rabbits in them!
*
* @param rabbitPositions an array of 3 integers with positions of the rabbits as indexes
* @param gluePositions an ArrayList of integers with positions of the glue positions as indexes (if any)
* @param thornPositions an ArrayList of integers with positions of the thorn positions as indexes (if any)
* @param bullPosition the position of the bull in the board
* @param game reference to the game object that called this constructor
*/
//TODO 10 fill in the missing parts of the constructor below
public Board(int rabbitPositions[],
ArrayList gluePositions,
ArrayList thornPositions,
int bullPosition,
Game game)
{
mSpaces = new ArrayList();
mGame = game;
//TODO 10a add to mSpaces ArrayList with 16 empty spaces (hint: use a for-loop)
//TODO 10b place the bull into the array list (hint use the ArrayList set method)
//Hint, BullSpace needs a "ResetBoard" object, this Board class implements it so you can pass "this"
//TODO 10c add the Punishable items (replace empty spaces with their corresponding Punishable)
//You may use two separate for loops. One for each positions array (thorns/glues)
//TODO 10d add the rabbits (replace empty spaces with their corresponding RabbitSpaces)
//Hint, Rabbit expects "Reset" object. Game implements Reset so you can pass the game.
}
/**
* This method prints out the board with numbers 1-16 initially
* in a 4x4 matrix.
* Once users select a number, that particular space is selected.
*
*/
public void displayBoard()
{
int sizeOfRowOrColumn = (int)Math.sqrt(mSpaces.size());
for (int i=0; i
for (int j=0; j
System.out.printf("%-7s", mSpaces.get((i*sizeOfRowOrColumn)+j).getAsString());
}
System.out.println(" ");
}
System.out.println(" ");
}
/**
* This method returns true if a rabbit exists at position "i"
* hint: use the method isRabbit inside Space.
* @param i index of space to check whether it has a rabbit or not
* @return returns true if a rabbit exists, false otherwise
*/
//TODO 05 implement the method below
public boolean getIsRabbit(int i)
{
return false; //FIXME
}
/**
* This method returns true if the space at i is revealed
*
* @param i index of space to check
* @return true if revealed, false otherwise
*
*/
public boolean isRevealed(int i)
{
return mSpaces.get(i).isRevealed();
}
/**
* Clicks on a space
* @param i the position that was selected or "clicked"
*/
public void clickSpace(int i) {
mSpaces.get(i).onClick();
}
/**
* Do not use this method in your code! You don't need it
*
* @return the array of spaces that this board has
*/
public ArrayList getSpaces() {
return mSpaces;
}
/**
* (BONUS) When the user encounters a bull, the user is knocked off and the
* rabbits run away. As such, the user must now look for the rabbits in the empty
* places again! This also means that all Empty and Rabbit spaces are reset to not revealed
*
* Keep in mind that this method is called from BullSpace's onClick().
*
* This method resets the board once a bull is encountered by the user.
* To reset the board successfully it does the following:
*
* 1- Get 3 new random rabbit positions (use getNewRabbitPositions() ).
* 2- Go over all spaces and do the following:
* a- If the space is either an EmptySpace or a RabbitSpace, then replace the space in that position
* with either a new Rabbit space, or a new Empty space depending on whether a rabbit has moved
* to this space (use the array from point 1). You can also use method "isPositionARabbit(int i)"
* below to help.
* b- If the space is anything else, leave it the way it is; this means
* that nothing changes for Bull, Thorn, and Glue spaces.
* 3- Number of caught rabbits in the game should be reset to 0 (they ran away!)
*
* At the moment, nothing is happening! It just adds more punishing points to the Game's turns
*/
//TODO 13 BONUS: implement the body of the method bullEncountered below.
@Override
public void bullEncountered()
{
Board.bullCalled = true; //DO NOT REMOVE THIS LINE!
//FIXME - type your code below this line for the bonus!
}
/**
* This method returns the number of thorns that exist in the board's spaces
*
* @return number of thorn spaces in this board
*/
//TODO 09 write the body of the function below such that it returns the number of ThornSpaces inside the Board.
public int getNumberOfThorns()
{
return 0; //FIXME
}
/**
* Simple method to check whether "position" exists in "rabbitPositions" or not.
* You can use this method to check whether one of the rabbits chose to hide in
* a given "new" position.
*
* @param position the index you are searching for
* @param rabbitPositions all the positions you are searching in
* @return true if position exists in rabbitPositions, false otherwise
*/
//TODO 06 complete this method based on the javadoc description above
protected boolean isPositionARabbit(int position, int[] rabbitPositions) {
return false; //FIXME
}
//DO NOT MODIFY ANYTHING BELOW THIS LINE
public int[] getNewRabbitPositions()
{
int [] newRabbitPositions = new int[Game.MAX_RABBITS];
ArrayList list = new ArrayList();
for (int i = 0; i
{
Space currentSpace = mSpaces.get(i);
if (currentSpace instanceof RabbitSpace ||
currentSpace instanceof EmptySpace)
list.add(mSpaces.get(i).getIndex());
}
Collections.shuffle(list, new Random(System.currentTimeMillis()));
for (int i = 0; i
newRabbitPositions[i] = list.get(i);
return newRabbitPositions;
}
public static boolean bullCalled = false; //do not remove
}
package cmps251.homework3;
import java.util.ArrayList;
import cmps251.homework3.interfaces.Punishable;
import cmps251.homework3.interfaces.Score;
/**
* Top level class. This class keeps track of the score and status of the game so far
* It is also responsible to advance the game by implementing "nextPlay"
*
*/
//TODO 08 Implement both Punishable and Score in this class. Read the JavaDoc of the
//two interfaces to understand what to do in the method bodies exactly
public class Game {
public static final int MAX_RABBITS = 3;
public static final int MAX_PUNISHABLES = 3;
private int mRabbitsCaught = 0;
private boolean isGameOver; // true if game is over
private Board mBoard;
private Player mPlayer;
private int mPlayCount;
/**
*
* This constructor sets initial state of the game it has (board game)
*
* You should initialize all your instance variables here
*
* @param rabbitPositions an array of 3 integers that have the locations of the rabbits
* @param gluePositions an ArrayList of glue positions (if any)
* @param thornPositions an ArrayList of thorn positions (if any)
* @param bullPosition the position of the bull in the board
* @param player player to add
*/
public Game(int[] rabbitPositions,
ArrayList gluePositions,
ArrayList thornPositions,
int bullPosition,
Player player)
{
isGameOver = false;
this.mPlayer = player;
mRabbitsCaught = 0;
mPlayCount = 0;
mBoard = new Board(rabbitPositions, gluePositions, thornPositions, bullPosition, this);
}
/**
* This method prints "Hello ! Your game is starting... "
*/
public void printStartingGreeting() {
System.out.println("Hello " + mPlayer.getName() +"! ");
System.out.println("Your game is starting... ");
}
/**
* Method returns whether game is over or not (when all rabbits are revealed)
*
* @return true if game ended, false otherwise
*/
public boolean getIsGameOver()
{
return isGameOver;
}
/**
* This method advances to the next stage (turn) of the game
* It takes a number which the user selected from the board
* and updates the status of the board spaces so that this place
* on the board is clicked.
* Once all rabbits are found, it sets the game ended boolean to
* true because all rabbits are found!
*
*
* @param index the number on the board that the user selected
*/
public void nextPlay(int index)
{
index--;
if (mBoard.isRevealed(index)) //if we are already revealed.. do nothing
return;
else {
mBoard.clickSpace(index);
}
mPlayCount++;
if (mRabbitsCaught == MAX_RABBITS)
isGameOver = true;
}
/**
* Get how many turns are played so far?
*
* @return the number of times the user selected a character so far.
*/
public int getPlayCount()
{
return mPlayCount;
}
/**
* @return the Board that this game has
*/
public Board getBoard() {
return mBoard;
}
/**
* @return the Player that this game has
*/
public Player getPlayer() {
return mPlayer;
}
/**
*
* @return the number of rabbits caught so far.
*/
public int getRabbitsCaught()
{
return mRabbitsCaught;
}
}
package cmps251.homework3;
/**
* Player information class.
* A player has name and age which gets set in the constructor
*/
public class Player {
private String name;
private int age;
/**
* Constructor sets the name and age
* @param name
* @param age
*/
public Player(String name, int age)
{
this.name = name;
this.age = age;
}
/**
* Method to get name
* @return the name of the player as string
*/
public String getName()
{
return name;
}
/**
* Method to get age
* @return the age of the player as an int
*/
public int getAge()
{
return age;
}
}
package cmps251.homework3.interfaces;
public interface Clickable {
/**
* Method to process clicking on the item
*/
public void onClick();
}
package cmps251.homework3.interfaces;
public interface Punishable {
public final int PUNISHMENT_THORN = 3;
public final int PUNISHMENT_GLUE = 5;
/**
* This methods add to the play count of the game
* (the more, the worse). Implement this in Game.
*
* @param numberOfSteps number of plays to add to the total game play
*/
public void punish(int numberOfSteps);
}
package cmps251.homework3.interfaces;
public interface ResetBoard {
/**
* This method should be called when a bull is revealed!
*
* All rabbits are knocked out. Implement it in Board class
*
*/
public void bullEncountered();
}
package cmps251.homework3.interfaces;
public interface Score {
/**
* Increases the total rabbits caught by one
*/
public void increaseRabbitsCaught();
/**
* Resets the number of rabbits caught back to 0
*/
public void resetRabbitsCaught();
}
package cmps251.homework3.spacetypes;
import cmps251.homework3.interfaces.ResetBoard;
/**
* The BullSpace represents a bull. When uncovered, it should reset
* the game by making all rabbits escape and hide in new places by calling bullEncountered()
* in the ResetBoard. Hint: you will use your work from todo XX here.
*
* BullSpace is displayed as "B" when it is revealed (uncovered).
*
*
*/
//TODO 04 Fix the errors. This class is not implementing all the abstract
//methods from the superclass! Read above for hint on what your new method
//bodies should contain
public class BullSpace extends Space {
private ResetBoard mResetBoard;
public BullSpace(int index, ResetBoard resetBoard) {
super(index);
mResetBoard = resetBoard;
}
/**
* 1. Call Space's onClick (which reveals the space), then:
* 2. print out "You were knocked down by a bull!"
* 3. call mResetBoard's bullEncountered (which should be implemented in Board)
*/
//TODO 12 implement the method based on the above description
@Override
public void onClick() {
//FIXME
}
}
package cmps251.homework3.spacetypes;
/**
* EmptySpace represents an empty space that does not contain anything.
* When uncovered, it should not do anything to the game.
*
* EmptySpace is displayed as " " (empty space) when it is revealed (uncovered).
*
*/
//TODO 00 Fix the errors. This class is not implementing all the abstract
//methods from the superclass! Read above for hint on what your new method
//bodies should contain
public class EmptySpace extends Space {
public EmptySpace(int index) {
super(index);
}
}
package cmps251.homework3.spacetypes;
import cmps251.homework3.interfaces.Punishable;
/**
* GlueSpace represents glue stuck on the floor. When uncovered, glue cause the player
* to stay in the same place for a number of playCounts specified in the interface Punishable.
* Additionally, the message: "You stepped on GLUE! Yuck!" is displayed to the user.
*
* Since GlueSpace causes additional playCounts, it should use the punish method available from the mPunishable instance.
*
* GlueSpace is displayed as "G" when it is revealed (uncovered).
*
*/
//TODO 03 Fix the errors. Read above for hints on what your method bodies should be
public class GlueSpace extends Space {
Punishable mPunishable;
public GlueSpace(int index, Punishable punishable) {
super(index);
mPunishable = punishable;
}
/**
* This method is called when the Glue is clicked
* 1. It should call super class onClick (which reveals the space)
* 2. it should print out "You stepped on GLUE! Yuck!"
* 3. It should call punish() method from Punishable and pass constant (PUNISHMENT_GLUE)
* The punish method is implemented in Game and should increase the number of
* plays by PUNISHMENT_GLUE
*
* Look at the implementation of the same method in ThornSpace for hints
*/
//TODO 11 fill the body based on the above
@Override
public void onClick() {
//FIXME
}
}
package cmps251.homework3.spacetypes;
import cmps251.homework3.interfaces.Score;
/**
* RabbitSpace represents a rabbit. When uncovered (clicked), it should first
* increase the number of rabbits in the game by one (using mScore), then display the message:
* "RABBIT CAUGHT SUCCESSFULLY!"
*
* RabbitSpace is displayed as "R" when it is revealed (uncovered).
*
*/
//TODO 01 Fix the errors. Read above for hint on what your new methods' bodies should do
public class RabbitSpace extends Space {
private Score mScore;
public RabbitSpace(int index, Score score) {
super(index);
mScore = score;
}
@Override
public void onClick() {
super.onClick();
mScore.increaseRabbitsCaught();
System.out.println(" RABBIT CAUGHT SUCCESSFULLY!");
}
}
package cmps251.homework3.spacetypes;
import cmps251.homework3.interfaces.Clickable;
/**
* This abstract class is a general representation of all possible Spaces
* in the game. The types of space include:
* EmptySpace, RabbitSpace, BullSpace, ThornSpace, and GlueSpace.
*
*/
public abstract class Space implements Clickable {
private boolean isRevealed;
private int mIndex;
/**
* This constructor should initialize the space
* At the beginning, it should be not revealed, and based
* on the parameters, it should set whether it has a rabbit
* and what position in the board it currently is
*
* @param index the index (position) of this space in the board (0-16)
* @param theGame a reference to the Game object that controls the flow of the entire game
*/
public Space(int index)
{
isRevealed = false;
mIndex = index;
}
/**
*
* This method returns String representation of a space
*
* If the space is not revealed (still not chosen by the user), then it will display the
* index of the space (plus one) as a string (hint: use Integer.toString(....) )
*
* If this space is revealed, it will either return an empty space string " " for empty spaces,
* or a letter (B, R, T, or G) depending on the type of Space.
*
* You have two cases you need to take care of:
* 1. If not revealed, then print out the number of the space (hint: use Integer.toString(....) )
* 2. If revealed, it should call the abstract method getRevealedString which will be different
* for each subclass of this class.
*
* @return "0"-"16", " ", "B", "R", "T", or "G" depending on the type of Space
*/
//TODO 07 add the body of the method below by reading the above
public String getAsString(){
return ""; //FIXME
}
//DO NOT CHANGE the signature of method getRevealedString below.
/**
* @return " ", "B", "R", "T", or "G" depending on the type of Space.
*/
public abstract String getRevealedString();
/**
* This method returns whether the space has rabbit or not.
*
* @return true if this space has rabbit, false otherwise
*/
public boolean isRabbit()
{
return (this instanceof RabbitSpace);
}
/**
* This method returns whether the space is revealed or not
*
* @return true if this space is revealed, false otherwise
*/
public boolean isRevealed()
{
return isRevealed;
}
/**
* This method makes this space reveal! (show itself/unhide)
*/
private void reveal()
{
isRevealed = true;
}
/**
* @return the index position of this space in the board.
*/
public int getIndex()
{
return mIndex;
}
/**
* All spaces should be revealed regardless of type.
* Make sure you call this method from all subclasses by using super.onClick();
*/
@Override
public void onClick() {
reveal();
}
}
package cmps251.homework3.spacetypes;
import cmps251.homework3.interfaces.Punishable;
/**
* ThorneSpace represents thorns (spikes in plants). When uncovered, thornes cause the player
* to stay in the same place for a number of play counts specified in the interface Punishable.
* Additionally, the message: "You stepped on THRONES! Ouch!" is displayed to the user.
*
* Since ThornSpace causes additional playCounts, it should use the punish method available from the mPunishable instance.
*
* ThornSpace is displayed as "T" when it is revealed (uncovered).
*
*/
//TODO 02 Fix the errors. Read above for hint on what you should do in the new methods
public class ThornSpace extends Space {
private Punishable mPunishable;
public ThornSpace(int index, Punishable punishable) {
super(index);
mPunishable = punishable;
}
/**
* This method calls super classes's onClick() which reveals the space
* Then it prints out You stepped on THORNS! Ouch!
* Then it punishes the user by incrementing the number of plays so far by PUNISHTMENT_THORN
*/
@Override
public void onClick() {
super.onClick();
System.out.println(" You stepped on THRONS! Ouch!");
mPunishable.punish(Punishable.PUNISHMENT_THORN);
}
}
Interfaces In this assignment you will be using the following interfaces (already provided in the project file) 1) Clickable: This interface is implemented by all spaces and has one abstract method called onClick() that will be handled differently for each space type. Note that the superclass Space also implements this class because it will reveal any space when it is selected. However, children classes of Space must Override this 2/3 method to add additional functionality. All overridden methods must call the super.onClick() method so the Space is revealed Punishable: This interface has one abstract method called punish(int) that will increase the play count of the game whenever the user falls into a thorn or glue space. Punishable is implemented by Game becauseit is the only class that has access to the game's playCount. The interface defines two constants that determine how many play counts to increase if the user falls into a ThornSpace, or a GlueSpace. 2) 3) ResetBoard: This interface has one abstract method called bullEncountered(). The method should be called whenever the player selects a space that contains a Bull. ResetBoard is implemented by the Board class because it has access to all spaces and can thus reset them accordingly Score: This interface contains two abstract methods. One resets the number of rabbits caught called resetRabbitsCaught), and the other one increases the rabbits caught by one; called increaseRabbitsCaught(). The interface is implemented by Game because game has access to the number of rabbits caught so far. These methods will be useful when a Rabbit is found, and when a Bull is encountered Running Game Snapshots: You stepped on THRONS! 0uch! ? Message displayed Current Play No: 27 Number of rabbits caught so far: 2 Number of thornes: 1 Number of glues: 2 Bull Space RRabbit found Thorn Space T GGlue Space Empty (no rabbit) 15 16 Unknown (not revealed) Please select a position ('116): Interfaces In this assignment you will be using the following interfaces (already provided in the project file) 1) Clickable: This interface is implemented by all spaces and has one abstract method called onClick() that will be handled differently for each space type. Note that the superclass Space also implements this class because it will reveal any space when it is selected. However, children classes of Space must Override this 2/3 method to add additional functionality. All overridden methods must call the super.onClick() method so the Space is revealed Punishable: This interface has one abstract method called punish(int) that will increase the play count of the game whenever the user falls into a thorn or glue space. Punishable is implemented by Game becauseit is the only class that has access to the game's playCount. The interface defines two constants that determine how many play counts to increase if the user falls into a ThornSpace, or a GlueSpace. 2) 3) ResetBoard: This interface has one abstract method called bullEncountered(). The method should be called whenever the player selects a space that contains a Bull. ResetBoard is implemented by the Board class because it has access to all spaces and can thus reset them accordingly Score: This interface contains two abstract methods. One resets the number of rabbits caught called resetRabbitsCaught), and the other one increases the rabbits caught by one; called increaseRabbitsCaught(). The interface is implemented by Game because game has access to the number of rabbits caught so far. These methods will be useful when a Rabbit is found, and when a Bull is encountered Running Game Snapshots: You stepped on THRONS! 0uch! ? Message displayed Current Play No: 27 Number of rabbits caught so far: 2 Number of thornes: 1 Number of glues: 2 Bull Space RRabbit found Thorn Space T GGlue Space Empty (no rabbit) 15 16 Unknown (not revealed) Please select a position ('116)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Introduction To Constraint Databases

Authors: Peter Revesz

1st Edition

1441931554, 978-1441931559

More Books

Students also viewed these Databases questions

Question

What was the valuebleable acquisition twain made

Answered: 1 week ago

Question

How would you assess the value of an approach like this?

Answered: 1 week ago