Search code examples
pythonturtle-graphicspython-turtlepong

Using the turtle package, is it possible to create a function asking for an argument? (And then use it for the .onkeypress method)


I tried myself at making the Pong project using the turtle package on Python.

I know how to make the code work (using 4 different functions taking no arguments, for each paddle and directions), but my question is if and how can I do it with this idea.

Here's the code I'm attempting to make work :

def move_paddle_up(paddle):
        y = paddle.ycor()
        y += 20
        paddle.sety(y)
    
def move_paddle_down(paddle):
        y = paddle.ycor()
        y -= 20
        paddle.sety(y)

#Keyboard binding movement
screen.listen()
screen.onkeypress(move_paddle_up(left_pad), "w")
screen.onkeypress(move_paddle_down(left_pad), "s")
screen.onkeypress(move_paddle_up(right_pad), "Up")
screen.onkeypress(move_paddle_down(right_pad), "Down")

When the screen is launched, the paddles won't move if I press the associated keys.

With the way of using the 4 different functions, it works.

It's just that I am curious to know how I should call or define the arguments in such a function.


Solution

  • I see then that is it quite more work than just creating 4 functions.

    I think you got the wrong take home message. @BehdadAbdollahiMoghadam's use of functools.partial() is spot on, but we can fit it into your existing code with less overhead:

    from functools import partial
    
    # ...
    
    def move_paddle_up(paddle):
        paddle.sety(paddle.ycor() + 20)
    
    def move_paddle_down(paddle):
        paddle.sety(paddle.ycor() - 20)
    
    # Keyboard binding movement
    screen.onkeypress(partial(move_paddle_up, left_pad), "w")
    screen.onkeypress(partial(move_paddle_down, left_pad), "s")
    screen.onkeypress(partial(move_paddle_up, right_pad), "Up")
    screen.onkeypress(partial(move_paddle_down, right_pad), "Down")
    screen.listen()
    
    # ...