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

Step 3: Six-Message Memory چالش 3 از جلسه‌ی 40، متوسط

بولت گفت‌وگو را یادش بماند. قبل از on_key_down بنویس history = [] و داخل on_key_down آن را به خط global اضافه کن. وقتی سؤال فرستاده می‌شود: ask(typed, system=SYSTEM, history=history)، بعد پیام کاربر و جواب را با نقش‌هایشان اضافه کن و history = history[-6:]. بپرس «My favourite colour is blue» و بعد «What is my favourite colour?».

import pgzrun
from ai import ask

WIDTH = 600
HEIGHT = 400
TITLE = "Bolt the Talking Robot"

hero = Actor("hero", (100, 250))
bolt = Actor("robot", (450, 150))
typed = ""
reply = "Walk to Bolt and type a question."

FACTS = [
    "The gold key is hidden in the dark cave.",
    "The bridge to the castle is broken.",
    "The river is safe to swim across.",
]
SYSTEM = ("You are Bolt, a friendly robot in a forest game. "
          + "Facts about the game: " + " ".join(FACTS) + " "
          + "Answer in one or two short sentences. Only talk about this game.")

def update():
    if keyboard.left:
        hero.x -= 3
    if keyboard.right:
        hero.x += 3
    if keyboard.up:
        hero.y -= 3
    if keyboard.down:
        hero.y += 3

def near():
    return hero.distance_to(bolt) < 120

def on_key_down(key, mod, unicode):
    global typed, reply
    if key == keys.RETURN:
        if near():
            reply = ask(typed, system=SYSTEM)
        else:
            reply = "Come closer to Bolt first."
        typed = ""
    elif key == keys.BACKSPACE:
        typed = typed[:-1]
    elif unicode and len(typed) < 40:
        typed += unicode

def draw():
    screen.fill("darkgreen")
    hero.draw()
    bolt.draw()
    screen.draw.filled_rect(Rect(0, 330, 600, 70), "black")
    screen.draw.text("> " + typed, (10, 338), fontsize=24, color="white")
    screen.draw.text(reply[:70], (10, 368), fontsize=20, color="yellow")

pgzrun.go()

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 40: پروژه: شخصیت سخنگوی بازی · چالش بعدی: Step 4: Test Bolt

بیشتر بخوان: بازی‌سازی با پایتون و Pygame Zero