1 #!/usr/bin/python3 2 # -*- coding: utf-8 -*- 3 4 """ 5 ZetCode PyQt5 tutorial 6 7 This is a Tetris game clone. 8 9 """ 10 11 from PyQt5.QtWidgets import QMainWindow, QFrame, QDesktopWidget, QApplication 12 from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal 13 from PyQt5.QtGui import QPainter, QColor 14 import sys, random 15 16 class Tetris(QMainWindow): 17 18 def __init__(self): 19 super().__init__() 20 21 self.initUI() 22 23 24 def initUI(self): 25 '''initiates application UI''' 26 27 self.tboard = Board(self) 28 self.setCentralWidget(self.tboard) 29 30 self.statusbar = self.statusBar() 31 self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage) 32 33 self.tboard.start() 34 35 self.resize(180, 380) 36 self.center() 37 self.setWindowTitle('Tetris') 38 self.show() 39 40 41 def center(self): 42 '''centers the window on the screen''' 43 44 screen = QDesktopWidget().screenGeometry() 45 size = self.geometry() 46 self.move((screen.width()-size.width())/2, 47 (screen.height()-size.height())/2) 48 49 50 class Board(QFrame): 51 52 msg2Statusbar = pyqtSignal(str) 53 54 BoardWidth = 10 55 BoardHeight = 22 56 Speed = 300 57 58 def __init__(self, parent): 59 super().__init__(parent) 60 61 self.initBoard() 62 63 64 def initBoard(self): 65 '''initiates board''' 66 67 self.timer = QBasicTimer() 68 self.isWaitingAfterLine = False 69 70 self.curX = 0 71 self.curY = 0 72 self.numLinesRemoved = 0 73 self.board = [] 74 75 self.setFocusPolicy(Qt.StrongFocus) 76 self.isStarted = False 77 self.isPaused = False 78 self.clearBoard() 79 80 81 def shapeAt(self, x, y): 82 '''determines shape at the board position''' 83 84 return self.board[(y * Board.BoardWidth) + x] 85 86 87 def setShapeAt(self, x, y, shape): 88 '''sets a shape at the board''' 89 90 self.board[(y * Board.BoardWidth) + x] = shape 91 92 93 def squareWidth(self): 94 '''returns the width of one square''' 95 96 return self.contentsRect().width() // Board.BoardWidth 97 98 99 def squareHeight(self): 100 '''returns the height of one square''' 101 102 return self.contentsRect().height() // Board.BoardHeight 103 104 105 def start(self): 106 '''starts game''' 107 108 if self.isPaused: 109 return 110 111 self.isStarted = True 112 self.isWaitingAfterLine = False 113 self.numLinesRemoved = 0 114 self.clearBoard() 115 116 self.msg2Statusbar.emit(str(self.numLinesRemoved)) 117 118 self.newPiece() 119 self.timer.start(Board.Speed, self) 120 121 122 def pause(self): 123 '''pauses game''' 124 125 if not self.isStarted: 126 return 127 128 self.isPaused = not self.isPaused 129 130 if self.isPaused: 131 self.timer.stop() 132 self.msg2Statusbar.emit("paused") 133 134 else: 135 self.timer.start(Board.Speed, self) 136 self.msg2Statusbar.emit(str(self.numLinesRemoved)) 137 138 self.update() 139 140 141 def paintEvent(self, event): 142 '''paints all shapes of the game''' 143 144 painter = QPainter(self) 145 rect = self.contentsRect() 146 147 boardTop = rect.bottom() - Board.BoardHeight * self.squareHeight() 148 149 for i in range(Board.BoardHeight): 150 for j in range(Board.BoardWidth): 151 shape = self.shapeAt(j, Board.BoardHeight - i - 1) 152 153 if shape != Tetrominoe.NoShape: 154 self.drawSquare(painter, 155 rect.left() + j * self.squareWidth(), 156 boardTop + i * self.squareHeight(), shape) 157 158 if self.curPiece.shape() != Tetrominoe.NoShape: 159 160 for i in range(4): 161 162 x = self.curX + self.curPiece.x(i) 163 y = self.curY - self.curPiece.y(i) 164 self.drawSquare(painter, rect.left() + x * self.squareWidth(), 165 boardTop + (Board.BoardHeight - y - 1) * self.squareHeight(), 166 self.curPiece.shape()) 167 168 169 def keyPressEvent(self, event): 170 '''processes key press events''' 171 172 if not self.isStarted or self.curPiece.shape() == Tetrominoe.NoShape: 173 super(Board, self).keyPressEvent(event) 174 return 175 176 key = event.key() 177 178 if key == Qt.Key_P: 179 self.pause() 180 return 181 182 if self.isPaused: 183 return 184 185 elif key == Qt.Key_Left: 186 self.tryMove(self.curPiece, self.curX - 1, self.curY) 187 188 elif key == Qt.Key_Right: 189 self.tryMove(self.curPiece, self.curX + 1, self.curY) 190 191 elif key == Qt.Key_Down: 192 self.tryMove(self.curPiece.rotateRight(), self.curX, self.curY) 193 194 elif key == Qt.Key_Up: 195 self.tryMove(self.curPiece.rotateLeft(), self.curX, self.curY) 196 197 elif key == Qt.Key_Space: 198 self.dropDown() 199 200 elif key == Qt.Key_D: 201 self.oneLineDown() 202 203 else: 204 super(Board, self).keyPressEvent(event) 205 206 207 def timerEvent(self, event): 208 '''handles timer event''' 209 210 if event.timerId() == self.timer.timerId(): 211 212 if self.isWaitingAfterLine: 213 self.isWaitingAfterLine = False 214 self.newPiece() 215 else: 216 self.oneLineDown() 217 218 else: 219 super(Board, self).timerEvent(event) 220 221 222 def clearBoard(self): 223 '''clears shapes from the board''' 224 225 for i in range(Board.BoardHeight * Board.BoardWidth): 226 self.board.append(Tetrominoe.NoShape) 227 228 229 def dropDown(self): 230 '''drops down a shape''' 231 232 newY = self.curY 233 234 while newY > 0: 235 236 if not self.tryMove(self.curPiece, self.curX, newY - 1): 237 break 238 239 newY -= 1 240 241 self.pieceDropped() 242 243 244 def oneLineDown(self): 245 '''goes one line down with a shape''' 246 247 if not self.tryMove(self.curPiece, self.curX, self.curY - 1): 248 self.pieceDropped() 249 250 251 def pieceDropped(self): 252 '''after dropping shape, remove full lines and create new shape''' 253 254 for i in range(4): 255 256 x = self.curX + self.curPiece.x(i) 257 y = self.curY - self.curPiece.y(i) 258 self.setShapeAt(x, y, self.curPiece.shape()) 259 260 self.removeFullLines() 261 262 if not self.isWaitingAfterLine: 263 self.newPiece() 264 265 266 def removeFullLines(self): 267 '''removes all full lines from the board''' 268 269 numFullLines = 0 270 rowsToRemove = [] 271 272 for i in range(Board.BoardHeight): 273 274 n = 0 275 for j in range(Board.BoardWidth): 276 if not self.shapeAt(j, i) == Tetrominoe.NoShape: 277 n = n + 1 278 279 if n == 10: 280 rowsToRemove.append(i) 281 282 rowsToRemove.reverse() 283 284 285 for m in rowsToRemove: 286 287 for k in range(m, Board.BoardHeight): 288 for l in range(Board.BoardWidth): 289 self.setShapeAt(l, k, self.shapeAt(l, k + 1)) 290 291 numFullLines = numFullLines + len(rowsToRemove) 292 293 if numFullLines > 0: 294 295 self.numLinesRemoved = self.numLinesRemoved + numFullLines 296 self.msg2Statusbar.emit(str(self.numLinesRemoved)) 297 298 self.isWaitingAfterLine = True 299 self.curPiece.setShape(Tetrominoe.NoShape) 300 self.update() 301 302 303 def newPiece(self): 304 '''creates a new shape''' 305 306 self.curPiece = Shape() 307 self.curPiece.setRandomShape() 308 self.curX = Board.BoardWidth // 2 + 1 309 self.curY = Board.BoardHeight - 1 + self.curPiece.minY() 310 311 if not self.tryMove(self.curPiece, self.curX, self.curY): 312 313 self.curPiece.setShape(Tetrominoe.NoShape) 314 self.timer.stop() 315 self.isStarted = False 316 self.msg2Statusbar.emit("Game over") 317 318 319 320 def tryMove(self, newPiece, newX, newY): 321 '''tries to move a shape''' 322 323 for i in range(4): 324 325 x = newX + newPiece.x(i) 326 y = newY - newPiece.y(i) 327 328 if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight: 329 return False 330 331 if self.shapeAt(x, y) != Tetrominoe.NoShape: 332 return False 333 334 self.curPiece = newPiece 335 self.curX = newX 336 self.curY = newY 337 self.update() 338 339 return True 340 341 342 def drawSquare(self, painter, x, y, shape): 343 '''draws a square of a shape''' 344 345 colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC, 346 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00] 347 348 color = QColor(colorTable[shape]) 349 painter.fillRect(x + 1, y + 1, self.squareWidth() - 2, 350 self.squareHeight() - 2, color) 351 352 painter.setPen(color.lighter()) 353 painter.drawLine(x, y + self.squareHeight() - 1, x, y) 354 painter.drawLine(x, y, x + self.squareWidth() - 1, y) 355 356 painter.setPen(color.darker()) 357 painter.drawLine(x + 1, y + self.squareHeight() - 1, 358 x + self.squareWidth() - 1, y + self.squareHeight() - 1) 359 painter.drawLine(x + self.squareWidth() - 1, 360 y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + 1) 361 362 363 class Tetrominoe(object): 364 365 NoShape = 0 366 ZShape = 1 367 SShape = 2 368 LineShape = 3 369 TShape = 4 370 SquareShape = 5 371 LShape = 6 372 MirroredLShape = 7 373 374 375 class Shape(object): 376 377 coordsTable = ( 378 ((0, 0), (0, 0), (0, 0), (0, 0)), 379 ((0, -1), (0, 0), (-1, 0), (-1, 1)), 380 ((0, -1), (0, 0), (1, 0), (1, 1)), 381 ((0, -1), (0, 0), (0, 1), (0, 2)), 382 ((-1, 0), (0, 0), (1, 0), (0, 1)), 383 ((0, 0), (1, 0), (0, 1), (1, 1)), 384 ((-1, -1), (0, -1), (0, 0), (0, 1)), 385 ((1, -1), (0, -1), (0, 0), (0, 1)) 386 ) 387 388 def __init__(self): 389 390 self.coords = [[0,0] for i in range(4)] 391 self.pieceShape = Tetrominoe.NoShape 392 393 self.setShape(Tetrominoe.NoShape) 394 395 396 def shape(self): 397 '''returns shape''' 398 399 return self.pieceShape 400 401 402 def setShape(self, shape): 403 '''sets a shape''' 404 405 table = Shape.coordsTable[shape] 406 407 for i in range(4): 408 for j in range(2): 409 self.coords[i][j] = table[i][j] 410 411 self.pieceShape = shape 412 413 414 def setRandomShape(self): 415 '''chooses a random shape''' 416 417 self.setShape(random.randint(1, 7)) 418 419 420 def x(self, index): 421 '''returns x coordinate''' 422 423 return self.coords[index][0] 424 425 426 def y(self, index): 427 '''returns y coordinate''' 428 429 return self.coords[index][1] 430 431 432 def setX(self, index, x): 433 '''sets x coordinate''' 434 435 self.coords[index][0] = x 436 437 438 def setY(self, index, y): 439 '''sets y coordinate''' 440 441 self.coords[index][1] = y 442 443 444 def minX(self): 445 '''returns min x value''' 446 447 m = self.coords[0][0] 448 for i in range(4): 449 m = min(m, self.coords[i][0]) 450 451 return m 452 453 454 def maxX(self): 455 '''returns max x value''' 456 457 m = self.coords[0][0] 458 for i in range(4): 459 m = max(m, self.coords[i][0]) 460 461 return m 462 463 464 def minY(self): 465 '''returns min y value''' 466 467 m = self.coords[0][1] 468 for i in range(4): 469 m = min(m, self.coords[i][1]) 470 471 return m 472 473 474 def maxY(self): 475 '''returns max y value''' 476 477 m = self.coords[0][1] 478 for i in range(4): 479 m = max(m, self.coords[i][1]) 480 481 return m 482 483 484 def rotateLeft(self): 485 '''rotates shape to the left''' 486 487 if self.pieceShape == Tetrominoe.SquareShape: 488 return self 489 490 result = Shape() 491 result.pieceShape = self.pieceShape 492 493 for i in range(4): 494 495 result.setX(i, self.y(i)) 496 result.setY(i, -self.x(i)) 497 498 return result 499 500 501 def rotateRight(self): 502 '''rotates shape to the right''' 503 504 if self.pieceShape == Tetrominoe.SquareShape: 505 return self 506 507 result = Shape() 508 result.pieceShape = self.pieceShape 509 510 for i in range(4): 511 512 result.setX(i, -self.y(i)) 513 result.setY(i, self.x(i)) 514 515 return result 516 517 518 if __name__ == '__main__': 519 520 app = QApplication([]) 521 tetris = Tetris() 522 sys.exit(app.exec_())
游戏很简单,所以也就很好理解。程序加载之后游戏也就直接开始了,可以用P键暂停游戏,空格键让方块直接落到最下面。游戏的速度是固定的,并没有实现加速的功能。分数就是游戏中消除的行数。
self.tboard = Board(self)
self.setCentralWidget(self.tboard)
创建了一个Board类的实例,并设置为应用的中心组件。
self.statusbar = self.statusBar()
self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)
创建一个statusbar
来显示三种信息:消除的行数,游戏暂停状态或者游戏结束状态。msg2Statusbar
是一个自定义的信号,用在(和)Board类(交互),showMessage()
方法是一个内建的,用来在statusbar上显示信息的方法。
self.tboard.start()
初始化游戏:
class Board(QFrame):
msg2Statusbar = pyqtSignal(str)
...
创建了一个自定义信号msg2Statusbar
,当我们想往statusbar
里显示信息的时候,发出这个信号就行了。
BoardWidth = 10
BoardHeight = 22
Speed = 300
这些是Board
类的变量。BoardWidth
和BoardHeight
分别是board的宽度和高度。Speed
是游戏的速度,每300ms出现一个新的方块。
...
self.curX = 0
self.curY = 0
self.numLinesRemoved = 0
self.board = []
...
在initBoard()
里初始化了一些重要的变量。self.board
定义了方块的形状和位置,取值范围是0-7。
def shapeAt(self, x, y):
return self.board[(y * Board.BoardWidth) + x]
shapeAt()
决定了board里方块的的种类。
def squareWidth(self):
return self.contentsRect().width() // Board.BoardWidth
board的大小可以动态的改变。所以方格的大小也应该随之变化。squareWidth()
计算并返回每个块应该占用多少像素--也即Board.BoardWidth
。
def pause(self):
'''pauses game'''
if not self.isStarted:
return
self.isPaused = not self.isPaused
if self.isPaused:
self.timer.stop()
self.msg2Statusbar.emit("paused")
else:
self.timer.start(Board.Speed, self)
self.msg2Statusbar.emit(str(self.numLinesRemoved))
self.update()
pause()
方法用来暂停游戏,停止计时并在statusbar
上显示一条信息。
def paintEvent(self, event):
'''paints all shapes of the game'''
painter = QPainter(self)
rect = self.contentsRect()
...
渲染是在paintEvent()方法里发生的QPainter
负责PyQt5里所有低级绘画操作。
for i in range(Board.BoardHeight):
for j in range(Board.BoardWidth):
shape = self.shapeAt(j, Board.BoardHeight - i - 1)
if shape != Tetrominoe.NoShape:
self.drawSquare(painter,
rect.left() + j * self.squareWidth(),
boardTop + i * self.squareHeight(), shape)
渲染游戏分为两步。第一步是先画出所有已经落在最下面的的图,这些保存在self.board
里。可以使用shapeAt()
查看这个这个变量。
if self.curPiece.shape() != Tetrominoe.NoShape:
for i in range(4):
x = self.curX + self.curPiece.x(i)
y = self.curY - self.curPiece.y(i)
self.drawSquare(painter, rect.left() + x * self.squareWidth(),
boardTop + (Board.BoardHeight - y - 1) * self.squareHeight(),
self.curPiece.shape())
第二步是画出更在下落的方块。
elif key == Qt.Key_Right:
self.tryMove(self.curPiece, self.curX + 1, self.curY)
在keyPressEvent()
方法获得用户按下的按键。如果按下的是右方向键,就尝试把方块向右移动,说尝试是因为有可能到边界不能移动了。
elif key == Qt.Key_Up:
self.tryMove(self.curPiece.rotateLeft(), self.curX, self.curY)
上方向键是把方块向左旋转一下
elif key == Qt.Key_Space:
self.dropDown()
空格键会直接把方块放到底部
elif key == Qt.Key_D:
self.oneLineDown()
D键是加速一次下落速度。
def tryMove(self, newPiece, newX, newY):
for i in range(4):
x = newX + newPiece.x(i)
y = newY - newPiece.y(i)
if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight:
return False
if self.shapeAt(x, y) != Tetrominoe.NoShape:
return False
self.curPiece = newPiece
self.curX = newX
self.curY = newY
self.update()
return True
tryMove()
是尝试移动方块的方法。如果方块已经到达board的边缘或者遇到了其他方块,就返回False。否则就把方块下落到想要
def timerEvent(self, event):
if event.timerId() == self.timer.timerId():
if self.isWaitingAfterLine:
self.isWaitingAfterLine = False
self.newPiece()
else:
self.oneLineDown()
else:
super(Board, self).timerEvent(event)
在计时器事件里,要么是等一个方块下落完之后创建一个新的方块,要么是让一个方块直接落到底(move a falling piece one line down)。
def clearBoard(self):
for i in range(Board.BoardHeight * Board.BoardWidth):
self.board.append(Tetrominoe.NoShape)
clearBoard(
)方法通过Tetrominoe.NoShape
清空broad
。
def removeFullLines(self):
numFullLines = 0
rowsToRemove = []
for i in range(Board.BoardHeight):
n = 0
for j in range(Board.BoardWidth):
if not self.shapeAt(j, i) == Tetrominoe.NoShape:
n = n + 1
if n == 10:
rowsToRemove.append(i)
rowsToRemove.reverse()
for m in rowsToRemove:
for k in range(m, Board.BoardHeight):
for l in range(Board.BoardWidth):
self.setShapeAt(l, k, self.shapeAt(l, k + 1))
numFullLines = numFullLines + len(rowsToRemove)
...
如果方块碰到了底部,就调用removeFullLines()
方法,找到所有能消除的行消除它们。消除的具体动作就是把符合条件的行消除掉之后,再把它上面的行下降一行。注意移除满行的动作是倒着来的,因为我们是按照重力来表现游戏的,如果不这样就有可能出现有些方块浮在空中的现象。
def newPiece(self):
self.curPiece = Shape()
self.curPiece.setRandomShape()
self.curX = Board.BoardWidth // 2 + 1
self.curY = Board.BoardHeight - 1 + self.curPiece.minY()
if not self.tryMove(self.curPiece, self.curX, self.curY):
self.curPiece.setShape(Tetrominoe.NoShape)
self.timer.stop()
self.isStarted = False
self.msg2Statusbar.emit("Game over")
newPiece()
方法是用来创建形状随机的方块。如果随机的方块不能正确的出现在预设的位置,游戏结束。
class Tetrominoe(object):
NoShape = 0
ZShape = 1
SShape = 2
LineShape = 3
TShape = 4
SquareShape = 5
LShape = 6
MirroredLShape = 7
Tetrominoe
类保存了所有方块的形状。我们还定义了一个NoShape
的空形状。
Shape类保存类方块内部的信息。
class Shape(object):
coordsTable = (
((0, 0), (0, 0), (0, 0), (0, 0)),
((0, -1), (0, 0), (-1, 0), (-1, 1)),
...
)
...
coordsTable元组保存了所有的方块形状的组成。是一个构成方块的坐标模版。
self.coords = [[0,0] for i in range(4)]
上面创建了一个新的空坐标数组,这个数组将用来保存方块的坐标。
坐标系示意图:
上面的图片可以帮助我们更好的理解坐标值的意义。比如元组(0, -1), (0, 0), (-1, 0), (-1, -1)
代表了一个Z形状的方块。这个图表就描绘了这个形状。
def rotateLeft(self):
if self.pieceShape == Tetrominoe.SquareShape:
return self
result = Shape()
result.pieceShape = self.pieceShape
for i in range(4):
result.setX(i, self.y(i))
result.setY(i, -self.x(i))
return result
rotateLeft()
方法向右旋转一个方块。正方形的方块就没必要旋转,就直接返回了。其他的是返回一个新的,能表示这个形状旋转了的坐标。
程序展示: