Question

I have already finished most of this assignment. I just need some help with the canMove...

I have already finished most of this assignment. I just need some help with the canMove and main methods; pseudocode is also acceptable. Also, the programming language is java.

Crickets and Grasshoppers is a simple two player game played on a strip of n spaces. Each space can be empty or have a piece. The first player plays as the cricket pieces and the other plays as grasshoppers and the turns alternate. We’ll represent crickets as C and grasshoppers as G. Crickets start on the left side moving right and grasshoppers start on the right side moving left. Each turn, a player must move one of their pieces. A piece can either move forward one space if it is empty, or jump over one of the opponent’s pieces immediately in front of the jumping piece, landing on an empty space right after the opponent’s piece. The number of pieces never changes (pieces are never captured or added). If no move is possible for the current player, their opponent wins the game.

Begin by asking how many pieces each player has with a prompt using System.out.print like the following, with 10 as the maximally allowed number of pieces (user input shown bold and underlined):

Please enter the number of pieces for each player (1-10): two

To do this, use the promptNumberReadLine method that you will write. If the user does not type a number in the correct range, that method will prompt them in this way:

That was not a valid number! Please try again.

Please enter the number of pieces for each player (1-10): 2

Next, ask how many spaces should be in the middle in the following way with 9 as the maximum:

Please enter the number of spaces in the middle (1-9): 1

The strip of n squares consists of the specified pieces for each player on their respective ends with the given empty spaces in the middle. Before each move, display the current state of the game by printing out the result of boardToString, then ask the player which position to move (1 through n) using the promptNumberReadLine method. Please also note the error messages and re-prompting below:

During the first move, only positions 1 and 2 contain the cricket pieces (and only the piece in position 2

can be moved), but as moves are made, other positions could contain crickets, so we always include all position numbers in the prompt. Notice that the same “does not contain” error message is given if a position that can’t move is entered, whether that position contains a trapped player piece, an opponent piece, or a space. However, the “valid number” error message is given if the number was not in the correct range. The promptNumberReadLine method will only provide the second error message.

Print the prompt using System.out.print(…). If the next piece of information in the Scanner represents an integer which is at least 1 and at most max, return the number, but make sure the Scanner also reads in the rest of the line before returning. Otherwise (if the next piece of information

doesn’t represent the above requirements), read in the rest of the line, print the line

That was not a valid number! Please try again. and repeat the process described in this box. Follow these directions precisely for full points.

public static int promptNumberReadLine(Scanner s, String prompt, int max)

Create and return an array representing a new game with the number of pieces for each player indicated. The pieces should be on the ends of the board with the specified empty spaces.

public static int[] createBoard(int piecesPerPlayer, int spacesInMiddle)

Create and return a String that represents the game board, all on one line. Don’t print it! Crickets are specified with C, grasshoppers with G, and empty spaces with . (period) Hint: Use string concatenation + public static String boardToString(int[] board)

Return true if the given player has any move they can make. Cricket is player 1 and grasshopper is 2.

public static boolean canMove(int[] board, int player)

The player moves their piece in the given position (numbered 1 through n). If the specified move is allowed, modify the board and return true. Otherwise, don’t modify board and return false. Don’t print! public static boolean move(int[] board, int player, int position)

Write a main method which creates the Crickets and Grasshoppers game with the wording provided. public static void main(String[] args)

Scanner scanner = new Scanner(System.in);   
       String prompt ="Please enter the number of pieces for each player (1-10): ";
       String prompt2 ="Please enter the number of spaces in the middle (1-9): ";
       int space = promptNumberReadLine(scanner, prompt, 10);
       int space2 = promptNumberReadLine(scanner, prompt2, 9);
       int[] board = new int[space];
       int[] board2 = new int[space2];
       System.out.println(boardToString(board));
       int count = 0;
       int player = 0;
       int player2 = 0;
       String pieceP1 ="Crickets, please enter your move (1-"+space+"): ";
       String pieceP2 ="Grasshoppers, please enter your move (1-"+space+"): ";
       int win = 0;

       if(count % 2 == 0){
           player = promptNumberReadLine(scanner, pieceP1, space);
          
           while(!move(board, 1, player)){
               System.out.println("That was not a valid move! Please try again.");
               player = promptNumberReadLine(scanner, pieceP1, space);
      
           }

               System.out.println(boardToString(board));

           }
          
       else{
           player2 = promptNumberReadLine(scanner, pieceP2, space);
           player2 = promptNumberReadLine(scanner, pieceP2, space2);
      
           while(move(board, 2, player2)){
               System.out.println("That was not a valid move! Please try again.");
               player2 = promptNumberReadLine(scanner, pieceP2, space);
               System.out.println("That was not a valid move! Please try again.");
               player2 = promptNumberReadLine(scanner, pieceP2, space2);      
           }

           System.out.println(boardToString(board));
           System.out.println(boardToString(board2));

           }

       count++;

       boolean win2 = move(board, player, player2);
  
       if(win2 = false){
           System.out.println("Crickets win!");
       }
      
       else if(win2 = true){
           System.out.println("Grasshoppers win!");
       }

   }

   public static int promptNumberReadLine(Scanner s, String prompt, int max) {
      
       int num = 1;
       String next = "";

       do {

       if(num < 1 || num > max){
           System.out.println("That was not a valid number! Please try again.");   
       }
      
       System.out.print(prompt);

       while (s.hasNextInt() == false) {
           s.nextLine();
           System.out.println("That was not a valid number! Please try again.");
           System.out.print(prompt);
       }   
       next = s.nextLine();

       while(isNumber(next) == false){
           System.out.println("That was not a valid number! Please try again.");
           System.out.print(prompt);
           next = s.nextLine();
       }

       int result = Integer.parseInt(next);
       num = result;
      
       }
      
       while (num < 1 || num > max);
           return num;
   }
  
       public static boolean isNumber(String string) {
           int size = string.length();

           for (int i = 0; i < size; i++) {
              
               if (Character.isDigit(string.charAt(i)) == false) {
                   return false;
               }
           }
       return size > 0;
      
       }
      
   public static int[] createBoard(int piecesPerPlayer, int spacesInMiddle) {
           int z[] = new int [piecesPerPlayer + spacesInMiddle + piecesPerPlayer];
               return z;
   }  
  
   public static String boardToString(int[] board) {
           String line = "";

           for(int i = 0; i < board.length; i++){

                       if(board[i] == 1) {
                           line += "C";
                   }
                       if(board[i] == 0) {
                           line += ".";
                   }
                       if(board[i] == 2) {
                           line += "G";
                   }
           }
           return line;
          
       }

   public static boolean canMove(int[] board, int player) {
       return true;
   }

0 0
Add a comment Improve this question Transcribed image text
Answer #1

package game;

import java.util.Scanner;

public class CricketsAndGrasshoppers {

   // main method to run program
   public static void main(String[] args) {  
       // create a scanner object to read user input
       Scanner scanner = new Scanner(System.in);
        String promptPieces ="Please enter the number of pieces for each player (1-10): ";
        String promptSpaces ="Please enter the number of spaces in the middle (1-9): ";
        // get number of pieces for each player
        int pieces = promptNumberReadLine(scanner, promptPieces, 10);
        // get number of spaces in middle
        int spaces = promptNumberReadLine(scanner, promptSpaces, 9);
        int totalSpace = spaces + (pieces*2);
        // create a board
        int[] board = createBoard(pieces, spaces);
        String cricketMove ="Crickets, please enter your move (1-" + totalSpace + "): ";
        String grasshopperMove ="Grasshoppers, please enter your move (1-" + totalSpace + "): ";
      
        // print the board
        System.out.println(boardToString(board));  
        // play the game till some one wins
        while(true) {
           // crickets plays first turn
            // check if cricket can make move
            if(canMove(board, 1)) {
               int cricket = promptNumberReadLine(scanner, cricketMove, totalSpace);
                while(!move(board, 1, cricket)){
                   System.out.println("That was not a valid move! Please try again.");
                   cricket = promptNumberReadLine(scanner, cricketMove, totalSpace);
                }
                // print the board
                System.out.println(boardToString(board));  
            }
            else {
               // grasshoppers are winner
               System.out.println("Grasshoppers win!");
               break;
            }
          
            // next is grasshopper's turn
            // check if grasshopper can make move
            if(canMove(board, 2)) {
               int grasshopper = promptNumberReadLine(scanner, grasshopperMove, totalSpace);
                while(!move(board, 2, grasshopper)){
                   System.out.println("That was not a valid move! Please try again.");
                   grasshopper = promptNumberReadLine(scanner, grasshopperMove, totalSpace);
                }
                // print the board
                System.out.println(boardToString(board));  
            }
            else {
               // crickets are winner
               System.out.println("Crickets win!");
               break;
            }
        }
   }
     
   public static int promptNumberReadLine(Scanner s, String prompt, int max) {
       int num = 1;
        String next = "";
        do {
           if(num < 1 || num > max){
               System.out.println("That was not a valid number! Please try again.");
           }
            System.out.print(prompt);
            while (s.hasNextInt() == false) {
               s.nextLine();
               System.out.println("That was not a valid number! Please try again.");
               System.out.print(prompt);
            }
            next = s.nextLine();
            while(isNumber(next) == false){
               System.out.println("That was not a valid number! Please try again.");
               System.out.print(prompt);
               next = s.nextLine();
            }
            int result = Integer.parseInt(next);
            num = result;
        } while (num < 1 || num > max);
        return num;
   }
  
   public static boolean isNumber(String string) {
       int size = string.length();
        for (int i = 0; i < size; i++) {
           if (Character.isDigit(string.charAt(i)) == false) {
               return false;
            }
        }
        return size > 0;
   }
        
   public static int[] createBoard(int piecesPerPlayer, int spacesInMiddle) {
       int z[] = new int [piecesPerPlayer + spacesInMiddle + piecesPerPlayer];
       // also initialize board with starting position
       for(int i=0; i<piecesPerPlayer; i++) {
           z[i] = 1; // crickets are on left side
       }
       for(int i=piecesPerPlayer; i<spacesInMiddle+piecesPerPlayer; i++) {
           z[i] = 0; // empty space in middle
       }
       for(int i=piecesPerPlayer+spacesInMiddle; i<z.length; i++) {
           z[i] = 2; // grasshoppers are on left side
       }  
        return z;
   }
  
   public static String boardToString(int[] board) {
       String line = "";
        for(int i = 0; i < board.length; i++){
           if(board[i] == 1) {
               line += "C";
           }
            if(board[i] == 0) {
               line += ".";
            }
            if(board[i] == 2) {
               line += "G";
            }
        }
        return line;
   }

   public static boolean canMove(int[] board, int player) {
       // check player and move on board to see if there is any move left
       boolean hasMove = false;
       if(player == 1) {
           // look for all pieces on board
           for(int i=0; i<board.length; i++) {
               // look for player pieces on board
               if(board[i] == player) {
                   // look for empty space on right
                   if(i+1 < board.length && board[i+1] == 0) {
                       // a valid move is found
                       return true;
                   }
                   else if(i+2 < board.length && board[i+1] == 2 && board[i+2] == 0) {
                       // a valid move is found
                       return true;
                   }
               }
           }
       }
       else {
           // player == 2
           for(int i=0; i<board.length; i++) {
               // look for player pieces on board
               if(board[i] == player) {
                   // look for empty space on left
                   if(i > 0 && board[i-1] == 0) {
                       // a valid move is found
                       return true;
                   }
                   else if(i-1 > 0 && board[i-1] == 1 && board[i-2] == 0) {
                       // a valid move is found
                       return true;
                   }
               }
           }
          
       }
      
       return hasMove;
   }
  
   public static boolean move(int[] board, int player, int position) {
       // position start from 1 but array index are 0 based so remove 1 from position
       if(player == 1 && board[position-1] == player) {
           // if piece is cricket then move to right if possible
           if(position < board.length && board[position] == 0) {
               // move to empty space
               board[position] = player; // cricket moved here
               board[position-1] = 0; // cricket left from here
               return true;
           }
           else if(position+1 < board.length && board[position] == 2 && board[position+1] == 0) {
               // there is grasshopper on right side, jump over it
               board[position+1] = player; // cricket moved here
               board[position-1] = 0; // cricket left from here
               return true;
           }
           else {
               return false;
           }
       }
       else if(player == 2 && board[position-1] == player) {
           // its grasshoppers turn, move to left
           if(position-1 > 0 && board[position-2] == 0) {
               // move to empty space
               board[position-2] = player; // grasshoppers moved here
               board[position-1] = 0; // grasshoppers left from here
               return true;
           }
           else if(position-2 > 0 && board[position-2] == 1 && board[position-3] == 0) {
               // there is cricket on left side, jump over it
               board[position-3] = player; // grasshoppers moved here
               board[position-1] = 0; // grasshoppers left from here
               return true;
           }
           else {
               return false;
           }
       }
       return false;
   }

}

let me know if you have any problem or doubts. thank you.

Add a comment
Know the answer?
Add Answer to:
I have already finished most of this assignment. I just need some help with the canMove...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Need help debugging. first class seems fine. second class is shooting an error on s =...

    Need help debugging. first class seems fine. second class is shooting an error on s = super.getString(prompt);   third class is giving me an error in the while loop where int num = console.getInt("Enter an integer:"); //-------------------------------------------------------------------------- import java.util.Scanner; public class Console {     private Scanner sc;     boolean isValid;     int i;     double d;        public Console()     {         sc = new Scanner(System.in);     }     public String getString(String prompt)     {         System.out.print(prompt);         return sc.nextLine();...

  • I need help with this method (public static int computer_move(int board[][])) . When I run it...

    I need help with this method (public static int computer_move(int board[][])) . When I run it and play the compute.The computer enters the 'O' in a location that the user has all ready enter it sometimes. I need to fix it where the computer enters the 'O' in a location the user has not enter the "X' already package tictactoe; import java.util.Scanner; public class TicTacToeGame { static final int EMPTY = 0; static final int NONE = 0; static final...

  • How would I code this method in Java using a scanner? Begin by asking how many...

    How would I code this method in Java using a scanner? Begin by asking how many spaces the row should be with a prompt using System.out.print like the following, with 40 as the maximally allowed number of spaces: (user input shown bold) Please enter the number of spaces for the game (1-40): eight To do this, use the promptNumberReadLine method that you will write, described on the back page. If the user does not type a number in the correct...

  • This is my code for my game called Reversi, I need to you to make the...

    This is my code for my game called Reversi, I need to you to make the Tester program that will run and complete the game. Below is my code, please add comments and Javadoc. Thank you. public class Cell { // Displays 'B' for the black disk player. public static final char BLACK = 'B'; // Displays 'W' for the white disk player. public static final char WHITE = 'W'; // Displays '*' for the possible moves available. public static...

  • Project 7-3 Guessing Game import java.util.Scanner; public class GuessNumberApp {    public static void main(String[] args)...

    Project 7-3 Guessing Game import java.util.Scanner; public class GuessNumberApp {    public static void main(String[] args) { displayWelcomeMessage(); // create the Scanner object Scanner sc = new Scanner(System.in); String choice = "y"; while (choice.equalsIgnoreCase("y")) { // generate the random number and invite user to guess it int number = getRandomNumber(); displayPleaseGuessMessage(); // continue until the user guesses the number int guessNumber = 0; int counter = 1; while (guessNumber != number) { // get a valid int from user guessNumber...

  • Help check why the exception exist do some change but be sure to use the printwriter...

    Help check why the exception exist do some change but be sure to use the printwriter and scanner and make the code more readability Input.txt format like this: Joe sam, thd, 9, 4, 20 import java.io.File; import java.io.PrintWriter; import java.io.IOException; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; public class Main1 { private static final Scanner scan = new Scanner(System.in); private static String[] player = new String[622]; private static String DATA = " "; private static int COUNTS = 0; public static...

  • JAVA TIC TAC TOE - please help me correct my code Write a program that will...

    JAVA TIC TAC TOE - please help me correct my code Write a program that will allow two players to play a game of TIC TAC TOE. When the program starts, it will display a tic tac toe board as below |    1       |   2        |   3 |    4       |   5        |   6                 |    7      |   8        |   9 The program will assign X to Player 1, and O to Player    The program will ask Player 1, to...

  • Hi I need help with a java program that I need to create a Airline Reservation...

    Hi I need help with a java program that I need to create a Airline Reservation System I already finish it but it doesnt work can someone please help me I would be delighted it doesnt show the available seats when running the program and I need it to run until someone says no for booking a seat and if they want to cancel a seat it should ask the user to cancel a seat or continue booking also it...

  • You are going to write a method (to be called validateBoard) that is going to validate...

    You are going to write a method (to be called validateBoard) that is going to validate whether or not a Tic-Tac-Toe board is possible. Tic- Tac-Toe is played on a 3 x 3 board and players take turns placing either an x or an o on the board. We will assume that in Tic-Tac-Toe the player placing x will go first arld that o will go second. (Learn more about the game here) As the player placing x pieces goes...

  • I need to create a code for this prompt: In this project we will build a...

    I need to create a code for this prompt: In this project we will build a generic UserInput class for getting keyboard input from the user. Implementation: The class UserInput is a 'Methods only' class, and all the methods should be declared static. Look at the TestScanner.java program at the bottom of this page that inputs a string, int and double. It shows you how to use Scanner class to get input from the keyboard. Write FOUR simple methods, one...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT