python - 如何创建同一类的多个对象,每个对象内部都有无限循环

标签 python turtle-graphics

我尝试使用 onkey(spawn, "space") 生成球,结果没问题。但如何使用 for 循环生成它们呢? 看来类方法内部的“while True”循环不允许在外部进行“for 循环”的迭代。

from turtle import *
from random import randint

w = 100
h = 100
BallList = []

sc = Screen()
sc.tracer(0)

class Ball(Turtle):
  def __init__(self, x, y, s, c):
    Turtle.__init__(self)
    self.x = x
    self.y = y
    self.s = s
    self.c = c
    self.color(self.c)
    self.shape("circle")
    self.penup()
    self.speed(0)
    self.setheading(self.towards(randint(-100, 100), randint(-100, 100)))

  def move(self):
    self.forward(self.s)

  def bounce(self):
    if self.xcor() > w:
      self.setheading(self.towards(-w, randint(-100, 100)))
    if self.xcor() < -w:
      self.setheading(self.towards(w, randint(-100, 100)))
    if self.ycor() > h:
      self.setheading(self.towards(randint(-100, 100), -h))
    if self.ycor() < -h:
      self.setheading(self.towards(randint(-100, 100), h))

  def loop(self):
    while True:
      self.move()
      self.bounce()
      sc.update()

for i in range(10):
  BallList.append(Ball(0, 0, 10, (0, 100, 0)))
  BallList[i].loop()

最佳答案

  1. 删除 Ball 类的 loop 方法中的无限循环,使其看起来像这样:
  def loop(self):
    self.move()
    self.bounce()
    sc.update()
  • 先创建你的球,暂时不要尝试处理它们:
  • for i in range(10):
      BallList.append(Ball(0, 0, 10, (0, 100, 0)))
    
  • 通过无限循环来更新球:
  • while True:
      for i in range(10):
        BallList[i].loop()
    
    <小时/>
    • 我认为将 Ball 类的 loop 方法重命名为 update 之类的方法是有意义的,因为它不再循环任何东西
    • BallList 不是一个类,我认为将其重命名为 balls 更有意义(注意小写字母,以免与类混淆)

    编辑: 我认为在 Ball-s loop 方法中调用 sc.update() 可能是多余的。在重新计算所有球之后,调用 sc.update() 一次可能就足够了,如下所示:

    while True:
      for i in range(10):
        BallList[i].loop()
      sc.update()
    

    关于python - 如何创建同一类的多个对象,每个对象内部都有无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58606686/

    相关文章:

    python - 将 Matplotlib 饼图百分比标签覆盖为总和不等于 100% 的特定值

    python - Turtle 中是否有一个原生函数可以调整图像大小以适应窗口?

    python - 使用递归绘制嵌套三角形

    python - E1101 :Module 'turtle' has no 'forward' member

    python - 是否可以部署使用 Python 3.4 和 Fabric 的应用程序?

    python - Paramiko PKey.from_private_key_file 给我 "__init__() got an unexpected keyword argument ' 文件名'”

    python - 从 multiprocessing.Process 继承的 Python 类的设置值问题

    python - 如何在 Python 中创建返回此列表的所有组合的函数?

    python - 如何在 Python 3 中使用 Turtle 绘制圆

    python - python 中的缩放功能? (2.7.9)