ComputerScienceExpert

(11)

$18/per page/

About ComputerScienceExpert

Levels Tought:
Elementary,Middle School,High School,College,University,PHD

Expertise:
Applied Sciences,Calculus See all
Applied Sciences,Calculus,Chemistry,Computer Science,Environmental science,Information Systems,Science Hide all
Teaching Since: Apr 2017
Last Sign in: 103 Weeks Ago, 3 Days Ago
Questions Answered: 4870
Tutorials Posted: 4863

Education

  • MBA IT, Mater in Science and Technology
    Devry
    Jul-1996 - Jul-2000

Experience

  • Professor
    Devry University
    Mar-2010 - Oct-2016

Category > Programming Posted 28 Apr 2017 My Price 9.00

Part 3 - Placing New PiecesProblem

Purpose

The purpose of this project is to help you become better at using arrays, 2D arrays and bounds checking. One of the most dangerous bugs that most recently affected Internet security was heartbleed, which was caused by not checking the bounds of an array!

 

Introduction

2048 is a game that became popular overnight a few years ago. You are going to implement a version of it in this lab.

The rules of the game you will implement are as follows:

  • The board starts with a single box filled with a value of 2
  • The score when you start the game is 0
  • A user can move all boxes in any direction at any time
  • When two tiles with the same number touch, they are merged together and its value is doubled
  • After a user moves, one more 2 is added into an empty space on the board
  • The goal is to create a tile with the value 2048 (hence, the name of the game!)

To get a true feel for the game, you can play it using the link above.

When you boot up our version of the game, you will see a board that looks like this:

Current score: 0 | Best score: 0
-------------------------
|     |     |     |     |
-------------------------
|     |     |     |     |
-------------------------
|     |     |    2|     |
-------------------------
|     |     |     |     |
-------------------------
Enter up, down, left or right to move in that direction.
Enter reset to reset the game or quit to exit.

You can grab the skeleton code here

 

Part 1 - ConstructorProblem

The constructor will set up the game so the user can start playing. Our version of 2048 will not be limited to a 4×4 grid. Instead, the constructor will receive a parameter that specifies the width and height of the board. In our version, the board is still square.

 

Preparation

  • Play 2048 to make sure you understand it.
  • Think about what variables you will need to store the “pieces” and score.
  • Look at the variable(s) passed into the constructor
    • Why is each variable there?
    • Which do you want to save for later on?

 

Procedure

  1. Create a new board and store it to the board variable
  2. Set up the initial score for the game
  3. Save any constructor parameters you think you'll use later
  4. Put a 2 in a random place on the board

 

Notes

  • You must use the board variable to store the board
  • You can use the placeRandom method (not created yet) to put a 2 on the board
  • Board spaces equal to 0 are empty

 

Part 2 - Resetting the gameProblem

When the game is over (or when a user feels like they could do better), they may want to reset the game. This is what the reset() method is for.

 

Procedure

  1. Reset all squares on the board to 0
  2. Reset the score to 0
  3. Place a 2 randomly on the board

 

Hints

  • The procedure for reset is similar to the constructor.

 

Part 3 - Placing New PiecesProblem

The board needs a new 2 added after each turn. To place new pieces you'll need to create two new methods. 

  1. numBlanks will count the number of blank spaces on the board
  2. placeRandom will put a new 2 in one of the blank spaces on the board

 

Preparation

  • Think about what your method should do if there are no more spaces to put a 2.
  • Try to think of a way that uses the number of blanks to place a random piece instead of randomly guessing and checking cells.

 

Procedure

  1. Fill in the numBlanks method. It returns the number of cells that are 0 on the board.
  2. Fill in the placeRandom method. If there are empty spaces on the board, it adds a 2 to a randomly chosen space. If there are no empty spaces it does nothing.

 

Part 4 - Moving PiecesProblem

Shifting pieces around and combining them is what makes the game so fun! The moveTo method receives four parameters, which are two sets of coordinates. The first pair are coordinates of the cell from which we are trying to move, while the second pair are the coordinates of the cell to which we are trying to move. Since moveTo is a helper function for later overall board functions, moveTo will only move or merge a piece at most one space in any direction (i.e. the from piece and the to piece should be adjacent).

2048 has the following rules when it comes to shifting adjacent pieces:

  1. If the to piece or the from piece is out of bounds, you cannot shift, so do nothing.
  2. If the to piece and the from piece are not adjacent, do nothing.
  3. If the from piece is a 0, do nothing (nothing to add/move)
  4. If the from piece and the to piece have the same value, shift the from piece into the to space, by doubling the to space's value and reducing from to zero.
  5. If the to piece is zero, simply move the from piece into the to space.

 

Preparation

  • Think about what values are valid for each of the four parameters to have.

 

Procedure

Implement the moveTo method. This method returns true if a piece was moved, otherwise it returns false.

  1. Check the bounds of all the variables (both for adjacency and for the bounds of the board itself)
  2. If the cell we are moving from is 0, return false
  3. If the to cell is 0, shift the value in the from cell to the to cell and erase the from cell.
  4. If the values in from and to are the same, add them, place the added value in to, and clear the from value.
  5. If the cell values are not equal and greater than zero, return false.

 

Part 5 - Move (up|right|down|left)Problem

If you play 2048, you can see that single pieces do not just move to the right when you send the “move right” command, but rather the entire board. Now that we can move pieces, the next step is to write functions that move an entire board in one direction (merging when necessary). The moveUp, moveDown, moveLeft, and moveRight functions will do this operation on the entire board, using the moveTo helper function to make moving cells more manageable.

 

Preparation

  • Think about how the board is represented in your program.
  • Think about how moveTo() can help you accomplish this task.

 

Procedure

Implement moveUp, moveDown, moveLeft, and moveRight. The procedure to move an entire board in direction X is as follows:

  1. For each cell C in a row or column (depending on move direction), beginning with the cell furthest in the direction X, move or merge that cell one space in direction X unless either:
    1. C cannot be moved due to either its value being zero or it being adjacent to a cell with a different value.
    2. C cannot be moved because it has reached the board boundary.
  2. After all moves are completed, determine if a cell was created with a higher value than the current score. If so, update the score variable with the highest value on the board.
  3. If at least one move was made, return true. Otherwise, return false.

 

Example

Note: moveX() only moves all pieces on the board at most 1 space in that direction. A single call to moveRight(), for example, will cause the following change to occur in the below example (note the order in which the merge happens, starting with the cell furthest to the right in the row, since this is a moveRight() call):

-------------------------
|    4|    4|    2|    2|
-------------------------
|     |     |     |    4|
-------------------------      
|     |     |     |     |
-------------------------
|     |     |     |     |
-------------------------

moveRight() ->

-------------------------
|     |    4|    4|    4|
-------------------------
|     |     |     |    4|
-------------------------      
|     |     |     |     |
-------------------------
|     |     |     |     |
-------------------------

If you look at the main(), main calls moveX() in a loop until it returns false to achieve the desired behavior of the game. main() is also responsible for calling placeRandom(); you should not do this in the moveX() functions. Below is an example of a complete move to the right, with a board that performs several merges while moving, calling moveRight() many times: 

Current score: 4 | Best score: 4
-------------------------
|    4|    4|    2|    2|
-------------------------
|     |     |     |    4|
-------------------------
|     |     |     |     |
-------------------------
|     |     |     |     |
-------------------------
Enter up, down, left or right to move in that direction.
Enter reset to reset the game or quit to exit.
right
Current score: 8 | Best score: 8
-------------------------
|     |     |    4|    8|
-------------------------
|     |     |     |    4|
-------------------------
|     |    2|     |     |
-------------------------
|     |     |     |     |
-------------------------
Enter up, down, left or right to move in that direction.
Enter reset to reset the game or quit to exit.

 

Hints

Remember, you can use your function moveTo and its return value to determine how an attempted move went.

 

 

import java.util.Random;
import java.util.Scanner;
public class TwentyFortyEight {
//This instance variable represents the board. Use this to make changes.
private int board;
//This variable keeps track of the current score.
private int score;
//Constructor
public TwentyFortyEight(int boardWidth){
// TODO
}
//This function resets the board to its initial state
public void reset() {
// TODO
}
//This function returns the total number of blank spaces on the board
public int numBlanks() {
// TODO
}
//This function places a 2 at a random blank space on the board.
//It does nothing if there are no blank spaces.
public void placeRandom(){
// TODO
}
//This function attempts to move a cell at coordinates fromRow,fromCol to
//the cell toRow,toCol. Refer to the handout for movement rules.
public boolean moveTo(int fromRow, int fromCol, int toRow, int toCol) {
// TODO
}
//The following four functions move the board in a single direction.
public boolean moveUp(){
// TODO
}
public boolean moveDown() {
// TODO
}
public boolean moveRight() {
// TODO
}
public boolean moveLeft() {
// TODO
}
////////////////////////////////////////////////////////////////////////
// Do not edit the methods below, they are for testing and running the
// program.
////////////////////////////////////////////////////////////////////////
public int getBoard() {
return board;
}
public void setBoard(int newBoard) {
board = newBoard;
} /**
* The main will allow you to play the game.
*
* @param args
*/
public static void main(String args) {
TwentyFortyEight tfe = new TwentyFortyEight(4);
Scanner s = new Scanner(System.in);
int bestScore = 0;
boolean resetFlag = false;
while(true) {
System.out.println("Current score: " + tfe.getScore() + " | Best
score: " + bestScore);
tfe.showBoard();
System.out.println("Enter up, down, left or right to move in that
direction.");
System.out.println("Enter reset to reset the game or quit to
exit.");
String line = s.nextLine();
switch(line){
case "up":
while(tfe.moveUp()){
// do nothing
}
break;
case "down":
while(tfe.moveDown()){
// do nothing
}
break;
case "left":
while(tfe.moveLeft()){
// do nothing
}
break;
case "right":
while(tfe.moveRight()){
// do nothing
}
break;
case "reset":
tfe.reset();
resetFlag = true;
break;
case "quit":
return;
default:
System.out.println("Invalid move, Please try again!!!!\n");
continue;
}
bestScore = Math.max(bestScore, tfe.getScore());
if(!resetFlag) {
tfe.placeRandom();
resetFlag = false;
} } } public void showBoard() {
for(int x = 0; x < boardWidth * 6 + 1; x++){
System.out.print("-");
}
System.out.println();
for(int x = 0; x < boardWidth; x++) {
for(int y = 0; y < boardWidth; y++) {
String square = (board[x][y] == 0)? "":board[x][y] + "";
System.out.printf("|%5s", square);
}
System.out.println("|");
for(int y = 0; y < boardWidth * 6 + 1; y++){
System.out.print("-");
}
System.out.println();
} } public int getScore() {
return score;
}
}

Answers

(11)
Status NEW Posted 28 Apr 2017 03:04 AM My Price 9.00

-----------

Not Rated(0)