I am creating a game, but when I press the Up or Down arrow keys, nothing happens. Instead of moving when I press those keys, the turtles have already moved when I run the code. Here is the code:
turtle_race.py:
from turtle import Screen
import elements
win = Screen()
win.setup(800, 600)
win.bgcolor("cyan")
win.title("Turtle Race")
win.tracer(0)
obj = elements.Objects()
win.onkeypress(obj.player_one_move(), "Up")
win.onkeypress(obj.player_two_move(), "Down")
win.listen()
while True:
win.update()
Here is elements.py:
from turtle import Turtle
class Objects:
def __init__(self):
self.player_one = Turtle("turtle")
self.player_one_init()
self.x1 = 0
self.x2 = 0
self.player_two = Turtle("turtle")
self.player_two_init()
def player_one_init(self):
self.x1 = -200
self.player_one.speed(5)
self.player_one.color("red")
self.player_one.penup()
self.player_one.setx(self.x1)
self.player_one.sety(150)
def player_two_init(self):
self.x2 = -200
self.player_two.speed(5)
self.player_two.color("green")
self.player_two.penup()
self.player_two.setx(self.x2)
self.player_two.sety(-150)
def player_one_move(self):
x = self.player_one.xcor() + 35
self.player_one.setx(x)
def player_two_move(self):
x = self.player_two.xcor() + 35
self.player_two.setx(x)