100 lines of Python code, make a whack-a-mole game

game screen

First, do the layout of the game screen.

class TopWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.virusnum = 0
        self.setWindowTitle("消灭地鼠小游戏")
        self.setWindowIcon(QIcon(r'sucai/图标.jpg'))


app = QApplication(sys.argv)
Display = TopWindow()
Display.setFixedSize(900, 600)
Display.show()
sys.exit(app.exec_())

For PyQt5, a global Application object needs to be created, whose parameter is a list of command line parameters, and the size of the game box can be set through setFixedSize.
We also set the class variable virusnum as the number of gophers

Next, we create a gopher class and arrange the relevant burrows

class virus(QPushButton):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedSize(160, 120) 
        self.setStyleSheet("QPushButton{border-image: url(sucai/地洞2.png)}") 
        self.upTime = QTimer()
        self.upTime.timeout.connect(self.up)

Create 25 more burrows

        for i in range(25):
            exec("self.virus{0}=virus()".format(i))
        for i in range(5):
            for j in range(5):
                exec("self.imagelayout.addWidget(self.virus{0},{1},{2})".format(t, i, j))
                t += 1

At this point, the effect of our program is as follows

set toolbar

Next, let's add the necessary toolbars for the game page, such as the start button, the game points box, etc.

# 右侧固定窗口内控件
        self.settingslayout = QGridLayout()  # 网格布局
        self.settingsWidget = QWidget()
        self.settingsWidget.setFixedSize(80, 350)
        self.imagelayout.addWidget(self.settingsWidget, 0, 5, 1, 5)
        self.settingsWidget.setLayout(self.settingslayout)

Then create the relevant buttons and input boxes

self.startPushButton = QtWidgets.QPushButton(text="开始游戏", clicked=self.handle_play_button)
        self.startPushButton.setFixedSize(80, 40)
        # self.startPushButton.clicked.connect(self.gamestart)  # 绑定信号

        self.textBrowser = QTextBrowser()
        self.textBrowser.setText('游戏未开始')
        self.textBrowser.setFixedSize(70, 40)

        self.killBrowser = QTextBrowser()
        self.killBrowser.setText('消灭病毒数:0')
        self.killBrowser.setFixedSize(70, 50)

        self.escapeBrowser = QTextBrowser()
        self.escapeBrowser.setText('逃离病毒数:0')
        self.escapeBrowser.setFixedSize(70, 50)

        self.remaintimeText = QTextBrowser()
        self.remaintimeText.setText('剩余时间:\n30s')
        self.remaintimeText.setFixedSize(70, 55)

Here, the start button is handled differently from other buttons. When the program is in the game, the button becomes "end game", so let's take a look at handle_play_button

@QtCore.pyqtSlot()
    def handle_play_button(self):
        btn = self.sender()
        if btn is not None:
            text = btn.text()
            if text == "开始游戏":
                btn.setText("结束游戏")
                self.gamestart()
            else:
                btn.setText("开始游戏")
                self.gameover()

For the two functions gamestart and gameover used, the code is as follows

    def gamestart(self):
        score = 0
        self.textBrowser.setText("正在游戏")
        self.timer.start(30000)  # 30秒执行1次
        self.virustimer.start(1000)
        self.remaintimer.start(1000)

    def gameover(self):
        self.timer.stop()
        self.virustimer.stop()
        self.textBrowser.setText("游戏结束")
        self.mousenum = 0
        for i in range(25):
            exec("self.virus{0}.flag = 0".format(i))

Finally, add buttons, etc. to the right side of the game page

self.settingslayout.addWidget(self.startPushButton, 0, 0)
        self.settingslayout.addWidget(self.textBrowser, 1, 0)
        self.settingslayout.addWidget(self.killBrowser, 2, 0)
        self.settingslayout.addWidget(self.escapeBrowser, 3, 0)
        self.settingslayout.addWidget(self.remaintimeText, 4, 0)
        # self.settingslayout.addWidget(self.endPushButton, 5, 0)
        self.settingslayout.addWidget(self.pauseMusicButton, 6, 0)

Now our game page looks like this

game credits

Since it is a game, of course, there must be a point function. For the gopher game, when we click the mouse, we smash the gopher

    def mousePressEvent(self, event):
        self.setCursor(QCursor(QPixmap(r"sucai/down.png")))
        self.upTime.start(100)
        self.kill()

    def up(self):
        self.setCursor(QCursor(QPixmap(r"sucai/up.png")))

Then proceed to the logic of the game scoring

    def kill(self):
        try:
            if self.flag == 1:
                self.setStyleSheet("QPushButton{border-image: url(sucai/killvirus2.png)}")  # 地鼠被砸
                global score
                score += 1
                self.flag = 0
        except:
            pass

In this way, a basic game credit is also available!

Here I would like to recommend the Python learning Q group I built by myself: 831804576. Everyone in the group is learning Python. If you want to learn or are learning Python, you are welcome to join. Everyone is a software development party and shares dry goods from time to time ( Only related to Python software development),
including a copy of the latest Python advanced materials and zero-based teaching in 2022 that I have compiled by myself. Welcome to the advanced middle and small partners who are interested in Python!

Guess you like

Origin blog.csdn.net/BYGFJ/article/details/124312639