I’m coding a quiz based Turtle Python based on Chicago related questions. I have an issue with the answers and questions sequence, the thing is when pressings at the answer option next answer options collection for the following question gets skipped and the quiz gets all wrong. I hope that somebody could help me with this problem as I am new to coding and not very adapted.
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()
The only part that matters in this code, is the quiz.
Again I have tried to use some ChatGpt but still there no success.
Imran Jabiyev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.