【发布时间】:2015-11-17 05:59:00
【问题描述】:
我的任务是在创建的窗口上显示 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()
【问题讨论】:
-
您每次都将相同的
ball附加到balls。每次执行 for 循环时,您都需要启动一个新的Ball()对象。 -
在代码审查方面: - 尽量不要硬编码像屏幕宽度这样的值(将它们作为参数传递或将它们声明为全局变量)。 - 不惜一切代价避免
from X import *,你的主要功能有点没用(除了C相似性之外没有其他原因改变声明) - 你的sleep(0.05)在ball.move()之后会出现问题(移动的球越多睡眠时间!),考虑在主事件循环中移动它。玩得开心:) -
另外,
Counter.__init__中的缩进问题。考虑在 CodeReview 网站上发布成功的代码 =) -
我不确定
Counter是干什么用的! :P -
那个也是。我刚刚还意识到不管
ball.x,你的绘图函数都会在同一个地方绘制:(25, 60)