免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 7851 | 回复: 8

用python+PYQT4写的一个俄罗斯方块游戏------申精! [复制链接]

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

论坛徽章:
0
发表于 2011-03-23 11:13 |显示全部楼层
赞的

论坛徽章:
0
发表于 2011-03-23 12:05 |显示全部楼层
赞一个……

论坛徽章:
0
发表于 2011-03-23 12:18 |显示全部楼层
最好附上你这个版本的pyqt的安装文件,以及其他一些第三方库

论坛徽章:
0
发表于 2011-03-23 21:41 |显示全部楼层
正在学习python,赞

论坛徽章:
0
发表于 2011-03-24 08:11 |显示全部楼层
改的太少了……
  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 j in range(TetrixBoard.BoardWidth):
  243.                 if self.shapeAt(j, i) == NoShape:
  244.                     lineIsFull = False
  245.                     break

  246.             if lineIsFull:
  247.                 numFullLines += 1
  248.                 for k in range(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, TetrixBoard.BoardHeight - 1, 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 int 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_())
复制代码

论坛徽章:
0
发表于 2011-03-24 09:19 |显示全部楼层
鼓励!
Keep up!

论坛徽章:
0
发表于 2011-03-24 15:59 |显示全部楼层
赞一个……

论坛徽章:
0
发表于 2011-03-28 12:40 |显示全部楼层
是原创么
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP