当前位置:   article > 正文

python -- PyQt5(designer)中文详细教程(十一)实例:俄罗斯方块游戏_pyqt 实例

pyqt 实例

俄罗斯方块游戏

本章我们要制作⼀个俄罗斯方块游戏。

Tetris

 译注:称呼:方块是由四个小方格组成的

俄罗斯方块游戏是世界上最流行的游戏之⼀。是由⼀名叫Alexey Pajitnov的俄罗斯程序员在1985年制作的,从那时起,这个游戏就风靡了各个游戏平台。 俄罗斯⽅块归类为下落块迷宫游戏。游戏有7个基本形状:S、Z、T、L、反向L、 直线、⽅块,每个形状都由4个方块组成,方块最终都会落到屏幕底部。所以玩家 通过控制形状的左右位置和旋转,让每个形状都以合适的位置落下,如果有⼀行全部被方块填充,这行就会消失,并且得分。游戏结束的条件是有形状接触到了屏幕 顶部。

方块展示:

PyQt5是专为创建图形界面产⽣的,⾥⾯⼀些专⻔为制作游戏⽽开发的组件,所 以PyQt5是能制作小游戏的。

  1. from PyQt5.QtWidgets import QMainWindow, QFrame, QDesktopWidget, QApplication
  2. from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal
  3. from PyQt5.QtGui import QPainter, QColor
  4. import sys, random
  5. class Tetris(QMainWindow):
  6. def __init__(self):
  7. super().__init__()
  8. self.initUI()
  9. def initUI(self):
  10. # '''initiates application UI'''
  11. self.tboard = Board(self)
  12. self.setCentralWidget(self.tboard)
  13. self.statusbar = self.statusBar()
  14. self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)
  15. self.tboard.start()
  16. self.resize(300, 500)
  17. self.center()
  18. self.setWindowTitle('Tetris')
  19. self.show()
  20. def center(self):
  21. # '''centers the window on the screen'''
  22. screen = QDesktopWidget().screenGeometry()
  23. size = self.geometry()
  24. self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
  25. class Board(QFrame):
  26. msg2Statusbar = pyqtSignal(str)
  27. BoardWidth = 10
  28. BoardHeight = 22
  29. Speed = 300
  30. def __init__(self, parent):
  31. super().__init__(parent)
  32. self.initBoard()
  33. def initBoard(self):
  34. # '''initiates board'''
  35. self.timer = QBasicTimer()
  36. self.isWaitingAfterLine = False
  37. self.curX = 0
  38. self.curY = 0
  39. self.numLinesRemoved = 0
  40. self.board = []
  41. self.setFocusPolicy(Qt.StrongFocus)
  42. self.isStarted = False
  43. self.isPaused = False
  44. self.clearBoard()
  45. def shapeAt(self, x, y):
  46. # '''determines shape at the board position'''
  47. return self.board[(y * Board.BoardWidth) + x]
  48. def setShapeAt(self, x, y, shape):
  49. # '''sets a shape at the board'''
  50. self.board[(y * Board.BoardWidth) + x] = shape
  51. def squareWidth(self):
  52. # '''returns the width of one square'''
  53. return self.contentsRect().width() // Board.BoardWidth
  54. def squareHeight(self):
  55. # '''returns the height of one square'''
  56. return self.contentsRect().height() // Board.BoardHeight
  57. def start(self):
  58. # '''starts game'''
  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. # '''pauses game'''
  70. if not self.isStarted:
  71. return
  72. self.isPaused = not self.isPaused
  73. if self.isPaused:
  74. self.timer.stop()
  75. self.msg2Statusbar.emit("paused")
  76. else:
  77. self.timer.start(Board.Speed, self)
  78. self.msg2Statusbar.emit(str(self.numLinesRemoved))
  79. self.update()
  80. def paintEvent(self, event):
  81. # '''paints all shapes of the game'''
  82. painter = QPainter(self)
  83. rect = self.contentsRect()
  84. boardTop = rect.bottom() - Board.BoardHeight * self.squareHeight()
  85. for i in range(Board.BoardHeight):
  86. for j in range(Board.BoardWidth):
  87. shape = self.shapeAt(j, Board.BoardHeight - i - 1)
  88. if shape != Tetrominoe.NoShape:
  89. self.drawSquare(painter,
  90. rect.left() + j * self.squareWidth(),
  91. boardTop + i * self.squareHeight(), shape)
  92. if self.curPiece.shape() != Tetrominoe.NoShape:
  93. for i in range(4):
  94. x = self.curX + self.curPiece.x(i)
  95. y = self.curY - self.curPiece.y(i)
  96. self.drawSquare(painter, rect.left() + x * self.squareWidth(),
  97. boardTop + (Board.BoardHeight - y - 1) * self.squareHeight(),
  98. self.curPiece.shape())
  99. def keyPressEvent(self, event):
  100. # '''processes key press events'''
  101. if not self.isStarted or self.curPiece.shape() == Tetrominoe.NoShape:
  102. super(Board, self).keyPressEvent(event)
  103. return
  104. key = event.key()
  105. if key == Qt.Key_P:
  106. self.pause()
  107. return
  108. if self.isPaused:
  109. return
  110. elif key == Qt.Key_Left:
  111. self.tryMove(self.curPiece, self.curX - 1, self.curY)
  112. elif key == Qt.Key_Right:
  113. self.tryMove(self.curPiece, self.curX + 1, self.curY)
  114. elif key == Qt.Key_Down:
  115. self.tryMove(self.curPiece.rotateRight(), self.curX, self.curY)
  116. elif key == Qt.Key_Up:
  117. self.tryMove(self.curPiece.rotateLeft(), self.curX, self.curY)
  118. elif key == Qt.Key_Space:
  119. self.dropDown()
  120. elif key == Qt.Key_D:
  121. self.oneLineDown()
  122. else:
  123. super(Board, self).keyPressEvent(event)
  124. def timerEvent(self, event):
  125. # '''handles timer event'''
  126. if event.timerId() == self.timer.timerId():
  127. if self.isWaitingAfterLine:
  128. self.isWaitingAfterLine = False
  129. self.newPiece()
  130. else:
  131. self.oneLineDown()
  132. else:
  133. super(Board, self).timerEvent(event)
  134. def clearBoard(self):
  135. # '''clears shapes from the board'''
  136. for i in range(Board.BoardHeight * Board.BoardWidth):
  137. self.board.append(Tetrominoe.NoShape)
  138. def dropDown(self):
  139. # '''drops down a shape'''
  140. newY = self.curY
  141. while newY > 0:
  142. if not self.tryMove(self.curPiece, self.curX, newY - 1):
  143. break
  144. newY -= 1
  145. self.pieceDropped()
  146. def oneLineDown(self):
  147. # '''goes one line down with a shape'''
  148. if not self.tryMove(self.curPiece, self.curX, self.curY - 1):
  149. self.pieceDropped()
  150. def pieceDropped(self):
  151. # '''after dropping shape, remove full lines and create new shape'''
  152. for i in range(4):
  153. x = self.curX + self.curPiece.x(i)
  154. y = self.curY - self.curPiece.y(i)
  155. self.setShapeAt(x, y, self.curPiece.shape())
  156. self.removeFullLines()
  157. if not self.isWaitingAfterLine:
  158. self.newPiece()
  159. def removeFullLines(self):
  160. # '''removes all full lines from the board'''
  161. numFullLines = 0
  162. rowsToRemove = []
  163. for i in range(Board.BoardHeight):
  164. n = 0
  165. for j in range(Board.BoardWidth):
  166. if not self.shapeAt(j, i) == Tetrominoe.NoShape:
  167. n = n + 1
  168. if n == 10:
  169. rowsToRemove.append(i)
  170. rowsToRemove.reverse()
  171. for m in rowsToRemove:
  172. for k in range(m, Board.BoardHeight):
  173. for l in range(Board.BoardWidth):
  174. self.setShapeAt(l, k, self.shapeAt(l, k + 1))
  175. numFullLines = numFullLines + len(rowsToRemove)
  176. if numFullLines > 0:
  177. self.numLinesRemoved = self.numLinesRemoved + numFullLines
  178. self.msg2Statusbar.emit(str(self.numLinesRemoved))
  179. self.isWaitingAfterLine = True
  180. self.curPiece.setShape(Tetrominoe.NoShape)
  181. self.update()
  182. def newPiece(self):
  183. # '''creates a new shape'''
  184. self.curPiece = Shape()
  185. self.curPiece.setRandomShape()
  186. self.curX = Board.BoardWidth // 2 + 1
  187. self.curY = Board.BoardHeight - 1 + self.curPiece.minY()
  188. if not self.tryMove(self.curPiece, self.curX, self.curY):
  189. self.curPiece.setShape(Tetrominoe.NoShape)
  190. self.timer.stop()
  191. self.isStarted = False
  192. self.msg2Statusbar.emit("Game over")
  193. def tryMove(self, newPiece, newX, newY):
  194. # '''tries to move a shape'''
  195. for i in range(4):
  196. x = newX + newPiece.x(i)
  197. y = newY - newPiece.y(i)
  198. if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight:
  199. return False
  200. if self.shapeAt(x, y) != Tetrominoe.NoShape:
  201. return False
  202. self.curPiece = newPiece
  203. self.curX = newX
  204. self.curY = newY
  205. self.update()
  206. return True
  207. def drawSquare(self, painter, x, y, shape):
  208. # '''draws a square of a shape'''
  209. colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC,
  210. 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00]
  211. color = QColor(colorTable[shape])
  212. painter.fillRect(x + 1, y + 1, self.squareWidth() - 2, self.squareHeight() - 2, color)
  213. painter.setPen(color.lighter())
  214. painter.drawLine(x, y + self.squareHeight() - 1, x, y)
  215. painter.drawLine(x, y, x + self.squareWidth() - 1, y)
  216. painter.setPen(color.darker())
  217. painter.drawLine(x + 1, y + self.squareHeight() - 1,
  218. x + self.squareWidth() - 1, y + self.squareHeight() -1)
  219. painter.drawLine(x + self.squareWidth() - 1,
  220. y + self.squareHeight() - 1, x + self.squareWidth() - 1, y +1)
  221. class Tetrominoe(object):
  222. NoShape = 0
  223. ZShape = 1
  224. SShape = 2
  225. LineShape = 3
  226. TShape = 4
  227. SquareShape = 5
  228. LShape = 6
  229. MirroredLShape = 7
  230. class Shape(object):
  231. coordsTable = (
  232. ((0, 0), (0, 0), (0, 0), (0, 0)),
  233. ((0, -1), (0, 0), (-1, 0), (-1, 1)),
  234. ((0, -1), (0, 0), (1, 0), (1, 1)),
  235. ((0, -1), (0, 0), (0, 1), (0, 2)),
  236. ((-1, 0), (0, 0), (1, 0), (0, 1)),
  237. ((0, 0), (1, 0), (0, 1), (1, 1)),
  238. ((-1, -1), (0, -1), (0, 0), (0, 1)),
  239. ((1, -1), (0, -1), (0, 0), (0, 1))
  240. )
  241. def __init__(self):
  242. self.coords = [[0,0] for i in range(4)]
  243. self.pieceShape = Tetrominoe.NoShape
  244. self.setShape(Tetrominoe.NoShape)
  245. def shape(self):
  246. # '''returns shape'''
  247. return self.pieceShape
  248. def setShape(self, shape):
  249. # '''sets a shape'''
  250. table = Shape.coordsTable[shape]
  251. for i in range(4):
  252. for j in range(2):
  253. self.coords[i][j] = table[i][j]
  254. self.pieceShape = shape
  255. def setRandomShape(self):
  256. # '''chooses a random shape'''
  257. self.setShape(random.randint(1, 7))
  258. def x(self, index):
  259. # '''returns x coordinate'''
  260. return self.coords[index][0]
  261. def y(self, index):
  262. # '''returns y coordinate'''
  263. return self.coords[index][1]
  264. def setX(self, index, x):
  265. # '''sets x coordinate'''
  266. self.coords[index][0] = x
  267. def setY(self, index, y):
  268. # '''sets y coordinate'''
  269. self.coords[index][1] = y
  270. def minX(self):
  271. # '''returns min x value'''
  272. m = self.coords[0][0]
  273. for i in range(4):
  274. m = min(m, self.coords[i][0])
  275. return m
  276. def maxX(self):
  277. # '''returns max x value'''
  278. m = self.coords[0][0]
  279. for i in range(4):
  280. m = max(m, self.coords[i][0])
  281. return m
  282. def minY(self):
  283. # '''returns min y value'''
  284. m = self.coords[0][1]
  285. for i in range(4):
  286. m = min(m, self.coords[i][1])
  287. return m
  288. def maxY(self):
  289. # '''returns max y value'''
  290. m = self.coords[0][1]
  291. for i in range(4):
  292. m = max(m, self.coords[i][1])
  293. return m
  294. def rotateLeft(self):
  295. # '''rotates shape to the left'''
  296. if self.pieceShape == Tetrominoe.SquareShape:
  297. return self
  298. result = Shape()
  299. result.pieceShape = self.pieceShape
  300. for i in range(4):
  301. result.setX(i, self.y(i))
  302. result.setY(i, -self.x(i))
  303. return result
  304. def rotateRight(self):
  305. # '''rotates shape to the right'''
  306. if self.pieceShape == Tetrominoe.SquareShape:
  307. return self
  308. result = Shape()
  309. result.pieceShape = self.pieceShape
  310. for i in range(4):
  311. result.setX(i, -self.y(i))
  312. result.setY(i, self.x(i))
  313. return result
  314. if __name__ == '__main__':
  315. app = QApplication([])
  316. tetris = Tetris()
  317. 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()f 法里发生的 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:
上⽅向键是把⽅块向左旋转⼀下

elif key == Qt.Key_Space:

        self.dropDown()

空格键会直接把方块放到底部

elif key == Qt.Key_D:

        self.oneLineDown()

D键是加速⼀次下落速度。

def tryMove(self, newPiece, newX, newY):
# '''tries to move a shape'''
        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()

tryMove() 是尝试移动方块的方法。如果方块已经到达board的边缘或者遇到了其他方块,就返回False。否则就把方块下落到想要位置。

 def timerEvent(self, event):
# '''handles timer 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):
# '''removes all full lines from the board'''
        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)

'''

如果f 块碰到了底部,就调用 removeFullLines() 方法,找到所有能消除的行消除它们。消除的具体动作就是把符合条件的行消除掉之后,再把它上面的行下降⼀行。注意移除满行的动作是倒着来的,因为我们是按照重力来表现游戏的,如果不这样就有可能出现有些方块浮在空中的现象。

def newPiece(self):
# '''creates a new shape'''
        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)),
 ((0, -1), (0, 0), (1, 0), (1, 1)),
 ((0, -1), (0, 0), (0, 1), (0, 2)),
 ((-1, 0), (0, 0), (1, 0), (0, 1)),
 ((0, 0), (1, 0), (0, 1), (1, 1)),
 ((-1, -1), (0, -1), (0, 0), (0, 1)),
 ((1, -1), (0, -1), (0, 0), (0, 1))
 )

'''

coordsTable元组保存了所有的f 块形状的组成。是⼀个构成f 块的坐标模版。

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

上面创建了⼀个新的空坐标数组,这个数组将来用保存方块的坐标。 坐标系示意图:

 

上面的图片可以帮助我们更好的理解坐标值的意义。比如元组 (0, -1), (0, 0), (-1, 0), (-1, -1) 代表了⼀个Z形状的方块。这个图表就描绘了这个形状。

def rotateLeft(self):
# '''rotates shape to the left'''
        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
    def rotateRight(self):
# '''rotates shape to the right'''
        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()方法向右旋转⼀个方块。正方形的方块就没必要旋转,就直接返回 了。其他的是返回⼀个新的,能表示这个形状旋转了的坐标。

程序展示:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/832553
推荐阅读
相关标签
  

闽ICP备14008679号