Python基础实战1:猜大小游戏

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()
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值