Professional Documents
Culture Documents
TP Java Thread Game Correction
TP Java Thread Game Correction
Classe Target :
1 class Target {
2 private int x;
3 private int y;
4
5 public Target() {
6 this.x = (int) (Math.random() * 760);
7 this.y = 0;
8 }
9
26 return x < projX + 5 && x + 20 > projX && y < projY + 5 && y + 20 > projY;
27 }
28 }
Classe Projectile :
1 class Projectile
2 { private int
3 x; private
4 int y;
5
6 public Projectile(int x) {
7 this.x = x + 18; // Adjust for cannon width
8 this.y = 500;
9 }
10
21 }
Classe ShootingGame :
1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
4 import java.util.ArrayList;
5 import java.util.Iterator;
6
15 public ShootingGame() {
16 setTitle("Shooting Game");
17 setSize(800, 600);
18 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19
29 addKeyListener(new KeyAdapter() {
30 @Override
31 public void keyPressed(KeyEvent e) {
32 if (e.getKeyCode() == KeyEvent.VK_SPACE) {
33 projectiles.add(new Projectile(cannonX));
34 }
35 if (e.getKeyCode() == KeyEvent.VK_P) {
36 isRunning = !isRunning;
37 }
38 if (e.getKeyCode() == KeyEvent.VK_LEFT) {
39 if (cannonX > 0) {
40 cannonX -= 10;
41 }
42 }
43 if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
44 if (cannonX < 760) {
45 cannonX += 10;
46 }
47 }
48 }
49 });
50
53 if (isRunning) {
54 targets.add(new Target());
55 }
56 }
57 });
58 targetTimer.start();
59
85 gamePanel.repaint();
86 }
87 });
88 gameTimer.start();
89 }
90
96 @Override
97 protected void paintComponent(Graphics g) {
98 super.paintComponent(g);
99
100 g.setColor(Color.BLACK);
101 g.fillRect(cannonX, 500, 40, 20);
102
103 g.setColor(Color.RED);
104 for (Projectile p : projectiles) {
105 g.fillRect(p.getX(), p.getY(), 5, 5);
106 }
107
108 g.setColor(Color.BLUE);
109 for (Target t : targets) {
110 g.fillRect(t.getX(), t.getY(), 20, 20);
111 }
112
113 g.setColor(Color.BLACK);
114 g.drawString("Score: " + score, 10, 20);
115 if (!isRunning) {
116 g.drawString("Paused (Press P to Resume)", 330, 300);
117 }
118 }
119 }
120