Using .goto() overwrites the location of previous objects in python turtle

Viewed 42
import turtle

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

class Paddle:
    paddle = turtle.Turtle()
    def __init__(self):
        self.paddle.speed(0)
        self.paddle.color("white")
        self.paddle.shape("square")
        self.paddle.shapesize(stretch_wid = 5, stretch_len= 1)
        self.paddle.penup()
    def goto(self,location):
        self.paddle.goto(location,0)   


paddleA = Paddle()
paddleB = Paddle()

paddleA.goto(350)

paddleB.goto(-350)
    
# Ball

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

# Movement Functions

# Game loop
while True:
    wn.update()

What I want this to display is two paddles on the left and right side of the screen. However, only one paddle is displayed in the screen created. This paddle would be the one last calling the function .goto(). Why is this happening? What is the correction for this behaviour?

1 Answers

You weren't creating a uniquely identifiable instance in your class, it was just reusing the same one that was already constructed.

class Paddle:
    paddle = turtle.Turtle()
    def __init__(self):
        print( id(self.paddle) )
        self.paddle.speed(0)
        self.paddle.color("white")
        self.paddle.shape("square")
        self.paddle.shapesize(stretch_wid = 5, stretch_len= 1)
        self.paddle.penup()
    def goto(self,location):
        self.paddle.goto(location,0)   
    def color(self,color):
        self.paddle.color(color) 

paddleA = Paddle()
paddleB = Paddle()

paddleA.color('red')
paddleB.color('blue')

paddleA.goto(350)
paddleB.goto(-350)
    
# Ball

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

3066489872
3066489872
3066490064

Put paddle construction within init block:

class Paddle:
    def __init__(self):
        self.paddle = turtle.Turtle()
        print( id(self.paddle) )
        self.paddle.speed(0)
        self.paddle.color("white")
        self.paddle.shape("square")
        self.paddle.shapesize(stretch_wid = 5, stretch_len= 1)
        self.paddle.penup()
    def goto(self,location):
        self.paddle.goto(location,0)   
    def color(self,color):
        self.paddle.color(color)

3065846920
3065847064
3065847184

Related