forked from rick2785/JavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameBoard.java
More file actions
439 lines (259 loc) · 10.5 KB
/
GameBoard.java
File metadata and controls
439 lines (259 loc) · 10.5 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// Layout used by the JPanel
import java.awt.BorderLayout;
// Define color of shapes
import java.awt.Color;
// Allows me to draw and render shapes on components
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
// Will hold all of my Rock objects
import java.util.ArrayList;
// Runs commands after a given delay
import java.util.concurrent.ScheduledThreadPoolExecutor;
// Defines time units. In this case TimeUnit.MILLISECONDS
import java.util.concurrent.TimeUnit;
import javax.swing.JComponent;
import javax.swing.JFrame;
// NEW Needed for sound to play
// Stores a predefined audio clip
import javax.sound.sampled.Clip;
// Can convert audio data to different playable formats
import javax.sound.sampled.AudioSystem;
// Works with streams of a definite length
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.IOException;
import java.net.*;
import javax.swing.*;
public class GameBoard extends JFrame{
private static final long serialVersionUID = 1L;
// Height and width of the game board
public static int boardWidth = 1000;
public static int boardHeight = 800;
// Used to check if a key is being held down
public static boolean keyHeld = false;
// Gets the keycode for the key being held down
public static int keyHeldCode;
// Holds every PhotonTorpedo I create
public static ArrayList<PhotonTorpedo> torpedos = new ArrayList<PhotonTorpedo>();
// NEW Location of sound files
String thrustFile = "file:./src/thrust.au";
String laserFile = "file:./src/laser.aiff";
public static void main(String [] args)
{
new GameBoard();
}
public GameBoard()
{
// Define the defaults for the JFrame
this.setSize(boardWidth, boardHeight);
this.setTitle("Java Asteroids");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Handles executing code based on keys being pressed
addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==87)
{
System.out.println("Forward");
// NEW play thrust noise when w is pressed
playSoundEffect(thrustFile);
keyHeldCode = e.getKeyCode();
keyHeld = true;
}
// Not currently used
else if (e.getKeyCode()==83){
System.out.println("Backward");
keyHeldCode = e.getKeyCode();
keyHeld = true;
}
// Id the d key is pressed set keyHeld as if it
// was being held down. This will cause the ship to
// constantly rotate. keyHeldCode stores the keyCode for d
else if (e.getKeyCode()==68){
System.out.println("Rotate Right");
keyHeldCode = e.getKeyCode();
keyHeld = true;
}
// Same thing is done here as was done with the last
// 65 is the keyCode for a
else if (e.getKeyCode()==65){
System.out.println("Rotate Left");
keyHeldCode = e.getKeyCode();
keyHeld = true;
}
// NEW Checks if Enter key is pressed ---------------
else if (e.getKeyCode()==KeyEvent.VK_ENTER){
System.out.println("Shoot");
// NEW play laser sound when enter is hit
playSoundEffect(laserFile);
// Creates a new torpedo and passes the ships nose position
// so the torpedo can start there. Also passes the ships
// rotation angle so the torpedo goes in the right direction
torpedos.add(new PhotonTorpedo(GameDrawingPanel2.theShip.getShipNoseX(),
GameDrawingPanel2.theShip.getShipNoseY(),
GameDrawingPanel2.theShip.getRotationAngle()));
System.out.println("RotationAngle " + GameDrawingPanel2.theShip.getRotationAngle());
}
}
// When the key is released this informs the code that
// the key isn't being held down
public void keyReleased(KeyEvent e) {
keyHeld = false;
}
});
GameDrawingPanel2 gamePanel = new GameDrawingPanel2();
// Make the drawing area take up the rest of the frame
this.add(gamePanel, BorderLayout.CENTER);
// Used to execute code after a given delay
// The attribute is corePoolSize - the number of threads to keep in
// the pool, even if they are idle
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5);
// Method to execute, initial delay, subsequent delay, time unit
executor.scheduleAtFixedRate(new RepaintTheBoard2(this), 0L, 20L, TimeUnit.MILLISECONDS);
// Show the frame
this.setVisible(true);
}
// NEW Handles playing all sound effects
public static void playSoundEffect(String soundToPlay){
// Pointer towards the resource to play
URL soundLocation;
try {
soundLocation = new URL(soundToPlay);
// Stores a predefined audio clip
Clip clip = null;
// Convert audio data to different playable formats
clip = AudioSystem.getClip();
// Holds a stream of a definite length
AudioInputStream inputStream;
inputStream = AudioSystem.getAudioInputStream(soundLocation);
// Make audio clip available for play
clip.open( inputStream );
// Define how many times to loop
clip.loop(0);
// Play the clip
clip.start();
}
catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (UnsupportedAudioFileException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (LineUnavailableException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
// Class implements the runnable interface
// By creating this thread we can continually redraw the screen
// while other code continues to execute
class RepaintTheBoard2 implements Runnable{
GameBoard theBoard;
public RepaintTheBoard2(GameBoard theBoard){
this.theBoard = theBoard;
}
@Override
public void run() {
// Redraws the game board
theBoard.repaint();
}
}
@SuppressWarnings("serial")
// GameDrawingPanel is what we are drawing on
class GameDrawingPanel2 extends JComponent {
// Holds every Rock I create
public static ArrayList<Rock> rocks = new ArrayList<Rock>();
// Get the original x & y points for the polygon
int[] polyXArray = Rock.sPolyXArray;
int[] polyYArray = Rock.sPolyYArray;
// Create a SpaceShip
static SpaceShip theShip = new SpaceShip();
// Gets the game board height and weight
int width = GameBoard.boardWidth;
int height = GameBoard.boardHeight;
// Creates 50 Rock objects and stores them in the ArrayList
// Suppress warnings when I clone the rocks array
public GameDrawingPanel2() {
for(int i = 0; i < 10; i++){
// Find a random x & y starting point
// The -40 part is on there to keep the Rock on the screen
int randomStartXPos = (int) (Math.random() * (GameBoard.boardWidth - 40) + 1);
int randomStartYPos = (int) (Math.random() * (GameBoard.boardHeight - 40) + 1);
// Add the Rock object to the ArrayList based on the attributes sent
rocks.add(new Rock(Rock.getpolyXArray(randomStartXPos), Rock.getpolyYArray(randomStartYPos), 13, randomStartXPos, randomStartYPos));
Rock.rocks = rocks;
}
}
public void paint(Graphics g) {
// Allows me to make many settings changes in regards to graphics
Graphics2D graphicSettings = (Graphics2D)g;
AffineTransform identity = new AffineTransform();
// Draw a black background that is as big as the game board
graphicSettings.setColor(Color.BLACK);
graphicSettings.fillRect(0, 0, getWidth(), getHeight());
// Set rendering rules
graphicSettings.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Set the drawing color to white
graphicSettings.setPaint( Color.WHITE );
// Cycle through all of the Rock objects
for(Rock rock : rocks){
// NEW Is rock viewable
if(rock.onScreen){
// NEW Move the Rock polygon
rock.move(theShip, GameBoard.torpedos);
// Stroke the polygon Rock on the screen
graphicSettings.draw(rock);
}
}
// Handles spinning the ship in the clockwise direction when the D key
// is pressed and held
if(GameBoard.keyHeld == true && GameBoard.keyHeldCode == 68){
theShip.increaseRotationAngle();
} else
// Continues to rotate the ship counter clockwise if the A key is held
if(GameBoard.keyHeld == true && GameBoard.keyHeldCode == 65){
theShip.decreaseRotationAngle();
} else
if (GameBoard.keyHeld == true && GameBoard.keyHeldCode == 87){
// Set movement angle to the current rotation angle
// This is done so that the ship rotation can be set by the A & D keys
// but when the throttle is hit the ship knows what direction to go
theShip.setMovingAngle(theShip.getRotationAngle());
theShip.increaseXVelocity(theShip.shipXMoveAngle(theShip.getMovingAngle())*0.1);
theShip.increaseYVelocity(theShip.shipYMoveAngle(theShip.getMovingAngle())*0.1);
}
theShip.move();
// Sets the origin on the screen so rotation occurs properly
graphicSettings.setTransform(identity);
// Moves the ship to the center of the screen
graphicSettings.translate(theShip.getXCenter(),theShip.getYCenter());
// Rotates the ship
graphicSettings.rotate(Math.toRadians(theShip.getRotationAngle()));
graphicSettings.draw(theShip);
// Draw torpedos
for(PhotonTorpedo torpedo : GameBoard.torpedos){
// Move the Torpedo polygon
torpedo.move();
// Make sure the Torpedo is on the screen
if(torpedo.onScreen){
// Stroke the polygon torpedo on the screen
graphicSettings.setTransform(identity);
// Changes the torpedos center x & y vectors
graphicSettings.translate(torpedo.getXCenter(),torpedo.getYCenter());
graphicSettings.draw(torpedo);
}
}
}
}