Python 入門指南 5.0

exercise4403.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# 從 Brython 引入 document 並以 doc 為別名
from browser import document as doc
# 從 Brython 引入 window
from browser import window
# 從 random 引入 randint
from random import randint
# 從 exercise2503 引入 DiceUser
from exercise2503 import DiceUser

# 計算秒數
t = 10

# 設定玩家與莊家
banker = DiceUser("莊家", 500)
user = DiceUser("玩家", 100)

# 顯示欄位設定為隱藏
doc["display"].style.display = "none"
doc["result"].style.display = "none"

# 擲骰子動畫
def animate_dice(event):
    global user, banker
    banker.roll2Dice()
    user.roll2Dice()
    doc["display"].style.display = "block"
    doc["result"].style.display = "none"
    d1 = user.dice1.point
    d2 = user.dice2.point
    total = user.total_points
    def show_rolling():
        doc["dice1"].text = f"{randint(1, 6)}"
        doc["dice2"].text = f"{randint(1, 6)}"
        doc["run"].disabled = True
        doc["display"].text = f"擲骰子中"
        global t
        t -= 1
        if t < 0:
            window.clearInterval(timer_id)
            doc["dice1"].text = f"{d1}"
            doc["dice2"].text = f"{d2}"
            t = 10
            doc["run"].disabled = False
            doc["display"].style.display = "none"
            run_game()
    timer_id = window.setInterval(show_rolling, 600)

# 判斷遊戲結果
def run_game():
    global user, banker
    if banker.asset - 30 > 0 and user.asset - 30 > 0:
        banker.asset -= 30
        user.asset -= 30
        doc["result"].style.display = "block"
        doc["result"].text = f"莊家擲出 {banker.total_points} 點,"
        if banker.total_points >= user.total_points:
            doc["result"].text += f"莊家贏,"
            banker.asset += 60
        else:
            doc["result"].text += f"玩家贏,"
            user.asset += 60
        doc["result"].text += f"玩家資產尚有 {user.asset}"
    else:
        if banker.asset - 30 < 0:
            doc["result"].text = "莊家資產不足以下注"
        else:
            doc["result"].text = "玩家資產不足以下注"
        doc["run"].disabled = True

# 按鈕註冊事件
doc["run"].bind("click", animate_dice)

# 檔名: exercise4403.py
# 說明:《Python入門指南》的練習
# 網站: http://kaiching.org
# 作者: 張凱慶
# 時間: 2023 年 12 月

回到練習題目
上一頁 exercise4402.py
回 Python 入門指南 5.0 首頁
下一頁 exercise4404.py
回 Python 教材首頁
回程式語言教材首頁