Google
 
Site navigation: [ Home | Theory | Java | Moodle courses | Resource wiki | About ]

Chomp

This page presents an application rather than an Applet.

It is text-based and uses the IBIO Console Classes which are described in more detail in the section on JETS .

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Constants defining the board (cookie) dimensions; the characters used in the board are also defined here.

If you wanted to make the game more interesting by adding scoring characters (see below) you would probably add more character constants here.

 

 

Set up a flag (or sentinel) to indicate when the poison has been swallowed.

Basically initialise the array with chars.

The basic routines required by many games. Notice we don't attempt to keep track of whose turn it is to play.

We would need to if we wanted to develop a computer-player strategy.

output is an IBIO method (see the full code listing ).

 

 

 

 

Fill the board array with characters.

Those nested loops again.

Poke the poison into the 0, 0 spot.

 

 

 

Pretty straightforward. The System Class includes a method to "print" Strings and characters on the screen. In this case it's easier than using the IBIO output() method.

 

 

 

 

If the POISON has gone from the board, somebody must have chomped it.

 

 

This is a long method that might have been broken down further.

We get the move as a String (we are expecting 2 numbers separated by a comma as in: 3, 4).

split is a String method that splits a String into substrings at the specified separator).

Thus the move array of two elements contains the required Strings.

We try to convert the Strings to numbers, if they are not the exception is thrown and the catch block deals with it.

We don't need more checks to do this if gotMove has already been set to false .

Here we use the constants, it makes the code more reaqdily understood.

If the current board coordinate is a SPACE, then the player can't chomp it (unless it happens to be the poison square).

 

 

Once the move has been checked for suitability ( validated ), we can actually carry out the chomp process:

 

 

 

 

 

 

 

 

 

 

On this page: [ chomp, the game | applications | main program loop | methods | Exercises ]

 

About Chomp

Chomp is a game for two players, I think it was originally a Martin Gardner game but I couldn't find a reference anywhere. The game is played on a two dimensional board which represents a cookie (biscuit). The top left corner of the board or cookie is a piece of poison. Players take turns to bite (or chomp) the cookie, the one who swallows the poison loses.

Here is a sample game (with comments):


*...................
....................
....................
....................
....................
....................
....................
....................
....................
....................

Input your move (row, col): 5, 5


*...................
....................
....................
....................
....................
.....
.....
.....
.....
.....

Input your move (row, col): 20, 20

You have to chomp on the board (0,0 up to 9, 19)

Input your move (row, col): 6, 6

You can't chomp empty space!
Input your move (row, col): 1, 0

*...................









Input your move (row, col): 0,1

*









Input your move (row, col): 0,0

Game over, you lose!

The original board (or cookie)

English people from outside the US and Canada generally refer to a cookie as a biscuit.

 

 

 

 

The first payer takes a big chomp.

 

 

 

 

The next player tries to chomp beyond the limits of the game board.

Then tries to chomp an already chomped peice.

 

We're on to them either way.

 

Notice that rows and columns start at 0 (not so user friendly).

 

 

 

Ah ha! No escape for the next player.

 

 

 

 

 

Stuffed!

This may not be a very exciting game but it does at least give us a chance to look at some features of 2D arrays and text-based applications. Of course, we will also suggest some ways in which you might make it more interesting.

Back to top

Applications

Applications are different to Applets. They must have a main method of the form:

       public static void main(String[] args)
     {
     }

public means that it can be accessed from outside the Class where it is defined (as it must be, to be run).

static means that no instance of the class need be created (as we have seen with the Fraction example), so the method can be run before any instances or objects are created.

The parameter String[] args is an array of String instances which can be used to pass information to the Class. This is only really useful for utility Classes run at a command prompt (like the Windows cmd.exe application).

The simplest way to start an Application is to have the main method call the Class constructor:

      public static void main(String[] args)
     {
       new Chomp();
     }

Back to top

The Main Program Loop

The next section of code shows the start of the application code - the main class, main method and constructor:


/**
* This application implements the game of Chomp
* Originally by Martin Gardner (I think)
* But I couldn't find a reference anywhere...
*
* @author Mr J
* @version 2004024
*/

public class Chomp
{
// data members of the class
// constants values

private static final int WIDTH = 20;
private static final int HEIGHT = 10;
private static final char POISON = '*';
private static final char COOKIE = '.';
private static final char SPACE = ' ';

// board array
private char[][] board = new char[HEIGHT][WIDTH];

// Applications always start at the public static main method
// This one simply calls the following constructor method

public static void main(String[] args)
{
   new Chomp();
}
/**
* Constructor for objects of class Chomp
*/

public Chomp()
{
   // application code

   // initialisation
   boolean gameOver = false;
   setUpBoard( board );

   // main game loop
   while (!gameOver)
   {
     printBoard( board );
     getPlayerMove();
     gameOver = testGameOver();
   }
   output("Game over, you lose!\n");
}

 

 

 

Methods called by the Constructor

/**
* This method sets up the game board
*
* @param board, the game board
*/

private void setUpBoard(char[][] board)
{
   for( int row = 0; row < HEIGHT; row ++)
   {
     for(int col = 0; col < WIDTH; col++)
     {
       board[row][col] = COOKIE;
     }
    
// add in the poison square
     board[0][0] = POISON;
   }
}
/**
* This method prints the game board
*
* @param board, the game board
*/

private void printBoard(char[][] board)
{
   System.out.print('\n');
   for( int row = 0; row < HEIGHT; row ++)
   {
     for(int col = 0; col < WIDTH; col++)
     {
       System.out.print(board[row][col]);
     }
    
// print a newline at the end of each row
     System.out.print('\n');
   }
}
/**
* This method tests if the POISON has been chomped yet
*
* @return true if the game has been completed
*/

private boolean testGameOver()
{
   return (board[0][0] == SPACE);
}
/**
* This method gets, validates and processes the player's move
*/

private void getPlayerMove()
{
   String[] move = new String[2];
// used to split the coordinates
   String theMove;                
// the player's move as a String
   int r = -1;
   int c = -1;                    
// the player's moves as row column indices
   boolean gotMove;

   do
   {
     gotMove = true;
     theMove = input("Input your move (row, col): ");
     move = theMove.split(",");
     try
     {
       r = Integer.parseInt(move[0].trim());
       c = Integer.parseInt(move[1].trim());
     }
     catch(Exception e)
     {
       gotMove = false;
       output(  "Illegal input - I need 2 whole numbers "
              + "separated with a comma.\n");
     }

    
// check that the coordinates are within the cookie area
     if (gotMove)
     {
       gotMove = ( (r < HEIGHT) && (c < WIDTH) );
       if (!gotMove)
       {
         output( "You have to chomp on the board "
         + "(0,0 up to " + (HEIGHT-1) + ", " + (WIDTH-1) + ")\n)");
       }
     }

    
// check that the coordinates have not been chomped yet
     if (gotMove)
     {
       gotMove = ((board[r][c] != SPACE) || (board[r][c] == POISON));
       if (!gotMove)
       {
         output("You can't chomp empty space!\n)");
       }

     }
   }while ( !gotMove );
// repeat until the move is valid

  
// turn the board into spaces from row to HEIGHT and col to WIDTH
   for( int row = r; row < HEIGHT; row ++)
   {
     for(int col = c; col < WIDTH; col++)
     {
       board[row][col] = SPACE;
     }
   }
}

Exercises

Consider the changes that would be required to allow the player to type in 1-based coordinates instead of zero-based ones. This is probably more natural for humans. (ie the starting square would be 1, 1 not 0, 0).

Consider allowing the players to input their names so you can announce the winner. You will have to swap players on a successfully completed move.

Consider adding more objects in the cookie (maybe plus points can be allocated for currants or choccie chips and negative points for poison or bits of fluff. Now you will also have to keep score for each player too.

 

Related: [ Java home | Previous: 2D arrays | Next: More 2D arrays ]

 


 
The site is partly financed by advertising revenue, partly by online teaching activities and partly by donations. If you or your organisation feel these resouces have been useful to you, please consider a donation, $9.95 is suggested. Please report any issues with the site, such as broken links, via the feedback page, thanks.

Questions or problems related to this web site should be addressed to Richard Jones who asserts his right to be identified as the author and owner of these materials - unless otherwise indicated. Please feel free to use the material presented here and to create links to it for non-commercial purposes; an acknowledgement of the source is required by the Creative Commons licence. Use of materials from this site is conditional upon your having read the additional terms of use on the about page and the Creative Commons Licence. View privacy policy.

Creative Commons License


This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. © 2001 - 2007 Richard Jones, PO BOX 246, Cambridge, New Zealand; This page was last modified: July 29, 200823, 2008