简体   繁体   中英

Simulation using python and graphics.py image

I am trying to create a simulator. ( referring to John Zelle's graphics.py ) Basically, my object will make use of graphics.py to display the object as a circle. Then, using the .move method in the class in graphics.py , the object will move in the x direction and y direction. If the object is currently drawn, the circle is adjusted to the new position.

Moving just one object can easily be done with the following codes:

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()

However, I want the program to display multiple circles at once that moves at different speed. I've created a Circle object class which takes speed as an input, and a list with 3 Circle objects in it

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

In summary, my question is, how do make use of this list such that I am able to display and move multiple circles in one window at once using the methods available in graphics.py ?

That all depends on how you create your Car class, but nothing stops you from using the same code to move multiple circles in the same refresh cycle, eg:

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()

Of course, if you're already going to use classes, you might as well implement move() in it so your Car instances can remember their speed and then just apply it when you call move() on them in a loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM