import turtle
wn = turtle.Screen()
wn.title('Pong game by @kahsengho')
wn.bgcolor('black')
wn.setup(width=800, height=600)
wn.tracer(0)
#Paddle a
paddle_a = turtle.Turtle() #This creates an object
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)
#Function for paddle a
def paddle_a_up() :
y = paddle_a.ycor()
y += 20
paddle_a.sety(y)
def paddle_a_down() :
y = paddle_a.ycor()
y -= 20
paddle_a.sety(y)
#Keyboard binding for paddle a
wn.listen()
wn.onkeypress(paddle_a_up, 'w')
wn.onkeypress(paddle_a_down, 's')
#Paddle b
paddle_b = turtle.Turtle() #This creates an object
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)
#Function for paddle b
def paddle_b_up() :
y = paddle_b.ycor()
y += 20
paddle_b.sety(y)
def paddle_b_down() :
y = paddle_b.ycor()
y -= 20
paddle_b.sety(y)
#Keyboard binding for paddle b
wn.listen()
wn.onkeypress(paddle_b_up, 'Up')
wn.onkeypress(paddle_b_down, 'Down')
#ball
ball = turtle.Turtle() #This creates an object
ball.speed(0)
ball.shape('square')
ball.color('white')
ball.penup()
ball.goto(0,0)
ball.dx = 2
ball.dy = 2
#Main game loop
while True :
wn.update()
#Move the ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
#Border checking
if ball.ycor() > 290 :
ball.sety(290)
ball.dy *= -1
if ball.ycor() < -290 :
ball.sety(-290)
ball.dy *= -1
if ball.xcor() > 390 :
ball.goto(0, 0)
ball.dx *= -1
if ball.ycor() < -390 :
ball.goto(0, 0)
ball.dx *= -1
Traceback (most recent call last):
File "/Users/kahsengho/PycharmProjects/Projects/Turtle module.py", line 73, in <module>
ball.setx(ball.xcor() + ball.dx)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/turtle.py", line 1808, in setx
self._goto(Vec2D(x, self._position[1]))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/turtle.py", line 3158, in _goto
screen._pointlist(self.currentLineItem),
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/turtle.py", line 755, in _pointlist
cl = self.cv.coords(item)
File "<string>", line 1, in coords
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 2761, in coords
self.tk.call((self._w, 'coords') + args))]
_tkinter.TclError: invalid command name ".!canvas"