Join 150,429 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,075 people online right now. Registration is fast and FREE... Join Now!
I am Having a problem with running a game in creating on java, it is a run time error which says "indexOutofBounsException: Index; 0, Size: 0 (in java.util.Arraylist)"
i have made bold the line of code java highlights with this error:
CODE
import java.util.ArrayList; import java.io.*; /** * Prototype "maze game" class. To play, create a new Game * object in BlueJ and invoke the goUp, goRight, etc commands * to move around the maze. */ public class Game { /** The player. */ private Player player;
/**The List of Mazes created. */ private ArrayList <Maze> listofMaze;
/** A panel in which the game state is displayed. */ private GameWindow view;
/** * current level in game */ private int currentLevel;
/** * Initialise a new Game. */
/** * the maze */
private Maze maze;
public Game() throws IOException { nextgame(); view = new GameWindow(this); view.addKeyListener(new KeyControl());
currentLevel = 0; listofMaze = new ArrayList<Maze>(); createMazes();
maze = listofMaze.get(0);
player = new Player(getMaze().getStartX(), getMaze().getStartY());
if (!isValidPosition(player.getX(), player.getY())) { throw new Error("Player has started in the wrong position: (" + player.getX() + "," + player.getY() + ")"); }
}
public void nextgame() { try { currentLevel = 0; listofMaze = new ArrayList<Maze>(); createMazes();
}catch(java.io.IOException e){} player = new Player(getMaze().getStartX(), getMaze().getStartY()); if (!isValidPosition(player.getX(), player.getY())) { throw new Error("Player has started in the wrong position: (" + player.getX() + "," + player.getY() + ")"); } }
/** * returns the maze object */
public Maze getMaze() { [b]return listofMaze.get(currentLevel);[/b] }
/** * creates different mazes. Add items in two cells. * Add the mazes to the list of mazes. */
/** * Move player into a certain position. * Do nothing if the player's current position is not * connected to a neighbour in that direction. * * @param d The direction in which to move. */
public void go(String d) { int x = player.getX(); int y = player.getY(); Cell currentCell = getMaze().getCell(x, y); if (currentCell.isOpen(d)) { if (d.equals("up")) { player.setPosition(x, y-1); } else if (d.equals("right")) { player.setPosition(x+1, y); } else if (d.equals("down")) { player.setPosition(x, y+1); } else if (d.equals("left")) { player.setPosition(x-1, y); } else { throw new Error("Wrong direction: " + d); } if (!isValidPosition(player.getX(), player.getY())) { throw new Error("Invaild Position: (" + player.getX() + "," + player.getY() + ")"); }
if (getMaze().getFinishX() == player.getX() && getMaze().getFinishY() == player.getY()) { if (currentLevel < listofMaze.size()-1) { currentLevel++; player.setPosition(getMaze().getStartX(), getMaze().getStartY()); } else { System.exit(0); } } Cell c = getMaze().getCell(player.getX(), player.getY());
// Points are increased by 20 when the player enters this cell if (c.getitem()!= null && c.getitem().getitemname() == "shield") { player.setscore(20);
c.setitem(null); }
//One life is added for the player when this cell is entered if (c.getitem()!= null && c.getitem().getitemname() == "Health") { player.sethealth(1);
c.setitem(null);
view.repaint(); } }
}
/** * Attempt to move the player up. * Do nothing if the player's current position is not * connected to a neighbour in that direction. * */ public void goUp() { go("up"); }
/** * Attempt to move the player right. * Do nothing if the player's current position is not * connected to a neighbour in that direction. * */ public void goRight() { go("right"); }
/** * Attempt to move the player down. * Do nothing if the player's current position is not * connected to a neighbour in that direction. * */ public void goDown() { go("down"); }
/** * Attempt to move the player left. * Do nothing if the player's current position is not * connected to a neighbour in that direction. * */ public void goLeft() { go("left"); } /** * *Returns player */
public Player getPlayer() { return player; }
/** * Is a given position a valid place for the player to be? * * @param x The x-position to test. * @param y The y-position to test. */
private boolean isValidPosition(int x, int y) { if (x >= 0 && x < getMaze().getWidth() && y >= 0 && y < getMaze().getHeight()) { return getMaze().getCell(x, y) !=null; } else { return false; } }
private class KeyControl extends java.awt.event.KeyAdapter { public void keyPressed(java.awt.event.KeyEvent e) { int code = e.getKeyCode(); if (code == java.awt.event.KeyEvent.VK_UP) { goUp(); } else if (code == java.awt.event.KeyEvent.VK_RIGHT) { goRight(); } else if (code == java.awt.event.KeyEvent.VK_DOWN) { goDown(); } else if (code == java.awt.event.KeyEvent.VK_LEFT) { goLeft(); } } } }
I will be very greatfull on any help solving this error, please ask if you need more information from me to slove the problem.
Thank you
This post has been edited by Jet_Man: 20 Apr, 2008 - 01:33 PM
/** * This maze class will contain all the information needed * * @author * */ public class Maze { /** Declaration of the cells field. */ private Cell[][] cells;
/** The height of the created maze. */ private int height;
/** The width of the created maze. */ private int width;
/** * the starting position. * the ending position. */ private int x_Start, y_Start, x_Finish, y_Finish;
/** * Constructor for objects of class Maze */
public Maze() { // Creates an empty cell. width = 20; height = 15; cells = new Cell[width][height]; }
public Maze(String fileName) throws IOException { FileReader fr = null; BufferedReader br = null; try { fr = new FileReader(fileName); br = new BufferedReader(fr); String line = br.readLine(); int y = 0; while (line != null) {
for(int x = 0; x < line.length();x++) { char c = line.charAt(x); if(c ==' '){ cells[x][y] = new Cell(); } } line =br.readLine(); y++;
}
} finally { if (br != null) br.close(); if (fr != null) fr.close(); } }
/** * Connect the cell at (x,y) to its neighbouring cell * in the given direction. The position (x,y) and the * neighbouring position must be non-null in the cells * array. * * @param d The direction of the neighbour. * @param x The x-position of the cell. * @param y The y-position of the cell. */ public void connect(String d, int x, int y) { if (d.equals("up")) { cells[x][y].openWall("up"); cells[x][y-1].openWall("down"); } else if (d.equals("right")) { cells[x][y].openWall("right"); cells[x+1][y].openWall("left"); } else if (d.equals("down")) { cells[x][y].openWall("down"); cells[x][y+1].openWall("up"); } else if (d.equals("left")) { cells[x][y].openWall("left"); cells[x-1][y].openWall("right"); } else { throw new Error("Wrong direction: " + d); } }
public void setStart(int x, int y) { x_Start = x; y_Start = y; }
public void setFinish(int x, int y) { x_Finish = x; y_Finish = y; }
/** * returns the x to the bigining. */
public int getStartX() { return x_Start; }
/** * returns the y to the bigining. */ public int getStartY() { return y_Start; }
/** * returns the x to the end. */
public int getFinishX() { return x_Finish; }
/** * returns the y to the end. */
public int getFinishY() { return y_Finish; }
/** * The maze cell at a given position. * * @param x The x-coordinate of the position. * @param y The y-coordinate of the position. */
public Cell getCell(int x, int y) { return cells[x][y]; }
public void addCell(int x, int y) {
cells[x][y] = new Cell(); }
/** * The width of maze. */
public int getWidth() { return width; }
/** * The height of maze. */ public int getHeight() { return height; }
}
Player
CODE
/** * A Player in the maze game. */ public class Player { /** Current x-position of the player in the maze. */ private int xPosition;
/** Current y-position of the player in the maze. */ private int yPosition;
/**health of player. */ private int lives;
/**points player achived. */ private int score;
/** * Initialise a new Player. The coordinate specifies a cell * in the maze grid (not a pixel position on the screen). * * @param x Initial x-position. * @param y Initial y-position. */ public Player(int x, int y) { this.setPosition(x, y); score = 0; lives = 4; }
/** * The x-position of the player's current cell in the maze grid. */ public int getX() { return xPosition; }
/** * The y-position of the player's current cell in the maze grid. */ public int getY() { return yPosition; }
/** * Set the player's position. The coordinate specifies a cell * in the maze grid (not a pixel position on the screen). * * @param x The new x-position. * @param y The new y-position. */ public void setPosition(int x, int y) { xPosition = x; yPosition = y; }
/**Set the health of the player. * * @parm scorenumber how high the players score is. */ public void setscore (int scorenumber) { score = scorenumber + score; }
/** * @parm healthbar how high the players health is. */ public void setlife (int add) { lives = lives + add; }
/**The Players Score.*/ public int getscore()
{ return score;
}
/**The amount of health the player has.*/ public int getlife()
/** * Panel for displaying the maze game state. */ public class GameWindow extends JFrame { /** Size in pixels to draw the cells of the maze. */ private static final int CELL_SIZE = 40;
public GameWindow(Game game) { super("game"); this.game = game; setPreferredSize(new Dimension(CELL_SIZE * game.getMaze().getWidth(), CELL_SIZE * game.getMaze().getHeight())); setFocusable(true); MazeView view = new MazeView (game); status = new StatusView (game); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.add(view); this.pack(); this.setVisible(true); this.add(status, BorderLayout.PAGE_END); menuBar = new JMenuBar(); fileMenu = new JMenu("file"); nextgameItem = new JMenu("Next Game"); closegameItem = new JMenu("Close Game"); menuBar.add(fileMenu); this.setJMenuBar(menuBar);
ActionListener closegame = new closegameListener(); closegameItem.addActionListener(closegame);
ActionListener nextgame = new nextgameListener(); nextgameItem.addActionListener(nextgame); } private class nextgameListener implements ActionListener { public void actionPerformed(ActionEvent e) { game.nextgame(); }
} private class closegameListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); }
/** * Draw a red dot showing where the player is. */ private void drawPlayer(Graphics g, Player player) { int x = player.getX() * CELL_SIZE; int y = player.getY() * CELL_SIZE; int dotSize = 10; int offset = (CELL_SIZE - dotSize)/2; g.setColor(Color.RED); g.fillOval(x + offset, y + offset, dotSize, dotSize); }
/** * Draw the cell which is at position (x,y) in the game grid. */ private void drawCell(Graphics g, int x, int y) { /**this code gets the cell from the game class * */ Cell cell = game.getMaze().getCell(x,y);
/**this code checks if created items exist * */ if (cell.getitem() !=null) { g.setColor(Color.RED); String s = cell.getitem().getitemname(); int offset = CELL_SIZE/8; g.drawString(s, x * CELL_SIZE + offset, y * CELL_SIZE + (3 * offset));
}
g.setColor(Color.BLACK); g.drawRect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
} } }
Thank you,
I have fixed the other mistakes 'm2s87' thank you,
the run time error is still present tho...
This post has been edited by Jet_Man: 20 Apr, 2008 - 03:54 PM
/** * Cells in a maze. Each cell may be open to neighbours in * any (or none) of the directions up, right, down, left. */ public class Cell { /** The directions in which this cell is open.**/ private Set <String> openWalls;
/** The Items within the.**/ private Item item;
/** * Initialise a new Cell. All walls are initially closed. */ public Cell() { openWalls = new java.util.HashSet<String>(); }
/** * Open the wall in the given direction. * * @param d The direction. */ public void openWall(String d) { openWalls.add(d); }
/** * Close a wall. * Has no effect if the cell is not open in that direction. * * @param d The direction. */ public void closeWall(String d) { openWalls.remove(d); }
/** * Is this cell open in the given direction? * * @param d The direction. */ public boolean isOpen(String d) { return openWalls.contains(d); }
/** * set the item * * @param name * */ public void setitem(Item name) { item = name; }
Not easy to find an error if we cannot run your code
Item
CODE
/** * Write a description of class Item here. * * @author () * @version (a version number or a date) */ public class Item { // instance variables - replace the example below with your own private String item;
/** * Constructor for objects of class Item */ public Item(String name) { // initialise instance variables item = name; }
/** * Return the Item * */ public String getitemname() {
return item; } /** * get the item * */ public void setItem(String name) {
/** * Panel for displaying the maze game state. */ public class StatusView extends JPanel { /** Size in pixels to draw the cells of the maze. */ private static final int CELL_SIZE = 40;
/** * Panel for displaying the maze game state. */ public class MazeView extends JPanel { /** Size in pixels to draw the cells of the maze. */ private static final int CELL_SIZE = 40;
/** * Draw the game state. */ public void paintComponent(Graphics g) { super.paintComponent(g); for (int x = 0; x < game.getMaze().getWidth(); x++) { for (int y = 0; y < game.getMaze().getHeight(); y++) { if (game.getMaze().getCell(x, y) != null) { drawCell(g, x, y); } } } drawPlayer(g, game.getPlayer()); }
/** * Draw a red dot showing where the player is. */ private void drawPlayer(Graphics g, Player player) { int x = player.getX() * CELL_SIZE; int y = player.getY() * CELL_SIZE; int dotSize = 10; int offset = (CELL_SIZE - dotSize)/2; g.setColor(Color.RED); g.fillOval(x + offset, y + offset, dotSize, dotSize); }
/** * Draw the cell which is at position (x,y) in the game grid. */ private void drawCell(Graphics g, int x, int y) { /**this code gets the cell from the game class * */ Cell cell = game.getMaze().getCell(x,y);
/**this code checks if created items exist * */ if (cell.getitem() !=null) { g.setColor(Color.RED); String s = cell.getitem().getitemname(); int offset = CELL_SIZE/8; g.drawString(s, x * CELL_SIZE + offset, y * CELL_SIZE + (3 * offset));
}
g.setColor(Color.BLACK); g.drawRect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
public void drawItem (Graphics g, int x, int y, Cell cell) { int a = x * CELL_SIZE; int b = y * CELL_SIZE; Item item = cell.getitem(); if(item != null){ if (item.getitemname().equals("health")) { ImageIcon icon = new ImageIcon("heart.gif"); icon.paintIcon(this, g, a + -3 , b + 2);
}if (item.getitemname().equals("shield")) { ImageIcon icon = new ImageIcon("shield.gif"); icon.paintIcon(this, g, a + -3 , b + 2);
}if (item.getitemname().equals("door")) { ImageIcon icon = new ImageIcon("Passage.gif"); icon.paintIcon(this, g, a + -3 , b + 2); } } }
}
Game
CODE
import java.util.ArrayList; import java.io.*; /** * Prototype "maze game" class. To play, create a new Game * object in BlueJ and invoke the goUp, goRight, etc commands * to move around the maze. */ public class Game { /** The player. */ private Player player;
/**The List of Mazes created. */ private ArrayList <Maze> listofMaze;
/** A panel in which the game state is displayed. */ private GameWindow view;
/** * current level in game */ private int currentLevel;
/** * Initialise a new Game. */
/** * the maze */
private Maze maze;
public Game() throws IOException { nextgame(); view = new GameWindow(this); view.addKeyListener(new KeyControl());
maze = listofMaze.get(currentLevel);
player = new Player(getMaze().getStartX(), getMaze().getStartY());
if (!isValidPosition(player.getX(), player.getY())) { throw new Error("Player has started in the wrong position: (" + player.getX() + "," + player.getY() + ")"); }
}
public void nextgame() { try { currentLevel = 0; listofMaze = new ArrayList<Maze>(); createMazes();
}catch(java.io.IOException e){} player = new Player(getMaze().getStartX(), getMaze().getStartY()); if (!isValidPosition(player.getX(), player.getY())) { throw new Error("Player has started in the wrong position: (" + player.getX() + "," + player.getY() + ")"); } }
/** * returns the maze object */
public Maze getMaze() { return listofMaze.get(currentLevel); }
/** * creates different mazes. Add items in two cells. * Add the mazes to the list of mazes. */