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.
import pgzrun
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
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 tick():
global dist, jumping, message
s = state_of(dist)
action = best_action(s)
jumping = action == "jump"
new_dist, reward, done = simulate(dist, action)
learn(s, action, reward, new_dist, done)
dist = new_dist
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("distance: " + str(dist) + " 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()
راهنما و جواب این چالش · برگشت به درس جلسهی 20: پروژه: بازیای که خودش یاد میگیرد · چالش بعدی: Step 4: The Learning Chart and My Change
بیشتر بخوان: بازیسازی با پایتون و Pygame Zero