The text and pictures of this article are from the Internet, only for learning and communication, and do not have any commercial use. The copyright belongs to the original author. If you have any questions, please contact us in time
This article is from Tencent cloud by Python sophomore
In that era when electronic products were relatively scarce, small game machines
Or one of the few game electronic products, has an irresistible magic for children. At that time, if a child bought a small game machine, everyone would quickly surround it
Tetris as one of the small games, although the rules are simple, only black and white, but its influence on the game players at that time is no less than that of lol, pesticides, eating chicken on the game players now. Let’s see how to use Python to realize this small game of Tetris.
Plates of different shapes composed of small squares fall down from the top of the screen one after another. Players can make them spell a complete one or several at the bottom of the screen by adjusting the position and direction of the plates. These complete bars will disappear immediately, making room for the newly fallen plates. Meanwhile, players will be rewarded with points. The blocks that have not been eliminated keep piling up. Once they reach the top of the screen, the player loses and the game ends.
– Baidu Encyclopedia
- Operating system: Windows
- Python version: 3.6
- Modules involved: sys, random, pyqt5
First, install the third-party module pyqt5, and use pip to install pyqt5.
The main interface of the game
Implementation code
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class MainBoard(QFrame):
msg = pyqtSignal(str)
BoardWidth = 10
BoardHeight = 22
Speed = 300
def __init__(self, parent):
super().__init__(parent)
self.initBoard()
def initBoard(self):
self.timer = QBasicTimer()
self.isWaitingAfterLine = False
self.curX = 0
self.curY = 0
self.numLinesRemoved = 0
self.board = []
self.setFocusPolicy(Qt.StrongFocus)
self.isStarted = False
self.isPaused = False
The effect picture is as follows
Small plate
Defines the shape of a small block
class ShapeForm(object):
NoShape = 0
ZShape = 1
SShape = 2
LineShape = 3
TShape = 4
SquareShape = 5
LShape = 6
MirroredLShape = 7
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))
)
def __init__(self):
self.coords = [[0,0] for i in range(4)]
self.pieceShape = ShapeForm.NoShape
self.setShape(ShapeForm.NoShape)
Draw a figure
def drawSquare(self, painter, x, y, shape):
colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC,
0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00]
color = QColor(colorTable[shape])
painter.fillRect(x + 1, y + 1, self.squareWidth() - 2,
self.squareHeight() - 2, color)
painter.setPen(color.lighter())
painter.drawLine(x, y + self.squareHeight() - 1, x, y)
painter.drawLine(x, y, x + self.squareWidth() - 1, y)
painter.setPen(color.darker())
painter.drawLine(x + 1, y + self.squareHeight() - 1,
x + self.squareWidth() - 1, y + self.squareHeight() - 1)
painter.drawLine(x + self.squareWidth() - 1,
y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + 1)
The effect picture is as follows
/ / key events
def keyPressEvent(self, event):
if not self.isStarted or self.curPiece.shape() == ShapeForm.NoShape:
super(MainBoard, self).keyPressEvent(event)
return
key = event.key()
if key == Qt.Key_P:
self.pause()
return
if self.isPaused:
return
elif key == Qt.Key_Left:
self.tryMove(self.curPiece, self.curX - 1, self.curY)
elif key == Qt.Key_Right:
self.tryMove(self.curPiece, self.curX + 1, self.curY)
elif key == Qt.Key_Down:
self.tryMove(self.curPiece.rotateRight(), self.curX, self.curY)
elif key == Qt.Key_Up:
self.tryMove(self.curPiece.rotateLeft(), self.curX, self.curY)
elif key == Qt.Key_Space:
self.dropDown()
elif key == Qt.Key_D:
self.oneLineDown()
else:
super(MainBoard, self).keyPressEvent(event)
def tryMove(self, newPiece, newX, newY):
for i in range(4):
x = newX + newPiece.x(i)
y = newY - newPiece.y(i)
if x < 0 or x >= MainBoard.BoardWidth or y < 0 or y >= MainBoard.BoardHeight:
return False
if self.shapeAt(x, y) != ShapeForm.NoShape:
return False
self.curPiece = newPiece
self.curX = newX
self.curY = newY
self.update()
return True
≠ timer events
def timerEvent(self, event):
if event.timerId() == self.timer.timerId():
if self.isWaitingAfterLine:
self.isWaitingAfterLine = False
self.newPiece()
else:
self.oneLineDown()
else:
super(MainBoard, self).timerEvent(event)
≠ start and pause
def start(self):
if self.isPaused:
return
self.isStarted = True
self.isWaitingAfterLine = False
self.numLinesRemoved = 0
self.clearBoard()
self.msg.emit(str(self.numLinesRemoved))
self.newPiece()
self.timer.start(MainBoard.Speed, self)
def pause(self):
if not self.isStarted:
return
self.isPaused = not self.isPaused
if self.isPaused:
self.timer.stop()
self.msg.emit(“paused”)
else:
self.timer.start(MainBoard.Speed, self)
self.msg.emit(str(self.numLinesRemoved))
self.update()
Game class and initialization
class Tetris(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.tboard = MainBoard(self)
self.setCentralWidget(self.tboard)
self.statusbar = self.statusBar()
self.tboard.msg[str].connect(self.statusbar.showMessage)
self.tboard.start()
self.resize(300, 500)
self.center()
self.setWindowTitle ('tetris')
self.show()
def center(self):
screen = QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width()-size.width())/2,
(screen.height()-size.height())/2)
start-up
if __name__ == '__main__':
app = QApplication([])
tetris = Tetris()
sys.exit(app.exec_())
The final effect