Question

In: Computer Science

Java program by using array only. II. The NumberTile Game (Unchanged) Number tiles are squares with...

Java program by using array only.

II. The NumberTile Game (Unchanged)

  • Number tiles are squares with a number from 1 to 9 at each side. A “board” for the game is a sequence of number tiles satisfying this property:

      The right side of each tile (except the last) = the left side of the next tile on the board

  • There are 2 players in the game, both of which are the computer. Each player starts with a "hand" of 5 number tiles. A move is made by a player removing tile from the hand and placing it on the board, if possible.   A tile may be placed on the board in any of 3 ways:
  1. As the new first tile
  2. Between two adjacent tiles
  3. As the new last tile
  • A number tile in the players hand can be rotated 90 degrees but once placed on the board its position is fixed
  • If none of the tiles in the hand can be placed on the board, then one random tile is added to the player's hand
  • A round is when player1 makes a move and then player2 makes a move (to make the game fair)
  • The game ends when all tiles are removed from one (or both) player's hand(s). If one player's hand is empty and the other player's hand still contains tiles, then the player with the empty hand is the winner. If both players’ hands are empty, then the game ends in a tie

III. Specifications

  • NEW: The output from 3 games must be written to an output file
  • Your program will consist of the same 5 classes
  • Use the skeletons of the NumberTile, Hand, Board, and TileGame classes provided
  1. Not allow to add or remove or relocate any methods
  2. Not allow to modify any of the method or instance variable declarations or add any new instance variables
  • create two Hand objects
  1. create a TileGame object using the two Hand objects
  2. call the toString() method of the Hand class for each initial hand and print them, properly labeled
  3. call the play() method of the TileGame class
  4. call the getResults() method of the TileGame class and print the string returned
  1. After each game, give the user the option to see another
  2. You must use the counter provided in each class as the upper bound on all loops that traverse the array! (see PartiallyFilled.java, online)
  3. You may use Arrays.copyOf, other Arrays class methods, and System.arraycopy ONLY to resize an array if it becomes full at it’s declared capacity. (If that happens, something’s wrong).
  4. No credit for using Arrays.copyOf or System.arraycopy to place a tile on the Board or remove or insert a tile from/to a Hand

NumberTile.java

import java.util.ArrayList ;
import java.util.Random;

// A NumberTile is a square tile with a number from 1 to 9 on each side
public class NumberTile 
{
    private ArrayList tile ;    // the 4-sided tile
    private static final Random gen = new Random() ;
      
    // Create a NumberTile object with 4 random ints in the range 1 to 9
    public NumberTile() 
    {
       // TO DO: Code the body of this method
    }
    
    // Rotate this NumberTile 90 degrees
    public void rotate() 
    {
       // TO DO: Code the body of this method
    }
    
    // Return the number on the left side of this NumberTile
    public int getLeft()
    {
        // Do NOT modify this method
        return tile.get(0) ;
    }
    
    // Return the number on the right side of this NumberTile
    public int getRight() 
    {
        // Do NOT modify this method
        return tile.get(2) ;
    }
    
    // Return this NumberTile as a multiline string in the form:
    //     9
    //  3     7
    //     6
    //
    public String toString() 
    {
       // TO DO: Code the body of this method
       
       // temporary return statement so program skeleton will compile and run
       return null ;
    }    
} // end of NumberTile class

Hand.java

import java.util.ArrayList;

// A player's hand of NumberTiles
public class Hand
{
    private ArrayList hand ;
    private final static int INITIAL_SIZE = 5 ;  // starting hand size
    
    // Creates a new hand of INITIAL_SIZE NumberTiles 
    public Hand()
    {
       // TO DO: Code the body of this method
    }
       
    // Get the NumberTile at the specified index in this Hand
    public NumberTile get(int index)
    {
       // TO DO: Code the body of this method
       
       // temporary return statement so program skeleton will compile and run
       return null ;
    }
    
    // Get the number of tiles in this Hand
    public int getSize()
    {
       // TO DO: Code the body of this method
       
       // temporary return statement so program skeleton will compile and run
       return -999 ;
    }
    
    // Add a new NumberTile to this Hand
    public void addTile()
    {
       // TO DO: Code the body of this method
    }
    
    // Remove the NumberTile at the specified index from this Hand
    public void removeTile(int index)
    {
        // TO DO: Code the body of this method
    }
    
    // Is this hand empty?
    public boolean isEmpty()
    {
       // TO DO: Code the body of this method
       
       // temporary return statement so program skeleton will compile and run
       return false ;
    }
    
    // Return this Hand as a multiline String.
    // If this Hand is empty, return an appropriate message
    public String toString()
    {
       // TO DO: Code the body of this method
       
       // temporary return statement so program skeleton will compile and run
       return "The hand" ;
    }
}
Board.java

import java.util.ArrayList;

// The board for the NumberTile game  
public class Board
{
    private ArrayList board ;    // the board for a NumberTile game
    
    // Creates a new Board containing a single NumberTile
    public Board()
    {
       // TO DO: Code the body of this method       
    }
    
    // Return the NumberTile at the specified index on this Board
    public NumberTile getTile (int index)
    {
       // TO DO: Code the body of this method
       
       // temporary return statement so program skeleton will compile and run
       return null ;   
    }
    
    // Return the current number of tiles on this Board
    public int getSize()
    {
       // TO DO: Code the body of this method
       
       // temporary return statement so program skeleton will compile and run
       return -999 ;
    }
    
    // Insert a new tile into this Board at the specified index
    public void addTile(int index, NumberTile tile)
    {
       // TO DO: Code the body of this method
    }
    
    // Return a multiline string containing all the tiles on this Board
    public String toString()
    {
       // TO DO: Code the body of this method
       
       // temporary return statement so program skeleton will compile and run
       return "The board" ;
    }           
}

TileGame.java

// Implements a domino-like game where two players, both of whom are
// the computer, take turns inserting NumberTiles into a Board
public class TileGame
{
   // instance vars
   private Board board ;     // the game board
   private Hand hand1 ;      // Player 1 hand
   private Hand hand2 ;      // Player 2 hand
   private String winner ;   // the winner - player1, player2,
                             // or a tie game
   
   // Creates a new TileGame with two initial hands and a board
   public TileGame(Hand firstHand, Hand secondHand)
   {
      // TO DO: Code the body of this method
   }
   
   // Players take turn moving until one or both hand are empty
   public void play()
   {
      // TO DO: Code the body of this method
   }

   // Utility method called by method makeMove.  Returns the index at which a
   // new tile will be inserted into the board, or -1 if the tile cannot
   // be inserted.  The new tile may be inserted either (1) between two 
   // existing tiles, (2) as the new first tile, or (3) as the new last tile
   private int getIndexForFit(NumberTile tile)
   {
      // TO DO: Code the body of this method
       
      // temporary return statement so program skeleton will compile and run
      return -1 ;
   }

   // Utility method called by method play().  Checks consecutive tiles in the 
   // hand - by calling method getIndexForFit() - to see if one can be inserted 
   // into the board. When the first tile that fits is found, removes it from
   // the hand, inserts it into the board, and the move ends.  The tile may be
   // rotated up to 3 times. If none of the tiles fit, adds a new, random tile
   // to the hand  
   private void makeMove(Hand hand)
   {
      // TO DO: Code the body of this method
   }
   
   // Return results of the game as a humongous multi-line String containing
   // the final board, both both player's final hands, and the winner
   public String getResults()
   {
      // TO DO: Code the body of this method
      // HINT: call toString for the board and for each hand and don't
      //       forget the winner
       
      // temporary return statement so program skeleton will compile and run
      return "Results" ;
   }
} // end of TileGame2 class

TileGameTester.java

// A test class for the NumberTile Game
public class TileGameTester
{
   public static void main(String[] args)
   {
      // TO DO: Code the body of this method
   }
} 

Basically, we will have 5 tiles on our hands. If tiles contain a number of the left/right number on board. We can place it on board.

Board:

5

4 6

2

so that we need to have 4/6 on our hand. if so, we can rotate the number for that tile and put it out.

4 2

2 5 ==> 6 4

6 5

TO board:

2

6 4

5

5

4 6

2

Starting a new game...

***** Player 1 Initial Hand *****

    7

5   7

    6

    4

1   1

    9

    2

2   6

    2

    9

7   7

    1

    9

6   5

    3

***** Player 2 Initial Hand *****

    7

6   2

    1

    8

2   8

    3

    9

2   4

    2

    1

9   6

    3

    9

2   3

    1

***** The Initial Board *****

    5

3   4

    1

***** The Final Board *****

    8

8   3

    2

    5

3   4

    1

    1

4   9

    1

    7

9   1

    7

    6

1   7

    2

    6

7   5

    7

    3

5   6

    9

    2

6   2

    2

    2

  2   9

    4

Solutions

Expert Solution

Answer:

NumberTile.java:
import java.util.ArrayList;

import java.util.HashSet;

import java.util.Random;

import java.util.Set;

/**

* A NumberTile is a square tile with an int between 1 and 9, inclusive, on

* each side

*/

public class NumberTile implements Cloneable

{

private ArrayList<Integer> tile ;

/**

* Create a NumberTile object using 4 random ints in the range 1..9

*/

public NumberTile()

{

Random r = new Random();

Set<Integer> set = new HashSet<>();

while(set.size() < 4) {

set.add(r.nextInt(9) + 1);

}

tile = new ArrayList<>(set);

}

/**

* Rotate this tile 90 degrees clockwise

*/

public void rotate()

{

// remove from last position

int n = tile.remove(3);

// insert at first position

tile.add(0, n);

}

/**

* Get the number on the left side of this tile

* @return the number on the left side of this tile

*/

public int getLeft()

{

// DO NOT MODIFY THIS METHOD!

// =========================

return tile.get(0) ;

}

/**

* Get the number on the right side of this tile

* @return the number on the right side of this tile

*/

public int getRight()

{

// DO NOT MODIFY THIS METHOD!

// =========================

return tile.get(2) ;

}

/**

* Return a String representation of this tile in the form

*

* 4

* 5 7

* 1

*

* @return the tile as a multi-line String

*/

public String toString()

{

return String.format("\n%5s\n%s%8s\n%5s\n", tile.get(1), tile.get(0), tile.get(2), tile.get(3));

}

@Override

public Object clone() throws CloneNotSupportedException {

return super.clone();

}

} // end of NumberTile class


Hand.java:
import java.util.ArrayList;

/**

* A Hand is a collection of NumberTiles. Tiles may be removed from

* the Hand and new tiles added to it

*/

public class Hand

{

private ArrayList<NumberTile> hand ;

private static int HAND_SIZE = 5 ; // starting hand size

/**

* Create a new Hand of HAND_SIZE tiles

*/

public Hand()

{

hand = new ArrayList<>();

for(int i=0; i<HAND_SIZE; i++) {

hand.add(new NumberTile());

}

}

/**

* Create a new Hand as an exact duplicate (i.e. a "deep copy") of another

* @param toBeCopied the Hand to be copied

* @throws CloneNotSupportedException

*/

public Hand(Hand toBeCopied) throws CloneNotSupportedException

{

hand = new ArrayList<>();

int size = toBeCopied.getSize();

for(int i=0; i<size; i++) {

hand.add((NumberTile) toBeCopied.get(i).clone());

}

}

/**

* Get the tile at a specified index in this Hand

* @param index the index (position) of the tile to be returned

* @return the NumberTile at the specified index

*/

public NumberTile get(int index)

{

return hand.get(index);

}

/**

* Get the size of this Hand

* @return the number of tiles in the Hand

*/

public int getSize()

{

// temporary return statement so skeleton will compile and run

return hand.size() ;

}

/**

* Add a new tile to this Hand

*/

public void addTile()

{

hand.add(new NumberTile());

}

/**

* Remove the tile at a specified index (position) from this Hand

* @param index the index (position) of the tile to be removed

*

*/

public void removeTile(int index)

{

hand.remove(index);

}

/**

* Is this Hand empty?

* @return true if this Hand is empty (contains no tiles); otherwise false

*

*/

public boolean isEmpty()

{

return hand.isEmpty() ;

}

/**

* Get a String representation of this Hand

* @return the NumberTiles in this Hand as a multi-line String

*/

public String toString()

{

// DO NOT MODIFY THIS METHOD!

// ==========================

return hand.toString() ; // call toString of ArrayList class

}

}

Board.java:
import java.util.ArrayList;

/**

* A Board is a collection of Number Tiles

*/

public class Board

{

private ArrayList<NumberTile> board ;

/**

* Create a new Board with one NumberTile

*/

public Board()

{

board = new ArrayList<>();

board.add(new NumberTile());

}

/**

* Get the tile at a specified index on this Board

* @param index the index (position) of the tile to be returned

* @return the NumberTile at the specified index

*/

public NumberTile getTile (int index)

{

return board.get(index);

}

/**

* Get the size of this Board

* @return the number of tiles on the Board

*/

public int getSize()

{

return board.size();

}

/**

* Add a new tile to this Board at a specified index (position)

* @param index the index (position) at which to insert the tile

* @param tile the tile to be inserted

*/

public void addTile(int index, NumberTile tile)

{

board.add(index, tile);

}

/**

* Get a String representation of this Board

* @return the NumberTiles on the Board as a multi-line String

*/

public String toString()

{

// DO NOT MODIFY THIS METHOD!

// ==========================

return board.toString() ; // call toString of ArrayList class

}

}


TileGame.java:
public class TileGame

{

// instance variable declarations go here

private Hand player1, player2;

private Board board;

private int turn = 1;

// Create a Tilegame object

public TileGame()

{

player1 = new Hand();

player2 = new Hand();

board = new Board();

}

// Play the game

public void play()

{

while(gameStatus() == -1) {

System.out.println(this + "\n");

if(turn == 1) {

System.out.println("Turn: Player 1");

makeMove(player1);

} else {

System.out.println("Turn: Player 2");

makeMove(player2);

}

turn++;

if(turn == 3) {

turn = 1;

}

}

System.out.println(this + "\n");

int status = gameStatus();

if(status == 0) {

System.out.println("\nIts a Tie!!!");

} else if(status == 1) {

System.out.println("\nPlayer1 won!!!");

} else if(status == 2) {

System.out.println("\nPlayer2 won!!!");

}

System.out.println();

}

// If the current tile fits in the board, returns the index at which

// it will be inserted. If the tile does not fit, returns -1

private int getIndexForFit(NumberTile tile)

{

int size = board.getSize();

for(int i=0; i<size; i++) {

if(i==0) {

if(tile.getRight()==board.getTile(0).getLeft()) {

return i;

}

}

if(i==size-1) {

if(tile.getLeft()==board.getTile(size-1).getRight()) {

return size;

}

} else if(tile.getLeft()==board.getTile(i).getRight() && tile.getRight()==board.getTile(i+1).getLeft()) {

return i;

}

}

return -1;

}

// Make a move from a hand. If a tile in the hand fits on the board

// then remove it from the hand and place it in the board. The tile may

// be rotated up to 3 times. If no tile from the hand fits, then add

// another tile to the hand

private void makeMove(Hand hand)

{

for(int i=0; i<hand.getSize(); i++) {

NumberTile tile = hand.get(i);

int index = getIndexForFit(tile);

int count = 0;

while(count < 3) {

if(index != -1) {

board.addTile(index, tile);

hand.removeTile(i);

return;

}

tile.rotate();

index = getIndexForFit(tile);

count++;

}

}

// No tile was able to be adjusted

hand.addTile();

}

/*

* Returns 0 on tie, 1 for player 1 s winner, 2 for player 2 as winner

* -1 for no results till now

*/

int gameStatus(){

if(player1.getSize()==0 && player2.getSize()==0) {

return 0; // tie

} else if(player1.getSize()==0){

return 1;

} else if(player2.getSize()==0) {

return 2;

} else {

return -1;

}

}

// Get the results of the game as a humongous multi-line String containing

// both starting hands, the final board, both final hands, and a message

// indicating the winner

// HINT: call the toString methods of the Hand and Board classes

public String toString()

{

StringBuilder sb = new StringBuilder();

sb.append("Player 1 Hands: \n");

sb.append(player1 + "\n");

sb.append("Player 2 Hands: \n");

sb.append(player2 + "\n");

sb.append("Board: \n");

sb.append(board + "\n");

return sb.toString();

}

public static void main(String args[]) {

TileGame tileGame = new TileGame();

tileGame.play();

}

} // end of TileGame class

If you do not get anything in this solution,please put a comment and i will help you out.

Do not give a downvote instantly.it is a humble request.

If you like my answer, please give an upvote...Thank you.


Related Solutions

Write a program in Java with a Scanner. Given an array and a number k where...
Write a program in Java with a Scanner. Given an array and a number k where k is smaller than the size of the array, write a program to find the k'th smallest element in the given array. It is given that all array elements are distinct. Example: Input: arr[] = {7,10,4,3,20,15} k = 3 Output: 7
Using pseudocode design a number guessing game program. The program should generate a random number and...
Using pseudocode design a number guessing game program. The program should generate a random number and then ask the user to guess the number. Each time the user enters his or her guess, the program should indicate it was too high or too low. The game is over when the user correctly guesses the number. When the game ends, the program should display the number of guesses that the user made.
java program that coverts base13 to decimal. without using array and methods.
java program that coverts base13 to decimal. without using array and methods.
Write a Java program that implements the Number Guessing Game: 1. First generate a random number...
Write a Java program that implements the Number Guessing Game: 1. First generate a random number (int) between 0 and 100, call it N 2. Read user input (a guess) 3. check the number, if it's smaller than N, output "The number is larger than that" 4. If the input is larger than N, output "The number is smaller than that" 5. If the input is equal to N, output " You got it!", and exit 6. Repeat until the...
Using a Java. 2. Write a Java program calculate_fare.java to take the input for number of...
Using a Java. 2. Write a Java program calculate_fare.java to take the input for number of miles, and the class of journey (1,2, or 3, for first, second, and third class respectively), for a train journey. The program should then calculate and display the fare of journey based on the following criteria: Note: Use Switch...case and if...else construct First (1) Class Second (1) Class Third (3) Class First 100 mile $ 3 per mile $ 2 per mile $ 1.50...
Write a java program of a multiplication table of binary numbers using a 2D array of...
Write a java program of a multiplication table of binary numbers using a 2D array of integers.
Using JAVA Write a program that uses a 2-D array to store the highest and lowest...
Using JAVA Write a program that uses a 2-D array to store the highest and lowest temperatures for each month of the year. The program should output the average high, average low, and highest and lowest temperatures of the year. Your program must consist of the following methods with their appropriate parameters: a.) getData: This method reads and stores the data in the 2-D array. b.) averageHigh: This method calculates and returns the average high temperature of the year. c.)...
Using Java, design a program that creates an array of Card objects, shuffles them, then recursively...
Using Java, design a program that creates an array of Card objects, shuffles them, then recursively sorts them by value and then recursively sorts them by value and suit You will need to create a Card class with the following two fields: • value (a String) • suit (a String) You may include any other fields, constructors, or methods as needed. Your single array will need to contain 52 card objects, one for each value of each suit. The values...
java program Create a program that creates and prints a random phone number using the following...
java program Create a program that creates and prints a random phone number using the following format: XXX-XXX-XXXX. Make sure your output include the dashes.  Do not let the first three digits contain an 8 or 9 (HINT: do not be more restrictive than that) and make sure that the second set of three digits is not greater than 773. Helpful Hint:   Think though the easiest way to construct the phone number. Each digit does do not have to be determined...
using java For this assignment, you will write a program that guesses a number chosen by...
using java For this assignment, you will write a program that guesses a number chosen by your user. Your program will prompt the user to pick a number from 1 to 10. The program asks the user yes or no questions, and the guesses the user’s number. When the program starts up, it outputs a prompt asking the user to choose a number from 1 to 10. It then proceeds to ask a series of questions requiring a yes or...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT