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_())
相关文章: