同时更新对象

时间:2013-11-19 07:07:34

标签: python class oop object

我必须在python中创建一个程序,我必须使用类在屏幕上弹出三十个球。我创建了一个名为“Ball”的类,我正在尝试创建一个Ball列表并立即更新所有对象,这样我就可以让所有的球同时移动。

from graphics import *
from random import *
from time import sleep

class Ball:

    def __init__(self, win):
        self.centerX, self.centerY = randrange(720), randrange(720)
        radius = randrange(5, 25)
        self.ball = Circle(Point(self.centerX, self.centerY), radius)
        colour = (randint(0,255), randint(0,255), randint(0,255))
        self.ball.setFill('cyan')
        self.ball.draw(win)


    def update(self):

        dx = 1
        dy = 1
        Point1 = 37
        Point2 = 22
        for j in range(1000):
            x = self.ball.getCenter()
            y = x.getX()
            z = x.getY()
            if y>= 720:
                Point1 *= (-1 * dx)
            if y<= 0:
                Point1 *= (-1 * dx)
            if z>= 720:
                Point2 *= (-1 * dy)
            if z<= 0:
                Point2 *= (-1 * dy)
            self.ball.move(Point1, Point2)
            print(y,z)
            sleep(0.05)


def main():
    win = GraphWin("Bouncy Many!", 720,720)
    for i in range(30):
        i = Ball(win)
        ballList.append(i)
        ballList.update()
main()

1 个答案:

答案 0 :(得分:1)

而不是运行self.ball.move 1000次INSIDE函数更新;你可以从外面拨打1000次这个功能。问题是:每次调用函数update都会循环1000次;并且你在运行时无法更新其他球。我的建议是编写一个外部函数,循环在balllist上更新每一个球。然后它睡觉(0.05)并再次做1000次:

class Ball:

    def __init__(self, win):
        self.centerX, self.centerY = randrange(720), randrange(720)
        radius = randrange(5, 25)
        self.ball = Circle(Point(self.centerX, self.centerY), radius)
        colour = (randint(0,255), randint(0,255), randint(0,255))
        self.ball.setFill('cyan')
        self.ball.draw(win)

        #I put Point1 and Point2 here so that they will not reset to
        #37, 22 every time you call update()
        self.Point1 = 37
        self.Point2 = 22

    def update(self):

        #Also, if you never plan to change dx, dy, you should declare them
        #inside the __init__ method as self.dx and self.dy, because they are not
        #local variables of update()
        dx = 1 
        dy = 1
        x = self.ball.getCenter()
        y = x.getX()
        z = x.getY()
        if y>= 720:
            self.Point1 *= (-1 * dx)
        if y<= 0:
            self.Point1 *= (-1 * dx)
        if z>= 720:
            self.Point2 *= (-1 * dy)
        if z<= 0:
            self.Point2 *= (-1 * dy)
        self.ball.move(self.Point1, self.Point2)
        print(y,z)

def moveAll(n):
#This updates all the balls, then sleeps(0.05)
#and does it again n times
    for i in range(n):
        for ball in ballList:
            ball.update()
        sleep(0.05)


def main():
    win = GraphWin("Bouncy Many!", 720,720)
    for i in range(30):
        i = Ball(win)
        ballList.append(i)
    moveAll(1000)


main()