1. 2行代碼實現擲骰子(數字版)
骰子(tóu zi)
,有些地方也叫色子(shǎi zi)
。是我國傳統的遊戲博弈道具,一般用於聚會娛樂時,筆者呢也是在工作的時候,才接觸到這個遊戲,未有敗績,嘿嘿。在生活中呢,我們最常見的骰子是六面骰,它是一顆正立方體,上面分別有一到六個孔(或數字)。請編寫一個程序,使用2
行代碼,隨機輸出一次骰子的投擲結果。運行效果如下圖所示。
示例代碼如下:
import random
print(f"你擲出的骰子點數爲: {random.choice(range(1, 7))}")
2. 擲多個骰子(數字版)
在實際投骰子博弈中,莊家先把三顆骰子放在有蓋的器皿內搖晃。當各閒家下注完畢,莊家便打開器皿並派彩。因爲最常見的賭注是買骰子點數的大小(總點數爲3至10稱作小,11至18爲大)
,下面就模擬投擲三顆骰子,運行效果如下圖所示。
示例代碼如下:
import random
point_list = [random.choice(range(1, 7)) for i in range(3)]
msg = "骰子點數和爲小" if 3 <= sum(point_list) <= 10 else "骰子點數和爲大"
print(f"你擲出的骰子點數爲: {','.join(map(str, point_list))}=>{msg}")
3. 猜骰子游戲
編寫一個簡單的猜骰子點數的遊戲,讓程序隨機輸出一個骰子數,用戶有兩次競猜機會。猜中提示用戶恭喜你,猜對了,競猜的點數爲
,猜錯提示用戶運氣不佳,猜錯了!
。若兩次競猜均失敗,則提示競猜失敗,競猜的點數爲
。運行效果如下圖所示。
示例代碼如下:
import random
if __name__ == '__main__':
print("==========猜骰子游戲==========")
print("*" * 29)
num = 2
point = random.choice(range(1, 7)) # 生成骰子點數
for i in range(num):
print(f"請猜猜骰子的點數,有{num}次機會哦!")
input_point = int(input("輸入點數:").strip())
if point == input_point:
print(f"恭喜你,猜對了!競猜的點數爲: {point}")
break
print("運氣不佳,猜錯了!")
num -= 1
else:
print(f"競猜失敗,競猜的點數爲: {point}")
4. 擲單個骰子(圖形版)
前面編寫程序中的骰子爲數字,比較單調。能不能動態模擬顯示骰子的隨機生成過程呢?編寫一個程序,單擊開始
按鈕,實現骰子在點數1~點數6
的快速轉換,最後停留在某一個點數上,運行效果如下圖所示。
示例代碼如下:
from tkinter import *
from tkinter.messagebox import *
import random
def call():
global image1
global count
num = random.choice(range(1, 7)) # 隨機產生骰子數量
img = "touzi/" + str(num) + "t.png"
image1 = PhotoImage(file=img)
Label(root, image=image1).grid(row=1, column=1)
count += 1
if count >= 20:
showwarning(title="擲骰子游戲", message="你骰子的點數爲:" + str(num))
else:
root.after(100, call)
def start():
global count
count = 0
call()
if __name__ == '__main__':
count = 1
root = Tk() # 創建根窗體
root.wm_attributes("-topmost", 1) # 置頂
root.title("擲骰子游戲") # 窗體標題
screenWidth = root.winfo_screenwidth() # 屏幕寬度
screenHeight = root.winfo_screenheight() # 屏幕高度
width = 330 # 窗體寬度
height = 180 # 窗體高度
x = (screenWidth - width) / 2 # 偏移量x
y = (screenHeight - height) / 2 # 偏移量y
root.geometry("%dx%d+%d+%d" % (width, height, x, y)) # 窗體居中顯示
root.resizable(width=False, height=False) # 決定框體大小是否能夠調整
msg = Label(root, text='請單擊"開始"進行遊戲').grid(row=0, column=0)
image1 = PhotoImage(file="./touzi/6t.png")
label = Label(root, image=image1).grid(row=1, column=1)
bank = Label(root, text=" ").grid(row=2, column=1)
start_button = Button(root, text="開始", command=start, width=8)
start_button.grid(column=1, row=3)
root.mainloop()
5. 擲多個骰子(圖形版)
上一個任務動態模擬顯示骰子的隨機生成的過程。修改上個程序,實現三個骰子同時投擲的過程,單擊開始
按鈕,實現3個骰子同時在點數1~點數6
的快速轉換,最後停留在某一個點數上,運行效果如下圖所示。
示例代碼如下:
from tkinter import *
from tkinter.messagebox import *
import random
def call():
global image1
global image2
global image3
global count
num1 = random.choice(range(1, 7))
num2 = random.choice(range(1, 7))
num3 = random.choice(range(1, 7))
img = "touzi/" + str(num1) + "t.png"
image1 = PhotoImage(file=img)
Label(root, image=image1).grid(row=1, column=0)
img = "touzi/" + str(num2) + "t.png"
image2 = PhotoImage(file=img)
Label(root, image=image2).grid(row=1, column=1)
img = "touzi/" + str(num3) + "t.png"
image3 = PhotoImage(file=img)
Label(root, image=image3).grid(row=1, column=2)
count += 1
if count >= 20:
showwarning(title="擲骰子游戲", message="你骰子的點數爲:" + str(num1 + num2 + num3))
else:
root.after(100, call)
def start():
global count
count = 0
call()
if __name__ == '__main__':
count = 1
root = Tk() # 創建根窗體
root.wm_attributes("-topmost", 1) # 置頂
root.title("擲骰子游戲") # 窗體標題
screenWidth = root.winfo_screenwidth() # 屏幕寬度
screenHeight = root.winfo_screenheight() # 屏幕高度
width = 330 # 窗體寬度
height = 180 # 窗體高度
x = (screenWidth - width) / 2 # 偏移量x
y = (screenHeight - height) / 2 # 偏移量y
root.geometry("%dx%d+%d+%d" % (width, height, x, y)) # 窗體居中顯示
root.resizable(width=False, height=False) # 決定框體大小是否能夠調整
msg = Label(root, text='請單擊"開始"進行遊戲').grid(row=0, column=0)
image1 = PhotoImage(file="./touzi/6t.png")
label1 = Label(root, image=image1).grid(row=1, column=0)
image2 = PhotoImage(file="./touzi/6t.png")
label2 = Label(root, image=image1).grid(row=1, column=1)
image3 = PhotoImage(file="./touzi/6t.png")
label3 = Label(root, image=image1).grid(row=1, column=2)
bank = Label(root, text=" ").grid(row=2, column=1)
start_button = Button(root, text="開始", command=start, width=8)
start_button.grid(column=1, row=3)
root.mainloop()
6. 擲骰子與後門程序
擲骰子高手可以控制擲出骰子的點數。編程能否控制輸出骰子的點數呢?當然可以,其實就是給程序添加一個後門程序。爲上面的程序擲多個骰子(圖形版)
添加一個後門程序,讓程序按要求投出指定的點數,例如投出點數爲4,6,3
。提示:在開始按鈕旁邊加一個按鈕,設置邊框爲無,點擊這個按鈕後,再點擊開始
按鈕,設置投出骰子點數爲4,6,3
如下圖所示。
示例代碼如下:
from tkinter import *
import random
def call():
global image1
global image2
global image3
global count
global flag
num1 = random.choice(range(1, 7))
num2 = random.choice(range(1, 7))
num3 = random.choice(range(1, 7))
if flag == 0 and count == 19:
num1 = 4
num2 = 6
num3 = 3
img = "touzi/" + str(num1) + "t.png"
image1 = PhotoImage(file=img)
Label(root, image=image1).grid(row=1, column=0)
img = "touzi/" + str(num2) + "t.png"
image2 = PhotoImage(file=img)
Label(root, image=image2).grid(row=1, column=1)
img = "touzi/" + str(num3) + "t.png"
image3 = PhotoImage(file=img)
Label(root, image=image3).grid(row=1, column=2)
count += 1
if count < 20:
root.after(100, call)
else:
flag = 1
def start():
global count
count = 0
call()
def gono():
global flag
flag = 0
if __name__ == '__main__':
count = 1
flag = 1
root = Tk() # 創建根窗體
root.wm_attributes("-topmost", 1) # 置頂
root.title("擲骰子游戲") # 窗體標題
screenWidth = root.winfo_screenwidth() # 屏幕寬度
screenHeight = root.winfo_screenheight() # 屏幕高度
width = 330 # 窗體寬度
height = 180 # 窗體高度
x = (screenWidth - width) / 2 # 偏移量x
y = (screenHeight - height) / 2 # 偏移量y
root.geometry("%dx%d+%d+%d" % (width, height, x, y)) # 窗體居中顯示
root.resizable(width=False, height=False) # 決定框體大小是否能夠調整
msg = Label(root, text='請單擊"開始"進行遊戲').grid(row=0, column=0)
image1 = PhotoImage(file="./touzi/6t.png")
label1 = Label(root, image=image1).grid(row=1, column=0)
image2 = PhotoImage(file="./touzi/6t.png")
label2 = Label(root, image=image1).grid(row=1, column=1)
image3 = PhotoImage(file="./touzi/6t.png")
label3 = Label(root, image=image1).grid(row=1, column=2)
bank = Label(root, text=" ").grid(row=2, column=1)
start_button = Button(root, text="開始", command=start, width=8)
start_button.grid(column=1, row=3)
Button(root, text=" ", command=gono, relief=FLAT, state="normal", width=8).grid(row=3, column=2)
root.mainloop()
7. 人機對話: 擲骰子游戲
我國民間擲骰子游戲以博弈點數猜大小爲主,每次下注前,莊家先把三顆骰子放在有蓋的器皿內搖晃,參與者下注猜骰子點數大小,下注結束後莊家打開器皿,計算三個骰子點數的和,小於等於10爲小,大於10爲大,猜中者獲勝。編寫一個人機對話的擲骰子游戲,玩者選擇大或者小,計算機會根據已出現的大小的概率來選擇大或小。單擊開始
按鈕,開始擲骰子,根據三個骰子點數的和來判斷玩家和電腦誰是贏家。運行效果如下動圖所示。
示例代碼如下:
from tkinter import *
import random
def call():
global image1
global image2
global image3
global count
global point_sum # 點數之和
num1 = random.choice(range(1, 7))
img = "touzi/" + str(num1) + "t.png"
image1 = PhotoImage(file=img)
Label(root, image=image1).grid(row=2, column=0)
point_sum += num1
num2 = random.choice(range(1, 7))
img = "touzi/" + str(num2) + "t.png"
image2 = PhotoImage(file=img)
Label(root, image=image2).grid(row=2, column=1)
point_sum += num2
num3 = random.choice(range(1, 7))
img = "touzi/" + str(num3) + "t.png"
image3 = PhotoImage(file=img)
Label(root, image=image3).grid(row=2, column=2)
point_sum += num3
count += 1
if count < 20:
root.after(100, call)
else:
judge()
point_sum = 0
def judge():
global big
global little
global s_sel
global y_sel
global count
global point_sum
if point_sum >= 11:
big += 1
if y_sel == "大":
if s_sel == "小":
Label(root, text="恭喜,你贏了電腦!").grid(row=3, column=2)
else:
Label(root, text="哦,你和電腦打平了!").grid(row=3, column=2)
else:
if s_sel == "大":
Label(root, text="哦耶,電腦贏了!").grid(row=3, column=2)
else:
Label(root, text="哦,你和電腦都輸了!").grid(row=3, column=2)
else:
little += 1
if y_sel == "大":
if s_sel == "小":
Label(root, text="哦耶,電腦贏了!").grid(row=3, column=2)
else:
Label(root, text="哦,你和電腦都輸了!").grid(row=3, column=2)
else:
if s_sel == "大":
Label(root, text="恭喜,你贏了電腦!").grid(row=3, column=2)
else:
Label(root, text="哦,你和電腦打平了!").grid(row=3, column=2)
def start():
global count
global y_sel
count = 0
y_sel = option_value()
Label(root, text="你選的是: " + y_sel).grid(column=0, row=3)
call()
def option_value():
global value
global big
global little
global s_sel
value = "大" if var.get() == 1 else "小"
Label(root, text="你選的是: " + value).grid(row=3, column=0)
s_sel = sys_value(big, little)
return value
def sys_value(value1, value2):
if value1 <= value2:
Label(root, text="電腦選的是: 大").grid(row=3, column=1)
return "大"
else:
Label(root, text="電腦選的是: 小").grid(row=3, column=1)
return "小"
if __name__ == '__main__':
count = 1
flag = 1
value = "" # 用來存儲用戶選擇是大 還是小
point_sum = 0 # 用來記錄點數之和
big = little = 0
y_sel = "" # 用戶選擇
s_sel = "" # 系統選擇
root = Tk() # 創建根窗體
root.wm_attributes("-topmost", 1) # 置頂
root.title("擲骰子游戲") # 窗體標題
screenWidth = root.winfo_screenwidth() # 屏幕寬度
screenHeight = root.winfo_screenheight() # 屏幕高度
width = 350 # 窗體寬度
height = 240 # 窗體高度
x = (screenWidth - width) / 2 # 偏移量x
y = (screenHeight - height) / 2 # 偏移量y
root.geometry("%dx%d+%d+%d" % (width, height, x, y)) # 窗體居中顯示
root.resizable(width=False, height=False) # 決定框體大小是否能夠調整
msg = Label(root, text="選擇骰子點數大小").grid(row=0, column=0)
var = IntVar() # 選項按鈕綁定的變量
var.set(1) # 默認選項是大
# 大選項按鈕
rb_big = Radiobutton(root, text="大", value=1, variable=var, command=option_value).grid(row=1, column=0)
# 小選項按鈕
rb_small = Radiobutton(root, text="小", value=0, variable=var, command=option_value).grid(row=1, column=1)
image1 = PhotoImage(file="./touzi/6t.png")
label1 = Label(root, image=image1).grid(row=2, column=0)
image2 = PhotoImage(file="./touzi/6t.png")
label2 = Label(root, image=image1).grid(row=2, column=1)
image3 = PhotoImage(file="./touzi/6t.png")
label3 = Label(root, image=image1).grid(row=2, column=2)
label4 = Label(root, text="你選的是: " + option_value()).grid(row=3, column=0)
label5 = Label(root, text="電腦選的是: 大").grid(row=3, column=1)
bank = Label(root, text="單擊'開始'競猜......").grid(row=4, column=0)
Button(root, text="開始", command=start, width=8).grid(row=5, column=1)
root.mainloop()
至此今天的案例就到此結束了,這個案例同樣本身的邏輯並不複雜,主要還是對tkinter
的運用,然而筆者也是辛苦的整理了一下午,筆者至此吐槽兩句,從今天開始不太想見到tkinter
了,界面佈局不咋美觀,處理起來還比較麻煩,以前筆者寫前端的時候簡直不要太享受~,後續如果讀者使用tkinter
較多或者是對它比較感興趣,可以去看一下Python GUI設計——tkinter菜鳥編程
這本書,寫得還挺不錯。最後筆者在這裏聲明,筆者寫文章只是爲了學習交流,以及讓更多學習Python基礎的讀者少走一些彎路,節省時間,並不用做其他用途,如有侵權,聯繫筆者刪除即可。編寫不易,請大家手留餘香~。