Current Position:Home > I'm writing a mazerace game...I need help from a Java Pro regarding GUI

I'm writing a mazerace game...I need help from a Java Pro regarding GUI

Update:10-11Source: network consolidation
Advertisement
I've tested my code using a textUI, but not successful with GUI.
Following are the files I have at present but are incomplete...someone please assist me, let me know what I'm missing to run the program successfully in a window.
All I need to do is to bring the maze (2D array) onto a window, and listen to the keys (A,S,D,W & J,K,L,I) and make the move accordingly (using the move method in the MazeRace Class)
This is my class - MazeRace
import javax.swing.*;
import java.io.*;
* This class is responsible for:
* -Initializes instance variables used to store the current state of the game
* -When a player moves it checks if the move is legal
* and updates the state of the game if move is allowable and made
* -Reports information about current state of the game when asked:
* o whether game has been won
* o how many moves have been made by a given player
* o what is the current configuration of the maze, etc.
public class MazeRace {
/** The Maze Race layout */
private static char[][] mazeLayout;
/** Dimensions of the maze */
//private static final int rowLength = mazeLayout.length;
//private static final int columnLength = mazeLayout[0].length;
/** space in the grid is a wall */
private static final char wall = 'X';
/** space in the grid has been used */
private static final char spaceUsed = '.';
/** space in the grid is available */
private static final char spaceAvailable = ' ';
/** Character for Charles, Ada & Goal*/
private static final char CHARLES = 'C';
private static final char ADA = 'A';
private static final char GOAL = 'G';
/** Location of Goal in the Maze */
private static int rowGoal = 0;
private static int columnGoal = 0;
/** Location of Ada in the Maze */
private static int rowAda = 0;
private static int columnAda = 0;
/** Location of Charles in the Maze */
private static int rowCharles = 0;
private static int columnCharles = 0;
/** Number of Ada's moves */
private static int countAdasMoves = 0;
/** Number of Charles's moves */
private static int countCharlesMoves = 0;
* Constructor for MazeRace
* &param mazeGrid - 2D array of characters
public MazeRace(char[][] mazeGrid){
this.mazeLayout = mazeGrid;
for (int row = 0; row < mazeLayout.length; row++){
for (int column = 0; column < mazeLayout[0].length; column++){
if (mazeLayout[row][column] == GOAL){
this.rowGoal = row;
this.columnGoal = column;
if (mazeLayout[row][column] == ADA){
this.rowAda = row;
this.columnAda = column;
if (mazeLayout[row][column] == CHARLES){
this.rowCharles = row;
this.columnCharles = column;
public boolean canMoveLeft(){
int rowA = this.rowAda;
int columnA = this.columnAda;
int rowC = this.rowCharles;
int columnC = this.rowCharles;
boolean canMove = false;
if (mazeLayout[rowA][columnA - 1] == spaceAvailable
|| mazeLayout[rowA][columnA - 1] == GOAL) {
canMove = true;
return canMove;
* This method takes in a single character value that indicates
* both the player making the move, and which direction the move is in.
* If move is legal, the player's position will be updated. Move is legal
* if player can move one space in that direction i.e. the player isn't
* moving out of the maze, into a wall or a space has already been used.
* @param moveDirection: indicates the player making the move and direction
* @return moveMade: boolean value true if move was made, false otherwise
public boolean move(char move){
boolean validMove = false;
/** store Ada's current row location in a temp variable */
int rowA = this.rowAda;
/** store Ada's current column location in a temp variable */
int columnA = this.columnAda;
/** store Charles current row location in a temp variable */
int rowC = this.rowCharles;
/** store Charles current column location in a temp variable */
int columnC = this.columnCharles;
/** if Ada is moving left, check if she can make a move */
if (move == 'A' && (mazeLayout[rowA][columnA - 1] == spaceAvailable
|| mazeLayout[rowA][columnA - 1] == GOAL)) {
/** if move is legal, then update old space to spaceUsed '.' */
mazeLayout[rowA][columnA] = spaceUsed;
/** update Ada's new position */
mazeLayout[rowA][columnA - 1] = ADA;
this.rowAda = rowA; //update new row location of Ada
this.columnAda = columnA - 1; //update new column location of Ada
validMove = true; //valid move has been made
countAdasMoves++; //increment Ada's legal move
/** if Ada is moving down, then check if she can make the move */
if (move == 'S'&& (mazeLayout[rowA + 1][columnA] == spaceAvailable
|| mazeLayout[rowA + 1][columnA] == GOAL)) {
mazeLayout[rowA][columnA] = spaceUsed;
mazeLayout[rowA + 1][columnA] = ADA;
this.rowAda = rowA + 1;
this.columnAda = columnA;
validMove = true;
countAdasMoves++;
/** if Ada is moving right, then check if she can make the move */
if (move == 'D'&& (mazeLayout[rowA][columnA + 1] == spaceAvailable
|| mazeLayout[rowA][columnA + 1] == GOAL)) {
mazeLayout[rowA][columnA] = spaceUsed;
mazeLayout[rowA][columnA + 1] = ADA;
this.rowAda = rowA;
this.columnAda = columnA + 1;
validMove = true;
countAdasMoves++;
/** if Ada is moving up, then check if she can make the move */
if (move == 'W'&& (mazeLayout[rowA - 1][columnA] == spaceAvailable
|| mazeLayout[rowA - 1][columnA] == GOAL)) {
mazeLayout[rowA][columnA] = spaceUsed;
mazeLayout[rowA - 1][columnA] = ADA;
this.rowAda = rowA - 1;
this.columnAda = columnA;
validMove = true;
countAdasMoves++;
/** if Charles is moving left, then check if he can make the move */
if (move == 'J'&& (mazeLayout[rowC][columnC - 1] == spaceAvailable
|| mazeLayout[rowC][columnC - 1] == GOAL)) {
mazeLayout[rowC][columnC] = spaceUsed;
mazeLayout[rowC][columnC -1] = CHARLES;
this.rowCharles = rowC;
this.columnCharles = columnC - 1;
validMove = true;
countCharlesMoves++;
/** if Charles is moving down, then check if he can make the move */
if (move == 'K'&& (mazeLayout[rowC + 1][columnC] == spaceAvailable
|| mazeLayout[rowC + 1][columnC] == GOAL)) {
mazeLayout[rowC][columnC] = spaceUsed;
mazeLayout[rowC + 1][columnC] = CHARLES;
this.rowCharles = rowC + 1;
this.columnCharles = columnC;
validMove = true;
countCharlesMoves++;
/** if Charles is moving right, then check if he can make the move */
if (move == 'L'&& (mazeLayout[rowC][columnC + 1] == spaceAvailable
|| mazeLayout[rowC][columnC + 1] == GOAL)) {
mazeLayout[rowC][columnC] = spaceUsed;
mazeLayout[rowC][columnC + 1] = CHARLES;
this.rowCharles = rowC;
this.columnCharles = columnC + 1;
validMove = true;
countCharlesMoves++;
/** if Charles is moving up, then check if he can make the move */
if (move == 'I'&& (mazeLayout[rowC - 1][columnC] == spaceAvailable
|| mazeLayout[rowC - 1][columnC] == GOAL)){
mazeLayout[rowC][columnC] = spaceUsed;
mazeLayout[rowC - 1][columnC] = CHARLES;
this.rowCharles = rowC - 1;
this.columnCharles = columnC;
validMove = true;
countCharlesMoves++;
return validMove;
* This method indicates whether the current maze configuration is a winning
* configuration for either player or not.
* Return 1 if Ada won
* Return 2 if Charles won
* Return 0 if neither won
* @return int won: Indicates who won the game (1 or 2) or no one won the
* game (0)
public static int hasWon() {
int won = 0;
/** if location of Goal's row and column equals Ada's then she won */
if (rowGoal == rowAda && columnGoal == columnAda){
won = 1;
/** if location of Goal's row and column equals Charles's then he won */
if (rowGoal == rowCharles && columnGoal == columnCharles){
won = 2;
/** if both players are away from the Goal then no one won */
if ((rowGoal != rowAda && columnGoal != columnAda) &&
(rowGoal != rowCharles && columnGoal != columnCharles)) {
won = 0;
return won;
* This method indicates whether in the current maze configuration both
* players are caught in dead ends.
* @return deadEnd: boolean value true if both players can't make a valid
* move, false otherwise
public static boolean isBlocked(){
boolean deadEnd = false;
/** Check if Ada & Charles are blocked */
if (((mazeLayout[rowAda][columnAda - 1] == wall
|| mazeLayout[rowAda][columnAda - 1] == spaceUsed
|| mazeLayout[rowAda][columnAda - 1] == CHARLES)
&& (mazeLayout[rowAda][columnAda + 1] == wall
|| mazeLayout[rowAda][columnAda + 1] == spaceUsed
|| mazeLayout[rowAda][columnAda + 1] == CHARLES)
&& (mazeLayout[rowAda + 1][columnAda] == wall
|| mazeLayout[rowAda + 1][columnAda] == spaceUsed
|| mazeLayout[rowAda + 1][columnAda] == CHARLES)
&& (mazeLayout[rowAda - 1][columnAda] == wall
|| mazeLayout[rowAda - 1][columnAda] == spaceUsed
|| mazeLayout[rowAda - 1][columnAda] == CHARLES))
&& ((mazeLayout[rowCharles][columnCharles - 1] == wall
|| mazeLayout[rowCharles][columnCharles - 1] == spaceUsed
|| mazeLayout[rowCharles][columnCharles - 1] == ADA)
&& (mazeLayout[rowCharles][columnCharles + 1] == wall
|| mazeLayout[rowCharles][columnCharles + 1] == spaceUsed
|| mazeLayout[rowCharles][columnCharles + 1] == ADA)
&& (mazeLayout[rowCharles + 1][columnCharles] == wall
|| mazeLayout[rowCharles + 1][columnCharles] == spaceUsed
|| mazeLayout[rowCharles + 1][columnCharles] == ADA)
&& (mazeLayout[rowCharles - 1][columnCharles] == wall
|| mazeLayout[rowCharles - 1][columnCharles] == spaceUsed
|| mazeLayout[rowCharles - 1][columnCharles] == ADA))) {
deadEnd = true;
return deadEnd;
* This method returns an integer that represents the number of moves Ada
* has made so far. Only legal moves are counted.
* @return int numberOfAdasMoves: number of moves Ada has made so far
public static int numAdaMoves() {
return countAdasMoves;
* This method returns an integer that represents the number of moves Charles
* has made so far. Only legal moves are counted.
* @return int numberOfCharlesMoves: number of moves Charles has made so far
public static int numCharlesMoves() {
return countCharlesMoves;
* This method returns a 2D array of characters that represents the current
* configuration of the maze
* @return mazeLayout: 2D array that represents the current configuration
* of the maze
public static char[][] getGrid() {
return mazeLayout;
* This method compares contents of this MazeRace object to given MazeRace.
* The two will not match if:
* o the two grids have different dimensions
* o the two grids have the same dimensios but positions of walls, players or
* goal differs.
* @param MazeRace: MazeRace object is passed in and compared with the given
* MazeRace grid
* @return boolean mazeEqual: true if both grids are same, false otherwise
public static boolean equals(char[][] mr) {
boolean mazeEqual = true;
/** If the length of the arrays differs, then they are not equal */
if (mr.length != mazeLayout.length || mr[0].length != mazeLayout[0].length){
mazeEqual = false;
} else {
/** If lengths are same, then compare every element of the array to other */
int count = 0;
int row = 0;
int column = 0;
while( count < mr.length && mazeEqual) {
if( mr[row][column] != mazeLayout[row][column]) {
mazeEqual = false;
count = count + 1;
row = row + 1;
column = column + 1;
return mazeEqual;
* This method represents the current state of the maze in a string form
* @return string mazeString: string representation of the maze configuration
public String toString() {
String mazeString = "";
for (int row = 0; row < mazeLayout.length; row++){
for (int column = 0; column < mazeLayout[0].length; column++){
mazeString = mazeString + mazeLayout[row][column];
mazeString = mazeString + "\n";
return mazeString.trim();
The following is the Driver class: MazeRaceDriver
import javax.swing.*;
import java.io.*;
* This class is the starting point for the maze race game. It is invoked
* from the command line, along with the location of the layout file and
* the desired interface type. Its main purpose is to initialize the
* components needed for the game and the specified interface.
public class MazeRaceDriver {
* A method that takes a text file representation of the maze and
* produces a 2D array of characters to represent the same maze.
* @param layoutFileName location of the file with the maze layout
* @return The maze layout.
public static char[][] getLayoutFromFile( String layoutFileName )
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(layoutFileName));
String s = br.readLine();
int r = 0; // start at row 1
int c = s.length(); // initialize column to the length of the string
while(s != null){
r++;
s = br.readLine();
char[][]grid = new char[r][c];
// this part, gets the text file into a char array
BufferedReader brr = new BufferedReader(new FileReader(layoutFileName));
String ss = brr.readLine();
int row = 0;
while(ss != null){
for(int col = 0; col < c; col++){
grid[row][col] = ss.charAt(col);
row++;
ss = brr.readLine();
return grid;
* The main method of your program.
* @param args command-line arguments provided by the user
public static void main( String[] args ) throws IOException {
// check for too few or too many command line arguments
if ( args.length != 2 ) {
System.out.println( "Usage: " +
"java MazeRaceDriver <location> <interface type>" );
return;
if ( args[1].toLowerCase().equals( "text" ) ) {
char[][] layout = getLayoutFromFile( args[0] );
MazeRace maze = new MazeRace( layout );
MazeRaceTextUI game = new MazeRaceTextUI( maze );
game.startGame();
else if ( args[1].toLowerCase().equals( "gui" ) ) {
// Get the filename using a JFileChooser
// read the layout from the file
// starting the window-based maze game
JFileChooser chooser = new JFileChooser("");
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
BufferedReader br =
new BufferedReader(new FileReader(chooser.getSelectedFile()));
String inputLine = br.readLine();
while (inputLine != null) {
System.out.println(inputLine);
inputLine = br.readLine();
char[][] layout = getLayoutFromFile( args[0] );
MazeRace maze = new MazeRace( layout );
MazeRaceWindow game = new MazeRaceWindow( maze );
game.startGame();
} else {
System.out.println("Cancel was selected");
} else {
System.out.println( "Invalid interface for game." +
" Please use either TEXT or GUI." );
return;
The following is the MazeRaceWindow class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
* This class is responsible for displaying the maze race game. It should
* set up the maze window when the game is started and update the display
* with each move.
public class MazeRaceWindow extends JFrame {
private JLabel[][] mazeLabel;
private JFrame mazeFrame;
* Reference to the underlying MazeRace object which needs to be
* updated when either player moves
private MazeRace maze;
* Class constructor for the GUI object
* @param maze the underlying MazeRace object
public MazeRaceWindow( MazeRace maze ) {
this.maze = maze;
System.out.println(maze);
mazeFrame = new JFrame();
mazeFrame.setSize(200,200);
Container content = mazeFrame.getContentPane();
System.out.println(content);
content.setLayout(new GridLayout(.length, mazeLayout[0].Length));
for (int i = 0; i < MazeRace.length; i++ ) {
for (int j = 0; j < MazeRace[0].length; j++ ) {
mazeLabel = new JLabel[MazeRace.rowLength][MazeRace.columnLength];
content.add(mazeLabel[i][j]);
System.out.println(mazeLabel[i][j]);
mazeFrame.pack();
mazeFrame.setVisible(true);
//content.add(mazeLabel);
//mazeFrame.addKeyListener(this);
* A method to be called to get the game running.
public void startGame() throws IOException {
System.out.println();
/* loop to continue to accept moves as long as there is at least one
* player able to move and no one has won yet
while ( !maze.isBlocked() && maze.hasWon() == 0 ) {
// prints out current state of maze
System.out.println( maze.toString() );
System.out.println();
// gets next move from players
System.out.println("Next move?");
System.out.print("> ");
BufferedReader buffer =
new BufferedReader( new InputStreamReader( System.in ) );
String moveText = "";
moveText = buffer.readLine();
System.out.println();
// note that even if a string of more than one character is entered,
// only the first character is used
if ( moveText.length() >= 1 ) {
char move = moveText.charAt( 0 );
boolean validMove = maze.move( move );
// The game has finished, so we output the final state of the maze, and
// a message describing the outcome.
System.out.println( maze );
int status = maze.hasWon();
if ( status == 1 ) {
System.out.println( "Congratulations Ada! You won the maze in "
+ maze.numAdaMoves() + " moves!" );
} else if ( status == 2 ) {
System.out.println( "Congratulations Charles! You won the maze in "
+ maze.numCharlesMoves() + " moves!" );
} else {
System.out.println( "Stalemate! Both players are stuck. "
+ "Better luck next time." );
The following is the Listener class: MazeRaceListener
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
/** Listens for keystrokes from the GUI interface to the MazeRace game. */
public class MazeRaceListener extends KeyAdapter {
* Reference to the underlying MazeRace object which needs to be updated
* when either player moves
private MazeRace maze;
* Reference to the MazeRaceWindow object that displays the state of
* the game
private MazeRaceWindow mazeWindow;
* Class constructor for the key listener object
* @param maze the underlying MazeRace object
public MazeRaceListener( MazeRace maze ) {
this.maze = maze;
* A method that sets which JFrame will display the game and need to be
* updated with each move.
* @param window the JFrame object that displays the state of the game
public void setMazeRaceWindow( MazeRaceWindow window ) {
mazeWindow = window;
* A method that will be called each time a key is pressed on the active
* game display JFrame.
* @param event contains the pertinent information about the keyboard
* event
public void keyTyped( KeyEvent event ) {
char move = event.getKeyChar();
// TODO: complete method so that the appropriate action is taken
// in the game
//mazeLabel.setText(String.valueOf(move).toUpperCase());
}

The Best Answer

Advertisement
and listen to the keys (A,S,D,W & J,K,L,I) and make the move accordingly [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings
  • I'm writing a mazerace game...I need help from a Java Pro regarding GUI Update:10-11

    I've tested my code using a textUI, but not successful with GUI. Following are the files I have at present but are incomplete...someone please assist me, let me know what I'm missing to run the program successfully in a window. All I need to do is to

  • HOWTO: Writing Out XML Query Results of Any Size in Java with XML SQL Utility Update:11-30

    A customer mailed me asking for an example of how to use our XML SQL Utility to write out query results for tons of query result rows. With tons of data, the getXMLDOM() and getXMLString() methods are not really appropriate due to the size. The XML S

  • Writing Contents Of TreeSet To File Update:11-30

    I am still a student of Java, so forgive me for the elementary question. Is it possible to write the contents of a TreeSet to a File? I would also like to be able to save the TreeSet in binary form instead of having it disappear when the program is c

  • Please help me in writing .jad file Update:11-30

    Hi friends, i am getting some problem in writing .jad file in J2ME. by now i created .java file from .java -> .class -> preverifying, o/p -> .class ->.jar files -> finally i need to create .jad i am trying to create a midlet. if you know so

  • Code for JProgressbar for monitoring  while writing into a files Update:11-30

    Could anybody help me in sample code to implement a JProgressbar while writing into a file.import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.lang.reflect.*; // for InvocationTargetException public class Test extends JApple

  • Optimizing writing time Update:11-30

    Hi experts, My program is writing data into a text file. My algorithm is. 1>Create a cursor to select proper rows to be written in the file. 2> open it. 3> for each row received from the database concatinate them all into one single variable. 4&g

  • Socket writing error Update:11-30

    Hi, I'm getting an OutputStream from a socket and I'm writing bytes in it, but i often have a java.net.SocketException with the message: socket write error (code=10053) Does anybody know where i can find the description of that error code. Thanks a l

  • Comments - writing good comments Update:11-30

    Is there a set of guidelines for writing good comments and method descriptions for producing good java documentation?Just my two cents, but document your interfaces extensively. Inherit this documentation in an implementation and only add if the impl

  • Applet not opening in browser  Help needed Update:10-11

    Hi experts, I have Java installed in my machine in the path C:\Program Files\Java While trying to open the link http://www.radinks.com/upload/applet.php in browser, I am being asked to install the missing plugin and that plugin is java. I do not know

  • In Lookout, how can I make the equivalent of a "4 changes per day" set-back thermostat? Update:10-11

    Ok... I need some help here.... I have a Pot_TSP (Temperature setpoint) that uses a PLC register as its remote source. I added a night-time temperature setback feature by adding a "DAYTIME" expression as a permissive, and tying two new Pots (Pot