簡體   English   中英

使用python和graphics.py image進行仿真

[英]Simulation using python and graphics.py image

我正在嘗試創建一個模擬器。 參考John Zelle的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提供的方法在一個窗口中一次顯示和移動多個圓?

所有這些都取決於您如何創建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()時才應用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM