python
复制代码
import random
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QCheckBox, QFrame
from PyQt5.QtGui import QIcon, QFont
class Game(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('剪刀石头布')
self.setWindowIcon(QIcon('./bitbug_favicon.ico')) # 窗口图标
self.resize(600, 300) # 窗口大小
self.move(600, 300)
self.label = QLabel(self) # 标签
self.label1 = QLabel(self)
self.label1.setText('电脑出招!') # 标签名称
self.label1.setFont(QFont('microsoft Yahei', 20)) # 标签字体
self.label1.move(50, 250)
# 空格用来占位, 代表后续只能输入这些数量的单词
self.label.setText('play! ')
self.label.setFont(QFont('microsoft Yahei', 20))
self.label.move(260, 150)
btn1 = QPushButton('剪刀', self) # 按钮
btn1.setIcon(QIcon('./game_1/jiandao.png')) # 按钮图标
# btn1.setStyleSheet('QPushButton{background-color:blue}') # 按钮颜色
btn1.move(50, 50)
btn1.resize(100, 60)
btn2 = QPushButton('石头', self)
btn2.setIcon(QIcon('./game_1/shitou.png'))
btn2.move(250, 50)
btn2.resize(100, 60)
btn3 = QPushButton('布', self)
btn3.setIcon(QIcon('./game_1/bu.png'))
btn3.move(450, 50)
btn3.resize(100, 60)
# 按钮连接信号函数buttonClicked
btn1.clicked.connect(self.buttonClicked)
btn2.clicked.connect(self.buttonClicked)
btn3.clicked.connect(self.buttonClicked)
self.show()
def buttonClicked(self):
ls = ['剪刀', '石头', '布']
a = random.choice(ls) # 随即出招
self.label1.setText(f'{a}')
# 判断输赢条件
if a == self.sender().text():
self.label.setText('平局')
self.label.move(260, 150)
elif self.sender().text() == '布' and a == '石头':
self.label.move(200, 150)
self.label.setText('恭喜你, 你赢啦')
elif self.sender().text() == '布' and a == '剪刀':
self.label.move(200, 150)
self.label.setText('很遗憾, 你输了')
elif self.sender().text() == '剪刀' and a == '布':
self.label.move(200, 150)
self.label.setText('恭喜你, 你赢啦')
elif self.sender().text() == '剪刀' and a == '石头':
self.label.move(200, 150)
self.label.setText('很遗憾, 你输了')
elif self.sender().text() == '石头' and a == '剪刀':
self.label.move(200, 150)
self.label.setText('恭喜你, 你赢啦')
else:
self.label.move(200, 150)
self.label.setText('很遗憾, 你输了')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Game()
sys.exit(app.exec_())