Turtle Python 中的问答顺序问题

问题描述 投票:0回答:1

我正在根据芝加哥相关问题编写基于 Turtle Python 的测验。我对答案和问题顺序有疑问,问题是当按下答案选项时,下一个问题的答案选项集合会被跳过,并且测验全部错误。我希望有人可以帮助我解决这个问题,因为我是编码新手,不太适应。

import turtle
import sys
import time
from turtle import Screen, Turtle


# Setup the screen
window = turtle.Screen()
window.title("Game Menu")
window.bgcolor("white")

# Draw title function
def draw_title(message, y_pos):
    title_turtle = turtle.Turtle()
    title_turtle.hideturtle()
    title_turtle.penup()
    title_turtle.goto(0, y_pos)
    title_turtle.write(message, align="center", font=("Arial", 24, "bold"))
    return title_turtle

# Generic button drawing function
def draw_button(label, y_pos, color):
    button = turtle.Turtle()
    button.shape("square")
    button.color(color)
    button.shapesize(stretch_wid=2, stretch_len=5)
    button.penup()
    button.goto(0, y_pos - 20)
    button.write(label, align="center", font=("Arial", 16, "bold"))
    button.sety(y_pos - 40)
    return button

# Function to start the game (first screen)
def start_game():
    turtle.clearscreen()
    draw_title("Welcome to the Game", 50)
    next_button = draw_button("Next", 0, "green")
    quit_button = draw_button("Quit", -100, "red")

    def on_start_click(x, y):
        if next_button.distance(x, y) < 50:
            name_entry_screen()
        elif quit_button.distance(x, y) < 50:
            quit_game()

    turtle.onscreenclick(on_start_click)

# Function for name entry screen (second screen)
def name_entry_screen():
    turtle.clearscreen()
    draw_title("Please enter your name:", 100)
    name = turtle.textinput("Name Entry", "Enter your name here:")
    if name:
        game_description_screen()

# Function for game description screen (third screen)
def game_description_screen():
    turtle.clearscreen()
    draw_title("Description", 200)
    description_text = (
        "This educational game focuses on data representation through interactive quizzes.\n"
        "Players are challenged with 10 questions about Chicago, requiring quick thinking and accuracy.\n"
        "Each participant must answer within a total of 100 seconds, aiming for the highest score possible out of 10.\n"
        "Upon completion, detailed graphical representations of data for each answer are provided, enhancing learning and offering valuable feedback."
    )
    description_turtle = draw_title(description_text, 0)
    next_button = draw_button("Next", -100, "blue")
    quit_button = draw_button("Quit", -200, "red")

    def on_description_click(x, y):
        if next_button.distance(x, y) < 50:
            ready_screen()
        elif quit_button.distance(x, y) < 50:
            quit_game()

    turtle.onscreenclick(on_description_click)

# Function to display the ready screen (fourth screen)
def ready_screen():
    turtle.clearscreen()
    draw_title("Ready?", 50)
    yes_button = draw_button("Yes", 0, "green")
    no_button = draw_button("No", -100, "red")

    def on_ready_click(x, y):
        if yes_button.distance(x, y) < 50:
            start_countdown()
        elif no_button.distance(x, y) < 50:
            quit_game()

    turtle.onscreenclick(on_ready_click)

# Function to start countdown
def start_countdown():
    turtle.clearscreen()
    count_title = draw_title("", 50)
    print("Countdown starting...")
    for i in range(3, 0, -1):
        count_title.write(f"{i}", align="center", font=("Arial", 24, "bold"))
        time.sleep(1)
        count_title.clear()
    count_title.write("Go!", align="center", font=("Arial", 24, "bold"))
    time.sleep(1)
    count_title.clear()  # Clear the last message before starting the quiz
    print("Go!")  # Log to console
    quiz()  # Start the quiz right after displaying "Go!"
    
def quiz():
    # Define the quiz questions, options, and answers
    quiz_questions = [
        {
            "question": "Which type of crime is most committed in Chicago?",
            "options": ["A. Burglary", "B. Theft", "C. Assault", "D. Vandalism"],
            "answer": "B"
        },
        {
            "question": "What is considered the most popular sport in Chicago according to recent surveys?",
            "options": ["A. Football", "B. Basketball", "C. Baseball", "D. Hockey"],
            "answer": "C"
        },
        {
            "question": "According to public opinion surveys, which public park in Chicago is the most visited?",
            "options": ["A. Lincoln Park", "B. Grant Park", "C. Public Transit", "D. Millenium Park"],
            "answer": "D"
        },
        {
            "question": "What mode of transportation do most Chicagoans prefer for commuting, based on city transportation surveys?",
            "options": ["A. Car", "B. Bicycle", "C. Public Transit", "D. Walking"],
            "answer": "C"
        },
        {
            "question": "Which neighborhood is commonly perceived as the culinary hotspot of Chicago, as per local food surveys?",
            "options": ["A. West Loop", "B. River North", "C. Noise Pollution", "D. Waste Management"],
            "answer": "A"
        },
        {
            "question": "Based on environmental surveys, what is Chicago's biggest environmental concern?",
            "options": ["A. Water Pollution", "B. Air Pollution", "C. Wicker Park", "D. Lincoln Square"],
            "answer": "B"
        },
        {
            "question": "What is the most attended annual event in Chicago, according to event attendance records?",
            "options": ["A. Chicago Marathon", "B. The Taste of Chicago", "C. Lollapalooza", "D. Chicago Auto Show"],
            "answer": "B"
        },
        {
            "question": "Which Chicago museum is rated the highest in visitor satisfaction surveys?",
            "options": ["A. Museum of Science and Industry", "B. Field Museum", "C. The Art Institute of Chicago", "D. Chicago History Museum"],
            "answer": "C"
        },
        {
            "question": "What is the most commonly spoken language in Chicago after English, according to demographic surveys?",
            "options": ["A. Hindi", "B. Chinese", "C. Spanish", "D. Vietnamese"],
            "answer": "C"
        },
        {
            "question": f"Based on urban development surveys, what is Chicago's most \nrapidly growing neighborhood in terms of new construction and business openings?",
            "options": ["A. Lincoln Park", "B. Fulton Market", "C. Hyde Park", "D. Logan Square"],
            "answer": "B"
        }
    ]

    # Initialize the screen
    screen = Screen()
    screen.setup(width=1.0, height=1.0)
    screen.bgcolor('white')

    # Create turtles for the question, options, score, and timer
    question_turtle = Turtle()
    question_turtle.hideturtle()
    question_turtle.penup()
    question_turtle.goto(0, 250)
    question_turtle.color('black')

    option_turtles = []
    option_texts = []  # List to hold the text turtles
    option_colors = ['red', 'black', 'blue', 'green']
    for i in range(4):
        option_turtle = Turtle(shape='square')
        option_turtle.penup()
        option_turtle.shapesize(stretch_wid=5, stretch_len=20)  # Larger buttons
        option_turtle.color(option_colors[i])
        option_turtle.goto(0, 150 - i * 120)  # Adjust the position
        
        # Create a turtle for the option text
        text_turtle = Turtle()
        text_turtle.hideturtle()
        text_turtle.penup()
        text_turtle.goto(option_turtle.xcor(), option_turtle.ycor() - 20)
        text_turtle.color('white')  # White text color
        
        option_turtles.append(option_turtle)
        option_texts.append(text_turtle)  # Add to the list of text turtles

    score_turtle = Turtle()
    score_turtle.hideturtle()
    score_turtle.penup()
    score_turtle.goto(200, 330)
    score_turtle.color('black')

    timer_turtle = Turtle()
    timer_turtle.hideturtle()
    timer_turtle.penup()
    timer_turtle.goto(-200, 330)
    timer_turtle.color('purple')

    # Draw timer circle
    timer_circle = Turtle()
    timer_circle.hideturtle()
    timer_circle.penup()
    timer_circle.color('purple')
    timer_circle.goto(-200, 220)
    timer_circle.shape('circle')
    timer_circle.shapesize(stretch_wid=3, stretch_len=3)  # Adjust size as needed


    def draw_question(question_number, question, options):
        question_turtle.clear()
        for i, option_turtle in enumerate(option_turtles):
            option_turtle.showturtle()

            # Clear the old text and write the new one
            option_texts[i].clear()
            option_texts[i].write(quiz_questions[current_question_index[0]-1]['options'][i], align="center", font=("Arial", 14, "bold"))

        question_turtle.write(f"Question {question_number}: {question}", align="center", font=("Arial", 18, "normal"))

    def show_score(score):
        score_turtle.clear()
        score_turtle.write(f"Score: {score}/10", align="center", font=("Arial", 18, "normal"))

    def show_timer(time_left):
        timer_turtle.clear()
        timer_turtle.write(f"Time: {time_left}s", align="center", font=("Arial", 18, "normal"))

    def handle_option_click(x, y, answer, correct_answer, callback):
        if answer == correct_answer:
            score[0] += 1  # Increment score if answer is correct
        show_score(score[0])
        callback()  # Call the callback function to proceed to the next question
        # Redraw text immediately after handling click
        draw_current_options()

    def draw_current_options():
        for i in range(4):
            option_texts[i].clear()
            if current_question_index[0] < len(quiz_questions):  # Ensure index is within bounds
                option_texts[i].write(quiz_questions[current_question_index[0]]['options'][i], align="center", font=("Arial", 16, "bold"))

    current_question_index = 0

    def setup_question(question_info):
        current_question_index[0] += 1  # Increment question index
        correct_answer = question_info['answer']
        for i, option_turtle in enumerate(option_turtles):
            option_turtle.onclick(lambda x, y, a=chr(65+i), ca=correct_answer: handle_option_click(x, y, a, ca, next_question))
        draw_question(current_question_index[0], question_info['question'], question_info['options'])

    def next_question():
        if quiz_questions and current_question_index[0] < len(quiz_questions):
            question_info = quiz_questions[current_question_index[0]]
            setup_question(question_info)
        else:
            finish_quiz()

    def update_timer():
        if time_elapsed[0] < 100:
            time_elapsed[0] += 1
            show_timer(100 - time_elapsed[0])
            screen.ontimer(update_timer, 1000)
        else:
            finish_quiz()

    def finish_quiz():
        question_turtle.goto(0, 0)
        question_turtle.write("Quiz Over! Final Score: {}/10".format(score[0]), align="center", font=("Arial", 24, "bold"))
        for option_turtle in option_turtles:
            option_turtle.hideturtle()

    score = [0]
    time_elapsed = [0]  # Timer counter
    current_question_index = [0]  # Track current question number

    # Show initial score
    show_score(score[0])  # Initialize score display
    show_timer(100 - time_elapsed[0])

    if quiz_questions:
        next_question()  # Start the quiz
        update_timer()  # Start the timer

    screen.mainloop()




# Function to quit the game
def quit_game():
    print("Quitting game...")
    turtle.bye()
    sys.exit()

start_game()
turtle.mainloop()

此代码中唯一重要的部分是测验。

我再次尝试使用一些ChatGpt,但仍然没有成功。

python turtle-graphics python-turtle
1个回答
0
投票

查看我的答案这里.

它解决了您描述的问题以及您没有提到的问题...(单击答案并不可靠,因为文本遮盖了按钮)。

© www.soinside.com 2019 - 2024. All rights reserved.