ise oint In this exercise, we will create a memory game called \"Mind Game\". In
ID: 3705187 • Letter: I
Question
ise oint In this exercise, we will create a memory game called "Mind Game". In this game, even number of tiles are placed face-down in rows on a "Mind Game Board". Each tile contains an image. For each tile, there is exactly one other tile with the same image. The player is to pick a tile, see which image it has, and try to find its match from the remaining face-down tiles. If the player fails to turn over its match, both tiles are turned face-down and the player attempts to pick a matching pair again. The game is over when all tiles on the board are turned face-up. In this implementation of a simplified version of Mind Game, Images will be strings chosen from a FixdLenStringList. (Use the FixdLenStringList dass from exercise 1). The mind game board will contain even number of Tiles The board will be implemented as a one-dimensional array of Tiles. For example, if the size of the mind game board is requested to be 4, then the board will have 16 tiles. The one dimension array, gameBoard, can be viewed as a 4-by-4 mind game board as follows gameBoard gameBoard gameBoard 2 gameBoard[3] gameBoard gameBoard5 ganeBoard6 gameBoard71 gameBoard gameBoard[9 ganeBoard[10] gameBoard11] gameBoardi12 gameBoard 13 ganeBoard 14 gameBoard[15] An incomplete implementation of the Tile and Board classes are provided with this exercise (Tile java, Board.java). You should examine these classes and complete them with the following methods. To implement the methods, see the specifications provided in the comments of the methods. a) Write the implementation of the Board method fillBoard, which will randomly fill the mind game board with Tiles whose images (strings) are randomly chosen from the strings contained in the FixdLenStringList.A tile image that appears on the board appears exactly twice on the board.Explanation / Answer
JAVA CODING:-
================
import java.util.Arrays;
/**
* FixdLenStringList defines a list of strings and a string length. All strings in the FixdLenStringList have the same length.
* There is no present number of strings that a FixdLenStringList can hold.
**/
public class FixdLenStringList {
// Instance variable
private String[] possibleStrings;
private int strLength;
/**
* Constructor for FixedLenStringList that initializes strLength and possibleStrings
* @param len ,the length of the FixdLenStringList's strings.
**/
public FixdLenStringList(int len) {
this.strLength = len;
this.possibleStrings = new String[0];
}
/**
* Gets the length of a string in FixdLenStringList
* @return length of the individual the strings in FixdLenStringList
**/
public int getStringLength() {
return this.strLength;
}
/**
* Returns the string in position x of FixdLenStringList's listimplementation.
*The first string is in position 0. Precondition: 0 <= x < availableStrings.length
* @param x an index value in the FixdLenStringList,@return returns the xth entry in FixdLenStringList
**/
public String getString(int x) {
if ((0 <= x) && (x < this.possibleStrings.length))
return this.possibleStrings[x];
else
return null;
}
//**
* Returns true if the string, key, is found in the FixdLenStringList's listof strings, false otherwise.
* @param key the string we are searching for @return true if key is found in FixdLenStringList; false otherwise
**//
public boolean found(String key)
for (String str : this.possibleStrings) {
if (str.equals(key)) // Compare key with the strings in the list
return true;
}
return false;
}
//**
* Adds the string, entry, to FixdLenStringList's list implementation if it is the correct length and not already in the list.
* If the string is already in the list or if the string is not the correct length, it is notadded.
* @param str string to add to FixdLenStringList
**//
public void addString(String entry) {
// Add entry only if its length is same as strLength and it is not already added
if ((entry.length() == this.strLength) && !(found(entry))) {
int len = this.possibleStrings.length;
// Make space for str in the possibleStrings array
this.possibleStrings = Arrays.copyOf(this.possibleStrings, len + 1);
this.possibleStrings[len] = entry;
}
}
//**
* Removes and returns a random string entry from the FixdLenStringList's list of strings.
*Precondition: the FixdLenStringList's list must not be empty.
* @return a random string from FixdLenStringList
**//
public String removeRandomString() {
int len = this.possibleStrings.length;
// Generate a random number
// This will generate a random from between [0 - (len - 1)]
// both inclusive
int randomNum = ((int) (Math.random() * 10)) % len;
// Get String at index randomNum
String str = this.possibleStrings[randomNum];
// Shift every string after randomNum one position back
for (int i = randomNum; i < (len - 1); i++) {
this.possibleStrings[i] = this.possibleStrings[i + 1];
}
// Resize array
this.possibleStrings = Arrays.copyOf(this.possibleStrings, len - 1);
// Return str
return str;
}
//** Displays the list as a comma separated value**//
@Override
public String toString() {
if (this.possibleStrings.length > 0) {
StringBuffer sb = new StringBuffer();
sb.append(this.possibleStrings[0]);
for (int i = 1; i < this.possibleStrings.length; i++) {
sb.append(", " + this.possibleStrings[i]);
}
return sb.toString();
} else
return "";
}
}
//**
* Tile for the Mind Game. A tile has an image and cabe be placed either face-up or face-down.
**//
public class Tile {
private String image;
private boolean faceUP;
//**
* Constructor for the Tile class. initially, face-down.
* @param word a tile is created with the string word
**//
public Tile(String word) {
this.image = word;
this.faceUP = false;
}
//**
* Shows image on face-up Tile
* @return image if Tile is face-up; otherwise returns the empty string
**//
public String showFace() {
if (this.faceUP)
return this.image
else
return "";
}
//**
* Checks whether Tile is face-up.
* @return true if Tile is face-up; false otherwise
**//
public boolean isFaceUp() {
return this.faceUP;
}
//**
* Getter method for image @return the image string.
**//
public String getImage() {
return image;
}
//**
* Compares images on Tiles @param other image to be compared to image on this tile
* @return true if the image on other is the same as this image; false otherwise
**//
@Override
public boolean equals(Object other) {
// self check
if (this == other)
return true;
// null check
if (other == null)
return false;
// type check and cast
if (other instanceof Tile) {
Tile another = (Tile)other;
// field comparison
return (this.getImage().equals(another.getImage()));
}
return false;
}
//**Turns Tile face-up Precondition: Tile is turned face-up**//
public void turnFaceUp() {
this.faceUP = true;
}
//**Turns Tile face-down Precondition: Tile is turned face-down**//
public void turnFaceDown() {
this.faceUP = false;
}
}import java.util.Random;
//**The mind game board containing n by n tiles.@author musfiqrahman**//
public class Board {
// Instance variables
private Tile[] gameBoard; // Mind Game board of Tiles
private int size; // Number of Tiles on board
private int rowLength; // Number of Tiles printed in a row
private int numberOfTileFaceUp; // Number of Tiles face-up
private FixdLenStringList possibleTileValues; // Possible Tile values
//**
* Constructs n by n mind game board of Tiles whose image values are chosen
* from the already filled FixdLenStringList.
* Precondition: n is the length of a side of the board, n is an even
* positive integer. FixdLenStringList contains at least n * n / 2 strings.
* @param n is length of the side of the mind game board (an even number)
* @param list the FixdLenStringList from which the values for the tiles are chosen
**//
public Board(int n, FixdLenStringList list) {
this.rowLength = n;
this.size = n * n;
this.gameBoard = new Tile[this.size];
this.possibleTileValues = list;
this.numberOfTileFaceUp = 0;
// Fill the board
fillBoard();
}
//**Generate a random positions which is not already occupied in the board**//
private int getRandomPosition() {
// Create random object to generate random numbers
Random r = new Random();
int pos = -1;
do {
pos = r.nextInt(this.size);
} while (this.gameBoard[pos] != null);
return pos;
}
//**
* Randomly fills this Mind Game Board with tiles. The number of distinct
* tiles used on the board is size/2. Any one tile image appears exactly
* twice. Precondition: number of position on board is even,
* FixdLenStringList contains at least size / 2 elements.
**//
private void fillBoard() {
// For each string in FixdLenStringList get two random position in the Board
int i = 0;
while (this.possibleTileValues.getString(i) != null) {
// Create Tile with image
Tile newTile = new Tile(this.possibleTileValues.getString(i));
// Generate two random positions which are not already occupied
// and set newTile at that position
int pos = getRandomPosition();
this.gameBoard[pos] = newTile;
pos = getRandomPosition();
this.gameBoard[pos] = newTile;
i += 1;
}
}
//**
* Precondition: 0 <= p < gameBoard.length. Precondition: Tile in position p
* is face-down. Postcondition: After execution, Tile in position p is
* face-up @param p the index of the tile to turn face-up
**//
public void lookAtTile(int p) {
this.gameBoard[p].turnFaceUp();
}
//**
* Checks whether the Tiles in pos1 and pos2 have the same image. If they
* do, the Tiles are turned face-up. If not, the Tiles are turned face-down.
* Precondition: gameBoard[pos1] is face-up, gameBoard[pos2] is face-up @param pos1
* index in gameBoard, 0 <= pos1 < gameBoard. length @param pos2
* index in gameBoard, 0 <= pos1 < gameBoard. length
**//
public void checkMatch(int pos1, int pos2) {
Tile t1 = pickTile(pos1);
Tile t2 = pickTile(pos2);
if (t1.equals(t2)) {
lookAtTile(pos1);
lookAtTile(pos2);
this.numberOfTileFaceUp += 2;
} else {
t1.turnFaceDown();
t2.turnFaceDown();
}
}
//**Board is printed for the Player. If the Tile is turned face-up, the image
* is printed. If the Tile is turned face-down, the Tile position isprinted.
**//
public void printBoard() {
final int PADDING = 3;
int spacing = possibleTileValues.getStringLength() + PADDING;
for (int i = 0; i < size; i++) {
if ((i % rowLength) == 0)
System.out.println();
String display = this.gameBoard[i].showFace();
if (!display.equals("")) // Tile is face-up
System.out.print(format(display, spacing));
else
System.out.print(format(i, spacing)
}
}
//** Returns Tile in position pos. Precondition: 0 <= pos < gameBoard.length.
* @param posis index in gameBoard @return tile in position pos, null otherwise
**//
public Tile pickTile(int pos) {
if (pos < 0 || pos >= gameBoard.length) {
return null;
}
return gameBoard[pos];
}
/**Right-justifies a number to a given number of places.
*@param numberan integer to be formatted
* @param ptotal number of characters in returned string
* @return right-justified number with p places as a string
*/
private String format(int number, int p) {
String str = String.format("%1$" + p + "s", (number + ""));
return str;
}
/**
* Right-justifies a string to a given number of places.
* @param word a string to be formatted
* @param p total number of characters in returned string
* @return right-justified word with p places as a string
*/
private String format(String word, int p) {
String str = String.format("%1$" + p + "s", word)
return str;
}
/**
* Checks whether all tiles are face-up. @return true if all tiles are face-up; false otherwise
*/
public boolean allTilesUp() {
return (this.numberOfTileFaceUp == this.size);
}
}
import java.util.Scanner;
/**
* This client class play starts the mind game and controls user input.
*/
public class MindGameClient {
public static void main(String[] args) {
// Create fixed length strings
FixdLenStringList fl = new FixdLenStringList(3);
fl.addString("cat");
fl.addString("dog");
fl.addString("pig");
fl.addString("eel");
fl.addString("pet");
fl.addString("net");
fl.addString("ted");
fl.addString("car");
// Create board
Board b = new Board(4, fl);
// Scanner to get user input
Scanner kb = new Scanner(System.in)
while (!b.allTilesUp()) {
// Display board
b.printBoard();
System.out.print(" Choose positions:");
// Get positions from the user
int n1 = kb.nextInt(
int n2 = kb.nextInt();
// Get tiles at n1, n2
Tile t1 = b.pickTile(n1);
Tile t2 = b.pickTile(n2);
boolean isValidSelection = true;
// Check if n1 and n2 are not same
if (n1 != n2) {
// Check if n1, n2 is a valid selection
if (t1 != null && t2 != null) {
// Check if tiles at n1 and n2 are not already face up
if (!t1.isFaceUp() && !t2.isFaceUp()) {
System.out.print(t1.getImage() + " , ");
System.out.println(t2.getImage());
System.out.println("");
// Check if both tiles match
b.checkMatch(n1, n2);
} else
isValidSelection = false;
} else
isValidSelection = false;
} else
isValidSelection = false;
if (!isValidSelection)
System.out.println("Invalid Selection!");
}
// Print the final board
b.printBoard();
// Close scanner
kb.close();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.