Question

This is java.

Goal is to create a pacman type game. I have most of the code done just need to add in ghosts score dots etc.

Attached is the assignment, and after the assignment is my current code.

Lab 5 Now that you had a chance to create players that move on the screen, mazes, and items to collect, you are going to create a Pacman clone. You are going to use the maze from Lab 4 and recreate that maze. Then, instead of blank spaces, you are to put dots in there. You must have at least 3 levels Then, you should have a single playerthat can move through the maze collecting the dots. Feel free to use the collision detection from the first three labs or the 4th lab. You should have three lives. As you collect dots, the score should continually update on the screen. Once you collect all the dots, you should move to the next level Finally, you should have a couple of monsters that follow you around the screen autonomously. Remember, they are unable to move through walls. However, if they hit you, you lose a life, and the monsters should increase in speed in each level. Specifics for Lab 5: 1. Come up with a class diagram of how you would approach a system like this 2. Design an inherited structure for the affecting factors (players, monsters, dots) 3. Outline all the attributes and methods. 4. Create a Use case diagram for your program -this means, write a description of how the simulation will play out. (i.e. User starts a game, the monsters move, the user moves and collects dots, etc.) 5. Create all the stub code for your design (do not fully implement; i e. method should not do a thing). Extra Credit: Provide Power Pellets that turn the monsters into a blue monsters that can be eaten for a certain amount of time.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Maze extends JFrame implements KeyListener {

private static final String[] FILE = { "maze1.txt", "maze2.txt" };
private static final int mazeWidth = 50;
private static final int mazeHeight = 50;
private static final int LEFT = -1;
private static final int RIGHT = 1;
private static final int UP = -1;
private static final int DOWN = 1;
private int[][] maze;
private JLabel[][] mazeLabel;
private int row;
private int col;
private int entryX = -1;
private int entryY = -1;
private int exitX = -1;
private int exitY = -1;
private int currX = -1;
private int currY = -1;
private ImageIcon playerImg;
private boolean hasWon;


public Maze() {
super("Maze");

// Reads the maze from input file
startMaze();

if (this.maze.length > 0) {

   // Finds entry and exit
findStartEnd();

if ((this.entryX != -1) && (this.entryY != -1) && (this.exitX != -1) && (this.exitY != -1)) {
  
   // Draws maze
drawMaze();

// Sets current position
this.currX = this.entryX;
this.currY = this.entryY;

// Place the player in the maze
setPlayer();

} else
  
   // Prints if error reading the input from maze ie no 0's on border
System.out.println("No Entry/Exit point(s) found.");
} else {
System.out.println("No maze found.");
}

setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

addKeyListener(this);
requestFocus();
this.hasWon = false;
}


private void startMaze() {
     
// Selects a random file for the maze, this fullfils requirement#3
int n = (int) (Math.random() * 10) % 2;

// Use scanner file to read it the maze.txt file. I also had to look for help with the try exception as i was having trouble getting the file read in this was what was best suggested so
// so this part isn't my code and i know we will learn about the try later but just wanted to give a heads up.
Scanner file = null;
try {
file = new Scanner(new File(FILE[n]));

// This puts the file into the array, once again not my code here here had help with this part. this fullfills requiremnt 2 i think?

String[] lines = new String[0];
while (file.hasNextLine()) {
int len = lines.length;
lines = Arrays.copyOf(lines, len + 1);
lines[len] = file.nextLine().replaceAll("\\s+", "");
}

if (lines.length > 0) {
this.row = lines.length;
this.col = lines[0].length();
this.maze = new int[row][col];

for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
this.maze[i][j] = (lines[i].charAt(j) == '0') ? 0 : 1;
}
}
} catch (FileNotFoundException e) {
System.out.println("No file found: " + FILE[n]);
System.exit(0);
} finally {
if (file != null)
file.close();
}
}


private void drawMaze() {

// This draws the maze from the txt file.
setLayout(null);
getContentPane().setPreferredSize(new Dimension((col * mazeWidth), (row * mazeHeight)));
pack();
ImageIcon image = new ImageIcon("brick.jpg");

// This resizes the image to the Maze, had help here as well with the Scale defualt I looked this up online.
image = new ImageIcon(image.getImage().getScaledInstance(mazeWidth, mazeHeight, Image.SCALE_DEFAULT));

  
this.mazeLabel = new JLabel[row][col];

int y = 0;
for (int i = 0; i < row; i++) {
int x = 0;

for (int j = 0; j < col; j++) {
this.mazeLabel[i][j] = new JLabel();
this.mazeLabel[i][j].setBounds(x, y, mazeWidth, mazeHeight);
this.mazeLabel[i][j].setOpaque(true);

if (this.maze[i][j] == 1)
this.mazeLabel[i][j].setIcon(image);
else
this.mazeLabel[i][j].setBackground(Color.WHITE);

// Adds Jlabel/Maze into the main panel
add(this.mazeLabel[i][j]);

x += mazeWidth;
}
y += mazeHeight;
}
}


//This is the method/logic that finds the start of the maze and exit of the maze. Had some help with this part as well as i was having trouble ending the game
private void findStartEnd() {
for (int i = 0; i < row; i++) {
if (this.maze[i][0] == 0) {
this.entryX = i;
this.entryY = 0;
break;
}
}
for (int i = 0; i < col; i++) {
if (this.maze[0][i] == 0) {
if ((this.entryX == -1) && (this.entryY == -1)) {
this.entryX = 0;
this.entryY = i;
break;
} else if ((this.exitX != -1) && (this.exitY != -1)) {
this.exitX = 0;
this.exitY = i;
break;
}
}
}

if (((this.entryX == -1) && (this.entryY == -1)) || ((this.exitX == -1) && (this.exitY == -1))) {
for (int i = 0; i < row; i++) {
if (this.maze[i][col - 1] == 0)
if ((this.entryX == -1) && (this.entryY == -1)) {
this.entryX = i;
this.entryY = col - 1;
break;
} else if ((this.exitX == -1) && (this.exitY == -1)) {
this.exitX = i;
this.exitY = col - 1;
break;
}
}
for (int i = 0; i < col; i++) {
if (this.maze[row - 1][i] == 0) {
if ((this.entryX == -1) && (this.entryY == -1)) {
this.entryX = row - 1;
this.entryY = i;
break;
} else if ((this.exitX == -1) && (this.exitY == -1)) {
this.exitX = row - 1;
this.exitY = i;
break;
}
}
}
}
}

//Puts the player in the maze
private void setPlayer() {
playerImg = new ImageIcon("2000px-Pacman.svg.png");
playerImg = new ImageIcon(playerImg.getImage().getScaledInstance(mazeWidth, mazeHeight, Image.SCALE_DEFAULT));
this.mazeLabel[currX][currY].setIcon(playerImg);
}

// checks the current loction of player
private void setNewLocation(int newX, int newY) {
this.mazeLabel[currX][currY].setIcon(null);
this.mazeLabel[currX][currY].setBackground(Color.WHITE);
currX = newX;
currY = newY;
this.mazeLabel[currX][currY].setIcon(playerImg);
}

// This checks to see if a horizontal move is valid and if there is a open space
private void checkHorizontal(int dir) {
if (dir == LEFT) {
if ((currY > 0) && (this.maze[currX][currY - 1] == 0)) {
setNewLocation(currX, currY - 1);
}

} else if (dir == RIGHT) {
if ((currY < (col - 1)) && (this.maze[currX][currY + 1] == 0)) {
setNewLocation(currX, currY + 1);
}
}
}

// This checks to see if a vertical move is valid and if there is a open space
private void checkVertical(int dir) {
if (dir == UP) {
if ((currX > 0) && (this.maze[currX - 1][currY] == 0)) {
setNewLocation(currX - 1, currY);
}
} else if (dir == DOWN) {
if ((currX < (row - 1)) && (this.maze[currX + 1][currY] == 0)) {
setNewLocation(currX + 1, currY);
}
}
}

// Player movement i use awsd for movement
public void keyPressed(KeyEvent ke) {
if (!hasWon) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_A:
checkHorizontal(LEFT);
break;
  
case KeyEvent.VK_W:
checkVertical(UP);
break;
  
case KeyEvent.VK_D:
checkHorizontal(RIGHT);
break;
  
case KeyEvent.VK_S:
checkVertical(DOWN);
}
  
// Check if the player exits the maze
if ((currX == exitX) && (currY == exitY)) {
this.hasWon = true;
JOptionPane.showMessageDialog(this, "You found the exit");
}
repaint();
}
}

@Override
public void keyReleased(KeyEvent arg0) {
}

@Override
public void keyTyped(KeyEvent arg0) {
  
}

public static void main(String[] args) {
Maze maze = new Maze();
maze.setVisible(true);
}
}

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

Find below code for your requirement..

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Maze extends JFrame implements KeyListener {

private static final String[] FILE = { "maze1.txt", "maze2.txt" };
private static final int mazeWidth = 50;
private static final int mazeHeight = 50;
private static final int LEFT = -1;
private static final int RIGHT = 1;
private static final int UP = -1;
private static final int DOWN = 1;
private int[][] maze;

this.currX = this.entryX;
this.currY = this.entryY;

String[] lines = new String[0];
while (file.hasNextLine()) {
int len = lines.length;
lines = Arrays.copyOf(lines, len + 1);
lines[len] = file.nextLine().replaceAll("\\s+", "");
}

if (lines.length > 0) {
this.row = lines.length;
this.col = lines[0].length();
this.maze = new int[row][col];

for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
this.maze[i][j] = (lines[i].charAt(j) == '0') ? 0 : 1;
}

if (((this.entryX == -1) && (this.entryY == -1)) || ((this.exitX == -1) && (this.exitY == -1))) {
for (int i = 0; i < row; i++) {
if (this.maze[i][col - 1] == 0)
if ((this.entryX == -1) && (this.entryY == -1)) {
this.entryX = i;
this.entryY = col - 1;
break;

if (!hasWon) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_A:
checkHorizontal(LEFT);
break;
  
case KeyEvent.VK_W:
checkVertical(UP);
break;
  
case KeyEvent.VK_D:
checkHorizontal(RIGHT);
break;
  
case KeyEvent.VK_S:
checkVertical(DOWN);
}

if ((currX == exitX) && (currY == exitY)) {
this.hasWon = true;
JOptionPane.showMessageDialog(this, "You found the exit");
}
repaint();
}
}

@Override
public void keyReleased(KeyEvent arg0) {
}

@Override
public void keyTyped(KeyEvent arg0) {
  
}

public static void main(String[] args) {
Maze maze = new Maze();
maze.setVisible(true);
}
}

  

Add a comment
Know the answer?
Add Answer to:
This is java. Goal is to create a pacman type game. I have most of the...
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
  • When outputting the path found in the proposed program, the direction of movement is output. Howe...

    When outputting the path found in the proposed program, the direction of movement is output. However, the direction of movement to the last movement, EXIT, is not output. To print this out, please describe how to modify the proposed program. #include <stdio.h> #define NUM_ROWS 5 #define NUM_COLS 3 #define BOUNDARY_COLS 5 #define MAX_STACK_SIZE 100 #define FALSE 0 #define TRUE 1 ​ ​ ​ typedef struct { short int row; short int col; short int dir; } element; ​ element stack[MAX_STACK_SIZE];...

  • JAVA JAR HELP...ASAP I have the code that i need for my game Connect 4, but...

    JAVA JAR HELP...ASAP I have the code that i need for my game Connect 4, but i need to create a jar file . the instructions are below. It has to pass some parameters. I am really confused on doing so.l I dont know what to do next. Can someone help me and give detailed descritiopm opn how you ran the jar file in CMD import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Connect4 {               ...

  • 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...

  • Need Help ASAP!! Below is my code and i am getting error in (public interface stack)...

    Need Help ASAP!! Below is my code and i am getting error in (public interface stack) and in StackImplementation class. Please help me fix it. Please provide a solution so i can fix the error. thank you.... package mazeGame; import java.io.*; import java.util.*; public class mazeGame {    static String[][]maze;    public static void main(String[] args)    {    maze=new String[30][30];    maze=fillArray("mazefile.txt");    }    public static String[][]fillArray(String file)    {    maze = new String[30][30];       try{...

  • Can you please help me to run this Java program? I have no idea why it...

    Can you please help me to run this Java program? I have no idea why it is not running. import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; @SuppressWarnings({"unchecked", "rawtypes"}) public class SmartPhonePackages extends JFrame { private static final long serialVersionID= 6548829860028144965L; private static final int windowWidth = 400; private static final int windowHeight = 200; private static final double SalesTax = 1.06; private static JPanel panel;...

  • Hello, I am currently taking a Foundations of Programming course where we are learning the basics of Java. I am struggli...

    Hello, I am currently taking a Foundations of Programming course where we are learning the basics of Java. I am struggling with a part of a question assigned by the professor. He gave us this code to fill in: import java.util.Arrays; import java.util.Random; public class RobotGo {     public static Random r = new Random(58);     public static void main(String[] args) {         char[][] currentBoard = createRandomObstacle(createBoard(10, 20), 100);         displayBoard(startNavigation(currentBoard))     }     public static int[] getRandomCoordinate(int maxY, int maxX) {         int[] coor = new...

  • Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static...

    Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static String solve(char[][] grid) {        // TODO        /*        * 1. Construct a graph using grid        * 2. Use BFS to find shortest path from start to finish        * 3. Return the sequence of moves to get from start to finish        */               // Hardcoded solution to toyTest        return...

  • 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...

  • why do i get this syntax error? for example: i have these two classes: class Maze...

    why do i get this syntax error? for example: i have these two classes: class Maze { private: int row, col; cell **arr; public: Maze(int r = 0, int c = 0) { this->row = r; this->col = c; arr = new cell*[row]; for (int i = 0; i < row; i++) arr[i] = new cell[col]; } }; class cell { private: bool visited; bool up, down, right, left; int x, y; int px, py; char status; public: cell() {...

  • Hello I am having trouble with a connectFour java program. this issue is in my findLocalWinner...

    Hello I am having trouble with a connectFour java program. this issue is in my findLocalWinner method, it declares a winner for horizontal wins, but not for vertical. if anyone can see what im doing wrong. public class ConnectFour { /** Number of columns on the board. */ public static final int COLUMNS = 7; /** Number of rows on the board. */ public static final int ROWS = 6; /** Character for computer player's pieces */ public static final...

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