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

这似乎是太多的代码和太少的计划。具体问题:你创建 Bob 两次,每个函数一次——你看到的蓝色 Bob 不是你移动的 Bob;太多的数字——找出你的基本尺寸并从中计算出其他所有东西;您将中心提取到循环之外,因此它永远不会改变——在循环内部进行,这样它会随着 Bob 的移动而改变。

下面是您的代码的修改,它可以按预期上下弹跳 Bob:

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 回答