问题描述
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()
我想要显示的是屏幕左侧和右侧的两个桨。但是,在创建的屏幕中只显示一个桨。此桨将是最后调用函数 .goto()
的桨。为什么会这样?这种行为的纠正措施是什么?
解决方法
您没有在类中创建一个唯一可识别的实例,它只是重用了已经构建的同一个实例。
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
在 init 块中放置 paddle 构造:
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,color):
self.paddle.color(color)
3065846920
3065847064
3065847184