-
Notifications
You must be signed in to change notification settings - Fork 0
/
PongComponent.java
76 lines (67 loc) · 1.32 KB
/
PongComponent.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
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PongComponent extends JComponent implements KeyListener, Runnable
{
private PongEnvironment environment;
private boolean pressingUp = false;
private boolean pressingDown = false;
public PongComponent()
{
super();
environment = new PongEnvironment();
environment.setComputer(false, true);
setPreferredSize(new Dimension(environment.WIDTH, environment.HEIGHT));
addKeyListener(this);
Thread run = new Thread(this);
run.start();
}
public void run()
{
while(true)
{
try
{
Thread.sleep(20);
}
catch(Exception ex)
{
}
requestFocus();
update();
repaint();
}
}
public void paint(Graphics g)
{
synchronized(g)
{
environment.draw(g);
}
}
public void update()
{
environment.update();
if(pressingUp)
environment.getLeft().moveUp();
else if(pressingDown)
environment.getLeft().moveDown();
}
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode() == KeyEvent.VK_UP)
pressingUp = true;
else if(ke.getKeyCode() == KeyEvent.VK_DOWN)
pressingDown = true;
}
public void keyReleased(KeyEvent ke)
{
if(ke.getKeyCode() == KeyEvent.VK_UP)
pressingUp = false;
else if(ke.getKeyCode() == KeyEvent.VK_DOWN)
pressingDown = false;
}
public void keyTyped(KeyEvent ke)
{
}
}