使用python和graphics.py图像进行模拟

时间:2017-06-20 14:04:10

标签: python

我正在尝试创建一个模拟器。 (referring to John Zelle's graphics.py) 基本上,我的对象将使用graphics.py将对象显示为圆形。然后,使用.move中类中的graphics.py方法,对象将沿x方向和y方向移动。如果当前正在绘制对象,则将圆圈调整到新位置。

使用以下代码可以轻松移动一个对象:

win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
    for i in range(40):       
      c.move(30, 0) #speed=30
      time.sleep(1)
win.close()

但是,我希望程序一次显示多个以不同速度移动的圆圈。我创建了一个Circle对象类,它将速度作为输入,并在其中包含3个Circle对象的列表

circle = []
circle1 = Car(40)
circle2= Car(50)
circle3 = Car(60)

总之,我的问题是,如何使用此列表,以便我能够使用graphics.py中提供的方法一次在一个窗口中显示和移动多个圈子?

1 个答案:

答案 0 :(得分:1)

这一切都取决于你如何创建Car类,但没有什么能阻止你使用相同的代码在同一个刷新周期中移动多个圆圈,例如:

win = GraphWin("My Circle", 1024, 400)

speeds = [40, 50, 60]  # we'll create a circle for each 'speed'
circles = []  # hold our circles
for speed in speeds:
    c = Circle(Point(50, speed), 10)  # use speed as y position, too
    c.draw(win)  # add it to the window
    circles.append((c, speed))  # add it to our circle list as (circle, speed) pair

for i in range(40):  # main animation loop
    for circle in circles:  # loop through the circles list
        circle[0].move(circle[1], 0)  # move the circle on the x axis by the defined speed
    time.sleep(1)  # wait a second...

win.close()

当然,如果您已经开始使用课程,那么您也可以在其中实施move(),以便Car个实例能够记住他们的speed,然后只需应用它你可以循环调用move()

相关问题