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

جواب «Step 3: Practise Fast, Then Watch» چالش 3 از جلسه‌ی 20

سؤال

قدم ۳. تماشای یادگیری کند است؛ پس اول بی‌صدا تمرین کنیم. اضافه کن:
- import random و epsilon = 0.2.
- play_round(): از فاصله‌ی ۱۰ شروع کند و تا تمام شدن دور: حالت را بگیرد، با کنجکاوی کار را انتخاب کند (random.random() < epsilon یعنی random.choice(["jump", "wait"]))، simulate و learn را صدا بزند و امتیاز را جمع کند؛ آخر امتیاز را برگرداند.
- قبل از باز شدن پنجره: random.seed(1) و ۲۰۰ بار play_round().
حالا tick فقط با best_action بازی کند و دیگر یاد نگیرد. بالای صفحه بنویس trained 200 rounds.

راهنما

در play_round از یک متغیر جدا مثل d برای فاصله استفاده کن تا با dist صفحه قاطی نشود: while not done:.

یک جواب درست

import pgzrun
import random

WIDTH = 600
HEIGHT = 300
TITLE = "Learning Runner"

dist = 10
jumping = False
message = ""
runner = Actor("robot", (80, 200))
rock = Actor("rock", (530, 200))
alpha = 0.5
epsilon = 0.2

def state_of(dist):
    return (dist - 1) // 2

def simulate(dist, action):
    if action == "jump":
        if dist <= 2:
            return 0, 10, True
        return dist - 2, -1, False
    dist = dist - 1
    if dist == 0:
        return 0, -10, True
    return dist, 0, False

Q = {}
for s in range(5):
    Q[s] = {"jump": 0, "wait": 0}

def best_action(s):
    if Q[s]["jump"] > Q[s]["wait"]:
        return "jump"
    return "wait"

def learn(s, action, reward, new_dist, done):
    target = reward
    if not done:
        s2 = state_of(new_dist)
        target = reward + max(Q[s2]["jump"], Q[s2]["wait"])
    Q[s][action] += alpha * (target - Q[s][action])

def play_round():
    d = 10
    score = 0
    done = False
    while not done:
        s = state_of(d)
        if random.random() < epsilon:
            action = random.choice(["jump", "wait"])
        else:
            action = best_action(s)
        new_d, reward, done = simulate(d, action)
        learn(s, action, reward, new_d, done)
        score += reward
        d = new_d
    return score

random.seed(1)
for i in range(200):
    play_round()

def tick():
    global dist, jumping, message
    action = best_action(state_of(dist))
    jumping = action == "jump"
    dist, reward, done = simulate(dist, action)
    if done:
        message = "cleared!" if reward > 0 else "crash!"
        dist = 10

def draw():
    screen.fill("skyblue")
    screen.draw.filled_rect(Rect(0, 225, 600, 75), "darkgreen")
    runner.y = 130 if jumping else 200
    rock.x = 80 + dist * 45
    runner.draw()
    rock.draw()
    screen.draw.text("trained 200 rounds   state: " + str(state_of(dist)), (10, 10), fontsize=28, color="black")
    screen.draw.text(message, (10, 40), fontsize=28, color="darkred")
    for s in range(5):
        row = "state " + str(s) + ": jump " + str(round(Q[s]["jump"], 1)) + "  wait " + str(round(Q[s]["wait"], 1))
        screen.draw.text(row, (330, 10 + s * 22), fontsize=22, color="navy")

clock.schedule_interval(tick, 0.5)
pgzrun.go()

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