-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cannon.java
97 lines (78 loc) · 2.88 KB
/
Cannon.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//Justin Baldeosingh
//816021226
//COMP 3609 - Assignment 2
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.Random;
/**
The Cannon class models the cannon from which the player shoots the incoming missiles.
*/
public class Cannon {
//Declares a JPanel object for storing the panel on which the cannon will be drawn.
private JPanel panel;
//Declares the coordinate variables of the cannon.
private int x;
private int y;
//Declares the width and height dimensions of the cannon.
private int width;
private int height;
//Declares the images that will be used for the cannon orientations.
private Image cannonImage;
private Image cannonImageLeft;
private Image cannonImageUp;
private Image cannonImageRight;
//Declares the sound manager.
private SoundManager soundManager;
/**
The cannon constructor takes the JPanel and the x, and y coordinates, on which the cannon will be drawn.
*/
public Cannon(JPanel p, int xPos, int yPos) {
//Sets the drawing panel to the global panel variable.
panel = p;
//Sets the fixed dimensions of the cannon.
width = 172;
height = 135;
//Sets the coordinates where the cannon will be drawn.
x = xPos;
y = yPos;
//Loads the images for the different orientations of the cannon.
cannonImageLeft = ImageManager.loadImage ("images/cannon-left.png");
cannonImageRight = ImageManager.loadImage ("images/cannon-right.png");
cannonImageUp = ImageManager.loadImage ("images/cannon-up.png");
//Sets the default orientation of the cannon.
cannonImage = cannonImageUp;
//Loads the single instance sound manager.
soundManager = SoundManager.getInstance();
}
/**
Updates the cannon orientation/image based on the direction supplied.
*/
public void updateCannonDirection(char dir){
if(dir == 'u')
cannonImage = cannonImageUp;
else if(dir == 'l')
cannonImage = cannonImageLeft;
else if (dir == 'r')
cannonImage = cannonImageRight;
}
/**
Draws the cannon to the image context, at the supplied coordinates using the supplied dimensions.
*/
public void draw (Graphics2D g2) {
g2.drawImage(cannonImage, x, y, width, height, null);
}
/**
Determines the orientation of the cannon based on the input coordinates that the user has shot. Also plays the sound for firing the cannon.
*/
public void fireCannon(int x, int y){
soundManager.playClip("fireLaser", false);
int screenWidth = panel.getWidth();
if(x < screenWidth/3)
updateCannonDirection('l');
else if (x < 2*screenWidth/3)
updateCannonDirection('u');
else if (x < screenWidth)
updateCannonDirection('r');
}
}