Step 4: Win Chart and Why It Works چالش 4 از جلسهی 24، سخت
قدم ۴. بعد از هر دور در play درصد برد کامپیوتر را (wins * 100 // rounds) به لیست history اضافه کن. در draw در قاب Rect(50, 190, 500, 100) پنجاه عدد آخر history را با screen.draw.line به هم وصل کن (هر دور ۱۰ پیکسل به راست، بالاتر یعنی درصد بیشتر). آخر یک جملهی انگلیسی در explain بنویس که با کلمهی because بگوید چرا ذهنخوان جواب میدهد، و پایین صفحه نشانش بده. ۵۰ دور با یک دوست بازی کن: خط کجا آرام میگیرد؟
import pgzrun
import random
WIDTH = 600
HEIGHT = 400
TITLE = "Mind Reader"
MOVES = ["rock", "paper", "scissors"]
BEATS = {"rock": "paper", "paper": "scissors", "scissors": "rock"}
buttons = {
"rock": Rect(40, 310, 160, 60),
"paper": Rect(220, 310, 160, 60),
"scissors": Rect(400, 310, 160, 60),
}
counts = {"rock": 0, "paper": 0, "scissors": 0}
wins = 0
losses = 0
draws = 0
message = "Click a button to play!"
def predict():
best = "rock"
for m in MOVES:
if counts[m] > counts[best]:
best = m
return best
def confidence():
total = counts["rock"] + counts["paper"] + counts["scissors"]
if total == 0:
return 33
return counts[predict()] * 100 // total
def computer_move():
return BEATS[predict()]
def play(move):
global wins, losses, draws, message
comp = computer_move()
counts[move] += 1
if comp == move:
draws += 1
message = "Both " + move + ": draw"
elif BEATS[move] == comp:
wins += 1
message = "My " + comp + " beats your " + move
else:
losses += 1
message = "Your " + move + " beats my " + comp
def on_mouse_down(pos):
for move in MOVES:
if buttons[move].collidepoint(pos):
play(move)
def draw():
screen.fill("navy")
screen.draw.text(message, center=(300, 30), fontsize=32, color="white")
score = "Computer " + str(wins) + " You " + str(losses) + " Draws " + str(draws)
screen.draw.text(score, center=(300, 70), fontsize=28, color="gold")
seen = "You played: rock " + str(counts["rock"]) + ", paper " + str(counts["paper"]) + ", scissors " + str(counts["scissors"])
screen.draw.text(seen, center=(300, 110), fontsize=24, color="lightblue")
conf = confidence()
screen.draw.text("I think you play " + predict() + ": " + str(conf) + "% sure", (150, 135), fontsize=24, color="white")
screen.draw.rect(Rect(150, 160, 300, 20), "white")
screen.draw.filled_rect(Rect(150, 160, conf * 3, 20), "orange")
for move in MOVES:
screen.draw.filled_rect(buttons[move], "indigo")
screen.draw.text(move, center=buttons[move].center, fontsize=32, color="white")
pgzrun.go()
راهنما و جواب این چالش · برگشت به درس جلسهی 24: پروژه: سنگکاغذقیچی ذهنخوان
بیشتر بخوان: بازیسازی با پایتون و Pygame Zero