Question

In: Computer Science

Step 1: Player Variable Declaration and Initialization Part A: In the Player class, declare two class...

Step 1: Player Variable Declaration and Initialization

Part A:

In the Player class, declare two class variables, map and guess that are two dimensional arrays of ints.

Part B:

In the constructor of the Player class, initialize the map and guess arrays with the appropriate size:

  • map: 10 by 10 (10 outer arrays with 10 elements each)
  • guess: 5 by 2 (5 outer arrays with 2 elements each)

Step 2: Player.readPlayerSheet() Part A

The readPlayerSheet method in the Player class is parsing through the player’s file sheet to initialize the map and guess arrays for that object.

In the readPlayerSheet method of the Player class, use two nested for loops to iterate through the size of the map array. Each element of the map array should be assigned the value of the next int from the scanner.

Step 3: Player.readPlayerSheet() Part B

After your code from Step 2, and after the scnr.nextLine(), read the next line from the player’s file.

Then, parse through that line to initialize the appropriate values in the guess array.

Review the file format shown above to understand what line you’re working with, and think back to previous labs and methods like parseInt, substring, and indexOf to parse the guesses.

For example, if we were to include a line of guesses in a player file like this:

1-2 9-5 4-5 3-6 5-9

Our array would look like this after parsing through the values in the readPlayerSheet method: [[1,2],[9,5],[4,5],[3,6],[5,9]]

Step 4: Game.mapToString()

Complete the method mapToString() in the Game class. This method takes a two dimensional array of ints as a parameter, and returns that result as a string.

Each element in an inner array should be separated by a space, and each inner array should be separated by a new line. The last inner array should also be followed by a new line.

You will be using a StringBuilder to concatenate the array elements into a single string and return it at the end.

Step 5: Game.compareMapToGuess()

Write a method called compareMapToGuess in the Game class that has the following characteristics:

  • takes two parameters, both two dimensional int arrays, with one that represents a map and one that represents a guess
  • returns an int
  • returns the number of guesses that successfully “hit” the opponent’s ship (the coordinates of the guess match a 1 in the same location on the map)

Hint: Consider iterating through the guesses, and extracting the row and column from the array to see if they are a “hit” in the map.

public class Game {

static Player player1;

static Player player2;

Game(String file1, String file2){

player1 = new Player(file1);

player2 = new Player(file2);

}

public void tallyScores() {

player1.score = compareMapToGuess(player2.map, player1.guess);

player2.score = compareMapToGuess(player1.map, player2.guess);

}

// Step 5: compareMapToGuess method

// Step 4: mapToString method

public String mapToString(int[][] arr) {

StringBuilder result = new StringBuilder();

return result.toString();

}

public String gameResults() {

StringBuilder result = new StringBuilder("Player 1's Board:\n");

result.append(mapToString(player1.map));

result.append("\nPlayer 2's Board:\n");

result.append(mapToString(player2.map));

result.append("Player 1 Score: " + player1.score + "\tPlayer 2 Score: " + player2.score + "\n");

String winner;

if(player1.score > player2.score) winner = "Player 1";

else if(player1.score < player2.score) winner = "Player 2";

else winner = "It's a tie!";

result.append("Winner: " + winner);

return result.toString();

}

public static void main(String [] args) {

}

}

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Player {
// Step 1 Part A: declare map and guess arrays
// student code here
int score;

Player(String filename){
// Step 1 Part B: initialize map and guess arrays
// student code here
score = 0;
readPlayerSheet(filename);
}

public void readPlayerSheet(String filename) {
try {
Scanner scnr = new Scanner(new File(filename));

// Step 2: fill map array
// student code here

// this discards the next line in the file, since there is an empty line between the player's map and the player's guess
scnr.nextLine();

// Step 3: parse guesses from guessStr and fill guess array
String guessStr = scnr.nextLine();

scnr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

map1 :

0 0 0 0 0 0 1 1 1 1

0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0

0 1 0 0 1 0 0 0 0 0

0 1 0 0 1 0 0 0 0 0

0 1 0 0 1 0 0 0 0 0

0 1 0 0 1 0 0 0 0 1

0 0 0 0 0 0 0 0 0 1

0 0 0 0 0 0 0 0 0 1

0 0 0 1 1 1 1 0 0 1

1-2 9-8 4-5 3-6 0-0

map2 :

1 0 0 0 0 0 0 0 0 0

1 0 0 0 0 0 0 0 0 0

1 0 0 0 0 1 1 1 1 0

1 0 0 0 0 0 0 0 0 0

0 0 0 1 0 0 0 0 0 0

0 0 0 1 0 0 1 1 1 1

0 0 0 1 0 0 0 0 0 0

0 0 0 1 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 1 1 1 1 0

0-8 9-2 3-5 4-6 2-9

Solutions

Expert Solution

ANSWER:

I have provided the properly commented and indented code so you can easily copy the code as well as check for correct indentation.
I have provided the output image of the code so you can easily cross-check for the correct output of the code.
Have a nice and healthy day!!

CODE

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

class Player {
    // Step 1 Part A: declare map and guess arrays
    // student code here
    int score;
    // map guess decleration
    int[][] map;
    int[][] guess;

    Player(String filename){
        // Step 1 Part B: initialize map and guess arrays
        // student code here
        score = 0;
        map = new int[10][10];
        guess = new int[5][2];
        // reading playersheet
        readPlayerSheet(filename);
        
        
    }
    
    public void readPlayerSheet(String filename) {
        try {
            Scanner scnr = new Scanner(new File(filename));
            
            // Step 2: fill map array
            // student code here
            for(int i=0;i<10;i++){
              for(int j=0;j<10;j++){
                int readInt = scnr.nextInt();
                map[i][j] = readInt;
              }
            }
            
            
            // this discards the next line in the file, since there is an empty line between the player's map and the player's guess
            scnr.nextLine();
            
            // Step 3: parse guesses from guessStr and fill guess array
            String guessStr = scnr.nextLine();
            // spliting guessStr by spaces
            String[] locs = guessStr.split(" ");
            // looping for each locs 
            for(int i=0;i<5;i++){
              // spliting locs[i] by - 
              String[] loc = locs[i].split("-");
              // looping for each loc and storing as int in guesses 
              for(int j=0;j<2;j++){
                int temp = Integer.parseInt(loc[j]);
                // storing in guesses 
                guess[i][j] = temp;
              }
            }
            
            scnr.close();
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            
        }
        
    }
}

public class Game {
    static Player player1;
    static Player player2;
    Game(String file1, String file2){
        player1 = new Player(file1);
        player2 = new Player(file2);
        
    }
    
    public void tallyScores() {
        player1.score = compareMapToGuess(player2.map, player1.guess);
        player2.score = compareMapToGuess(player1.map, player2.guess);
        int i;
    }
    
    
    // Step 4: mapToString method
    
    public String mapToString(int[][] arr) {
        StringBuilder result = new StringBuilder();
        // looping for array in row
        for(int i=0;i<arr.length;i++){
          // looping to inner array 
          for(int j=0;j<arr[i].length;j++){
            // appending value to result + space 
            result.append(arr[i][j]+" ");
          }
          // appending newline to result 
          result.append("\n");
        }
        return result.toString();
        
    }
    // Step 5: compareMapToGuess method
    public int compareMapToGuess(int[][] map,int[][] guess){
      // defining result count
      int result = 0;

      // looping through each guess
      for(int i=0;i<guess.length;i++){
        // if location value at map is 1 incrementing result 
        if(map[guess[i][0]][guess[i][1]]==1){
          result += 1;
        }
      }

      // return result 
      return result;
    }

    
    public String gameResults() {
        tallyScores();
        StringBuilder result = new StringBuilder("Player 1's Board:\n");
        result.append(mapToString(player1.map));
        result.append("\nPlayer 2's Board:\n");
        result.append(mapToString(player2.map));
        result.append("Player 1 Score: " + player1.score + "\tPlayer 2 Score: " + player2.score + "\n");
        
        String winner;
        
        if(player1.score > player2.score) 
            winner = "Player 1";
        else if(player1.score < player2.score)
            winner = "Player 2";
        
        else
            winner = "It's a tie!";
            
        result.append("Winner: " + winner);
        
        return result.toString();
        
    }
    
    public static void main(String [] args) {
        Game g = new Game("players1.txt", "players2.txt");
        String result= g.gameResults();
        // display result 
        System.out.println(result);
    }

}

OUTPUT IMAGE


Related Solutions

How does one declare a class variable in C#?
How does one declare a class variable in C#?
Questions: 1) // declare integer variable sum equal to zero // declare variable integer i //...
Questions: 1) // declare integer variable sum equal to zero // declare variable integer i // declare while loop condition where i is less then 25 // inside of brackets calculate the sum of i (addition) // increment i // outside the loop print the sum of values ============================================= 2) Create a sentinel value example if I press number 0 it will display the sum of data // create a scanner // prompt the user to to enter the numbers...
Rewrite your program for part 1. Do not declare the array globally, declare it in the...
Rewrite your program for part 1. Do not declare the array globally, declare it in the loop function. This now requires that you add two parameters to your fill array and print array functions. You must now pass the array name and array size as arguments, when the program calls these functions. The program has the same behavior as problem 1, but illustrates the difference between globally and locally declared variables. The program code for part 1 was: int Array[15]...
Never declare a C++ global variable in this class. But global constants are ok. unsigned Size1...
Never declare a C++ global variable in this class. But global constants are ok. unsigned Size1 = 100; // never do this at global scope const unsigned Size2 = 120; // this is ok (but probably not very helpful) Don't use the string class and don't use system functions for math (like pow) or strings (like strlen). These functions are meant to be short and simple; if you're writing something long and complicated, look for a simpler solution. void countdown(...
1. Declare/define the variable/constant as indicated: a. a variable to store the grade for a student...
1. Declare/define the variable/constant as indicated: a. a variable to store the grade for a student (as whole number) b. a variable to store a letter grade for a course, like A, B, or C c. a variable to store an average for a student (may have decimal places) d. a variable to represent if a student passed the course or not, with a value of TRUE or FALSE e. a constant to represent the passing grade of 65 2....
swift language declare a Swift array variable that can hold instances of any class type
swift language declare a Swift array variable that can hold instances of any class type
(1) Create three files to submit. ContactNode.h - Class declaration ContactNode.cpp - Class definition main.cpp -...
(1) Create three files to submit. ContactNode.h - Class declaration ContactNode.cpp - Class definition main.cpp - main() function (2) Build the ContactNode class per the following specifications: Parameterized constructor. Parameters are name followed by phone number. Public member functions InsertAfter() (2 pts) GetName() - Accessor (1 pt) GetPhoneNumber - Accessor (1 pt) GetNext() - Accessor (1 pt) PrintContactNode() Private data members string contactName string contactPhoneNum ContactNode* nextNodePtr Ex. of PrintContactNode() output: Name: Roxanne Hughes Phone number: 443-555-2864 (3) In main(),...
(1) Create three files to submit: ItemToPurchase.h - Class declaration ItemToPurchase.cpp - Class definition main.cpp -...
(1) Create three files to submit: ItemToPurchase.h - Class declaration ItemToPurchase.cpp - Class definition main.cpp - main() function Build the ItemToPurchase class with the following specifications: Default constructor Public class functions (mutators & accessors) SetName() & GetName() (2 pts) SetPrice() & GetPrice() (2 pts) SetQuantity() & GetQuantity() (2 pts) Private data members string itemName - Initialized in default constructor to "none" int itemPrice - Initialized in default constructor to 0 int itemQuantity - Initialized in default constructor to 0 (2)...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the following variables: an instance variable that describes the title - String an instance variable that describes the ISBN - String an instance variable that describes the publisher - String an instance variable that describes the price - double an instance variable that describes the year – integer Provide a toString() method that returns the information stored in the above variables. Create the getter and...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the following variables: an instance variable that describes the title - String an instance variable that describes the ISBN - String an instance variable that describes the publisher - String an instance variable that describes the price - double an instance variable that describes the year – integer Provide a toString() method that returns the information stored in the above variables. Create the getter and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT