بتل کد 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).

import app

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

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(questions)}"
    question.value = questions[index]["q"]
    answer_box.value = ""

def start_quiz():
    global index, score
    if len(questions) == 0:
        app.toast("Make some questions first!")
        return
    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 = questions[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(questions):
        show_question()
    else:
        result.value = f"Score: {score} of {len(questions)}"
        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("")

show_questions()
app.run()

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 16: پروژه: آزمون‌ساز

بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال