Python pong invalid name ".!canvas" - the ball doesnt update coords

30 Views Asked by At

Starting on a simple python lesson. Already blocked somehow by updating the x and y coords in the while loop. It gets better if i move wn.update() to the end of the def, however its still no good. Im new to python so cant spot what im missing. All the paddles move correctly. It must be something to do with the dx dy mathods. It does mention and issue with passing self.

Traceback (most recent call last):
  File "c:\Users\tom_b\Documents\code\python\games\pong.py", line 77, in <module>
    ball.sety(ball.ycor() + ball.dy)
  File "C:\Users\tom_b\pyver\py311\Lib\turtle.py", line 1827, in sety
    self._goto(Vec2D(self._position[0], y))
  File "C:\Users\tom_b\pyver\py311\Lib\turtle.py", line 3175, in _goto
    screen._pointlist(self.currentLineItem),
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\tom_b\pyver\py311\Lib\turtle.py", line 754, in _pointlist
    cl = self.cv.coords(item)
         ^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 1, in coords
  File "C:\Users\tom_b\pyver\py311\Lib\tkinter\__init__.py", line 2822, in coords
    self.tk.call((self._w, 'coords') + args))]
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_tkinter.TclError: invalid command name ".!canvas"

Line 77 is ball.sety(ball.ycor() + ball.dy)

import turtle 

# Set up game screen
wn = turtle.Screen()
wn.title("Pong by Tom")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)

# Paddle a
# Make a turtle object
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350, 0)

# Paddle b
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.penup()
paddle_b.goto(+350, 0)

# Ball
ball = turtle.Turtle()
ball.speed()
ball.shape("square")
ball.color("white")
ball.penup()
ball.goto(0, 0)
# delta change = dx
ball.dx = 2
ball.dy = 2

# Functions
## Paddle A Up
def paddle_a_up():
    y = paddle_a.ycor()
    y += 20
    paddle_a.sety(y)
    
## Paddle A Down
def paddle_a_down():
    y = paddle_a.ycor()
    y -= 20
    paddle_a.sety(y)
    
## Paddle B Up
def paddle_b_up():
    y = paddle_b.ycor()
    y += 20
    paddle_b.sety(y)
    
## Paddle B Down
def paddle_b_down():
    y = paddle_b.ycor()
    y -= 20
    paddle_b.sety(y)


## Keyborad binding
wn.listen()
wn.onkeypress(paddle_a_up, "w")
wn.onkeypress(paddle_a_down, "s")
wn.onkeypress(paddle_b_up, "Up")
wn.onkeypress(paddle_b_down, "Down")


# Main game loop
while True:
    wn.update()
    ball.sety(ball.ycor() + ball.dy)
    ball.setx(ball.xcor() + ball.dx)

adding more update window code and moving it around. Added an init (self) function to the coords and broke everything

0

There are 0 best solutions below