设为首页收藏本站

SKY外语、计算机论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 4941|回复: 5

[代码分享] python pyqt tetrix

[复制链接]

65

主题

3

好友

739

积分

超级版主

Rank: 8Rank: 8

自我介绍
新年第一天据说有雨,全民齐赏日出的计划恐要泡汤。”宋仁宗拍着包拯的肩,“朕决定把你悬挂在城门上。”“但微臣额上的不是太阳是月亮啊!”“没事,挂久一点就会升级成太阳
生肖
星座
狮子座
性别

最佳新人 活跃会员 热心会员 推广达人 宣传达人 灌水之王 突出贡献 优秀版主 论坛元老

发表于 2012-10-4 19:08:19 |显示全部楼层

  1. #!/usr/bin/env python


  2. #############################################################################
  3. ##
  4. ## Copyright (C) 2010 Riverbank Computing Limited.
  5. ## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
  6. ## All rights reserved.
  7. ##
  8. ## This file is part of the examples of PyQt.
  9. ##
  10. ## $QT_BEGIN_LICENSE:BSD$
  11. ## You may use this file under the terms of the BSD license as follows:
  12. ##
  13. ## "Redistribution and use in source and binary forms, with or without
  14. ## modification, are permitted provided that the following conditions are
  15. ## met:
  16. ##   * Redistributions of source code must retain the above copyright
  17. ##     notice, this list of conditions and the following disclaimer.
  18. ##   * Redistributions in binary form must reproduce the above copyright
  19. ##     notice, this list of conditions and the following disclaimer in
  20. ##     the documentation and/or other materials provided with the
  21. ##     distribution.
  22. ##   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
  23. ##     the names of its contributors may be used to endorse or promote
  24. ##     products derived from this software without specific prior written
  25. ##     permission.
  26. ##
  27. ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  28. ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  29. ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  30. ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  31. ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  32. ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  33. ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  34. ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  35. ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  36. ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  37. ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
  38. ## $QT_END_LICENSE$
  39. ##
  40. #############################################################################


  41. import random

  42. from PyQt4 import QtCore, QtGui


  43. NoShape, ZShape, SShape, LineShape, TShape, SquareShape, LShape, MirroredLShape = range(8)


  44. class TetrixWindow(QtGui.QWidget):
  45.     def __init__(self):
  46.         super(TetrixWindow, self).__init__()

  47.         self.board = TetrixBoard()

  48.         nextPieceLabel = QtGui.QLabel()
  49.         nextPieceLabel.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Raised)
  50.         nextPieceLabel.setAlignment(QtCore.Qt.AlignCenter)
  51.         self.board.setNextPieceLabel(nextPieceLabel)

  52.         scoreLcd = QtGui.QLCDNumber(5)
  53.         scoreLcd.setSegmentStyle(QtGui.QLCDNumber.Filled)
  54.         levelLcd = QtGui.QLCDNumber(2)
  55.         levelLcd.setSegmentStyle(QtGui.QLCDNumber.Filled)
  56.         linesLcd = QtGui.QLCDNumber(5)
  57.         linesLcd.setSegmentStyle(QtGui.QLCDNumber.Filled)

  58.         startButton = QtGui.QPushButton("&Start")
  59.         startButton.setFocusPolicy(QtCore.Qt.NoFocus)
  60.         quitButton = QtGui.QPushButton("&Quit")
  61.         quitButton.setFocusPolicy(QtCore.Qt.NoFocus)
  62.         pauseButton = QtGui.QPushButton("&Pause")
  63.         pauseButton.setFocusPolicy(QtCore.Qt.NoFocus)

  64.         startButton.clicked.connect(self.board.start)
  65.         pauseButton.clicked.connect(self.board.pause)
  66.         quitButton.clicked.connect(QtGui.qApp.quit)
  67.         self.board.scoreChanged.connect(scoreLcd.display)
  68.         self.board.levelChanged.connect(levelLcd.display)
  69.         self.board.linesRemovedChanged.connect(linesLcd.display)

  70.         layout = QtGui.QGridLayout()
  71.         layout.addWidget(self.createLabel("NEXT"), 0, 0)
  72.         layout.addWidget(nextPieceLabel, 1, 0)
  73.         layout.addWidget(self.createLabel("LEVEL"), 2, 0)
  74.         layout.addWidget(levelLcd, 3, 0)
  75.         layout.addWidget(startButton, 4, 0)
  76.         layout.addWidget(self.board, 0, 1, 6, 1)
  77.         layout.addWidget(self.createLabel("SCORE"), 0, 2)
  78.         layout.addWidget(scoreLcd, 1, 2)
  79.         layout.addWidget(self.createLabel("LINES REMOVED"), 2, 2)
  80.         layout.addWidget(linesLcd, 3, 2)
  81.         layout.addWidget(quitButton, 4, 2)
  82.         layout.addWidget(pauseButton, 5, 2)
  83.         self.setLayout(layout)

  84.         self.setWindowTitle("Tetrix")
  85.         self.resize(550, 370)

  86.     def createLabel(self, text):
  87.         lbl = QtGui.QLabel(text)
  88.         lbl.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignBottom)
  89.         return lbl


  90. class TetrixBoard(QtGui.QFrame):
  91.     BoardWidth = 10
  92.     BoardHeight = 22

  93.     scoreChanged = QtCore.pyqtSignal(int)

  94.     levelChanged = QtCore.pyqtSignal(int)

  95.     linesRemovedChanged = QtCore.pyqtSignal(int)

  96.     def __init__(self, parent=None):
  97.         super(TetrixBoard, self).__init__(parent)

  98.         self.timer = QtCore.QBasicTimer()
  99.         self.nextPieceLabel = None
  100.         self.isWaitingAfterLine = False
  101.         self.curPiece = TetrixPiece()
  102.         self.nextPiece = TetrixPiece()
  103.         self.curX = 0
  104.         self.curY = 0
  105.         self.numLinesRemoved = 0
  106.         self.numPiecesDropped = 0
  107.         self.score = 0
  108.         self.level = 0
  109.         self.board = None

  110.         self.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken)
  111.         self.setFocusPolicy(QtCore.Qt.StrongFocus)
  112.         self.isStarted = False
  113.         self.isPaused = False
  114.         self.clearBoard()

  115.         self.nextPiece.setRandomShape()

  116.     def shapeAt(self, x, y):
  117.         return self.board[(y * TetrixBoard.BoardWidth) + x]

  118.     def setShapeAt(self, x, y, shape):
  119.         self.board[(y * TetrixBoard.BoardWidth) + x] = shape   

  120.     def timeoutTime(self):
  121.         return 1000 / (1 + self.level)

  122.     def squareWidth(self):
  123.         return self.contentsRect().width() / TetrixBoard.BoardWidth

  124.     def squareHeight(self):
  125.         return self.contentsRect().height() / TetrixBoard.BoardHeight

  126.     def setNextPieceLabel(self, label):
  127.         self.nextPieceLabel = label

  128.     def sizeHint(self):
  129.         return QtCore.QSize(TetrixBoard.BoardWidth * 15 + self.frameWidth() * 2,
  130.                 TetrixBoard.BoardHeight * 15 + self.frameWidth() * 2)

  131.     def minimumSizeHint(self):
  132.         return QtCore.QSize(TetrixBoard.BoardWidth * 5 + self.frameWidth() * 2,
  133.                 TetrixBoard.BoardHeight * 5 + self.frameWidth() * 2)

  134.     def start(self):
  135.         if self.isPaused:
  136.             return

  137.         self.isStarted = True
  138.         self.isWaitingAfterLine = False
  139.         self.numLinesRemoved = 0
  140.         self.numPiecesDropped = 0
  141.         self.score = 0
  142.         self.level = 1
  143.         self.clearBoard()

  144.         self.linesRemovedChanged.emit(self.numLinesRemoved)
  145.         self.scoreChanged.emit(self.score)
  146.         self.levelChanged.emit(self.level)

  147.         self.newPiece()
  148.         self.timer.start(self.timeoutTime(), self)

  149.     def pause(self):
  150.         if not self.isStarted:
  151.             return

  152.         self.isPaused = not self.isPaused
  153.         if self.isPaused:
  154.             self.timer.stop()
  155.         else:
  156.             self.timer.start(self.timeoutTime(), self)

  157.         self.update()

  158.     def paintEvent(self, event):
  159.         super(TetrixBoard, self).paintEvent(event)

  160.         painter = QtGui.QPainter(self)
  161.         rect = self.contentsRect()

  162.         if self.isPaused:
  163.             painter.drawText(rect, QtCore.Qt.AlignCenter, "Pause")
  164.             return

  165.         boardTop = rect.bottom() - TetrixBoard.BoardHeight * self.squareHeight()

  166.         for i in range(TetrixBoard.BoardHeight):
  167.             for j in range(TetrixBoard.BoardWidth):
  168.                 shape = self.shapeAt(j, TetrixBoard.BoardHeight - i - 1)
  169.                 if shape != NoShape:
  170.                     self.drawSquare(painter,
  171.                             rect.left() + j * self.squareWidth(),
  172.                             boardTop + i * self.squareHeight(), shape)

  173.         if self.curPiece.shape() != NoShape:
  174.             for i in range(4):
  175.                 x = self.curX + self.curPiece.x(i)
  176.                 y = self.curY - self.curPiece.y(i)
  177.                 self.drawSquare(painter, rect.left() + x * self.squareWidth(),
  178.                         boardTop + (TetrixBoard.BoardHeight - y - 1) * self.squareHeight(),
  179.                         self.curPiece.shape())

  180.     def keyPressEvent(self, event):
  181.         if not self.isStarted or self.isPaused or self.curPiece.shape() == NoShape:
  182.             super(TetrixBoard, self).keyPressEvent(event)
  183.             return

  184.         key = event.key()
  185.         if key == QtCore.Qt.Key_Left:
  186.             self.tryMove(self.curPiece, self.curX - 1, self.curY)
  187.         elif key == QtCore.Qt.Key_Right:
  188.             self.tryMove(self.curPiece, self.curX + 1, self.curY)
  189.         elif key == QtCore.Qt.Key_Down:
  190.             self.tryMove(self.curPiece.rotatedRight(), self.curX, self.curY)
  191.         elif key == QtCore.Qt.Key_Up:
  192.             self.tryMove(self.curPiece.rotatedLeft(), self.curX, self.curY)
  193.         elif key == QtCore.Qt.Key_Space:
  194.             self.dropDown()
  195.         elif key == QtCore.Qt.Key_D:
  196.             self.oneLineDown()
  197.         else:
  198.             super(TetrixBoard, self).keyPressEvent(event)

  199.     def timerEvent(self, event):
  200.         if event.timerId() == self.timer.timerId():
  201.             if self.isWaitingAfterLine:
  202.                 self.isWaitingAfterLine = False
  203.                 self.newPiece()
  204.                 self.timer.start(self.timeoutTime(), self)
  205.             else:
  206.                 self.oneLineDown()
  207.         else:
  208.             super(TetrixBoard, self).timerEvent(event)

  209.     def clearBoard(self):
  210.         self.board = [NoShape for i in range(TetrixBoard.BoardHeight * TetrixBoard.BoardWidth)]

  211.     def dropDown(self):
  212.         dropHeight = 0
  213.         newY = self.curY
  214.         while newY > 0:
  215.             if not self.tryMove(self.curPiece, self.curX, newY - 1):
  216.                 break
  217.             newY -= 1
  218.             dropHeight += 1

  219.         self.pieceDropped(dropHeight)

  220.     def oneLineDown(self):
  221.         if not self.tryMove(self.curPiece, self.curX, self.curY - 1):
  222.             self.pieceDropped(0)

  223.     def pieceDropped(self, dropHeight):
  224.         for i in range(4):
  225.             x = self.curX + self.curPiece.x(i)
  226.             y = self.curY - self.curPiece.y(i)
  227.             self.setShapeAt(x, y, self.curPiece.shape())

  228.         self.numPiecesDropped += 1
  229.         if self.numPiecesDropped % 25 == 0:
  230.             self.level += 1
  231.             self.timer.start(self.timeoutTime(), self)
  232.             self.levelChanged.emit(self.level)

  233.         self.score += dropHeight + 7
  234.         self.scoreChanged.emit(self.score)
  235.         self.removeFullLines()

  236.         if not self.isWaitingAfterLine:
  237.             self.newPiece()

  238.     def removeFullLines(self):
  239.         numFullLines = 0

  240.         for i in range(TetrixBoard.BoardHeight - 1, -1, -1):
  241.             lineIsFull = True

  242.             for lj in range(TetrixBoard.BoardWidth):
  243.                 if self.shapeAt(lj, i) == NoShape:
  244.                     lineIsFull = False
  245.                     break

  246.             if lineIsFull:
  247.                 numFullLines += 1
  248.                 for k in range(i,TetrixBoard.BoardHeight - 1):
  249.                     for j in range(TetrixBoard.BoardWidth):
  250.                         self.setShapeAt(j, k, self.shapeAt(j, k + 1))

  251. #                for j in range(TetrixBoard.BoardWidth):
  252. #                    self.setShapeAt(j, lj, NoShape)

  253.         if numFullLines > 0:
  254.             self.numLinesRemoved += numFullLines
  255.             self.score += 10 * numFullLines
  256.             self.linesRemovedChanged.emit(self.numLinesRemoved)
  257.             self.scoreChanged.emit(self.score)

  258.             self.timer.start(500, self)
  259.             self.isWaitingAfterLine = True
  260.             self.curPiece.setShape(NoShape)
  261.             self.update()

  262.     def newPiece(self):
  263.         self.curPiece = self.nextPiece
  264.         self.nextPiece.setRandomShape()
  265.         self.showNextPiece()
  266.         self.curX = TetrixBoard.BoardWidth // 2 + 1
  267.         self.curY = TetrixBoard.BoardHeight - 1 + self.curPiece.minY()

  268.         if not self.tryMove(self.curPiece, self.curX, self.curY):
  269.             self.curPiece.setShape(NoShape)
  270.             self.timer.stop()
  271.             self.isStarted = False

  272.     def showNextPiece(self):
  273.         if self.nextPieceLabel is not None:
  274.             return

  275.         dx = self.nextPiece.maxX() - self.nextPiece.minX() + 1
  276.         dy = self.nextPiece.maxY() - self.nextPiece.minY() + 1

  277.         pixmap = QtGui.QPixmap(dx * self.squareWidth(), dy * self.squareHeight())
  278.         painter = QtGui.QPainter(pixmap)
  279.         painter.fillRect(pixmap.rect(), self.nextPieceLabel.palette().background())

  280.         for i in range(4):
  281.             x = self.nextPiece.x(i) - self.nextPiece.minX()
  282.             y = self.nextPiece.y(i) - self.nextPiece.minY()
  283.             self.drawSquare(painter, x * self.squareWidth(),
  284.                     y * self.squareHeight(), self.nextPiece.shape())

  285.         self.nextPieceLabel.setPixmap(pixmap)

  286.     def tryMove(self, newPiece, newX, newY):
  287.         for i in range(4):
  288.             x = newX + newPiece.x(i)
  289.             y = newY - newPiece.y(i)
  290.             if x < 0 or x >= TetrixBoard.BoardWidth or y < 0 or y >= TetrixBoard.BoardHeight:
  291.                 return False
  292.             if self.shapeAt(x, y) != NoShape:
  293.                 return False

  294.         self.curPiece = newPiece
  295.         self.curX = newX
  296.         self.curY = newY
  297.         self.update()
  298.         return True

  299.     def drawSquare(self, painter, x, y, shape):
  300.         colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC,
  301.                       0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00]

  302.         color = QtGui.QColor(colorTable[shape])
  303.         painter.fillRect(x + 1, y + 1, self.squareWidth() - 2,
  304.                 self.squareHeight() - 2, color)

  305.         painter.setPen(color.light())
  306.         painter.drawLine(x, y + self.squareHeight() - 1, x, y)
  307.         painter.drawLine(x, y, x + self.squareWidth() - 1, y)

  308.         painter.setPen(color.dark())
  309.         painter.drawLine(x + 1, y + self.squareHeight() - 1,
  310.                 x + self.squareWidth() - 1, y + self.squareHeight() - 1)
  311.         painter.drawLine(x + self.squareWidth() - 1,
  312.                 y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + 1)


  313. class TetrixPiece(object):
  314.     coordsTable = (
  315.         ((0, 0),     (0, 0),     (0, 0),     (0, 0)),
  316.         ((0, -1),    (0, 0),     (-1, 0),    (-1, 1)),
  317.         ((0, -1),    (0, 0),     (1, 0),     (1, 1)),
  318.         ((0, -1),    (0, 0),     (0, 1),     (0, 2)),
  319.         ((-1, 0),    (0, 0),     (1, 0),     (0, 1)),
  320.         ((0, 0),     (1, 0),     (0, 1),     (1, 1)),
  321.         ((-1, -1),   (0, -1),    (0, 0),     (0, 1)),
  322.         ((1, -1),    (0, -1),    (0, 0),     (0, 1))
  323.     )

  324.     def __init__(self):
  325.         self.coords = [[0,0] for _ in range(4)]
  326.         self.pieceShape = NoShape

  327.         self.setShape(NoShape)

  328.     def shape(self):
  329.         return self.pieceShape

  330.     def setShape(self, shape):
  331.         table = TetrixPiece.coordsTable[shape]
  332.         for i in range(4):
  333.             for j in range(2):
  334.                 self.coords[i][j] = table[i][j]

  335.         self.pieceShape = shape

  336.     def setRandomShape(self):
  337.         self.setShape(random.randint(1, 7))

  338.     def x(self, index):
  339.         return self.coords[index][0]

  340.     def y(self, index):
  341.         return self.coords[index][1]

  342.     def setX(self, index, x):
  343.         self.coords[index][0] = x

  344.     def setY(self, index, y):
  345.         self.coords[index][1] = y

  346.     def minX(self):
  347.         m = self.coords[0][0]
  348.         for i in range(4):
  349.             m = min(m, self.coords[i][0])

  350.         return m

  351.     def maxX(self):
  352.         m = self.coords[0][0]
  353.         for i in range(4):
  354.             m = max(m, self.coords[i][0])

  355.         return m

  356.     def minY(self):
  357.         m = self.coords[0][1]
  358.         for i in range(4):
  359.             m = min(m, self.coords[i][1])

  360.         return m

  361.     def maxY(self):
  362.         m = self.coords[0][1]
  363.         for i in range(4):
  364.             m = max(m, self.coords[i][1])

  365.         return m

  366.     def rotatedLeft(self):
  367.         if self.pieceShape == SquareShape:
  368.             return self

  369.         result = TetrixPiece()
  370.         result.pieceShape = self.pieceShape
  371.         for i in range(4):
  372.             result.setX(i, self.y(i))
  373.             result.setY(i, -self.x(i))

  374.         return result

  375.     def rotatedRight(self):
  376.         if self.pieceShape == SquareShape:
  377.             return self

  378.         result = TetrixPiece()
  379.         result.pieceShape = self.pieceShape
  380.         for i in range(4):
  381.             result.setX(i, -self.y(i))
  382.             result.setY(i, self.x(i))

  383.         return result


  384. if __name__ == '__main__':

  385.     import sys

  386.     app = QtGui.QApplication(sys.argv)
  387.     window = TetrixWindow()
  388.     window.show()
  389.     random.seed(None)
  390.     sys.exit(app.exec_())

复制代码
无效楼层,该帖已经被删除
无效楼层,该帖已经被删除
无效楼层,该帖已经被删除
5#
无效楼层,该帖已经被删除
您需要登录后才可以回帖 登录 | 立即注册


手机版|SKY外语计算机学习 ( 粤ICP备12031577 )    

GMT+8, 2024-3-29 00:34 , Processed in 0.117292 second(s), 28 queries .

回顶部