在屏幕周围弹出30个球

时间:2015-11-16 20:47:10

标签: python class

我的任务是在创建的窗口上显示30个弹跳球。我只是开始学习课程,而且我似乎无法找到如何显示30个球反弹的循环。我能够从四面墙上弹出一个球。

#! /usr/bin/env python3

# Dorthy Petrick
# Display 30 bouncing balls bouncing around the screen

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

class Ball:
    def __init__(self):
        self.dx = 1
        self.dy = 1

    def draw(self, win):
        self.ball = Circle(Point(25, 60), 3)
        self.ball.setFill('blue')
        self.ball.draw(win)

    def move(self):
        self.ball.move(self.dx,self.dy)

        xValue = self.ball.getCenter().getX()
        yValue = self.ball.getCenter().getY()

        if 550 < xValue:
            self.dx = -self.dx

        if -xValue > xValue:
            self.dx = -self.dx

        if 500 < yValue:
            self.dy = -self.dy

        if -yValue > yValue:
            self.dy = -self.dy

def main():
    win = GraphWin("bouncy.py", 550, 500)
    ball = Ball()
    ball.draw(win)
    counters = []

    while True:
        for i in range(30):
            ball.move()
            counter = Counter()
            counter.setCounterId(i + 1)
            balls.append(ball)



    win.getMouse()
    win.close()

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:2)

考虑到你的球类是好的:

  

编辑以修复您的Ball类:

import random
class Ball:
    def __init__(self):
        self.dx = 1
        self.dy = 1
        self.ball = Circle(Point(random.randint(0, 550), random.randint(0, 500)), 3) # use random to randomly display the balls
        self.ball.setFill('blue')

    def draw(self, win):
        self.ball.draw(win)

    def move(self):
        self.ball.move(self.dx,self.dy)
        #sleep(0.005) #not needed...

        xValue = self.ball.getCenter().getX()
        yValue = self.ball.getCenter().getY()

        if 550 < xValue:
            self.dx = -self.dx

        if -xValue > xValue:
            self.dx = -self.dx

        if 500 < yValue:
            self.dy = -self.dy

    if -yValue > yValue:
        self.dy = -self.dy

def main():
    win = GraphWin("bouncy.py", 550, 500)
    ball_lst = [Ball() for i in range(30)] #Initialize 30 balls
    for ball in ball_lst:
        ball.draw(win)
    while True:
        for ball in ball_lst: # for each ball in our balls list
            ball.move() #move the ball
    win.getMouse()
    win.close()

这应该可以胜任。