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

جواب «Step 4: Shuffle and Play Again» چالش 4 از جلسه‌ی 16

سؤال

قدم ۴ از ۴: سؤال‌ها را به هم بریز! بالای برنامه import random بنویس و یک لیست order = [] کنار index و score بساز. در start_quiz (با global برای order هم) یک کپی از سؤال‌ها بگیر، order = questions[:]، و random.shuffle(order) کن. در show_question و check_answer به جای questions از order استفاده کن. در صفحه‌ی score دو دکمه بگذار: Play again (آزمون را از اول شروع کند) و Edit questions (برو به make).

راهنما

random.shuffle(order) را تنها در یک خط بنویس، نه order = random.shuffle(...). دکمه‌ی Play again همان تابع start_quiz را صدا می‌زند: app.button("Play again", start_quiz) زیر result.

یک جواب درست

import app
import random

questions = app.load("questions", [])
index = 0
score = 0
order = []

def show_questions():
    qlist.clear()
    for item in questions:
        qlist.add(f"{item['q']} = {item['a']}")

def add_question():
    q = q_box.value.strip()
    a = a_box.value.strip()
    if q == "" or a == "":
        app.toast("Write a question and its answer")
        return
    questions.append({"q": q, "a": a})
    app.save("questions", questions)
    q_box.value = ""
    a_box.value = ""
    show_questions()

def show_question():
    progress.value = f"Question {index + 1} of {len(order)}"
    question.value = order[index]["q"]
    answer_box.value = ""

def start_quiz():
    global index, score, order
    if len(questions) == 0:
        app.toast("Make some questions first!")
        return
    order = questions[:]
    random.shuffle(order)
    index = 0
    score = 0
    show_question()
    app.go("play")

def check_answer():
    global index, score
    typed = answer_box.value.strip().lower()
    if typed == "":
        app.toast("Type an answer first")
        return
    right = order[index]["a"]
    if typed == right.lower():
        score = score + 1
        app.toast("Right!")
    else:
        app.toast(f"Wrong! The answer is {right}")
    index = index + 1
    if index < len(order):
        show_question()
    else:
        result.value = f"Score: {score} of {len(order)}"
        app.go("score")

app.screen("make")
app.title("Quiz Maker")
q_box = app.input("Question")
a_box = app.input("Answer")
app.button("Add question", add_question)
app.button("Play", start_quiz)
qlist = app.list()

app.screen("play")
app.title("Quiz")
progress = app.text("")
question = app.text("")
answer_box = app.input("Your answer")
app.button("Check", check_answer)

app.screen("score")
app.title("Score")
result = app.text("")
app.button("Play again", start_quiz)
app.button("Edit questions", lambda: app.go("make"))

show_questions()
app.run()

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