0

ウィンドウ内の立方体を上下に「バウンス」するプログラムを作成しようとしています。すべてが適切に作成されていますが、立方体は跳ねません。

コードは次のとおりです。

from graphics import *
import time # Used for slowing animation if needed
i=0

def create_win():
    win= GraphWin("Animation",500,500)
    cornerB1= Point(235,235)
    cornerB2= Point(265,265)
    Bob= Rectangle(cornerB1, cornerB2)
    Bob.setFill('blue')
    Bob.draw(win)
    win.getMouse()
    win.close()
create_win()

def main():
    cornerB1= Point(235,235)
    cornerB2= Point(265,265)
    Bob= Rectangle(cornerB1, cornerB2)
    center= Rectangle.getCenter(Bob)
    center_point= Point.getX(center)
    for i in range(500):
        Bob.move(0,5)
        if center_point<15:
            dy= -dy
        elif center_point>485:
            dy= -dy

main()

任意の入力をいただければ幸いです。

4

1 に答える 1

0

これは、計画が少なすぎるコードが多すぎるようです。特定の問題: 各関数で 1 回ずつ、2 回ボブを作成します。表示される青いボブは、移動しているボブではありません。数字が多すぎます -- 基本次元を把握し、そこから他のすべてを計算します。ループの外側の中心を抽出して、変化しないようにします。ループの内側で抽出して、ボブが動くと変化するようにします。

以下は、意図したとおりにボブを上下にバウンスするコードのリワークです。

from graphics import *

WIDTH, HEIGHT = 500, 500

BOB_SIZE = 30
BOB_DISTANCE = 5

def main():
    win = GraphWin("Animation", WIDTH, HEIGHT)

    # Create Bob in the middle of the window
    cornerB1 = Point(WIDTH/2 + BOB_SIZE/2, HEIGHT/2 + BOB_SIZE/2)
    cornerB2 = Point(WIDTH/2 - BOB_SIZE/2, HEIGHT/2 - BOB_SIZE/2)

    Bob = Rectangle(cornerB1, cornerB2)
    Bob.setFill('blue')
    Bob.draw(win)

    dy = BOB_DISTANCE

    for _ in range(500):
        Bob.move(0, dy)

        center = Rectangle.getCenter(Bob)
        centerY = Point.getY(center)

        # If too close to edge, reverse direction
        if centerY < BOB_SIZE/2 or centerY > HEIGHT - BOB_SIZE/2:
            dy = -dy

    win.close()

main()
于 2017-01-05T05:33:42.897 に答える