Back to Code List
java

Slippery Maze

A simple game in Java that requires you to get from start to end. It introduces some basic game concepts and user input.

   SlipperyMaze.java

package game;

import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class SlipperyMaze extends JPanel {
	private Board board = null;
	private int width, height, moveCount;
	private JLabel scoreLabel;
	
	AbstractAction goUp, goDown, goLeft, goRight, reset, newGame;
	
	void addHandlers() {
		/*getInputMap().put(KeyStroke.getKeyStroke("UP"), "goUp");
		getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "goDown");
		getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "goLeft");
		getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "goRight");*/
		getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP,0,true), "goUp");
		getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN,0,true), "goDown");
		getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT,0,true), "goLeft");
		getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT,0,true), "goRight");
		getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R,0,true), "reset");
		getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N,0,true), "newGame");
		goUp = new AbstractAction(){
			@Override
			public void actionPerformed(ActionEvent e) {
                int move = board.movePlayer("up");
                checkMove(move);
            }
		};
		goDown = new AbstractAction(){
			@Override
		    public void actionPerformed(ActionEvent arg0) {
				int move = board.movePlayer("down");
				checkMove(move);
			}
		};
		goLeft = new AbstractAction(){
			@Override
		    public void actionPerformed(ActionEvent arg0) {
				int move = board.movePlayer("left");
				checkMove(move);
			}
		};
		goRight = new AbstractAction(){
			@Override
		    public void actionPerformed(ActionEvent arg0) {
				int move = board.movePlayer("right");
				checkMove(move);
			}
		};
		reset = new AbstractAction(){
			@Override
			public void actionPerformed(ActionEvent e) {
                board.resetPlayer();
                moveCount = 0;
                updateScoreLabel();
            }
		};
		newGame = new AbstractAction(){
			@Override
			public void actionPerformed(ActionEvent e) {
                newGamePrompt();
            }
		};
		getActionMap().put("goUp", goUp);
		getActionMap().put("goDown", goDown);
		getActionMap().put("goLeft", goLeft);
		getActionMap().put("goRight", goRight);
		getActionMap().put("reset", reset);
		getActionMap().put("newGame", newGame);
	}
	
	public void newGamePrompt() {
		if (board != null) {
			board.clear();
			remove(board);
			board = null;
			repaint();
		}
		moveCount = 0;
		
		Object[] options = {
			"Easy",
	        "Medium",
	        "Hard"
        };
		int difficulty = JOptionPane.showOptionDialog(
				this,
				"Choose your Difficulty",
				"Select Difficulty",
				JOptionPane.YES_NO_CANCEL_OPTION,
				JOptionPane.PLAIN_MESSAGE,
				null,
				options,
				options[2]
		);
		
		int size = difficulty+5;
		
		Object[] options2 = {
				"1",
		        "2",
		        "3"
	        };
		int level = JOptionPane.showOptionDialog(
				this,
				"Choose your Level",
				"Select Level",
				JOptionPane.YES_NO_CANCEL_OPTION,
				JOptionPane.PLAIN_MESSAGE,
				null,
				options2,
				options2[2]
		);
		
		board = new Board(size, width-40);
		add(board);
		board.revalidate();
		board.setBounds(20,20,width-40,width-40);
		board.selectLevel(size,level);
		
		updateScoreLabel();
	}
	
	private void checkMove(int move) {
		if (move == 1 || move == 2) moveCount = moveCount + 1;
		updateScoreLabel();
		
		if (move == 2) {
			Object[] options = {"Play Again", "New Level"};
			int choice = JOptionPane.showOptionDialog(
			    this,
			    "You won with "+ moveCount +" moves! Would you like to play this level again or do a new level?",
			    "Winner!",
			    JOptionPane.YES_NO_OPTION,
			    JOptionPane.WARNING_MESSAGE,
			    null,
			    options,
			    options[1]
		    );
			
			board.resetPlayer();
			moveCount = 0;
			updateScoreLabel();
			
			if (choice == 1) {
				newGamePrompt();
			}
		}
	}
	
	private void updateScoreLabel() {
		scoreLabel.setText(moveCount + " moves.");
	}
	
	public SlipperyMaze() {
		width = 500;
		height = 600;
		moveCount = 0;
		setPreferredSize(new Dimension(width,height));
		addHandlers();
		setLayout(null);
		
		JPanel temp = new JPanel();
		add(temp);
		temp.setBounds(0, height-(height-width), width, (height-width));
		temp.setLayout(null);
		
		scoreLabel = new JLabel();
		scoreLabel.setText(moveCount + " moves.");
		scoreLabel.setBounds(width-100,0,100,20);
		temp.add(scoreLabel);
		
		JLabel info = new JLabel();
		info.setText("Use buttons or arrow keys to move.");
		info.setBounds(5,0,width-100,20);
		temp.add(info);
		
		JButton btnNewGame = new JButton("New Level");
		btnNewGame.setMargin(new Insets(2, 5, 2, 5));
		btnNewGame.setBounds(10, 38, 89, 23);
		btnNewGame.addActionListener(newGame);
		temp.add(btnNewGame);
		
		JButton btnReset = new JButton("Reset");
		btnNewGame.setMargin(new Insets(2, 5, 2, 5));
		btnReset.setBounds(401, 38, 89, 23);
		btnReset.addActionListener(reset);
		temp.add(btnReset);
		
		JButton buttonUp = new JButton("\u25B2");
		buttonUp.setMargin(new Insets(2, 5, 2, 5));
		buttonUp.setBounds(228, 11, 43, 23);
		buttonUp.addActionListener(goUp);
		temp.add(buttonUp);
		
		JButton buttonDown = new JButton("\u25BC");
		buttonDown.setMargin(new Insets(2, 5, 2, 5));
		buttonDown.setBounds(228, 66, 43, 23);
		buttonDown.addActionListener(goDown);
		temp.add(buttonDown);
		
		JButton buttonRight = new JButton("\u25BA");
		buttonRight.setMargin(new Insets(2, 5, 2, 5));
		buttonRight.setBounds(270, 38, 43, 23);
		buttonRight.addActionListener(goRight);
		temp.add(buttonRight);
		
		JButton buttonLeft = new JButton("\u25C4");
		buttonLeft.setMargin(new Insets(2, 5, 2, 5));
		buttonLeft.setBounds(186, 38, 43, 23);
		buttonLeft.addActionListener(goLeft);
		temp.add(buttonLeft);
		
		newGamePrompt();
	}
	
	public static void main(String[] args) {
		SlipperyMaze pane = new SlipperyMaze();
		JFrame wdw = new JFrame("Slippery Maze");
		wdw.getContentPane().add(pane);
		wdw.pack();
		wdw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		wdw.setVisible(true);
	}
}
    

   Board.java

package game;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.Border;

public class Board extends JPanel {
	private JPanel[][] cells;
	private int[][] obstacleList;
	private Player player;
	boolean playerAdded;
	private int[] winSpot;
	private int cellWidth, boardWidth, boardSize;
	
	public void setWinPosition(int row, int col) {
		winSpot[0] = row;
		winSpot[1] = col;
		cells[row][col].setBackground(Color.GREEN);
	}
	
	public void addObstacle(int row, int col) {
		if (obstacleList[row][col] != 1) {
			Obstacle obs = new Obstacle(row, col);
			cells[row][col].add(obs);
			obstacleList[row][col] = 1;
		}
	}
	
	public void addPlayer(int row, int col) {
		if (!playerAdded && obstacleList[row][col] != 1) {
			player = new Player(row,col);
			player.setBounds(col*cellWidth, row*cellWidth, cellWidth, cellWidth);
			add(player,0);
			playerAdded = true;
		}
	}
	
	public void movePlayer(final String direction, boolean extraParam) {
		int row = player.getCurrPos()[0];
		int col = player.getCurrPos()[1];
		
		final int startX = col*cellWidth;
		final int startY = row*cellWidth;
		
		if (
			(direction == "right" && col < boardSize-1)	 ||
			(direction == "left"  && col > 0)			 ||
			(direction == "up"    && row > 0) 			 ||
			(direction == "down"  && row < boardSize-1)
		) {
			if (direction == "right") ++col;
			if (direction == "left")  --col;
			if (direction == "up")    --row;
			if (direction == "down")  ++row;
			
			if (obstacleList[row][col] != 1) {
				player.setCurrPos(row,col);
				
				//int duration = 100;
				//final Timer t = new Timer(duration/(cellWidth/10), null);
				final int endX = col*cellWidth;
				final int endY = row*cellWidth;
				
				
				player.setBounds(endX, endY, cellWidth, cellWidth); // remove this when putting animation back in
				movePlayer(direction,true);
				
				/*t.addActionListener(new ActionListener() {
					private int newStartX = startX;
					private int newStartY = startY;
					public void actionPerformed(ActionEvent evt) {
						if (newStartX != endX) {
							if (startX<endX) newStartX = newStartX+10;
							else newStartX = newStartX-10;
							player.setBounds(newStartX,newStartY, cellWidth,cellWidth);
						}
						if (newStartY != endY) {
							if (startY<endY) newStartY = newStartY+10;
							else newStartY = newStartY-10;
							player.setBounds(newStartX, newStartY, cellWidth, cellWidth);
						}
						
						if (
				    		(startX < endX && newStartX >= endX) || // right
				    		(startX > endX && newStartX <= endX) || // left
				    		(startY > endY && newStartY <= endY) || // up
				    		(startY < endY && newStartY >= endY)    // down
				    	) {
					    	t.stop();
							player.setBounds(endX, endY, cellWidth, cellWidth);
							movePlayer(direction,true);
					    }
			        }
			    });*/
			    
			    //t.start();
			}
		}
	}
	
	public int movePlayer(String direction) {
		int[] startPos = player.getCurrPos().clone();
		movePlayer(direction,true); // would be animation but timer doesn't pause code...
		int[] endPos = player.getCurrPos().clone();
		
		if (startPos[0]==endPos[0] && startPos[1] == endPos[1]) return 0; // no change
		if (endPos[0] == winSpot[0] && endPos[1] == winSpot[1]) return 2; // winner
		return 1; 														  // player has moved
	}

	public void resetPlayer() {
		int row = player.getStartPos()[0];
		int col = player.getStartPos()[1];
		player.setBounds(col*cellWidth,row*cellWidth,cellWidth,cellWidth);
		player.setCurrPos(row,col);
	}
	
	public void selectLevel(int size, int level) {
		if (size == 5) {
			switch (level) {
			case 0:
				addPlayer(4,4);
				addObstacle(1,2);
				addObstacle(2,0);
				addObstacle(2,1);
				addObstacle(2,4);
				addObstacle(4,1);
				setWinPosition(1,1);
				break;
			case 1:
				addPlayer(2,1);
				addObstacle(2,2);
				addObstacle(1,3);
				addObstacle(4,4);
				addObstacle(3,1);
				addObstacle(0,0);
				setWinPosition(2,3);
				break;
			case 2:
				addPlayer(1,0);
				addObstacle(0,0);
				addObstacle(3,1);
				addObstacle(2,3);
				setWinPosition(2,2);
				break;
			}
		} else if (size == 6) {
			switch (level) {
			case 0:
				addPlayer(0,1);
				addObstacle(0,0);
				addObstacle(1,4);
				setWinPosition(1,3);
				break;
			case 1:
				addPlayer(0,0);
				addObstacle(1,1);
				addObstacle(2,1);
				addObstacle(3,5);
				addObstacle(4,2);
				addObstacle(0,3);
				setWinPosition(1,2);
				break;
			case 2:
				addPlayer(5,0);
				addObstacle(5,2);
				addObstacle(4,0);
				addObstacle(4,4);
				addObstacle(1,3);
				addObstacle(2,1);
				setWinPosition(2,2);
				break;
			}
		} else if (size == 7) {
			switch (level) {
			case 0:
				addPlayer(2,2);
				addObstacle(1,1);
				addObstacle(2,1);
				addObstacle(1,2);
				addObstacle(5,3);
				addObstacle(4,1);
				addObstacle(6,2);
				addObstacle(4,4);
				addObstacle(4,5);
				addObstacle(0,6);
				addObstacle(2,3);
				setWinPosition(3,0);
				break;
			case 1:
				addPlayer(4,4);
				addObstacle(1,4);
				addObstacle(4,5);
				addObstacle(0,6);
				addObstacle(1,0);
				addObstacle(2,5);
				addObstacle(5,4);
				setWinPosition(0,0);
				break;
			case 2:
				addPlayer(3,3);
				addObstacle(3,1);
				addObstacle(0,2);
				addObstacle(1,5);
				addObstacle(5,4);
				setWinPosition(2,6);
				break;
			}
		}
	}
	
	public void clear() {
		for (int i=0; i<cells.length; i++)
			for (int z=0; z<cells[i].length; z++) {
				remove(cells[i][z]);
				cells[i][z] = null;
			}
		for (int i=0; i<obstacleList.length; i++)
			for (int z=0; z<obstacleList[i].length; z++)
				obstacleList[i][z] = 0;
		player = null;
		removeAll();
		repaint();
	}
	
	public Board(int size, int width) {
		setLayout(null);
		Border whiteline = BorderFactory.createLineBorder(Color.WHITE);
		setBorder(whiteline);
		
		boardSize = size;
		boardWidth = width;
		cellWidth = width/size;
		cells = new JPanel[size][size];
		obstacleList = new int[size][size];
		playerAdded = false;
		winSpot = new int[2];
		
		for(int row=0; row<size; row++) {
			for(int col=0; col<size; col++) {
				JPanel cell = new JPanel();
					cell.setBorder(whiteline);
					cell.setLayout(new GridLayout(1,1));
					cell.setBackground(Color.DARK_GRAY);
					cell.setBounds(col*cellWidth, row*cellWidth, cellWidth, cellWidth);
				cells[row][col] = cell;
				add(cell,-1);
			}
		}
	}
}    

   Obstacle.java

package game;

import java.awt.GridLayout;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Obstacle extends JPanel {
	ImageIcon image = new ImageIcon(this.getClass().getResource("/images/rock.png"));
	private int[] coords;
	
	public Obstacle(int row, int col) {
		coords = new int[2];
		coords[0] = row; coords[1] = col;
		setLayout(new GridLayout(1,1));
		
		add(new JLabel(image));
	}
}
    

   Player.java

package game;

import java.awt.Color;

import javax.swing.JPanel;

public class Player extends JPanel {
	//image
	private int[] currPos;
	private int[] startPos;
	
	public int[] getCurrPos() { return currPos; }
	
	public int[] getStartPos() { return startPos; }
	
	public void setCurrPos(int row, int col) {
		currPos[0] = row;
		currPos[1] = col;
	}
	
	public Player(int row, int col) {
		startPos = new int[2];
		startPos[0] = row; startPos[1] = col;
		currPos = startPos.clone();
		
		setBackground(Color.BLUE);
	}
}