Is there a way to run a boolean if statement in Python Turtle?

Question:

I’m editing a Turtle Pong template and realized that two paddles can’t move at the same time, so I’m trying to fix that bug by having it so, when a key is pressed, a boolean is set to true, and that is referenced in an if statement to move up or down if True. However, whenever I try to create this system, the boolean will always stay as it is declared, so I start off declaring it as False and no matter how many times I set it to True using the key press, it gets set back to False. I am confused about this, because I tried placing a print below the declaration and that never ran at all, but this False declaration seems to keep running over and over again. I wonder if it’s because of the window.listen function, but then the print would theoretically run too. I’m just confused so any assistance would be greatly appreciated, thank you! Here’ the relevant code.


import turtle

wn = turtle.Screen()
wn.title('Pong')
wn.bgcolor('black')
WIDTH, HEIGHT = 800, 600
wn.setup(width=WIDTH, height=HEIGHT)
wn.tracer(0)

# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape('square')
paddle_a.color('white')
paddle_a.penup()
paddle_a.goto(-WIDTH/2, 0)
paddle_a.shapesize(5, 1)

#THIS here is the bit where I'm stuck
paddle_a_up = False
print(paddle_a_up)
  
def move_paddle_a_up():
  paddle_a_up = True
  print("I cant understand you")
  print(paddle_a_up)
  
def move_paddle_a_down():
  print(paddle_a_up)
  
wn.onkeypress(move_paddle_a_up, 'w')
wn.onkeypress(move_paddle_a_down, 's')
wn.listen()
  
if paddle_a_up == True:
  y = paddle_a.ycor()
  y += 20
  paddle_a.sety(y)

while True:
  wn.update()
Asked By: Whatshisface77

||

Answers:

The way to use a global variable in python is different than in other languages. To use the global variable inside a method, You must need to declare the variable as global inside the method otherwise python will consider it as a new local variable.

So, to use the global variable inside the method, you need to make these changes in your method move_paddle_a_up

def move_paddle_a_up():
  global paddle_a_up
  paddle_a_up = True
  print("I can understand you now")
  print(paddle_a_up)
Answered By: Hassan Nawaz