I have created two turtles say 'tur1' and 'tur2' in python using turtle module. I have created event listener on the screen. I have created a function 'move_fwd(turte_name)' which moves the turtle forward by 20 steps.
I want that if key 'w' is pressed then this method shoud be called by 'tur1' and tur1 should move and if key 'i' is pressed then this function should be called by 'tur2' turtle and it should move.
I dont know how to pass argument 'turtle_name' while this method is called by event_listener.
from turtle import Turtle, Screen
screen = Screen()
tur1 = Turtle()
tur1.shape("turtle")
tur1.shape("turtle")
tur1.penup()
tur1.setposition(x=-200, y=-100)
tur2 = Turtle()
tur2.shape("turtle")
tur2.penup()
tur2.setposition(x=200, y=100)
def move_fwd(turtle_name):
turtle_name.forward(20)
screen.listen()
screen.onkey(move_fwd, "w") # how to tell that this is to be called for tur1
screen.onkey(move_fwd, "i") # how to tell that this is to be called for tur2
screen.exitonclick()
I have some idea how to do this in javascript by adding addEventListener ..
document.addEventListener("keypress", function(event) {
makeSound(event.key);
buttonAnimation(event.key);
});
function makeSound(key) {
switch (key) {
case "w":
var tom1 = new Audio("sounds/tom-1.mp3");
tom1.play();
break;
case "a":
var tom2 = new Audio("sounds/tom-2.mp3");
tom2.play();
break;
case "s":
var tom3 = new Audio('sounds/tom-3.mp3');
tom3.play();
break;
But no idea about how to do in python.
Thanks for your valuable time.
Use a lambda
screen.onkey(lambda: move_fwd(tur1), "w")
screen.onkey(lambda: move_fwd(tur2), "i")