Making a Race game
- 라임 샹큼
- Mar 11
- 2 min read
This project was to enhance my understanding of OOP and the modules in python.
This project is done by adjusting the speeds of each object at random. Something I didn't totally get at first was how to adjust the speed. I thought I was to change the speed by changing the speed method. However, I just needed to set the amount the object goes forward by.
Also, I underestimated the capabilities of for loops. This will be further elaborated on later on.
from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width = 500, height = 400)
user_bet = screen.textinput(title = 'Make your bet', prompt= 'Which turtle do you think will win? Enter a color:')
colors = ['red', 'blue', 'yellow', 'purple','orange', 'black']
y_coordinates = [-150, -100, -50, 0, 50, 100]
is_game_on = False
turtles = []
for _ in range(6):
tim = Turtle(shape= 'turtle')
tim.color(colors[_])
tim.penup()
tim.goto(x=-230, y = y_coordinates[_])
turtles.append(tim)
if user_bet:
is_game_on = True
while is_game_on:
for _ in turtles:
distance = random.randint(1, 10)
_.forward(distance)
if _.xcor() >= 210:
winning_color = _.pencolor()
is_game_on = False
if winning_color.lower() == user_bet.lower():
print('You won')
else:
print('You lost')
The turtle module is something offered by python. It enables the user to draw and show things on the interface. This is quite the change as I have not been able to really show things on the interface.
In the part 'for _ in turtles' I initially wrote 6 independent turtles. This is time-consuming and ineffective. By using the for loop I could repeat the loop until I had 6 turtles, tweaking little elements so that each turtle's position differed.
Things learned
from filename import *
#this imports all classes from the file
from turtle import Turtle
tim= Turtle()
import turtle as t
tim = t.Turtle()
if try to install pack that isn't installed, can actually install by clicking on some shortkeys
if you use function as an argument, you don't have to add parentheses at the end.
def move():
tim.forward(10)
screen.onkey('space', move)
higher order functions : functions that can work with other functions
event listeners: waits for input of keys
screen.listen() - preset
screen.onkey(func, key)
setting a new heading in turtle:
tim= Turtle()
new_heading = tim.heading() + 10
tim.setheading(new_heading)
with classes, you can create multiple instances.
Kommentare