السلام عليكم، انا الحمد لله حليت اخر تحدي في وحدة رهان سباق السلاحف، لكني استخدم طريقة الObject Oriented Programming من الوحدة اللي قبليها في المستوى الثاني
from turtle import Turtle, Screen
from random import choice
#Global Variables
turtle_speeds = [10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
turtles_status = {"red": False, "green": False, "blue": False}
race_finished = False
race_deadline = 300
user_choice = ""
text_brush = Turtle()
text_brush.hideturtle()
#Initalize screen
window = Screen()
window.title("Turtle Race")
#Race Turtle Class
class RaceTurtle:
def __init__(self, color):
# Initalized Object Attributes
self.python_turtle = Turtle()
self.color = color
self.reached_deadline = False
# Initialize the turtle properties
self.python_turtle.shape("turtle")
self.python_turtle.color(self.color)
self.python_turtle.penup()
def goto_start_position(self, yaxis_position):
self.python_turtle.goto(-320, yaxis_position)
self.python_turtle.speed("slowest")
def start_race(self):
if self.python_turtle.xcor() >= race_deadline:
finish_race(self.color)
self.reached_deadline = True
else:
self.python_turtle.forward(choice(turtle_speeds))
def start_game():
#Variables
user_choice = ""
# Initalize Turtles
turtles = [RaceTurtle("red"), RaceTurtle("green"), RaceTurtle("blue")]
for turtle in turtles:
turtle_enabled(turtle, False)
#Check User Choice
while user_choice not in turtles_status:
user_choice = window.textinput(title="Turtle Race", prompt="Choose a winner:\nWhat do you expect to win ? (Red/Green/Blue)").lower()
#Put each turtle in the right place
yaxis_position = 250
for turtle in turtles:
turtle_enabled(turtle, True)
turtle.goto_start_position(yaxis_position)
yaxis_position -= 250
#Start race
race_finished = False
while not race_finished:
for turtle in turtles:
turtle.start_race()
if turtle.reached_deadline:
race_finished = True
break
#Dispaly the status screen depending on the user expectation
if turtles_status[user_choice] == True:
winner_screen()
else:
loser_screen()
#True if you want to show the turtle, otherwise it's False to be hidden
def turtle_enabled(turtle, enabled):
turtle.python_turtle.hideturtle() if not enabled else turtle.python_turtle.showturtle()
def finish_race(turtle_color):
turtles_status[turtle_color] = True
def winner_screen():
window.bgcolor("lime")
text_brush.write("You Won !", font=("arial", 25, "bold"), align="center")
def loser_screen():
window.bgcolor("pink")
text_brush.write("You Losed !", font=("arial", 25, "bold"), align="center")
#Start Game
start_game()
#Exit program
window.exitonclick()