原文: http://zetcode.com/gui/pyqt4/thetetrisgame/

在本章中,我们将创建一个俄罗斯方块游戏克隆。

俄罗斯方块

俄罗斯方块游戏是有史以来最受欢迎的计算机游戏之一。 原始游戏是由俄罗斯程序员 Alexey Pajitnov 于 1985 年设计和编程的。此后,几乎所有版本的几乎所有计算机平台上都可以使用俄罗斯方块。

俄罗斯方块被称为下降块益智游戏。 在这个游戏中,我们有七个不同的形状,称为 tetrominoes :S 形,Z 形,T 形,L 形,线形,MirroredL 形和正方形。 这些形状中的每一个都形成有四个正方形。 形状从板上掉下来。 俄罗斯方块游戏的目的是移动和旋转形状,以使其尽可能地适合。 如果我们设法形成一行,则该行将被破坏并得分。 我们玩俄罗斯方块游戏,直到达到顶峰。

PyQt4 中的俄罗斯方块游戏 - 图1

图:Tetrominoes

PyQt4 是旨在创建应用的工具包。 还有其他一些旨在创建计算机游戏的库。 不过,PyQt4 和其他应用工具包可用于创建简单的游戏。

创建计算机游戏是增强编程技能的好方法。

开发

我们的俄罗斯方块游戏没有图像,我们使用 PyQt4 编程工具包中提供的绘图 API 绘制四面体。 每个计算机游戏的背后都有一个数学模型。 俄罗斯方块也是如此。

游戏背后的一些想法:

  • 我们使用QtCore.QBasicTimer()创建游戏周期。
  • 绘制四方块。
  • 形状以正方形为单位移动(而不是逐个像素移动)。
  • 从数学上讲,棋盘是一个简单的数字列表。

该代码包括四个类别:TetrisBoardTetrominoeShapeTetris类设置游戏。 Board是编写游戏逻辑的地方。 Tetrominoe类包含所有俄罗斯方块的名称,Shape类包含俄罗斯方块的代码。

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt4 tutorial
  5. This is a Tetris game clone.
  6. author: Jan Bodnar
  7. website: zetcode.com
  8. last edited: October 2013
  9. """
  10. import sys, random
  11. from PyQt4 import QtCore, QtGui
  12. class Tetris(QtGui.QMainWindow):
  13. def __init__(self):
  14. super(Tetris, self).__init__()
  15. self.initUI()
  16. def initUI(self):
  17. self.tboard = Board(self)
  18. self.setCentralWidget(self.tboard)
  19. self.statusbar = self.statusBar()
  20. self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)
  21. self.tboard.start()
  22. self.resize(180, 380)
  23. self.center()
  24. self.setWindowTitle('Tetris')
  25. self.show()
  26. def center(self):
  27. screen = QtGui.QDesktopWidget().screenGeometry()
  28. size = self.geometry()
  29. self.move((screen.width()-size.width())/2,
  30. (screen.height()-size.height())/2)
  31. class Board(QtGui.QFrame):
  32. msg2Statusbar = QtCore.pyqtSignal(str)
  33. BoardWidth = 10
  34. BoardHeight = 22
  35. Speed = 300
  36. def __init__(self, parent):
  37. super(Board, self).__init__(parent)
  38. self.initBoard()
  39. def initBoard(self):
  40. self.timer = QtCore.QBasicTimer()
  41. self.isWaitingAfterLine = False
  42. self.curX = 0
  43. self.curY = 0
  44. self.numLinesRemoved = 0
  45. self.board = []
  46. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  47. self.isStarted = False
  48. self.isPaused = False
  49. self.clearBoard()
  50. def shapeAt(self, x, y):
  51. return self.board[(y * Board.BoardWidth) + x]
  52. def setShapeAt(self, x, y, shape):
  53. self.board[(y * Board.BoardWidth) + x] = shape
  54. def squareWidth(self):
  55. return self.contentsRect().width() / Board.BoardWidth
  56. def squareHeight(self):
  57. return self.contentsRect().height() / Board.BoardHeight
  58. def start(self):
  59. if self.isPaused:
  60. return
  61. self.isStarted = True
  62. self.isWaitingAfterLine = False
  63. self.numLinesRemoved = 0
  64. self.clearBoard()
  65. self.msg2Statusbar.emit(str(self.numLinesRemoved))
  66. self.newPiece()
  67. self.timer.start(Board.Speed, self)
  68. def pause(self):
  69. if not self.isStarted:
  70. return
  71. self.isPaused = not self.isPaused
  72. if self.isPaused:
  73. self.timer.stop()
  74. self.msg2Statusbar.emit("paused")
  75. else:
  76. self.timer.start(Board.Speed, self)
  77. self.msg2Statusbar.emit(str(self.numLinesRemoved))
  78. self.update()
  79. def paintEvent(self, event):
  80. painter = QtGui.QPainter(self)
  81. rect = self.contentsRect()
  82. boardTop = rect.bottom() - Board.BoardHeight * self.squareHeight()
  83. for i in range(Board.BoardHeight):
  84. for j in range(Board.BoardWidth):
  85. shape = self.shapeAt(j, Board.BoardHeight - i - 1)
  86. if shape != Tetrominoe.NoShape:
  87. self.drawSquare(painter,
  88. rect.left() + j * self.squareWidth(),
  89. boardTop + i * self.squareHeight(), shape)
  90. if self.curPiece.shape() != Tetrominoe.NoShape:
  91. for i in range(4):
  92. x = self.curX + self.curPiece.x(i)
  93. y = self.curY - self.curPiece.y(i)
  94. self.drawSquare(painter, rect.left() + x * self.squareWidth(),
  95. boardTop + (Board.BoardHeight - y - 1) * self.squareHeight(),
  96. self.curPiece.shape())
  97. def keyPressEvent(self, event):
  98. if not self.isStarted or self.curPiece.shape() == Tetrominoe.NoShape:
  99. super(Board, self).keyPressEvent(event)
  100. return
  101. key = event.key()
  102. if key == QtCore.Qt.Key_P:
  103. self.pause()
  104. return
  105. if self.isPaused:
  106. return
  107. elif key == QtCore.Qt.Key_Left:
  108. self.tryMove(self.curPiece, self.curX - 1, self.curY)
  109. elif key == QtCore.Qt.Key_Right:
  110. self.tryMove(self.curPiece, self.curX + 1, self.curY)
  111. elif key == QtCore.Qt.Key_Down:
  112. self.tryMove(self.curPiece.rotateRight(), self.curX, self.curY)
  113. elif key == QtCore.Qt.Key_Up:
  114. self.tryMove(self.curPiece.rotateLeft(), self.curX, self.curY)
  115. elif key == QtCore.Qt.Key_Space:
  116. self.dropDown()
  117. elif key == QtCore.Qt.Key_D:
  118. self.oneLineDown()
  119. else:
  120. super(Board, self).keyPressEvent(event)
  121. def timerEvent(self, event):
  122. if event.timerId() == self.timer.timerId():
  123. if self.isWaitingAfterLine:
  124. self.isWaitingAfterLine = False
  125. self.newPiece()
  126. else:
  127. self.oneLineDown()
  128. else:
  129. super(Board, self).timerEvent(event)
  130. def clearBoard(self):
  131. for i in range(Board.BoardHeight * Board.BoardWidth):
  132. self.board.append(Tetrominoe.NoShape)
  133. def dropDown(self):
  134. newY = self.curY
  135. while newY > 0:
  136. if not self.tryMove(self.curPiece, self.curX, newY - 1):
  137. break
  138. newY -= 1
  139. self.pieceDropped()
  140. def oneLineDown(self):
  141. if not self.tryMove(self.curPiece, self.curX, self.curY - 1):
  142. self.pieceDropped()
  143. def pieceDropped(self):
  144. for i in range(4):
  145. x = self.curX + self.curPiece.x(i)
  146. y = self.curY - self.curPiece.y(i)
  147. self.setShapeAt(x, y, self.curPiece.shape())
  148. self.removeFullLines()
  149. if not self.isWaitingAfterLine:
  150. self.newPiece()
  151. def removeFullLines(self):
  152. numFullLines = 0
  153. rowsToRemove = []
  154. for i in range(Board.BoardHeight):
  155. n = 0
  156. for j in range(Board.BoardWidth):
  157. if not self.shapeAt(j, i) == Tetrominoe.NoShape:
  158. n = n + 1
  159. if n == 10:
  160. rowsToRemove.append(i)
  161. rowsToRemove.reverse()
  162. for m in rowsToRemove:
  163. for k in range(m, Board.BoardHeight):
  164. for l in range(Board.BoardWidth):
  165. self.setShapeAt(l, k, self.shapeAt(l, k + 1))
  166. numFullLines = numFullLines + len(rowsToRemove)
  167. if numFullLines > 0:
  168. self.numLinesRemoved = self.numLinesRemoved + numFullLines
  169. self.msg2Statusbar.emit(str(self.numLinesRemoved))
  170. self.isWaitingAfterLine = True
  171. self.curPiece.setShape(Tetrominoe.NoShape)
  172. self.update()
  173. def newPiece(self):
  174. self.curPiece = Shape()
  175. self.curPiece.setRandomShape()
  176. self.curX = Board.BoardWidth / 2 + 1
  177. self.curY = Board.BoardHeight - 1 + self.curPiece.minY()
  178. #print self.curY
  179. if not self.tryMove(self.curPiece, self.curX, self.curY):
  180. self.curPiece.setShape(Tetrominoe.NoShape)
  181. self.timer.stop()
  182. self.isStarted = False
  183. self.msg2Statusbar.emit("Game over")
  184. def tryMove(self, newPiece, newX, newY):
  185. for i in range(4):
  186. x = newX + newPiece.x(i)
  187. y = newY - newPiece.y(i)
  188. if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight:
  189. return False
  190. if self.shapeAt(x, y) != Tetrominoe.NoShape:
  191. return False
  192. self.curPiece = newPiece
  193. self.curX = newX
  194. self.curY = newY
  195. self.update()
  196. return True
  197. def drawSquare(self, painter, x, y, shape):
  198. colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC,
  199. 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00]
  200. color = QtGui.QColor(colorTable[shape])
  201. painter.fillRect(x + 1, y + 1, self.squareWidth() - 2,
  202. self.squareHeight() - 2, color)
  203. painter.setPen(color.light())
  204. painter.drawLine(x, y + self.squareHeight() - 1, x, y)
  205. painter.drawLine(x, y, x + self.squareWidth() - 1, y)
  206. painter.setPen(color.dark())
  207. painter.drawLine(x + 1, y + self.squareHeight() - 1,
  208. x + self.squareWidth() - 1, y + self.squareHeight() - 1)
  209. painter.drawLine(x + self.squareWidth() - 1,
  210. y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + 1)
  211. class Tetrominoe(object):
  212. NoShape = 0
  213. ZShape = 1
  214. SShape = 2
  215. LineShape = 3
  216. TShape = 4
  217. SquareShape = 5
  218. LShape = 6
  219. MirroredLShape = 7
  220. class Shape(object):
  221. coordsTable = (
  222. ((0, 0), (0, 0), (0, 0), (0, 0)),
  223. ((0, -1), (0, 0), (-1, 0), (-1, 1)),
  224. ((0, -1), (0, 0), (1, 0), (1, 1)),
  225. ((0, -1), (0, 0), (0, 1), (0, 2)),
  226. ((-1, 0), (0, 0), (1, 0), (0, 1)),
  227. ((0, 0), (1, 0), (0, 1), (1, 1)),
  228. ((-1, -1), (0, -1), (0, 0), (0, 1)),
  229. ((1, -1), (0, -1), (0, 0), (0, 1))
  230. )
  231. def __init__(self):
  232. self.coords = [[0,0] for i in range(4)]
  233. self.pieceShape = Tetrominoe.NoShape
  234. self.setShape(Tetrominoe.NoShape)
  235. def shape(self):
  236. return self.pieceShape
  237. def setShape(self, shape):
  238. table = Shape.coordsTable[shape]
  239. for i in range(4):
  240. for j in range(2):
  241. self.coords[i][j] = table[i][j]
  242. self.pieceShape = shape
  243. def setRandomShape(self):
  244. self.setShape(random.randint(1, 7))
  245. def x(self, index):
  246. return self.coords[index][0]
  247. def y(self, index):
  248. return self.coords[index][1]
  249. def setX(self, index, x):
  250. self.coords[index][0] = x
  251. def setY(self, index, y):
  252. self.coords[index][1] = y
  253. def minX(self):
  254. m = self.coords[0][0]
  255. for i in range(4):
  256. m = min(m, self.coords[i][0])
  257. return m
  258. def maxX(self):
  259. m = self.coords[0][0]
  260. for i in range(4):
  261. m = max(m, self.coords[i][0])
  262. return m
  263. def minY(self):
  264. m = self.coords[0][1]
  265. for i in range(4):
  266. m = min(m, self.coords[i][1])
  267. return m
  268. def maxY(self):
  269. m = self.coords[0][1]
  270. for i in range(4):
  271. m = max(m, self.coords[i][1])
  272. return m
  273. def rotateLeft(self):
  274. if self.pieceShape == Tetrominoe.SquareShape:
  275. return self
  276. result = Shape()
  277. result.pieceShape = self.pieceShape
  278. for i in range(4):
  279. result.setX(i, self.y(i))
  280. result.setY(i, -self.x(i))
  281. return result
  282. def rotateRight(self):
  283. if self.pieceShape == Tetrominoe.SquareShape:
  284. return self
  285. result = Shape()
  286. result.pieceShape = self.pieceShape
  287. for i in range(4):
  288. result.setX(i, -self.y(i))
  289. result.setY(i, self.x(i))
  290. return result
  291. def main():
  292. app = QtGui.QApplication([])
  293. tetris = Tetris()
  294. sys.exit(app.exec_())
  295. if __name__ == '__main__':
  296. main()

游戏进行了简化,以便于理解。 游戏启动后立即开始。 我们可以通过按 p 键暂停游戏。 Space 键将使俄罗斯方块立即下降到底部。 游戏以恒定速度进行,没有实现加速。 分数是我们已删除的行数。

  1. self.tboard = Board(self)
  2. self.setCentralWidget(self.tboard)

创建Board类的实例,并将其设置为应用的中央窗口小部件。

  1. self.statusbar = self.statusBar()
  2. self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)

我们创建一个状态栏,在其中显示消息。 我们将显示三种可能的消息:已删除的行数,暂停的消息或游戏结束消息。 msg2Statusbar是在Board类中实现的自定义信号。 showMessage()是一种内置方法,可在状态栏上显示一条消息。

  1. self.tboard.start()

这条线启动了游戏。

  1. class Board(QtGui.QFrame):
  2. msg2Statusbar = QtCore.pyqtSignal(str)
  3. ...

创建自定义信号。 msg2Statusbar是当我们要向状态栏写消息或乐谱时发出的信号。

  1. BoardWidth = 10
  2. BoardHeight = 22
  3. Speed = 300

这些是Board's类变量。 BoardWidthBoardHeight以块为单位定义电路板的大小。 Speed定义游戏的速度。 每 300 毫秒将开始一个新的游戏周期。

  1. ...
  2. self.curX = 0
  3. self.curY = 0
  4. self.numLinesRemoved = 0
  5. self.board = []
  6. ...

initBoard()方法中,我们初始化了一些重要的变量。 变量self.board是从 0 到 7 的数字的列表。它表示各种形状的位置以及板上形状的其余部分。

  1. def shapeAt(self, x, y):
  2. return self.board[(y * Board.BoardWidth) + x]

shapeAt()方法确定给定块上的形状类型。

  1. def squareWidth(self):
  2. return self.contentsRect().width() / Board.BoardWidth

电路板可以动态调整大小。 结果,块的大小可能改变。 squareWidth()计算单个正方形的宽度(以像素为单位)并将其返回。 Board.BoardWidth是板的大小,以块为单位。

  1. for i in range(Board.BoardHeight):
  2. for j in range(Board.BoardWidth):
  3. shape = self.shapeAt(j, Board.BoardHeight - i - 1)
  4. if shape != Tetrominoe.NoShape:
  5. self.drawSquare(painter,
  6. rect.left() + j * self.squareWidth(),
  7. boardTop + i * self.squareHeight(), shape)

游戏的绘图分为两个步骤。 在第一步中,我们绘制所有形状或已放置到板底部的形状的其余部分。 所有正方形都记在self.board列表变量中。 使用shapeAt()方法访问该变量。

  1. if self.curPiece.shape() != Tetrominoe.NoShape:
  2. for i in range(4):
  3. x = self.curX + self.curPiece.x(i)
  4. y = self.curY - self.curPiece.y(i)
  5. self.drawSquare(painter, rect.left() + x * self.squareWidth(),
  6. boardTop + (Board.BoardHeight - y - 1) * self.squareHeight(),
  7. self.curPiece.shape())

下一步是下落的实际零件的图纸。

  1. elif key == QtCore.Qt.Key_Right:
  2. self.tryMove(self.curPiece, self.curX + 1, self.curY)

keyPressEvent()方法中,我们检查按键是否按下。 如果按向右箭头键,我们将尝试将棋子向右移动。 我们说尝试,因为该部分可能无法移动。

  1. elif key == QtCore.Qt.Key_Up:
  2. self.tryMove(self.curPiece.rotateLeft(), self.curX, self.curY)

向上方向键将使下降片向左旋转。

  1. elif key == QtCore.Qt.Key_Space:
  2. self.dropDown()

空格键将立即将下降的片段降到底部。

  1. elif key == QtCore.Qt.Key_D:
  2. self.oneLineDown()

按下 d 键,乐曲将向下移动一个格。 它可以用来加速一块的下落。

  1. def tryMove(self, newPiece, newX, newY):
  2. for i in range(4):
  3. x = newX + newPiece.x(i)
  4. y = newY - newPiece.y(i)
  5. if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight:
  6. return False
  7. if self.shapeAt(x, y) != Tetrominoe.NoShape:
  8. return False
  9. self.curPiece = newPiece
  10. self.curX = newX
  11. self.curY = newY
  12. self.update()
  13. return True

tryMove()方法中,我们尝试移动形状。 如果形状在板的边缘或与其他零件相邻,则返回False。 否则,我们将当前的下降片放到新位置。

  1. def timerEvent(self, event):
  2. if event.timerId() == self.timer.timerId():
  3. if self.isWaitingAfterLine:
  4. self.isWaitingAfterLine = False
  5. self.newPiece()
  6. else:
  7. self.oneLineDown()
  8. else:
  9. super(Board, self).timerEvent(event)

在计时器事件中,我们要么在上一个下降到底部之后创建一个新作品,要么将下降的一块向下移动一行。

  1. def clearBoard(self):
  2. for i in range(Board.BoardHeight * Board.BoardWidth):
  3. self.board.append(Tetrominoe.NoShape)

clearBoard()方法通过在板的每个块上设置Tetrominoe.NoShape来清除板。

  1. def removeFullLines(self):
  2. numFullLines = 0
  3. rowsToRemove = []
  4. for i in range(Board.BoardHeight):
  5. n = 0
  6. for j in range(Board.BoardWidth):
  7. if not self.shapeAt(j, i) == Tetrominoe.NoShape:
  8. n = n + 1
  9. if n == 10:
  10. rowsToRemove.append(i)
  11. rowsToRemove.reverse()
  12. for m in rowsToRemove:
  13. for k in range(m, Board.BoardHeight):
  14. for l in range(Board.BoardWidth):
  15. self.setShapeAt(l, k, self.shapeAt(l, k + 1))
  16. numFullLines = numFullLines + len(rowsToRemove)
  17. ...

如果片段触底,我们将调用removeFullLines()方法。 我们找出所有实线并将其删除。 通过将所有行移动到当前全行上方来将其向下移动一行来实现。 请注意,我们颠倒了要删除的行的顺序。 否则,它将无法正常工作。 在我们的情况下,我们使用天真重力。 这意味着碎片可能会漂浮在空的间隙上方。

  1. def newPiece(self):
  2. self.curPiece = Shape()
  3. self.curPiece.setRandomShape()
  4. self.curX = Board.BoardWidth / 2 + 1
  5. self.curY = Board.BoardHeight - 1 + self.curPiece.minY()
  6. if not self.tryMove(self.curPiece, self.curX, self.curY):
  7. self.curPiece.setShape(Tetrominoe.NoShape)
  8. self.timer.stop()
  9. self.isStarted = False
  10. self.msg2Statusbar.emit("Game over")

newPiece()方法随机创建一个新的俄罗斯方块。 如果棋子无法进入其初始位置,则游戏结束。

  1. class Tetrominoe(object):
  2. NoShape = 0
  3. ZShape = 1
  4. SShape = 2
  5. LineShape = 3
  6. TShape = 4
  7. SquareShape = 5
  8. LShape = 6
  9. MirroredLShape = 7

Tetrominoe类包含所有可能形状的名称。 我们还有一个NoShape用于空白。

Shape类保存有关俄罗斯方块的信息。

  1. class Shape(object):
  2. coordsTable = (
  3. ((0, 0), (0, 0), (0, 0), (0, 0)),
  4. ((0, -1), (0, 0), (-1, 0), (-1, 1)),
  5. ...
  6. )
  7. ...

coordsTable元组保存我们的零件的所有可能的坐标值。 这是一个模板,所有零件均从该模板获取其坐标值。

  1. self.coords = [[0,0] for i in range(4)]

创建后,我们将创建一个空坐标列表。 该列表将保存俄罗斯方块的坐标。

PyQt4 中的俄罗斯方块游戏 - 图2

图:坐标

上面的图片将帮助您更多地了解坐标值。 例如,元组(0,-1),(0,0),(-1,0),(-1,-1)表示 Z 形。 该图说明了形状。

  1. def rotateLeft(self):
  2. if self.pieceShape == Tetrominoe.SquareShape:
  3. return self
  4. result = Shape()
  5. result.pieceShape = self.pieceShape
  6. for i in range(4):
  7. result.setX(i, self.y(i))
  8. result.setY(i, -self.x(i))
  9. return result

rotateLeft()方法将一块向左旋转。 正方形不必旋转。 这就是为什么我们只是将引用返回到当前对象。 将创建一个新零件,并将其坐标设置为旋转零件的坐标。

PyQt4 中的俄罗斯方块游戏 - 图3

图:俄罗斯方块

这是 PyQt4 中的俄罗斯方块游戏。