Python基础实战1:猜大小游戏
规则:
(1)计算机随机抛3个骰子(3个随机数),和在11-18之间为大,小于等于10为小。
(2)玩家输入自己的猜测(“大”或“小”)
(3)显示游戏结果
介绍:本来是书本中一个简单小游戏,我结合了GUI界面,做了一点改进。(Python3.8)
代码:
import random
from tkinter import *
class Application(Frame):
"""GUI application"""
def __init__(self,master):
super(Application,self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
Label(self,text = "猜大小").grid(row = 0,column = 0,sticky = W) #标签
self.ent = Entry(self) #单行输入
self.ent.grid(row = 0,column = 1,sticky = W) #显示Entry
Button(self,text = "显示结果",command = self.start_game).grid(row = 3,column = 0,sticky = W) #显示结果按钮
self.txt = Text(self,width = 35,height = 5,wrap = WORD) #
self.txt.grid(row = 6,column = 0,columnspan = 3,sticky = W)
self.txt.insert(0.0, '<<<<GAME START!>>>>')
def roll_dice(self,numbers=3,points=None): #类内函数方法参数不要漏了self
if points is None:
points = []
while numbers > 0:
point = random.randrange(1,7)
points.append(point)
numbers = numbers-1
return points
def roll_result(self,total):
isBig = 11 <= total <=18
isSmall = 3 <=total <=10
if isBig:
return 'Big'
elif isSmall:
return 'Small'
def start_game(self):
choice = ['大','小']
your_choice = self.ent.get()
if your_choice in choice:
if your_choice == '大':
your_choice = 'Big'
else:
your_choice = 'Small'
points = self.roll_dice()
total = sum(points)
youwin = your_choice == self.roll_result(total)
if youwin:
self.txt.delete(0.0, END)
self.txt.insert(0.0,'The points are ' + str(points) +' and total is ' + str(total)\
+ ' , you win!') #使用“+”将字符连接,只能显示字符
else:
self.txt.delete(0.0, END)
self.txt.insert(0.0,'The points are '+ str(points) + ' and total is '+ str(total)\
+' , you lose!')
else:
self.txt.delete(0.0, END)
self.txt.insert(0.0,'invalid words')
def main():
root = Tk()
root.title("猜大小游戏")
root.geometry("400x300")
app = Application(root)
root.mainloop()
main()