Search code examples
pythonturtle-graphicspython-turtlepong

This isn't changing the position of the paddles in Pong


this is the Code I wrote; Not sure what I did wrong here. When you press W and S the left paddle should go Up and down, and a and d should work for the other paddle. I'm currently just following a tutorial online, and I've already hit a wall. I just can't for the life of me see what's wrong with this; unless if python doesn't allow variables to be put into the function like this

import turtle

#window set up
wn = turtle.Screen()
wn.title = ("Main Test")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer = 0

#paddleA

paddleA = turtle.Turtle()
paddleA.speed(0)
paddleA.shape("square")
paddleA.color("white")
paddleA.shapesize(stretch_wid=5, stretch_len= 1)
paddleA.penup()
paddleA.goto(-350,0)

#paddleB

paddleB = turtle.Turtle()
paddleB.speed(0)
paddleB.shape("square")
paddleB.color("white")
paddleB.shapesize(stretch_wid=5, stretch_len= 1)
paddleB.penup()
paddleB.goto(350,0)

#ball

ball = turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0,0)

#function
def paddle(paddle, dir):
    y = paddle.ycor()
    y += 20 * dir
    paddle.sety(y)

#Keyboard Binding

wn.listen()
wn.onkeypress(paddle(paddleA, 1), "w")
wn.onkeypress(paddle(paddleA, -1), "s")
wn.onkeypress(paddle(paddleB, 1), "a")
wn.onkeypress(paddle(paddleB, -1), "d")

#Main Game Loop
while True:
    wn.update()

Solution

  • onkeypress requires:

    a function with no arguments or None

    as the first parameter. You are effectively passing None as that's what a function call evaluates to. You can see that for yourself by executing:

    print(type(paddle(paddleA, 1)))
    

    A function call is not a function!


    One way to get around this is to wrap your function call into an anonymous function using lambda, like so:

    wn.listen()
    wn.onkeypress(lambda: paddle(paddleA, 1), "w")
    wn.onkeypress(lambda: paddle(paddleA, -1), "s")
    wn.onkeypress(lambda: paddle(paddleB, 1), "a")
    wn.onkeypress(lambda: paddle(paddleB, -1), "d")