Graphics.py Bouncing Cube

时间:2016-07-11 22:35:15

标签: python zelle-graphics

I am trying to create a program that "bounces" a cube in a window up and down. Everything is created properly but the cube will not bounce.

The code is as follows:

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

Any input would be greatly appreciated.

1 个答案:

答案 0 :(得分: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()
相关问题