天天看點

使用tkinter 實作一個猜數字遊戲

使用tkinter 實作一個猜數字遊戲

實作效果如下

使用tkinter 實作一個猜數字遊戲

先導入我們要實作的子產品名

import time
import tkinter as tk
import tkinter.font as tkFont
import random

LOG_LINE_NUM = 0      

後面我們開始編寫實作的類

類名,定位為APP類

類方法裡面變量初始化,我們後面要用到的變量

def __init__(self, root):
        self.initUI(root)
        self.initGame()
        self.initData()

    def initGame(self):
        self.module = True  # 更新模式  True 積分模式 False猜準即更新
        self.bonus = 10  # 遊戲積分,初始為10
        self.coins = 10  # 猜數字次數,初始為10
        self.level = 1  # 遊戲級别,初始為1
        self.buycoins_temp = 0  # 額外猜數次數,初始為0,未消耗永久有效
        self.buycoins_forever = 0  # 額外永久猜數次數,初始為0,永久有效
        self.status_coinsforever = True  # 額外永久猜數次數是否使用過
        self.status_leveup = False  # 更新狀态
        self.burynumber = 0
        self.helpnumber = [1, 50, 100]  # 助猜數字
        self.status_helpnumber = False
        self.status_hint = True
        self.hintmin = 1
        self.hintmax = 100
        self.setDataLabel()
        self.GButton_submit['state'] = 'disabled'
        self.GButton_hint['state'] = 'disabled'
        self.GButton_buycoins_temp['state'] = 'disabled'
        self.GButton_buycoins_forever['state'] = 'disabled'
        self.GLineEdit_buycoins_forever['fg'] = "green"
        self.GLineEdit_buycoins_temp['fg'] = "green"
        global LOG_LINE_NUM
        LOG_LINE_NUM = 0
        self.GLineEdit_log.delete(1.0, 'end')      

定義一個函數編寫界面的标簽

def setDataLabel(self):
        self.set_bonus_lable(self.GLineEdit_bonus, self.bonus)
        self.set_bonus_lable(self.GLineEdit_level, self.level)
        self.set_bonus_lable(self.GLineEdit_coins, self.coins)
        self.set_bonus_lable(self.GLineEdit_buycoins_forever, self.buycoins_forever)
        self.set_bonus_lable(self.GLineEdit_buycoins_temp, self.buycoins_temp)
        if self.status_hint:
            self.GLabel_numrange['text'] = f'1-{self.level * 100}'
        else:
            self.GLabel_numrange['text'] = f'{self.hintmin}-{self.hintmax}'
        if self.status_helpnumber:
            self.GLabel_helpnum['text'] = f'健康遊戲忠告{self.helpnumber[1]}'
        else:
            self.GLabel_helpnum['text'] = f'健康遊戲忠告'
        self.GLabel_burynumber['text'] = f"抵制不良遊戲,拒絕盜版遊戲。\n注意自我保護,謹防受騙上當。\n" \
                                         f"适度遊戲益腦,沉迷遊戲傷身。\n合理安排時間,享受健康生活。"      

初始化界面的編寫

def initUI(self, root):
        # setting title
        root.title("猜數字遊戲  dltest@52pojie")
        # setting window size
        width = 600
        height = 500
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)

        ft_entry = tkFont.Font(family='Times', size=12)

        GLabel_770 = tk.Label(root, text="級别")
        GLabel_770.place(x=30, y=10, width=32, height=30)

        GLabel_975 = tk.Label(root, text="積分")
        GLabel_975.place(x=190, y=10, width=44, height=31)

        GLabel_917 = tk.Label(root, text="額外次數")
        GLabel_917.place(x=350, y=10, width=73, height=30)

        GLabel_30 = tk.Label(root, text="臨時次數")
        GLabel_30.place(x=350, y=50, width=73, height=34)

        GLabel_37 = tk.Label(root, text="剩餘猜測")
        GLabel_37.place(x=360, y=90, width=55, height=30)

        self.GButton_buycoins_forever = tk.Button(root, text="10分買一次")
        self.GButton_buycoins_forever.place(x=510, y=10, width=71, height=30)
        self.GButton_buycoins_forever["command"] = self.GButton_buycoins_forever_command

        self.GButton_buycoins_temp = tk.Button(root, text="2分買一次")
        self.GButton_buycoins_temp.place(x=510, y=50, width=71, height=30)
        self.GButton_buycoins_temp["command"] = self.GButton_buycoins_temp_command

        self.GLabel_result = tk.Label(root, text="猜測結果")
        self.GLabel_result.place(x=110, y=50, width=205, height=72)

        self.GLineEdit_log = tk.Text(root)  # "記錄"
        self.GLineEdit_log.place(x=10, y=130, width=408, height=360)

        self.GLineEdit_numinput = tk.Entry(root, text="輸入框", justify="center", font=ft_entry, validate='key',
                                           validatecommand=(root.register(self.checkInput), '%P'))
        self.GLineEdit_numinput.place(x=460, y=240, width=98, height=34)

        self.GButton_submit = tk.Button(root, text="送出")
        self.GButton_submit["command"] = self.GButton_submit_command
        self.GButton_submit.place(x=460, y=280, width=99, height=30)

        self.GLabel_helpnum = tk.Label(root, text="健康遊戲忠告")
        self.GLabel_helpnum.bind('<Button-1>', self.changeHelpStatus)
        self.GLabel_helpnum.place(x=430, y=370, width=160, height=30)

        self.GLabel_burynumber = tk.Label(root, text="抵制不良遊戲,拒絕盜版遊戲。\n注意自我保護,謹防受騙上當。\n"
                                                     "适度遊戲益腦,沉迷遊戲傷身。\n合理安排時間,享受健康生活。")
        ft = tkFont.Font(family='宋體', size=8)
        self.GLabel_burynumber["font"] = ft
        self.GLabel_burynumber["fg"] = "#5fb878"
        self.GLabel_burynumber.bind('<Button-1>', self.GLabel_getburynumber)
        self.GLabel_burynumber.place(x=430, y=400, width=171, height=75)

        self.GButton_star = tk.Button(root, text="開始遊戲")
        self.GButton_star.place(x=510, y=90, width=72, height=30)
        self.GButton_star["command"] = self.GButton_star_command

        GLabel_512 = tk.Label(root, text="本次數字區間")
        GLabel_512.place(x=450, y=170, width=120, height=30)

        self.GLabel_numrange = tk.Label(root, text="1-100")  # "1-100"
        self.GLabel_numrange.place(x=450, y=200, width=122, height=30)

        self.GLineEdit_level = tk.Entry(root, state='readonly', justify="center", font=ft_entry)  # "級别"
        self.GLineEdit_level.place(x=70, y=10, width=90, height=30)

        self.GLineEdit_bonus = tk.Entry(root, justify="center", font=ft_entry)  # "積分"
        self.GLineEdit_bonus.place(x=240, y=10, width=81, height=30)

        self.GLineEdit_buycoins_forever = tk.Entry(root, justify="center", font=ft_entry)  # 額外
        self.GLineEdit_buycoins_forever.place(x=420, y=10, width=72, height=30)

        self.GLineEdit_buycoins_temp = tk.Entry(root, justify="center", font=ft_entry)  # 臨時
        self.GLineEdit_buycoins_temp.place(x=420, y=50, width=72, height=30)

        self.GLineEdit_coins = tk.Entry(root, justify="center", font=ft_entry)  # 剩餘
        self.GLineEdit_coins.place(x=420, y=90, width=72, height=30)

        self.GButton_reset = tk.Button(root, text="重玩")
        self.GButton_reset.place(x=30, y=70, width=61, height=30)
        self.GButton_reset["command"] = self.GButton_reset_command

        self.GButton_hint = tk.Button(root, text="5積分縮小範圍1次")
        self.GButton_hint.place(x=430, y=130, width=149, height=30)
        self.GButton_hint["command"] = self.GButton_hint_command      

由于代碼太多了

隻貼上上面的代碼

# -*- coding:utf-8 -*-
# @FileName  :myguestnumberUI.py
# @Time      :2022/7/23 12:03
# @AuThor     :dltest@52pojie
import time
import tkinter as tk
import tkinter.font as tkFont
import random

LOG_LINE_NUM = 0


class App:
    def __init__(self, root):
        self.initUI(root)
        self.initGame()
        self.initData()

    def initGame(self):
        self.module = True  # 更新模式  True 積分模式 False猜準即更新
        self.bonus = 10  # 遊戲積分,初始為10
        self.coins = 10  # 猜數字次數,初始為10
        self.level = 1  # 遊戲級别,初始為1
        self.buycoins_temp = 0  # 額外猜數次數,初始為0,未消耗永久有效
        self.buycoins_forever = 0  # 額外永久猜數次數,初始為0,永久有效
        self.status_coinsforever = True  # 額外永久猜數次數是否使用過
        self.status_leveup = False  # 更新狀态
        self.burynumber = 0
        self.helpnumber = [1, 50, 100]  # 助猜數字
        self.status_helpnumber = False
        self.status_hint = True
        self.hintmin = 1
        self.hintmax = 100
        self.setDataLabel()
        self.GButton_submit['state'] = 'disabled'
        self.GButton_hint['state'] = 'disabled'
        self.GButton_buycoins_temp['state'] = 'disabled'
        self.GButton_buycoins_forever['state'] = 'disabled'
        self.GLineEdit_buycoins_forever['fg'] = "green"
        self.GLineEdit_buycoins_temp['fg'] = "green"
        global LOG_LINE_NUM
        LOG_LINE_NUM = 0
        self.GLineEdit_log.delete(1.0, 'end')

    def setDataLabel(self):
        self.set_bonus_lable(self.GLineEdit_bonus, self.bonus)
        self.set_bonus_lable(self.GLineEdit_level, self.level)
        self.set_bonus_lable(self.GLineEdit_coins, self.coins)
        self.set_bonus_lable(self.GLineEdit_buycoins_forever, self.buycoins_forever)
        self.set_bonus_lable(self.GLineEdit_buycoins_temp, self.buycoins_temp)
        if self.status_hint:
            self.GLabel_numrange['text'] = f'1-{self.level * 100}'
        else:
            self.GLabel_numrange['text'] = f'{self.hintmin}-{self.hintmax}'
        if self.status_helpnumber:
            self.GLabel_helpnum['text'] = f'健康遊戲忠告{self.helpnumber[1]}'
        else:
            self.GLabel_helpnum['text'] = f'健康遊戲忠告'
        self.GLabel_burynumber['text'] = f"抵制不良遊戲,拒絕盜版遊戲。\n注意自我保護,謹防受騙上當。\n" \
                                         f"适度遊戲益腦,沉迷遊戲傷身。\n合理安排時間,享受健康生活。"

    def initUI(self, root):
        # setting title
        root.title("猜數字遊戲  dltest@52pojie")
        # setting window size
        width = 600
        height = 500
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)

        ft_entry = tkFont.Font(family='Times', size=12)

        GLabel_770 = tk.Label(root, text="級别")
        GLabel_770.place(x=30, y=10, width=32, height=30)

        GLabel_975 = tk.Label(root, text="積分")
        GLabel_975.place(x=190, y=10, width=44, height=31)

        GLabel_917 = tk.Label(root, text="額外次數")
        GLabel_917.place(x=350, y=10, width=73, height=30)

        GLabel_30 = tk.Label(root, text="臨時次數")
        GLabel_30.place(x=350, y=50, width=73, height=34)

        GLabel_37 = tk.Label(root, text="剩餘猜測")
        GLabel_37.place(x=360, y=90, width=55, height=30)

        self.GButton_buycoins_forever = tk.Button(root, text="10分買一次")
        self.GButton_buycoins_forever.place(x=510, y=10, width=71, height=30)
        self.GButton_buycoins_forever["command"] = self.GButton_buycoins_forever_command

        self.GButton_buycoins_temp = tk.Button(root, text="2分買一次")
        self.GButton_buycoins_temp.place(x=510, y=50, width=71, height=30)
        self.GButton_buycoins_temp["command"] = self.GButton_buycoins_temp_command

        self.GLabel_result = tk.Label(root, text="猜測結果")
        self.GLabel_result.place(x=110, y=50, width=205, height=72)

        self.GLineEdit_log = tk.Text(root)  # "記錄"
        self.GLineEdit_log.place(x=10, y=130, width=408, height=360)

        self.GLineEdit_numinput = tk.Entry(root, text="輸入框", justify="center", font=ft_entry, validate='key',
                                           validatecommand=(root.register(self.checkInput), '%P'))
        self.GLineEdit_numinput.place(x=460, y=240, width=98, height=34)

        self.GButton_submit = tk.Button(root, text="送出")
        self.GButton_submit["command"] = self.GButton_submit_command
        self.GButton_submit.place(x=460, y=280, width=99, height=30)

        self.GLabel_helpnum = tk.Label(root, text="健康遊戲忠告")
        self.GLabel_helpnum.bind('<Button-1>', self.changeHelpStatus)
        self.GLabel_helpnum.place(x=430, y=370, width=160, height=30)

        self.GLabel_burynumber = tk.Label(root, text="抵制不良遊戲,拒絕盜版遊戲。\n注意自我保護,謹防受騙上當。\n"
                                                     "适度遊戲益腦,沉迷遊戲傷身。\n合理安排時間,享受健康生活。")
        ft = tkFont.Font(family='宋體', size=8)
        self.GLabel_burynumber["font"] = ft
        self.GLabel_burynumber["fg"] = "#5fb878"
        self.GLabel_burynumber.bind('<Button-1>', self.GLabel_getburynumber)
        self.GLabel_burynumber.place(x=430, y=400, width=171, height=75)

        self.GButton_star = tk.Button(root, text="開始遊戲")
        self.GButton_star.place(x=510, y=90, width=72, height=30)
        self.GButton_star["command"] = self.GButton_star_command

        GLabel_512 = tk.Label(root, text="本次數字區間")
        GLabel_512.place(x=450, y=170, width=120, height=30)

        self.GLabel_numrange = tk.Label(root, text="1-100")  # "1-100"
        self.GLabel_numrange.place(x=450, y=200, width=122, height=30)

        self.GLineEdit_level = tk.Entry(root, state='readonly', justify="center", font=ft_entry)  # "級别"
        self.GLineEdit_level.place(x=70, y=10, width=90, height=30)

        self.GLineEdit_bonus = tk.Entry(root, justify="center", font=ft_entry)  # "積分"
        self.GLineEdit_bonus.place(x=240, y=10, width=81, height=30)

        self.GLineEdit_buycoins_forever = tk.Entry(root, justify="center", font=ft_entry)  # 額外
        self.GLineEdit_buycoins_forever.place(x=420, y=10, width=72, height=30)

        self.GLineEdit_buycoins_temp = tk.Entry(root, justify="center", font=ft_entry)  # 臨時
        self.GLineEdit_buycoins_temp.place(x=420, y=50, width=72, height=30)

        self.GLineEdit_coins = tk.Entry(root, justify="center", font=ft_entry)  # 剩餘
        self.GLineEdit_coins.place(x=420, y=90, width=72, height=30)

        self.GButton_reset = tk.Button(root, text="重玩")
        self.GButton_reset.place(x=30, y=70, width=61, height=30)
        self.GButton_reset["command"] = self.GButton_reset_command

        self.GButton_hint = tk.Button(root, text="5積分縮小範圍1次")
        self.GButton_hint.place(x=430, y=130, width=149, height=30)
        self.GButton_hint["command"] = self.GButton_hint_command

    def initData(self):
        pass

    def GButton_buycoins_forever_command(self):
        if self.bonus >= 20 and self.buycoins_forever < 10:
            self.bonus -= 10
            self.buycoins_forever += 1
            self.write_log_to_Text(f'購買成功,已為您增加永久次數:1')
            if self.status_coinsforever:
                self.write_log_to_Text(f'本局可以使用購買得永久次數。')
            else:
                self.write_log_to_Text(f'永久次數已部份使用,下局可用新購次數。')
        else:
            if self.bonus < 20:
                self.write_log_to_Text(f'購買失敗!請預留至少10點遊戲積分!您目前遊戲積分:{self.bonus}')
            elif self.buycoins_forever >= 10:
                self.write_log_to_Text(f'購買失敗!額外猜數次數存儲上限為10次!')
        self.setDataLabel()

    def GButton_buycoins_temp_command(self):
        if self.bonus >= 12:
            self.bonus -= 2
            self.buycoins_temp += 1
            self.write_log_to_Text(f'購買成功,已為您增加臨時次數:1')
        else:
            self.write_log_to_Text(f'購買失敗!請預留至少10點遊戲積分!您目前遊戲積分:{self.bonus}')
        self.setDataLabel()

    def changeHelpStatus(self, event):
        self.status_helpnumber = not self.status_helpnumber
        self.setDataLabel()

    def GLabel_getburynumber(self, event):
        self.GLabel_burynumber['text'] = self.burynumber

    def GButton_submit_command(self):
        if self.bonus <= 0:
            self.write_log_to_Text(f'您的遊戲積分為0,GAME OVER!重玩請點選按鈕【重玩】')
            # self.write_log_to_Text('很遺憾!您沒有猜對數字!埋藏的數字為:{input:3}')
            return
        input = self.GLineEdit_numinput.get()
        self.GLineEdit_numinput.delete(0, 'end')
        x = 0
        if input:
            try:
                x = int(input)
            except:
                self.write_log_to_Text(f'請輸入整數')
                return
        else:
            self.write_log_to_Text(f'未輸入數字')
            return
        if x > self.burynumber:
            self.GLabel_result['fg'] = "#ff7800"
            ft = tkFont.Font(family='Times', size=12)
            self.GLabel_result["font"] = ft
            self.GLabel_result['text'] = "大了"
            self.write_log_to_Text(f'您猜的數[{input:>3}]太大了!扣除1點遊戲積分,剩餘遊戲積分:{self.bonus - 1}')
            self.helpnumber[2] = x
            self.helpnumber[1] = int((self.helpnumber[0] + self.helpnumber[2]) / 2)

        elif x < self.burynumber:
            self.GLabel_result['text'] = "小了"
            self.write_log_to_Text(f'您猜的數[{input:>3}]太小了!扣除1點遊戲積分,剩餘遊戲積分:{self.bonus - 1}')
            self.helpnumber[0] = x
            self.helpnumber[1] = int((self.helpnumber[0] + self.helpnumber[2]) / 2)
        else:
            self.status_leveup = True
            print("神啦!您居然猜對了")
            self.GLabel_result['text'] = "猜對了"
            self.write_log_to_Text(f'神啦!您居然猜對了!埋藏的數确實是[{input:>3}]。')
            self.write_log_to_Text(f'獎勵10點遊戲積分,剩餘遊戲積分:{self.bonus + 10}')
        self.setGameStaus()

    def setGameStaus(self):
        self.bonus -= 1
        if self.status_leveup:
            self.bonus += 11
            self.coins = 10
            self.GLineEdit_buycoins_forever['fg'] = "green"
        else:
            self.coins -= 1
        if self.coins == 0 and self.bonus > 0 and not self.status_leveup:
            if self.status_coinsforever and self.buycoins_forever > 0:
                self.status_coinsforever = False
                self.GLineEdit_buycoins_forever['fg'] = "red"
                self.coins += self.buycoins_forever
                self.write_log_to_Text(f'使用道具“主角光環”成功!額外增加[{self.buycoins_forever}]次猜測,請繼續加油!')
            elif self.buycoins_temp > 0:
                self.coins += 1
                self.buycoins_temp -= 1
                self.write_log_to_Text(f'幸運加持!額外增加[{1}]次猜測,請繼續加油!')
            else:
                self.write_log_to_Text(f'很遺憾!您沒有猜對數字!埋藏的數字為:{self.burynumber:>3}')
                self.write_log_to_Text(f'您的猜測次數為0,GAME OVER!重玩請點選按鈕【重玩】')
                self.GameOver()
        self.uplevel()
        if self.status_leveup:
            self.GButton_star_command()
        self.setDataLabel()  # 重新整理顯示

    def GButton_hint_command(self):
        if self.bonus > 5:
            self.status_hint = False
            self.bonus -= 5
            min = random.randint(1, 25)
            max = random.randint(1, 25)
            hintmin = 1
            if self.burynumber - self.hintmin > min:
                hintmin = self.burynumber - min
            else:
                hintmin = self.burynumber - random.randint(1, (self.burynumber - self.hintmin))
            hintmax = self.level * 100
            if self.hintmax - self.burynumber > max:
                hintmax = self.burynumber + max
            else:
                hintmax = self.burynumber + random.randint(1, (self.hintmax - self.burynumber))
            if hintmin < 0:
                hintmin = random.randint(1, self.burynumber)
            if hintmax > self.level * 100:
                hintmax = random.randint(self.burynumber, self.level * 100)
            self.hintmin = hintmin
            self.hintmax = hintmax
            self.write_log_to_Text(f'-----------消耗5點遊戲積分擷取埋藏數字區間提示 ------')
            self.write_log_to_Text(f'埋藏的數字在「{self.hintmin}~{self.hintmax}」之間,剩餘遊戲積分:{self.bonus}')
        else:
            self.write_log_to_Text(f'購買失敗!請預留至少5點遊戲積分!您目前遊戲積分:{self.bonus}')
        self.setDataLabel()

    def GButton_star_command(self):
        self.burynumber = self.BuryNumber(self.level)
        self.GButton_star['state'] = 'disabled'
        self.GButton_submit['state'] = 'active'
        self.GButton_hint['state'] = 'active'
        self.GButton_buycoins_temp['state'] = 'active'
        self.GButton_buycoins_forever['state'] = 'active'
        self.status_hint = True
        self.status_leveup = False
        self.status_coinsforever = True
        print(self.level)
        self.helpnumber[2] = self.level * 100
        self.helpnumber[0] = 1
        self.helpnumber[1] = int((self.helpnumber[0] + self.helpnumber[2]) / 2)
        print(self.helpnumber)

    def GButton_reset_command(self):
        self.bonus = 10
        self.level = 1
        self.set_bonus_lable(self.GLineEdit_bonus, self.bonus)
        self.set_bonus_lable(self.GLineEdit_level, self.level)
        self.GButton_star['state'] = 'active'
        self.initGame()
        self.setDataLabel()

    # 根據遊戲級别埋藏數字
    def BuryNumber(self, level):
        return random.randint(1, level * 100)

    def checkInput(self, char):
        if (char.isdigit() or char == ""):
            return True
        else:
            return False

    def write_log_to_Text(self, logmsg):
        global LOG_LINE_NUM
        logmsg_in = str(logmsg) + "\n"  # 換行
        if LOG_LINE_NUM <= 24:
            self.GLineEdit_log.insert('end', logmsg_in)
            LOG_LINE_NUM = LOG_LINE_NUM + 1
        else:
            self.GLineEdit_log.delete(1.0, 2.0)
            self.GLineEdit_log.insert('end', logmsg_in)

    def set_bonus_lable(self, _Edit, value):
        _Edit.config(state='normal')
        _Edit.delete(0, 'end')
        _Edit.insert(0, f"{value}")
        _Edit.config(state='readonly')

    def GameOver(self):
        self.GButton_submit['state'] = 'disabled'

    # 根據遊戲積分提升遊戲級别
    def uplevel(self):
        level = self.level
        if self.status_leveup and not self.module:
            level += 1
        else:
            level = self.bonus // 10 + 1
        if level > self.level:
            self.level = level
            self.write_log_to_Text(f'-----------遊戲難度更新至:{self.level}  ------')


if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()      

繼續閱讀