بتل کد Battle Codeدارد باز می‌شود…

جواب «Step 2: Predict and Beat It» چالش 2 از جلسه‌ی 24

سؤال

قدم ۲. حالا ذهن‌خوانی! تابع predict() بنویس که پرتکرارترین حرکت بازیکن را برگرداند (از "rock" شروع کن و فقط اگر حرکتی بیشتر بود عوضش کن). بعد computer_move() به جای حرکت تصادفی، حرکتی را برگرداند که پیش‌بینی را می‌برد: BEATS[predict()]. ده بار سنگ بزن و ببین چه می‌شود!

راهنما

در predict: best = "rock" و for m in MOVES: if counts[m] > counts[best]: best = m. فراموش نکن return best.

یک جواب درست

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 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")
    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()

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن