"""pymunk物理引擎基本例子 """ import turtle import pymunk import pymunk.util from pymunk import Vec2d import math, sys, random def main(): space = pymunk.Space() space.gravity = (0.0, -900.0) ## Balls balls = [] balls_for_render = [] ticks_to_next_ball = 10 for x in range(5008880): ticks_to_next_ball -= 1 if ticks_to_next_ball <= 0: ticks_to_next_ball = 10000 mass = 10 radius = 25 inertia = pymunk.moment_for_circle(mass, 0, radius, (0,0)) body = pymunk.Body(mass, inertia) x = random.randint(-200,200) body.position = x, 400 shape = pymunk.Circle(body, radius, Vec2d(0,0)) space.add(body, shape) balls.append(shape) # 以下代码是lixingqiu加的 b = turtle.Turtle(visible=False,shape='circle') b.penup() b.shapesize(radius/10,radius/10) # 海龟画图中小球默认半径为10 b.goto(x, 400) b.showturtle() balls_for_render.append(b) balls_to_remove = [] for i in range(len(balls)): ball = balls[i] if ball.body.position.y < 0: balls_to_remove.append(i)# 加到待移除列表 b = balls_for_render[i] b.goto(ball.body.position) for i in balls_to_remove: space.remove(balls[i], balls[i].body) balls.pop(i) balls_for_render.pop(i) if len(balls) >= 1: v = balls[0].body.position print("(in on_draw): point = %.2f, %.2f" % (v.x,v.y)) ### Update physics for x in range(1): space.step(1/50.0) if __name__ == '__main__': width,height = 600,600 screen = turtle.Screen() screen.delay(0) screen.setup(width,height) screen.title("pymunk物理引擎基本例子") sys.exit(main())