-
Notifications
You must be signed in to change notification settings - Fork 0
/
World.java
94 lines (89 loc) · 3.16 KB
/
World.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
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Map;
class World extends JComponent implements KeyListener, ActionListener {
boolean validates(Map<String, Square> squares) {
boolean answer = true;
for (String key : squares.keySet()) {
System.out.println(key);
Square square = squares.get(key);
if (square != null)
if ( square.conflictsWith(ROWS, COLS) ||
background.conflictsWith(square) )
answer = false;
}
// System.out.println( answer );
return answer;
}
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
// System.out.println("Ouch. You have typed: " + ((char) keycode));
switch (keycode) {
case KeyEvent.VK_LEFT : // System.out.println("Left arrow key.");
current.moveLeft(); this.repaint();
break;
case KeyEvent.VK_RIGHT: // System.out.println("Right arrow key.");
current.moveRight(); this.repaint();
break;
case KeyEvent.VK_UP : // System.out.println("Up arrow key.");
current.rotateRight(); this.repaint();
break;
case KeyEvent.VK_DOWN : // System.out.println("Down arrow key.");
current.rotateLeft(); this.repaint();
break;
case KeyEvent.VK_SPACE: // System.out.println("Down arrow key.");
timer.setDelay(50);
break;
default : // System.out.println("No arrow key.");
break;
}
}
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
int count;
Timer timer;
public void actionPerformed(ActionEvent e) {
this.count += 1;
// System.out.println( "ActionEvent received: " + this.count );
if (current != null) {
if (! current.moveDown()) {
this.background.receive(current);
this.lines += this.background.shrink();
this.statusbar.setText("Total: " + this.lines);
timer.setDelay(1000); // thanks to Jake and Thijs for catching this
current = Shape.randomShape(this);
if (! this.validates(current.squares)) {
current = null;
timer.stop();
System.out.println("Game over!");
}
}
} else {
timer.stop();
}
repaint();
}
Shape current;
BackGround background;
JLabel statusbar;
int lines = 0;
World(JLabel statusbar) {
this.statusbar = statusbar;
this.timer = new Timer(1000, this);
this.background = new BackGround(this);
this.current = Shape.randomShape(this);
}
void start() {
this.timer.start();
}
public void paintComponent(Graphics g) {
this.background.draw(g);
if (current != null)
this.current.draw(g);
}
static final int ROWS = 22;
static final int COLS = 10;
int squareWidth() { return (int) getSize().getWidth() / World.COLS; }
int squareHeight() { return (int) getSize().getHeight() / World.ROWS; }
}