-
Notifications
You must be signed in to change notification settings - Fork 277
/
tetris_game.py
265 lines (204 loc) · 7.87 KB
/
tetris_game.py
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
import sys, random
from PyQt5.QtWidgets import QMainWindow, QFrame, QDesktopWidget, QApplication, QHBoxLayout, QLabel
from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal
from PyQt5.QtGui import QPainter, QColor, QFont
from tetris_model import BOARD_DATA, Shape
from tetris_ai import TETRIS_AI
# TETRIS_AI = None
class Tetris(QMainWindow):
def __init__(self):
super().__init__()
self.isStarted = False
self.isPaused = False
self.isGameOver = False
self.nextMove = None
self.lastShape = Shape.shapeNone
self.initUI()
def initUI(self):
self.gridSize = 22
self.speed = 100
self.timer = QBasicTimer()
self.setFocusPolicy(Qt.StrongFocus)
hLayout = QHBoxLayout()
self.tboard = Board(self, self.gridSize)
hLayout.addWidget(self.tboard)
self.sidePanel = SidePanel(self, self.gridSize)
hLayout.addWidget(self.sidePanel)
self.statusbar = self.statusBar()
self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)
self.start()
self.center()
self.setWindowTitle('Tetris')
self.show()
self.setFixedSize(self.tboard.width() + self.sidePanel.width(),
self.sidePanel.height() + self.statusbar.height())
def center(self):
screen = QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2)
def start(self):
if self.isPaused:
return
self.isStarted = True
self.isGameOver = False
self.tboard.score = 0
BOARD_DATA.clear()
self.tboard.msg2Statusbar.emit(str(self.tboard.score))
BOARD_DATA.createNewPiece()
self.timer.start(self.speed, self)
def pause(self):
if not self.isStarted or self.isGameOver:
return
self.isPaused = not self.isPaused
if self.isPaused:
self.timer.stop()
self.tboard.msg2Statusbar.emit("Paused")
else:
self.timer.start(self.speed, self)
self.updateWindow()
def updateWindow(self):
self.tboard.updateData()
self.sidePanel.updateData()
self.update()
def timerEvent(self, event):
if event.timerId() == self.timer.timerId():
if self.isGameOver:
self.timer.stop()
return
if TETRIS_AI and not self.nextMove:
self.nextMove = TETRIS_AI.nextMove()
if self.nextMove:
k = 0
while BOARD_DATA.currentDirection != self.nextMove[0] and k < 4:
BOARD_DATA.rotateRight()
k += 1
k = 0
while BOARD_DATA.currentX != self.nextMove[1] and k < 5:
if BOARD_DATA.currentX > self.nextMove[1]:
BOARD_DATA.moveLeft()
elif BOARD_DATA.currentX < self.nextMove[1]:
BOARD_DATA.moveRight()
k += 1
lines = BOARD_DATA.moveDown()
self.tboard.score += lines
if BOARD_DATA.gameOver():
self.gameOver()
return
if self.lastShape != BOARD_DATA.currentShape:
self.nextMove = None
self.lastShape = BOARD_DATA.currentShape
self.updateWindow()
else:
super(Tetris, self).timerEvent(event)
def keyPressEvent(self, event):
if self.isGameOver:
if event.key() == Qt.Key_R:
self.restartGame()
return
if not self.isStarted or BOARD_DATA.currentShape == Shape.shapeNone:
super(Tetris, self).keyPressEvent(event)
return
key = event.key()
if key == Qt.Key_P:
self.pause()
return
if self.isPaused:
return
elif key == Qt.Key_Left:
BOARD_DATA.moveLeft()
elif key == Qt.Key_Right:
BOARD_DATA.moveRight()
elif key == Qt.Key_Up:
BOARD_DATA.rotateLeft()
elif key == Qt.Key_Space:
self.tboard.score += BOARD_DATA.dropDown()
elif key == Qt.Key_R:
self.restartGame()
else:
super(Tetris, self).keyPressEvent(event)
self.updateWindow()
def gameOver(self):
self.isGameOver = True
self.timer.stop()
self.tboard.msg2Statusbar.emit("Game Over! Press R to Restart.")
self.updateWindow()
def restartGame(self):
self.isPaused = False
self.isGameOver = False
self.tboard.score = 0
BOARD_DATA.clear()
BOARD_DATA.createNewPiece()
self.timer.start(self.speed, self)
self.updateWindow()
class SidePanel(QFrame):
def __init__(self, parent, gridSize):
super().__init__(parent)
self.setFixedSize(gridSize * 5, gridSize * BOARD_DATA.height)
self.move(gridSize * BOARD_DATA.width, 0)
self.gridSize = gridSize
def updateData(self):
self.update()
def paintEvent(self, event):
painter = QPainter(self)
minX, maxX, minY, maxY = BOARD_DATA.nextShape.getBoundingOffsets(0)
dy = 3 * self.gridSize
dx = int((self.width() - (maxX - minX) * self.gridSize) / 2)
val = BOARD_DATA.nextShape.shape
for x, y in BOARD_DATA.nextShape.getCoords(0, 0, -minY):
drawSquare(painter, x * self.gridSize + dx, y * self.gridSize + dy, val, self.gridSize)
class Board(QFrame):
msg2Statusbar = pyqtSignal(str)
speed = 10
def __init__(self, parent, gridSize):
super().__init__(parent)
self.setFixedSize(gridSize * BOARD_DATA.width, gridSize * BOARD_DATA.height)
self.gridSize = gridSize
self.initBoard()
def initBoard(self):
self.score = 0
BOARD_DATA.clear()
def gameOver(self):
spawn_x, spawn_y = self.width // 2, self.height - 1
for x, y in self.getCurrentShapeCoord(spawn_x, spawn_y):
if self.getValue(x, y) != 0:
return True
return False
def paintEvent(self, event):
painter = QPainter(self)
for x in range(BOARD_DATA.width):
for y in range(BOARD_DATA.height):
val = BOARD_DATA.getValue(x, y)
drawSquare(painter, x * self.gridSize, y * self.gridSize, val, self.gridSize)
for x, y in BOARD_DATA.getCurrentShapeCoord():
val = BOARD_DATA.currentShape.shape
drawSquare(painter, x * self.gridSize, y * self.gridSize, val, self.gridSize)
if self.parent().isGameOver:
self.drawGameOverMessage(painter)
painter.setPen(QColor(0x777777))
painter.drawLine(self.width()-1, 0, self.width()-1, self.height())
painter.setPen(QColor(0xCCCCCC))
painter.drawLine(self.width(), 0, self.width(), self.height())
def drawGameOverMessage(self, painter):
painter.setPen(QColor(255, 0, 0))
painter.setFont(QFont('Arial', 20, QFont.Bold))
painter.drawText(self.rect(), Qt.AlignCenter, "Game Over!")
def updateData(self):
self.msg2Statusbar.emit(str(self.score))
self.update()
def drawSquare(painter, x, y, val, s):
colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC,
0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00]
if val == 0:
return
color = QColor(colorTable[val])
painter.fillRect(x + 1, y + 1, s - 2, s - 2, color)
painter.setPen(color.lighter())
painter.drawLine(x, y + s - 1, x, y)
painter.drawLine(x, y, x + s - 1, y)
painter.setPen(color.darker())
painter.drawLine(x + 1, y + s - 1, x + s - 1, y + s - 1)
painter.drawLine(x + s - 1, y + s - 1, x + s - 1, y + 1)
if __name__ == '__main__':
app = QApplication([])
tetris = Tetris()
sys.exit(app.exec_())