Question: Need help with Java Objectives Call and write methods with parameters and return values. Use the DrawingPanel, Graphics, and Color classes. Use for loops and

Need help with Java

Objectives

Call and write methods with parameters and return values. Use the DrawingPanel, Graphics, and Color classes. Use for loops and if statements to control assignments.

Introduction

In this project you will write a program that could be the basis for a simple version of the space invaders video game. This project will involve graphics and animation. (See BouncingBall.java in Canvas->Files This project has several parts and should be started early.

Make sure your program and each method is preceded by a descriptive comment.

Part 1: Setup

Start a new project in Dr. Java. Load BouncingBall.java into Dr. Java and change the name of the class to Project2.

Also get a copy of DrawingPanel.java from Canvas->File and put it into the same directory as Project2.java.

Change drawCircles to startGame. In startGame, change loop variable 'I' to 'time' and make the time go up to 1000 instead of 90. Remove everything from the body of the for loop except for the sleep method. In the main method, before the call to startGame, print the following on the screen in black at position x = 10 and y = 15:

Project 2 by YOURNAME. Replace YOURNAME with your full name.

Part 2: The Patrol ship

Create class constants PATROL_Y initialized to 250 and PATROL_SIZE initialized to 20. For example, put public static final int PATROL_Y = 250; after the class header: public class Project2.

Make a (non-constant) class variable called patrolX initialized to 270. For example, put public static int patrolX = 270; after the class constants.

Write the method: public static void drawPatrol(Graphics g, Color c); that fills a square at x = patrolX, y = PATROL_Y, with side PATROL_SIZE in the given color. Do a Google for Java Graphics fillRect to find a graphics method. Call drawPatrol(g, Color.GREEN) before the for loop statement. Get it working.

Part 3: The enemy ship

Make class constants ENEMY_Y and ENEMY_SIZE initialized to 20 and 30, respectively. Make a class variable enemyX initialized to 0. The enemy ship will be a red square with the given position and size. Write the method:

public static void moveEnemyShipAndDraw(Graphics g); that draws the enemy ship first in white, then increment enemyX by 1, and then draws the ship again in red. Put a call to this method inside the for loop.

Part 4: Moving the patrol ship

Make integer constants RIGHT_ARROW = 39, LEFT_ARROW = 37, and UP_ARROW = 38. Write the method: public static void handleKeys(DrawingPanel panel, Graphics g);

This will call panel.getKeyCode() that returns a code for a key. It returns 0 if no key has been pushed, and will return one of the above constants if the corresponding arrow key has been pushed.

The method handleKeys should do nothing if the returned key code is 0. If the key code is RIGHT_ARROW or LEFT_ARROW, move the patrol ship to the right or left by 3 pixels, but do not let any part of the patrol ship move off the screen. To move the patrol ship:

draw the patrol ship in white (to erase the old one) change patrolX draw the patrol ship in green

Call the method handleKeys in the loop. You should be able to move the patrol ship by pushing the left and right arrows on the keyboard. Before using the arrow keys, make sure your drawing window is the active window by clicking the mouse in this window.

Part 5: Shooting

The patrol ship will shoot a missile when the up arrow key is pushed. Make class variables patrolMissileX and patrolMissileY. Initialize patrolMissileY to 0. Make a contant PATROL_MISSILE_LENGTH initialized to 10.

Write a method: public static void movePatrolMissileAndDraw(Graphics g); that moves the missile and draws it similar to moveEnemyShipAndDraw:

Do not draw anything if patrolMissileY is 0. Otherwise, the missile as a vertical line with the stated length and x-position. PatrolMissileY is the top of the line. Draw the missile in white, move the missile up 5 pixels, and draw it again in black. If the patrolMissileY is 0 or negative, do not draw the missile in black, but set patrolMissileY to 0.

Call this method before the sleep in the loop. When the up arrow key is pushed and patrolMissileY is 0, set patrolMissileX to be the center of the patrol ship and set the top of the missile so that its bottom is one pixel above the top of the patrol ship (PATROL_Y). You should only be able to fire one missile at a time and the up arrow should not do anything if a missile is still displayed.

Part 6: Detecting a hit

Make a boolean class variable, hit, initialized to false; Write the method: public static boolean detectHit(); that returns true if the current missile has hit the enemy ship and false otherwise. There is a hit if the top of the missile is inside the enemy ship. For this to happen two thing must be true:

the x value of the top of the missile must be between the left and right sides of the enemy the y value of the top of the missile must be between the top and bottom of the enemy.

At the end of the loop in startGame, set hit to true if detectHit() returns true. Modify moveEnemyShipAndDraw so that if hit is true, the enemy ship is drawn in black and does not move. In this case, display the message: Enemy ship hit! in green on a line below the patrol ship. If the enemy ship moves off the screen or time runs out, Display the message: Enemy ship got away! in red on a line below the patrol ship.

Rubric for Project 2

Your program should compile without any errors. A program with more than one or two compile errors will likely get a zero for the whole assignment.

The following criteria will also be used to determine the grade for Project 2.

[1 point] Your submission was a file named Project2.java [1 point] Your program contains a comment that describes what the program does and contains a descriptive comment for each method. [1 point] Your program in indented properly. [2 points] Part 1 has been completed and the program displays your name appropriately. [2 points] You have declared the appropriate constants and variables for the patrol ship and the patrol ship is displayed appropriately. [3 points] You have declared the appropriate constants and variables for the enemy ship and the enemy ship is moves appropriately. [3 points] The patrol ship can be correctly moved by the arrow keys and will not move off the screen. [3 points] The partol ship can shoot properly and cannot shoot more than one missile at a time. [3 points] Your program correctly detects a hit and displays messages appropriately. [1 point] Your program detects and handles the enemy ship getting away.

///////BouncingBall.java

import java.awt.*;

public class BouncingBall {

public static void main(String[] args) {

DrawingPanel panel = new DrawingPanel(300, 300);

Graphics g = panel.getGraphics( );

drawCircles(panel, g);

}

public static void drawCircles(DrawingPanel panel, Graphics g) {

int x = 0;

int y = 270;

int deltaX = 1;

int deltaY = -3;

for (int i = 0; i <= 90; i++) {

panel.sleep(50);

g.setColor(Color.WHITE);

g.fillOval(x, y, 30, 30);

g.setColor(Color.RED);

x = x + deltaX;

y = y + deltaY;

g.fillOval(x, y, 30, 30);

}

}

}

////////DrawingPanel.java

/*

Stuart Reges and Marty Stepp

February 24, 2007

Changes by Tom Bylander in 2010 (no anti-alias, repaint on sleep)

Changes by Tom Bylander in 2012 (track mouse clicks and movement)

Changes by Tom Bylander in 2013 (fix bug in tracking mouse clicks)

Changes by S. Robbins in 2014 (getters for width and height)

Changes by S. Robbins in 2014 (addKeyListener added)

Changes by S. Robbins in 2014 (catch exception on default close so that it works in an applet)

Changes by S. Robbins in 2015 (buffer key events)

Changes by S. Robbins in 2015 (show mouse status by default is off)

The DrawingPanel class provides a simple interface for drawing persistent

images using a Graphics object. An internal BufferedImage object is used

to keep track of what has been drawn. A client of the class simply

constructs a DrawingPanel of a particular size and then draws on it with

the Graphics object, setting the background color if they so choose.

To ensure that the image is always displayed, a timer calls repaint at

regular intervals.

*/

import java.awt.*;

import java.awt.event.*;

import java.awt.image.*;

import javax.swing.*;

import javax.swing.event.*;

import java.util.ArrayList;

public class DrawingPanel implements ActionListener {

private static final String versionMessage =

"Drawing Panel version 1.1, January 25, 2015";

private static final int DELAY = 100; // delay between repaints in millis

private static final boolean PRETTY = false; // true to anti-alias

private static boolean showStatus = false;

private static final int MAX_KEY_BUF_SIZE = 10;

private int width, height; // dimensions of window frame

private JFrame frame; // overall window frame

private JPanel panel; // overall drawing surface

private BufferedImage image; // remembers drawing commands

private Graphics2D g2; // graphics context for painting

private JLabel statusBar; // status bar showing mouse position

private volatile MouseEvent click; // stores the last mouse click

private volatile boolean pressed; // true if the mouse is pressed

private volatile MouseEvent move; // stores the position of the mouse

private ArrayList keys;

// construct a drawing panel of given width and height enclosed in a window

public DrawingPanel(int width, int height) {

this.width = width;

this.height = height;

keys = new ArrayList();

image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

statusBar = new JLabel(" ");

statusBar.setBorder(BorderFactory.createLineBorder(Color.BLACK));

statusBar.setText(versionMessage);

panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));

panel.setBackground(Color.WHITE);

panel.setPreferredSize(new Dimension(width, height));

panel.add(new JLabel(new ImageIcon(image)));

click = null;

move = null;

pressed = false;

// listen to mouse movement

MouseInputAdapter listener = new MouseInputAdapter() {

public void mouseMoved(MouseEvent e) {

pressed = false;

move = e;

if (showStatus)

statusBar.setText("moved (" + e.getX() + ", " + e.getY() + ")");

}

public void mousePressed(MouseEvent e) {

pressed = true;

move = e;

if (showStatus)

statusBar.setText("pressed (" + e.getX() + ", " + e.getY() + ")");

}

public void mouseDragged(MouseEvent e) {

pressed = true;

move = e;

if (showStatus)

statusBar.setText("dragged (" + e.getX() + ", " + e.getY() + ")");

}

public void mouseReleased(MouseEvent e) {

click = e;

pressed = false;

if (showStatus)

statusBar.setText("released (" + e.getX() + ", " + e.getY() + ")");

}

public void mouseEntered(MouseEvent e) {

// System.out.println("mouse entered");

panel.requestFocus();

}

};

panel.addMouseListener(listener);

panel.addMouseMotionListener(listener);

new DrawingPanelKeyListener();

g2 = (Graphics2D)image.getGraphics();

g2.setColor(Color.BLACK);

if (PRETTY) {

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

g2.setStroke(new BasicStroke(1.1f));

}

frame = new JFrame("Drawing Panel");

frame.setResizable(false);

try {

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // so that this works in an applet

} catch (Exception e) {}

frame.getContentPane().add(panel);

frame.getContentPane().add(statusBar, "South");

frame.pack();

frame.setVisible(true);

toFront();

frame.requestFocus();

// repaint timer so that the screen will update

new Timer(DELAY, this).start();

}

public void showMouseStatus(boolean f) {

showStatus = f;

}

public void addKeyListener(KeyListener listener) {

panel.addKeyListener(listener);

panel.requestFocus();

}

// used for an internal timer that keeps repainting

public void actionPerformed(ActionEvent e) {

panel.repaint();

}

// obtain the Graphics object to draw on the panel

public Graphics2D getGraphics() {

return g2;

}

// set the background color of the drawing panel

public void setBackground(Color c) {

panel.setBackground(c);

}

// show or hide the drawing panel on the screen

public void setVisible(boolean visible) {

frame.setVisible(visible);

}

// makes the program pause for the given amount of time,

// allowing for animation

public void sleep(int millis) {

panel.repaint();

try {

Thread.sleep(millis);

} catch (InterruptedException e) {}

}

// close the drawing panel

public void close() {

frame.dispose();

}

// makes drawing panel become the frontmost window on the screen

public void toFront() {

frame.toFront();

}

// return panel width

public int getWidth() {

return width;

}

// return panel height

public int getHeight() {

return height;

}

// return the X position of the mouse or -1

public int getMouseX() {

if (move == null) {

return -1;

} else {

return move.getX();

}

}

// return the Y position of the mouse or -1

public int getMouseY() {

if (move == null) {

return -1;

} else {

return move.getY();

}

}

// return the X position of the last click or -1

public int getClickX() {

if (click == null) {

return -1;

} else {

return click.getX();

}

}

// return the Y position of the last click or -1

public int getClickY() {

if (click == null) {

return -1;

} else {

return click.getY();

}

}

// return true if a mouse button is pressed

public boolean mousePressed() {

return pressed;

}

public synchronized int getKeyCode() {

if (keys.size() == 0)

return 0;

return keys.remove(0).keyCode;

}

public synchronized char getKeyChar() {

if (keys.size() == 0)

return 0;

return keys.remove(0).keyChar;

}

public synchronized int getKeysSize() {

return keys.size();

}

private synchronized void insertKeyData(char c, int code) {

keys.add(new KeyInfo(c,code));

if (keys.size() > MAX_KEY_BUF_SIZE) {

keys.remove(0);

// System.out.println("Dropped key");

}

}

private class KeyInfo {

public int keyCode;

public char keyChar;

public KeyInfo(char keyChar, int keyCode) {

this.keyCode = keyCode;

this.keyChar = keyChar;

}

}

private class DrawingPanelKeyListener implements KeyListener {

int repeatCount = 0;

public DrawingPanelKeyListener() {

panel.addKeyListener(this);

panel.requestFocus();

}

public void keyPressed(KeyEvent event) {

// System.out.println("key pressed");

repeatCount++;

if ((repeatCount == 1) || (getKeysSize() < 2))

insertKeyData(event.getKeyChar(),event.getKeyCode());

}

public void keyTyped(KeyEvent event) {

}

public void keyReleased(KeyEvent event) {

repeatCount = 0;

}

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!