Exemplo n.º 1
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.prog = self.ctx.program(
            vertex_shader='''
                #version 330

                uniform vec4 Camera;

                // Per vertex
                in vec2 in_vert;
                in vec2 in_texture;

                // Per instance
                in vec3 in_pos;
                in vec2 in_size;
                in vec4 in_tint;

                out vec2 v_vert;
                out vec2 v_texture;
                out vec4 v_tint;

                void main() {
                    mat2 rotate = mat2(
                        cos(in_pos.z), sin(in_pos.z),
                        -sin(in_pos.z), cos(in_pos.z)
                    );
                    v_vert = rotate * (in_vert * in_size) + in_pos.xy;
                    gl_Position = vec4((v_vert - Camera.xy) / Camera.zw, 0.0, 1.0);
                    v_texture = in_texture;
                    v_tint = in_tint;
                }
            ''',
            fragment_shader='''
                #version 330

                uniform sampler2D Texture;

                in vec2 v_vert;
                in vec2 v_texture;
                in vec4 v_tint;

                out vec4 f_color;

                void main() {
                    vec4 tex = texture(Texture, v_texture);
                    vec3 color = tex.rgb * (1.0 - v_tint.a) + v_tint.rgb * v_tint.a;
                    f_color = vec4(color, tex.a);
            }
            ''',
        )

        self.tex1 = self.load_texture_2d('crate.png')
        self.tex1.use(0)

        self.tex2 = self.load_texture_2d('ball.png')
        self.tex2.use(1)

        vertices = np.array([
            -1.0,
            -1.0,
            0.0,
            0.0,
            -1.0,
            1.0,
            0.0,
            1.0,
            1.0,
            -1.0,
            1.0,
            0.0,
            1.0,
            1.0,
            1.0,
            1.0,
        ])

        vbo1 = self.ctx.buffer(vertices.astype('f4'))

        self.vbo2 = self.ctx.buffer(reserve=1024 * 1024)

        vao_content = [
            (vbo1, '2f 2f', 'in_vert', 'in_texture'),
            (self.vbo2, '3f 2f 4f/i', 'in_pos', 'in_size', 'in_tint'),
        ]

        self.vao = self.ctx.vertex_array(self.prog, vao_content)

        self.space = pymunk.Space()
        self.space.gravity = (0.0, -900.0)

        shape = pymunk.Segment(self.space.static_body, (5, 100), (595, 100),
                               1.0)
        shape.friction = 1.0
        self.space.add(shape)

        self.bodies = []
        self.balls = []

        for x in range(5):
            for y in range(10):
                size = 20
                mass = 10.0
                moment = pymunk.moment_for_box(mass, (size, size))
                body = pymunk.Body(mass, moment)
                body.position = Vec2d(300 + x * 50, 105 + y * (size + 0.1))
                shape = pymunk.Poly.create_box(body, (size, size))
                shape.friction = 0.3
                self.space.add(body, shape)
                self.bodies.append(body)
Exemplo n.º 2
0
def main():
    pygame.init()
    pygame.display.set_caption("Damped Rotary Spring Pointer")
    screen = pygame.display.set_mode((600, 600))
    clock = pygame.time.Clock()
    running = True

    ### Physics stuff
    space = pymunk.Space()
    draw_options = pymunk.pygame_util.DrawOptions(screen)

    pointer_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)

    ps = [(80, 0), (0, 20), (0, -20)]
    moment = pymunk.moment_for_poly(1, ps)
    gun_body = pymunk.Body(1, moment)
    gun_body.position = 300, 300
    gun_shape = pymunk.Poly(gun_body, ps)

    rest_angle = 0
    stiffness = 125000.
    damping = 6000.

    rotary_spring = pymunk.constraint.DampedRotarySpring(
        pointer_body, gun_body, rest_angle, stiffness, damping)

    space.add(gun_body, gun_shape, rotary_spring)

    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                running = False
            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, "damped_rotary_sprint_pointer.png")
            elif event.type == pygame.MOUSEMOTION:
                mouse_pos = pymunk.pygame_util.get_mouse_pos(screen)
                pointer_body.position = mouse_pos
                pointer_body.angle = (pointer_body.position -
                                      gun_body.position).angle

            # to easily find good values for the damped rortary spring
            # as with most simulations done with pymunk, the imporant thing
            # is that it looks good, not the exact parameters
            elif event.type == KEYDOWN and event.key == K_q:
                rotary_spring.stiffness *= .5
                print(rotary_spring.stiffness, rotary_spring.damping)
            elif event.type == KEYDOWN and event.key == K_w:
                rotary_spring.stiffness *= 2
                print(rotary_spring.stiffness, rotary_spring.damping)
            elif event.type == KEYDOWN and event.key == K_a:
                rotary_spring.damping *= .5
                print(rotary_spring.stiffness, rotary_spring.damping)
            elif event.type == KEYDOWN and event.key == K_s:
                rotary_spring.damping *= 2
                print(rotary_spring.stiffness, rotary_spring.damping)

        ### Clear screen
        screen.fill(THECOLORS["white"])

        ### Draw stuff
        space.debug_draw(draw_options)

        ### Update physics
        dt = 1.0 / 60.0
        for x in range(1):
            space.step(dt)

        ### Flip screen
        pygame.display.flip()
        clock.tick(50)
Exemplo n.º 3
0
    point_1 = body.position + line.a.rotated(body.angle)
    point_2 = body.position + line.b.rotated(body.angle)
    return to_pygame(point_1), to_pygame(point_2)


###options####
screen_x = 600
screen_y = 400
num_balls = 10

pygame.init()
screen = pygame.display.set_mode((screen_x, screen_y))
clock = pygame.time.Clock()
running = True

space = pymunk.Space()
space.gravity = (0.0, -200.0)

#create the base segment
base = pymunk.Segment(pymunk.Body(), (0, 50), (screen_x, 0), 0)
base.elasticity = 0.90
space.add(base)

#create the spinner
spinner_points = [(0, 0), (100, -50), (-100, -50)]
spinner_body = pymunk.Body(100000, 100000)
spinner_body.position = 300, 200
spinner_shape = pymunk.Poly(spinner_body, spinner_points)
spinner_shape.elasticity = 0.5
spinner_joint_body = pymunk.Body()
spinner_joint_body.position = spinner_body.position
def main():
    sys.setrecursionlimit(10000)

    width, height = 690,600

    ### PyGame init
    pygame.init()
    screen = pygame.display.set_mode((width,height)) 
    clock = pygame.time.Clock()
    running = True
    font = pygame.font.SysFont("Arial", 16)
    
    ### Physics stuff
    space = pymunk.Space()   
    draw_options = pymunk.pygame_util.DrawOptions(screen)

    env_xml = EnvironmentXml("/home/dseredyn/ws_stero/src/multilevel_planning/data/environments/env_push.xml")
    models = env_xml.getModels()

    for model in models:
        model.addToSpace(space)

    damped_objects_list = []
    for model in models:
        if not model.damping is None:
            damped_objects_list.append( (model.body, model.damping[0], model.damping[1]) )

#    cab = ModelCabinet(200, 100, Vec2d(200,200), -0.05)
#    cab.addToSpace(space)

#    box = ModelBox(50, 10, Vec2d(200,200), 0*math.pi/4.0)
#    box.addToSpace( space )

#    damped_objects_list.append( (box.body, 300.0, 3000.0) )

    # robot
#    rob = ModelRobot( Vec2d(100,100), 0.0 )
#    rob = ModelRobot( Vec2d(220,225), 0.0 )
#    rob.addToSpace(space)
    for ob in models:
        if ob.name == "robot":
            rob = ob
        if ob.name == "box":
            box = ob

    control_mode = "target_pos"
    position_control = ManualPositionControl(1000.0, 500.0, 50000.0, 50000.0)

    control_mode = "auto"

    dest_point = Vec2d(550,270)

#    info_exp_motion = InformationExpectedMotion()
#    info_exp_motion.anchor = "instance_box"
#    info_exp_motion.target_point = Vec2d(500,500)

    move_command = InformationMoveObjectCommand("box", Vec2d(500,500))
    # provide information
    information = [
        #InformationSpatialMapRange( (0, width), 100, (0, height), 100 ),        # range and resolution of spatial map
        InformationRobotPose( rob.robot_body.position, rob.robot_body.angle ),  # current pose of robot
        InformationPerceptionSpace( space, models ),                                    # percepted environment (exact, full perception)
#        InformationDestinationGeom( dest_point ),                               # target point for motion
#        InformationOpenDoorCommand(),
#        info_exp_motion,
        move_command,
    ]

    behaviors = [
        BehaviorSpatialMapGeneration(models),
#        BehaviorSpaceDigging(env),
        BehaviorKeepContact(),
        BehaviorSpatialPathPlanner(),
        BehaviorMoveTowards(),
        BehaviorObstacleAvoidance(),
        BehaviorTightPassage(),
#        BehaviorDoorPerception(cab.left_door),
#        BehaviorOpenDoor(),
        BehaviorMoveObject(),
        BehaviorObjectPerception(),#box, "box"),
        BehaviorPushObject(),
        BehaviorPushExecution(),
        BehaviorRobotControl(),
    ]

#    behaviors[0].update(information)
#    behaviors[0].plotTriangulation()
#    behaviors[0].plotGraph()
#    plt.show()
#    behaviors[1].update(information)
#    behaviors[1].plotTriangulation()
#    behaviors[1].plotGraph()
#    behaviors[1].plotOccludedSimplices()
#    behaviors[1].plotBorder()
#    plt.show()
#    exit(0)

    generateBehaviorsDotGraph('/home/dseredyn/svn/phd/ds/doktorat/rozwazania_2018_04/img/zachowania.dot', behaviors)

    first_behavior_iteration = True
    iterations = 0
    pause = False
    show_debug = False
    while running:
        iterations += 1
        if iterations == 10:
            generateBehaviorsDotGraph('/home/dseredyn/svn/phd/ds/doktorat/rozwazania_2018_04/img/zachowania_2.dot', behaviors)

        for event in pygame.event.get():
            if event.type == QUIT or \
                event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):  
                running = False
            if event.type == KEYDOWN and event.key == K_SPACE:
                pause = not pause
            if event.type == KEYDOWN and event.key == K_d:
                show_debug = not show_debug

        if pause:
            time.sleep(0.1)
            continue

        debug_info = []

        keys = pygame.key.get_pressed()

        active_behaviors = []

        # manual control
        if control_mode == "force":
            manualForceControl(rob.robot_body, keys)
        elif control_mode == "target_pos":
            position_control.update( rob.robot_body, keys )
        elif control_mode == "auto":
            position_control.update( rob.robot_body, keys )
            joinInformation( information, [ InformationRobotPose( rob.robot_body.position, rob.robot_body.angle ) ] )   # current pose of robot

            for b in behaviors:
                new_inf = b.update( information )
                joinInformation( information, new_inf )
                if len(new_inf) > 0:
                    active_behaviors.append( b.name )
                    #print new_inf[0].type
            inf_list = []
            for inf in information:
                inf_list.append( inf.type )
                if inf.type == "robot_total_control":
                    lin_damping = 300.0
                    lin_stiffness = 5000.0
                    rot_damping = 5000.0
                    rot_stiffness = 5000.0
                    #print inf.force, inf.torque
                    rob.robot_body.force = lin_stiffness*inf.force - lin_damping * rob.robot_body.velocity
                    rob.robot_body.torque = rot_stiffness*inf.torque - rot_damping * rob.robot_body.angular_velocity
            #print inf.torque
            #print "data:", inf_list
            # TODO: fix removing old information wrt. behavior execution sequence
            clearObsoleteInformation( information )
            #print active_behaviors
#        print "plan_idx", plan_idx
        #cab.debugVis(debug_info)

        #rob.debugVisQhull(debug_info)
        #rob.debugVisPushing(debug_info)

        applyDamping( damped_objects_list )

        mouse_position = pymunk.pygame_util.from_pygame( Vec2d(pygame.mouse.get_pos()), screen )
        mouse_position_munk = MunkToGame(mouse_position, height)

        move_command.dest_position = mouse_position

        ### Clear screen
        screen.fill(pygame.color.THECOLORS["black"])
        
        ### Draw stuff
        space.debug_draw(draw_options)

        if control_mode == "target_pos":
            position_control.debugInfoDraw( debug_info )
        elif control_mode == "auto":
            #behaviors[2].debugVisDraw(debug_info)
            #drawDebugCircle(debug_info, "green", 5, dest_point)
            vis_behaviors = ["keep_contact", "push_object", "spatial_path_planner", "obstacle_avoidance", "move_towards"]
            for b in behaviors:
                if b.name in vis_behaviors and b.name in active_behaviors:
                    b.debugVisDraw(debug_info)

        # draw debug info
        if show_debug:
            drawDebugInfo(screen, height, debug_info)

        # Info and flip screen
        screen.blit(font.render("fps: " + str(clock.get_fps()), 1, THECOLORS["white"]), (0,0))
        screen.blit(font.render("Mouse position (in world coordinates): " + str(mouse_position[0]) + "," + str(mouse_position[1]), 1, THECOLORS["darkgrey"]), (5,height - 35))
        screen.blit(font.render("Press ESC or Q to quit", 1, THECOLORS["darkgrey"]), (5,height - 20))
        
        pygame.display.flip()
        
        ### Update physics
        fps = 60
        dt = 1./fps
        space.step(dt)
        
        clock.tick(fps)
Exemplo n.º 5
0
def init():
    
    space = pymunk.Space()
    space.iterations = 10
    space.sleep_time_threshold = 0.5
    
    static_body = space.static_body
        
    # Create segments around the edge of the screen.
    shape = pymunk.Segment(static_body, (1,1), (1,480), 1.0)
    space.add(shape)
    shape.elasticity = 1
    shape.friction = 1

    shape = pymunk.Segment(static_body, (640,1), (640,480), 1.0)
    space.add(shape)
    shape.elasticity = 1
    shape.friction = 1
    
    shape = pymunk.Segment(static_body, (1,1), (640,1), 1.0)
    space.add(shape)
    shape.elasticity = 1
    shape.friction = 1
    
    shape = pymunk.Segment(static_body, (1,480), (640,480), 1.0)
    space.add(shape)
    shape.elasticity = 1
    shape.friction = 1
    
    for _ in range(50):
        body = add_box(space, 20, 1)
        
        pivot = pymunk.PivotJoint(static_body, body, (0,0), (0,0))
        space.add(pivot)
        pivot.max_bias = 0 # disable joint correction
        pivot.max_force = 1000 # emulate linear friction
        
        gear = pymunk.GearJoint(static_body, body, 0.0, 1.0)
        space.add(gear)
        gear.max_bias = 0 # disable joint correction
        gear.max_force = 5000  # emulate angular friction
    
    # We joint the tank to the control body and control the tank indirectly by modifying the control body.
    global tank_control_body
    tank_control_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    tank_control_body.position = 320, 240
    space.add(tank_control_body)
    global tank_body
    tank_body = add_box(space, 30, 10)
    tank_body.position = 320, 240
    for s in tank_body.shapes:
        s.color = (0,255,100,255)
    
    pivot = pymunk.PivotJoint(tank_control_body, tank_body, (0,0), (0,0))
    space.add(pivot)
    pivot.max_bias = 0 # disable joint correction
    pivot.max_force = 10000 # emulate linear friction
    
    gear = pymunk.GearJoint(tank_control_body, tank_body, 0.0, 1.0)
    space.add(gear)    
    gear.error_bias = 0 # attempt to fully correct the joint each step
    gear.max_bias = 1.2  # but limit it's angular correction rate
    gear.max_force = 50000 # emulate angular friction
        
    return space
Exemplo n.º 6
0
    def __init__(self, params, seed, fidelity=10, debug_options=None):
        """Constructor
        Args:
            params: dict of parameters that define how symbols behave and are rendered. See the
                    detailed description for this class for supported parameters.
            seed: Seed for the RNG (int)
            fidelity: How many iterations to run in the physics simulator per step (int)
            debug_options: dict with options for visual debugging, or None if visual debugging
                           should be turned off. The following key-value pairs are supported:
                              - show_pymunk_debug, bool: Whether to use PyMunk's default drawing
                                function
                              - show_bounding_poly, bool: Whether to render PyMunk surface outlines
                              - show_frame_number, bool: Whether to show the index of the frame
                              - frame_number_font_size, int: Size of the frame index font
                              - frame_rate, int: Frame rate of the debug visualization

        """

        self.params = merge_dicts(MovingSymbolsEnvironment.DEFAULT_PARAMS,
                                  params)
        self.fidelity = fidelity
        self.debug_options = None if debug_options is None \
            else merge_dicts(MovingSymbolsEnvironment.DEFAULT_DEBUG_OPTIONS, debug_options)
        self.video_size = self.params['video_size']

        self._subscribers = []
        self._init_messages = []
        self._step_called = False

        self._add_init_message(
            dict(step=-1, type='params', meta=dict(self.params)))

        # Convert translation/rotation/scale period/speed limits to lists
        if isinstance(self.params['scale_period_limits'], tuple):
            self.params['scale_period_limits'] = [
                self.params['scale_period_limits']
            ]
        if isinstance(self.params['rotation_speed_limits'], tuple):
            self.params['rotation_speed_limits'] = [
                self.params['rotation_speed_limits']
            ]
        if isinstance(self.params['position_speed_limits'], tuple):
            self.params['position_speed_limits'] = [
                self.params['position_speed_limits']
            ]

        self.cur_rng_seed = seed
        np.random.seed(self.cur_rng_seed)

        if self.debug_options is not None:
            self._pg_screen = pg.display.set_mode(self.video_size)
            self._pg_draw_options = pmu.DrawOptions(self._pg_screen)
            pg.font.init()
            font_size = self.debug_options['frame_number_font_size']
            self._pg_font = pg.font.SysFont(pg.font.get_default_font(),
                                            font_size)
            self._pg_clock = pg.time.Clock()
            self._add_init_message(
                dict(step=-1, type='debug_options', meta=dict(debug_options)))

        self._space = pm.Space()
        self.symbols = []
        image_loader = ImageLoader(
            os.path.join(self.params['data_dir'], self.params['split']),
            'tight_crop')

        if self.params['background_data_dir'] is None or self.params[
                'background_labels'] is None:
            bg_image_loader = None
        else:
            bg_image_loader = ImageLoader(
                os.path.join(self.params['background_data_dir'],
                             self.params['split']))

        for id in xrange(self.params['num_symbols']):
            label = self.params['symbol_labels'][np.random.randint(
                len(self.params['symbol_labels']))]
            image, image_path = image_loader.get_image(label)

            # Define the scale function
            period_limits_index = np.random.choice(
                len(self.params['scale_period_limits']))
            period = np.random.uniform(*tuple(
                self.params['scale_period_limits'][period_limits_index]))

            amplitude = (self.params['scale_limits'][1] -
                         self.params['scale_limits'][0]) / 2.
            x_offset = np.random.uniform(period)

            # Override offset if digits should not start at random scale
            if not self.params['rescale_at_start']:
                x_offset = 0

            # Randomly shift offset (i.e. symbol can either grow or shrink at start)
            x_offset += (period / 2 if np.random.choice([True, False]) else 0)
            y_offset = (self.params['scale_limits'][1] +
                        self.params['scale_limits'][0]) / 2.

            if self.params['scale_function_type'] == 'sine':
                scale_fn = create_sine_fn(period, amplitude, x_offset,
                                          y_offset)
            elif self.params['scale_function_type'] == 'triangle':
                scale_fn = create_triangle_fn(period, y_offset,
                                              self.params['movement'])
            elif self.params['scale_function_type'] == 'constant':
                scale = np.random.uniform(*self.params['scale_limits'])
                scale_fn = lambda x: scale
            else:
                raise ValueError('scale_function_type "%s" is unsupported' %
                                 self.params['scale_function_type'])

            symbol = Symbol(id, label, image, image_path, scale_fn)

            # Set the symbol's initial rotation and scale
            symbol.set_scale(0)
            start_angle = np.random.uniform(2 * math.pi)
            if self.params['rotate_at_start']:
                symbol.body.angle = start_angle

            # Compute the minimum possible margin between the symbol's center and the wall
            w_half = image.size[0] / 2.
            h_half = image.size[1] / 2.
            margin = math.sqrt(w_half**2 +
                               h_half**2) * self.params['scale_limits'][1]

            # Set the symbol position at least one margin's distance from any wall
            x_limits = (margin + 1, self.video_size[0] - margin - 1)
            y_limits = (margin + 1, self.video_size[1] - margin - 1)
            symbol.body.position = (np.random.uniform(*x_limits),
                                    np.random.uniform(*y_limits))

            # If symbols will interact with each other, make sure they don't overlap initially
            while self.params['interacting_symbols'] and len(
                    self._space.shape_query(symbol.shape)) > 0:
                symbol.body.position = (np.random.uniform(*x_limits),
                                        np.random.uniform(*y_limits))

            # Set angular velocity
            rotation_speed_limit_index = np.random.choice(
                len(self.params['rotation_speed_limits']))
            symbol.body.angular_velocity = np.random.uniform(
                *tuple(self.params['rotation_speed_limits']
                       [rotation_speed_limit_index]))

            symbol.body.angular_velocity *= 1 if np.random.binomial(1,
                                                                    .5) else -1
            symbol.angular_velocity = symbol.body.angular_velocity

            # Set translational velocity
            sampled_velocity = np.random.uniform(-1, 1, 2)

            if self.params['movement'] == 'Down':
                sampled_velocity = np.array([0, -1])

            elif self.params['movement'] == 'Right':
                sampled_velocity = np.array([1, 0])

            elif self.params['movement'] == 'Up':
                sampled_velocity = np.array([0, 1])

            elif self.params['movement'] == 'Left':
                sampled_velocity = np.array([-1, 0])

            elif self.params['movement'] == 'Horizontal':
                sampled_velocity = np.array([1, 0])

            elif self.params['movement'] == 'Vertical':
                sampled_velocity = np.array([0, 1])

            elif self.params['movement'] == 'Circle':
                x = np.linspace(-1.0, 1.0, 100)
                y = np.linspace(-1.0, 1.0, 100)
                X, Y = np.meshgrid(x, y)
                F = X**2 + Y**2 - 1
                c = plt.contour(X, Y, F, [0])
                dat0 = c.allsegs[0][0]
                self.dat1 = np.zeros((self.params['video_len'], 2))
                indices = np.linspace(0,
                                      dat0.shape[0] - 1,
                                      self.params['video_len'],
                                      dtype='int')
                for i, j in enumerate(indices):
                    self.dat1[i] = dat0[j]
                sampled_velocity = self.dat1[0]

            elif self.params['movement'] == 'Square':
                self.dat1 = np.zeros((self.params['video_len'], 2))
                count = 0
                for i in range(self.params['video_len']):
                    if count < 5:
                        self.dat1[i] = [0, -1]
                    elif 5 <= count < 10:
                        self.dat1[i] = [1, 0]
                    elif 10 <= count < 15:
                        self.dat1[i] = [0, 1]
                    elif 15 <= count < 20:
                        self.dat1[i] = [-1, 0]
                    count += 1
                sampled_velocity = self.dat1[0]

            elif self.params['movement'] == 'Triangle':
                self.dat1 = np.zeros((self.params['video_len'], 2))
                count = 0
                for i in range(self.params['video_len']):
                    if count < 6:
                        self.dat1[i] = [-1, -1]
                    elif 6 <= count < 13:
                        self.dat1[i] = [1, 0]
                    elif 13 <= count < 20:
                        self.dat1[i] = [-1, 1]
                    count += 1
                sampled_velocity = self.dat1[0]

            elif self.params['movement'] == 'Eight':
                x = np.linspace(-1.0, 1.0, 100)
                y = np.linspace(-1.0, 1.0, 100)
                X, Y = np.meshgrid(x, y)
                F = X**2 + Y**2 - 1
                c = plt.contour(X, Y, F, [0])
                dat = c.allsegs[0][0]
                dat0 = np.concatenate((dat, dat), axis=0)
                self.dat1 = np.zeros((self.params['video_len'], 2))
                indices = np.linspace(0,
                                      dat0.shape[0] - 1,
                                      self.params['video_len'],
                                      dtype='int')
                count = 0
                for i, j in enumerate(indices):
                    if count < 5:
                        self.dat1[i] = [dat0[j][1], dat0[j][0]]
                    elif 5 <= count < 10:
                        self.dat1[i] = [dat0[j][1], -dat0[j][0]]
                    elif 10 <= count < 15:
                        self.dat1[i] = [dat0[j][1], -dat0[j][0]]
                    elif 15 <= count < 20:
                        self.dat1[i] = [dat0[j][1], dat0[j][0]]
                    count += 1
                sampled_velocity = self.dat1[0]

            elif self.params['movement'] == 'Infinite':
                x = np.linspace(-1.0, 1.0, 100)
                y = np.linspace(-1.0, 1.0, 100)
                X, Y = np.meshgrid(x, y)
                F = X**2 + Y**2 - 1
                c = plt.contour(X, Y, F, [0])
                dat = c.allsegs[0][0]
                dat0 = np.concatenate((dat, dat), axis=0)
                self.dat1 = np.zeros((self.params['video_len'], 2))
                indices = np.linspace(0,
                                      dat0.shape[0] - 1,
                                      self.params['video_len'],
                                      dtype='int')
                count = 0
                for i, j in enumerate(indices):
                    if count < 5:
                        self.dat1[i] = [-dat0[j][0], dat0[j][1]]
                    elif 5 <= count < 10:
                        self.dat1[i] = [dat0[j][0], dat0[j][1]]
                    elif 10 <= count < 15:
                        self.dat1[i] = [dat0[j][0], dat0[j][1]]
                    elif 15 <= count < 20:
                        self.dat1[i] = [-dat0[j][0], dat0[j][1]]
                    count += 1
                sampled_velocity = self.dat1[0]

            symbol.body.velocity = sampled_velocity / np.linalg.norm(
                sampled_velocity)
            self.position_speed_limit_index = np.random.choice(
                len(self.params['position_speed_limits']))
            symbol.body.velocity *= np.random.uniform(
                *tuple(self.params['position_speed_limits'][
                    self.position_speed_limit_index]))

            # Add symbol to the space and environment
            self._space.add(symbol.body, symbol.shape)
            self.symbols.append(symbol)

            # Publish message about the symbol
            # self._publish_message(symbol.get_init_message())
            self._add_init_message(symbol.get_init_message())

        # Add walls
        self._add_walls()

        # Add collision handlers
        self._add_collision_handlers(
            interacting_symbols=self.params['interacting_symbols'])

        # Init step count
        self._step_count = 0

        # Set background image
        self.background = Image.fromarray(
            np.zeros((self.video_size[0], self.video_size[1], 3),
                     dtype=np.uint8))
        if bg_image_loader is not None:
            # Choose a category
            bg_labels = self.params['background_labels']
            category_name = bg_labels[np.random.randint(len(bg_labels))]

            # Choose an image
            bg_image, full_image_path = bg_image_loader.get_image(
                category_name)
            self.background.paste(bg_image)

            # Publish information about the chosen background
            self._add_init_message(
                dict(step=-1,
                     type='background',
                     meta=dict(label=category_name,
                               image=np.array(self.background),
                               image_path=full_image_path)))
Exemplo n.º 7
0
    def create_world(self):
        self.space = pymunk.Space()
        self.space.gravity = Vec2d(0., -900.)
        self.space.sleep_time_threshold = 0.9
        self.boxes = [
        ]  # 2d array box instances correspondingly for each layer
        self.predicted_stability = False
        self.removed_object = False

        # Create the ground line
        ground_line = pymunk.Segment(
            self.space.static_body, Vec2d(20, self.bottom_edge),
            Vec2d(self.window_width - 20, self.bottom_edge), 1)
        ground_line.friction = 0.9
        self.space.add(ground_line)

        # With this model putting boxes and setting up number of boxes happens in parallel
        n = self.n
        layer_num = -1  # Represents the index of the current layer
        while n > 0:
            layer_num += 1
            self.boxes.append([])
            right_edge, left_edge = self.get_right_left_edge(layer_num - 1)

            if right_edge == left_edge:  # The layer below has one element
                x_pos = random.randint(
                    int(left_edge - self.rect_width_min / 2),
                    int(left_edge + self.rect_width_min / 2))
                rect_width = random.randint(
                    self.rect_width_min,
                    self.rect_width_min + self.rect_width_range)
                self.put_box(layer_num=layer_num,
                             x_pos=x_pos,
                             y_pos=self.bottom_edge +
                             int(self.rect_height / 2) +
                             self.rect_height * layer_num,
                             rect_width=rect_width)
                n -= 1
                continue

            # Start from the left_edge and put boxes towards right edge
            # Stop putting boxes if the number of objects required is reached
            # Move on to the next layer if the right edge is reached
            left_edge -= (layer_num > 0) * int(self.rect_width_average / 2)
            rect_width = random.randint(
                self.rect_width_min,
                self.rect_width_min + self.rect_width_range)
            left_edge += rect_width
            while left_edge - rect_width / 2 < right_edge and n > 0:
                self.put_box(layer_num=layer_num,
                             x_pos=left_edge - rect_width / 2,
                             y_pos=self.bottom_edge + self.rect_height / 2 +
                             self.rect_height * layer_num,
                             rect_width=rect_width)
                n -= 1
                space_between = random.randint(0, self.max_space_rects)
                left_edge += space_between  # Put a space between rectangles
                rect_width = random.randint(
                    self.rect_width_min,
                    self.rect_width_min + self.rect_width_range)
                left_edge += rect_width

        self.flat_boxes = []
        for i in range(len(self.boxes)):
            for j in range(len(self.boxes[i])):
                self.flat_boxes.append(self.boxes[i][j])
        print('len(flat_boxes): {}'.format(len(self.flat_boxes)))
        print('len(trajectories): {}'.format(len(self.trajectories)))
        if len(self.flat_boxes) == self.n:
            self.trajectories.append([])
Exemplo n.º 8
0
    def pymunk_setup(self, experiment):
        # Initialize space and set gravity for space to do simulation over
        self.width = 800
        self.height = 600
        self.ball_size = 60
        self.speed = 200  # scales how fast balls are moving
        self.step_size = 1 / 50.0
        self.step_max = 300  # step at which to stop the animation
        self.step = 0  # used to record when events happen
        self.space = pymunk.Space()
        self.events = {
            'collisions': [],
            'outcome': None,
            'outcome_fine': None
        }  # used to record events
        # containers for bodies and shapes
        self.bodies = collections.OrderedDict()
        self.shapes = collections.OrderedDict()
        self.sprites = collections.OrderedDict()

        self.collision_types = {'static': 0, 'dynamic': 1, 'teleport': 2}
        self.experiment = experiment

        if self.experiment == '3ball':
            self.target_ball = 'E'
        else:
            self.target_ball = 'B'

        # add walls
        self.add_wall(position=(400, 590),
                      length=800,
                      height=20,
                      name='top_wall',
                      space=self.space)
        self.add_wall(position=(400, 10),
                      length=800,
                      height=20,
                      name='bottom_wall',
                      space=self.space)
        self.add_wall(position=(10, 100),
                      length=20,
                      height=200,
                      name='top_left_wall',
                      space=self.space)
        self.add_wall(position=(10, 500),
                      length=20,
                      height=200,
                      name='bottom_left_wall',
                      space=self.space)

        # read in trial info
        self.read_trials()
        self.balls = self.trials[self.trial]['balls']

        # add objects
        if self.experiment == 'teleport':
            self.objects = self.trials[self.trial]['objects']
            for object in self.objects:
                if object['name'] == 'brick':
                    body, shape = self.add_brick(position=object['position'],
                                                 name=object['name'],
                                                 rotation=object['rotation'],
                                                 space=self.space)
                if object['name'] == 'teleport_entrance':
                    body, shape = self.add_teleport_entrance(
                        position=object['position'],
                        name=object['name'],
                        rotation=object['rotation'],
                        status=object['status'],
                        space=self.space)
                if object['name'] == 'teleport_exit':
                    body, shape = self.add_teleport_exit(
                        position=object['position'],
                        name=object['name'],
                        status=object['status'],
                        space=self.space)
                self.bodies[object['name']] = body
                self.shapes[object['name']] = shape

        # add balls
        for ball in self.balls:
            body, shape = self.add_ball(position=ball['position'],
                                        name=ball['name'],
                                        velocity=ball['velocity'],
                                        size=self.ball_size,
                                        space=self.space)
            self.bodies[ball['name']] = body
            self.shapes[ball['name']] = shape
Exemplo n.º 9
0
def main():

    pygame.init()
    screen = pygame.display.set_mode((600, 600))
    clock = pygame.time.Clock()
    running = True

    ### Physics stuff
    space = pymunk.Space()
    space.gravity = 0.0, -900.0

    ## Balls
    balls = []

    ### Mouse
    mouse_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    mouse_shape = pymunk.Circle(mouse_body, 3, (0, 0))
    mouse_shape.collision_type = COLLTYPE_MOUSE
    space.add(mouse_body, mouse_shape)

    space.add_collision_handler(
        COLLTYPE_MOUSE, COLLTYPE_BALL
    ).pre_solve = mouse_coll_func

    ### Static line
    line_point1 = None
    static_lines = []
    run_physics = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_p:
                pygame.image.save(screen, "balls_and_lines.png")
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                p = event.pos[X], flipy(event.pos[Y])
                body = pymunk.Body(10, 100)
                body.position = p
                shape = pymunk.Circle(body, 10, (0, 0))
                shape.friction = 0.5
                shape.collision_type = COLLTYPE_BALL
                space.add(body, shape)
                balls.append(shape)

            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:
                if line_point1 is None:
                    line_point1 = Vec2d(event.pos[X], flipy(event.pos[Y]))
            elif event.type == pygame.MOUSEBUTTONUP and event.button == 3:
                if line_point1 is not None:

                    line_point2 = Vec2d(event.pos[X], flipy(event.pos[Y]))
                    shape = pymunk.Segment(
                        space.static_body, line_point1, line_point2, 0.0
                    )
                    shape.friction = 0.99
                    space.add(shape)
                    static_lines.append(shape)
                    line_point1 = None

            elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                run_physics = not run_physics

        p = pygame.mouse.get_pos()
        mouse_pos = Vec2d(p[X], flipy(p[Y]))
        mouse_body.position = mouse_pos

        if pygame.key.get_mods() & pygame.KMOD_SHIFT and pygame.mouse.get_pressed()[0]:
            body = pymunk.Body(10, 10)
            body.position = mouse_pos
            shape = pymunk.Circle(body, 10, (0, 0))
            shape.collision_type = COLLTYPE_BALL
            space.add(body, shape)
            balls.append(shape)

        ### Update physics
        if run_physics:
            dt = 1.0 / 60.0
            for x in range(1):
                space.step(dt)

        ### Draw stuff
        screen.fill(pygame.Color("white"))

        # Display some text
        font = pygame.font.Font(None, 16)
        text = """LMB: Create ball
LMB + Shift: Create many balls
RMB: Drag to create wall, release to finish
Space: Pause physics simulation"""
        y = 5
        for line in text.splitlines():
            text = font.render(line, True, pygame.Color("black"))
            screen.blit(text, (5, y))
            y += 10

        for ball in balls:
            r = ball.radius
            v = ball.body.position
            rot = ball.body.rotation_vector
            p = int(v.x), int(flipy(v.y))
            p2 = p + Vec2d(rot.x, -rot.y) * r * 0.9
            p2 = int(p2.x), int(p2.y)
            pygame.draw.circle(screen, pygame.Color("blue"), p, int(r), 2)
            pygame.draw.line(screen, pygame.Color("red"), p, p2)

        if line_point1 is not None:
            p1 = int(line_point1.x), int(flipy(line_point1.y))
            p2 = mouse_pos.x, flipy(mouse_pos.y)
            pygame.draw.lines(screen, pygame.Color("black"), False, [p1, p2])

        for line in static_lines:
            body = line.body

            pv1 = body.position + line.a.rotated(body.angle)
            pv2 = body.position + line.b.rotated(body.angle)
            p1 = int(pv1.x), int(flipy(pv1.y))
            p2 = int(pv2.x), int(flipy(pv2.y))
            pygame.draw.lines(screen, pygame.Color("lightgray"), False, [p1, p2])

        ### Flip screen
        pygame.display.flip()
        clock.tick(50)
        pygame.display.set_caption("fps: " + str(clock.get_fps()))
Exemplo n.º 10
0
    def __init__(self, config_file, trial_number):
        # Use the base of the config file's name as the name of the output dir
        output_dir_base = str.split(config_file, '.')[0]
        self.output_dir = output_dir_base + '/' + str(trial_number)
        print(self.output_dir)

        config = ConfigSingleton.get_instance(config_file)

        # Load parameters from config file.
        self.width_cm = config.getint("AlvinSim", "width_cm")
        self.height_cm = config.getint("AlvinSim", "height_cm")
        self.width = int(self.width_cm * CM_TO_PIXELS)
        self.height = int(self.height_cm * CM_TO_PIXELS)
        #print "width, height: {}, {}".format(self.width, self.height);
        self.circ_border = config.getboolean("AlvinSim", "circ_border")
        self.number_robots = config.getint("AlvinSim", "number_robots")
        self.number_pucks = config.getint("AlvinSim", "number_pucks")
        self.number_puck_kinds = config.getint("AlvinSim", "number_puck_kinds")
        self.number_steps = config.getint("AlvinSim", "number_steps")
        self.puck_ring = config.getboolean("AlvinSim", "puck_ring")
        self.puck_ring_radius = config.getint("AlvinSim", "puck_ring_radius")
        self.canned_landmarks_name = config.get("AlvinSim",
                                                "canned_landmarks_name")
        self.puck_shape = config.get("AlvinSim", "puck_shape")
        self.lmark_pair_dist = config.getint("AlvinSim", "lmark_pair_dist")
        self.puck_kinds = list(range(self.number_puck_kinds))
        self.wall_thickness = config.getint("AlvinSim", "wall_thickness")
        self.capture_interval = config.getint("AlvinSim", "capture_interval")
        self.analyze = config.getboolean("AlvinSim", "analyze")
        self.capture_screenshots = config.getboolean("AlvinSim",
                                                     "capture_screenshots")
        self.visualize_probes = config.getboolean("AlvinSim",
                                                  "visualize_probes")
        self.controller_name = config.get("AlvinSim", "controller_name")
        self.render_skip = config.getint("AlvinSim", "render_skip")

        # build simulation environment
        self.env = pymunk.Space()
        self.env.damping = 0.0001  # 9999% of velocity is lost per second

        # Seed random number generator.
        seed(trial_number)

        # Create the walls, robots, pucks, and landmarks
        if self.circ_border:
            self.create_circ_border()
        else:
            self.create_rect_border()
        #self.create_random_walls()
        #self.create_one_wall()
        self.robots = []
        self.pucks = []
        self.landmarks = []
        self.probes = []
        self.create_robots()

        if self.puck_ring:
            self.create_pucks_ring()
        else:
            self.create_pucks_random()
        #self.create_immobile_pucks()
        self.create_canned_landmarks()
        if self.visualize_probes:
            self.create_probe_grid()

        # Prepare output directory.
        shutil.rmtree(self.output_dir, ignore_errors=True)
        os.makedirs(self.output_dir)

        if self.analyze:
            #init(self.output_dir)
            self.analyzer = Analyzer(self.output_dir, self.landmarks)

        # Setup to handle collisions
        #self.env.add_default_collision_handler().begin = self.collision_handler

        self.avg_dt = None
Exemplo n.º 11
0
def main():

    # Setup Level common variables -------------------------------- ##

    force = 2300  # Force upon the ball when it is fired
    rampsize = 100  # end coordinate of the ball's ramp

    pygame.init()
    pygame.display.set_caption("Angry Clones")
    clock = pygame.time.Clock()

    # Set up static images, these never move
    greyed_out = Image("greyed_out.jpg")
    background = Image("machinarium_floor.jpg")
    trebuchet = Image("trebuchet.png", (20, 450))

    global screen
    screen = pygame.display.set_mode(background.get_size())

    space = pm.Space()
    space.gravity = (0.0, -300.0)
    body = pm.Body()

    # ground
    ground = pm.Segment(body, (0, 100), (1050, 100), .0)
    ground.friction = 6.0
    space.add(ground)

    #left wall
    left_wall = pm.Segment(body, to_pygame((0, 0)), to_pygame((0, 2000)), .0)
    left_wall.friction = 6.0
    space.add(left_wall)

    # ball area
    ball_area = pm.Segment(body, (0, 110), (60, 110), .0)
    space.add(ball_area)

    # Title Screen ------------------------------------------------- ##

    count = 0
    while count < 70:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit(0)
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    pygame.quit()
                    sys.exit(0)
                # Space bar skips the title screen
                if event.key == 32:
                    count = 71

        greyed_out.display()

        Message("Angry Clones!", (220, 250), 95).display_shadow()

        pygame.display.flip()
        count += 1

    # End Title Screen ---------------------------------------------- ##

    # Main Game loop ------------------------------------------------ ##

    game_complete = False
    level = 0
    while not game_complete:

        # Record time now, to see how fast you complete the game
        start_game_timer = datetime.datetime.now()

        trying_again = True
        while trying_again:

            # Level setup ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##

            if level == 0:
                balls = []
                x, y = (2, 110)
                balls.append(Ball(space, x, y))

                # Add crates
                crates = []
                crates += [
                    Crate(space, (500, 85 + (23 + i * 51))) for i in range(3)
                ]
                crates += [
                    Crate(space, (600, 85 + (23 + i * 51))) for i in range(3)
                ]
                crates += [Crate(space, (505 + 46, 278), True)]

                # Add one snake
                snakes = []
                snakes.append(Snake(space, to_pygame((551, 232))))

                level_complete = False
                level_failed = False
                count = 0

            if level == 1:

                # Remove all old crates etc from the playing area
                for crate in crates:
                    crate.delete(space)
                for ball in balls:
                    ball.delete(space)
                for snake in snakes:
                    snake.delete(space)

                balls = []
                x, y = (2, 110)
                balls.append(Ball(space, x, y))

                # Map of intended level     -   Key
                #------------------------------------------------
                #                #T#            S = Snake
                #             S  ###  S
                #            #T# #T# #T#      #T# = TNT crate
                #            ### ### ###      ###
                #           #   #   #   #
                #           #   #   #   #
                #           #   #   #   #
                #           A B C D E F G

                # Add crates
                crates = []
                crates += [
                    Crate(space, (500, 85 + (23 + i * 51))) for i in range(3)
                ]  #A
                crates += [
                    Crate(space, (600, 85 + (23 + i * 51))) for i in range(3)
                ]  #C
                crates += [
                    Crate(space, (700, 85 + (23 + i * 51))) for i in range(3)
                ]  #E
                crates += [
                    Crate(space, (800, 85 + (23 + i * 51))) for i in range(3)
                ]  #G
                crates += [Crate(space, (505 + 46, 278), True)]  #B
                crates += [Crate(space, (605 + 46, 278), True)]  #D
                crates += [Crate(space, (705 + 46, 278), True)]  #F
                crates += [Crate(space, (605 + 46, 378), True)]  #D higher

                # Add snakes
                Snake.snakes_alive = 0
                snakes = []
                snakes.append(Snake(space, (551, 350)))
                snakes.append(Snake(space, (751, 350)))

                level_complete = False
                level_failed = False
                count = 0
                start_timer = datetime.datetime.now()

            if level == 2:

                # Remove all old crates etc from the playing area
                for crate in crates:
                    crate.delete(space)
                for ball in balls:
                    ball.delete(space)
                for snake in snakes:
                    snake.delete(space)

                balls = []
                x, y = (2, 110)
                balls.append(Ball(space, x, y))

                # Map of intended level     - Key
                #------------------------------------------------
                #              S          S = Snake
                #             #T#
                #          S  ###       #T# = TNT crate
                #         #T# #T#       ###
                #      S  ### ###
                #     #T# #T# #T#
                #     ### ### ###
                #      A   B   C

                # Add crates
                crates = []
                crates += [Crate(space, (305 + 46, 170), True)]  #A
                crates += [Crate(space, (505 + 46, 170), True)]  #B
                crates += [Crate(space, (505 + 46, 270), True)]  #
                crates += [Crate(space, (705 + 46, 170), True)]  #C
                crates += [Crate(space, (705 + 46, 270), True)]  #
                crates += [Crate(space, (705 + 46, 370), True)]  #

                # Add snakes
                Snake.snakes_alive = 0
                snakes = []
                snakes.append(Snake(space, (351, 310)))
                snakes.append(Snake(space, (551, 410)))
                snakes.append(Snake(space, (751, 510)))

                level_complete = False
                level_failed = False
                count = 0
                start_timer = datetime.datetime.now()

            # End Level Setup ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##

            # Game-play loop ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##

            while not level_complete and not level_failed:

                space.step(1 / 30.0)
                clock.tick(30)

                for event in pygame.event.get():
                    if event.type == QUIT:
                        pygame.quit()
                        sys.exit(0)
                    elif event.type == KEYDOWN:
                        if event.key == K_ESCAPE:
                            pygame.quit()
                            sys.exit(0)
                        # Spacebar is pressed
                        if event.key == 32:  # Reset the ball if lost
                            balls[0].delete(space)
                            balls = []
                            x, y = (2, 110)
                            balls.append(Ball(space, x, y))
                            balls[0].random_colour()

                #Get ramp slope from mouse 'y'
                rampsize = to_pygame(pygame.mouse.get_pos())[1]
                slope = pm.Segment(body, (60, 110), (250, rampsize), .0)
                space.add(slope)

                background.display()
                trebuchet.display()
                balls[0].draw()

                if pygame.mouse.get_pressed()[0]:
                    balls[0].fire(force / 3)

                for crate in crates:
                    crate.draw()

                # Add variety to crate's looks
                if level == 0:
                    crates[1].brake_crate()
                    crates[5].brake_crate()
                    crates[0].brake_crate()

                if level == 1:
                    crates[3].brake_crate()
                    crates[8].brake_crate()
                    crates[1].brake_crate()
                    crates[5].brake_crate()

                for snake in snakes:
                    snake.draw()
                    if snake.is_dead():
                        snake.kill_snake()  #This doesn't make sense!
                        Message("The Snake is Dead!", \
                                                (600,600)).display_shadow()

                    #If you kill all the snakes you win the level
                    if Snake.all_snakes_dead():
                        level_complete = True
                        level_failed = False
                        pass

                #Draw Ramp
                pygame.draw.aaline(screen, THECOLORS['red'], \
                                to_pygame((60,110)), to_pygame((250,rampsize)))
                #Draw Ball Area
                pygame.draw.aaline(screen, THECOLORS['red'],\
                                to_pygame((0,110)), to_pygame((60,110)))

                #If mouse goes of screen to the right, bring it back
                if to_pygame(balls[0].get_position())[0] > 1024:
                    balls[0].reposition(1, 110)

                #Display number of snakes left
                Message("{0}".format("Snakes Left: {0}"\
                        .format(Snake.snakes_alive)),(0,0), 30).display_shadow()

                #Time attack for levels 2 and 3
                if level > 0:
                    #Work out time remaining
                    delta = datetime.datetime.now() - start_timer
                    Message("{0}".format("Time Left: {0}"\
                                    .format(30 - delta.seconds)),(830,0),30)\
                                                            .display_shadow()

                    #If time has passed, you fail the level
                    if 30 - delta.seconds <= 0:
                        level_failed = True

                pygame.display.flip()
                count += 1
                #del slope

            # End Game-play Loop ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##

            # You have either completed the level or failed it

            # FAILED: Ask if you would like to try again --------------- ##

            if level_failed:
                count = 0
                while count < 70:
                    space.step(1 / 30.0)
                    clock.tick(30)

                    for event in pygame.event.get():
                        if event.type == QUIT:
                            pygame.quit()
                            sys.exit(0)
                        elif event.type == KEYDOWN:
                            if event.key == K_ESCAPE:
                                pygame.quit()
                                sys.exit(0)
                            # Spacebar is pressed
                            if event.key == 32:
                                trying_again = True
                                # End the loop and start next level
                                count = 71

                    greyed_out.display()

                    if count < 30:
                        Message("Good Try!", (320, 250), 95).display_shadow()

                    if count > 30:
                        Message("Press SPACE to try again", (80,250), 80)\
                                                            .display_shadow()
                        Message("Press ESC to quit", (300,400), 60)\
                                                            .display_shadow()

                    pygame.display.flip()
                    count += 1

                    # Trick to halt the game on message
                    if count == 32:
                        count = 31

            # End Try again screen ------------------------------------ ##

            # You didn't fail, show next level screen ----------------- ##

            if level_complete:
                count = 0
                while count < 70:

                    for event in pygame.event.get():
                        if event.type == QUIT:
                            pygame.quit()
                            sys.exit(0)
                        elif event.type == KEYDOWN:
                            if event.key == K_ESCAPE:
                                pygame.quit()
                                sys.exit(0)
                            if event.key == 32:
                                want_to_try_again = True
                                count = 71

                    greyed_out.display()

                    # No need if you are on the last level,
                    # Just go to final conratulations screen
                    if level < 2:
                        # Display this message first
                        if count < 30:
                            Message("Well Done", (320, 250),
                                    95).display_shadow()

                        # Then this
                        if count > 30:
                            next_lvl = level + 2
                            Message("Level {0}".format(next_lvl),\
                                                 (350,250), 95).display_shadow()
                    else:
                        count = 71

                    pygame.display.flip()
                    count += 1
                if level == 2:
                    game_complete = True
                    trying_again = False
                else:
                    level += 1

        # End next level screen -------------------------------------- ##

        # Completed the game
        # (can only try again or quit so must have won to get here)

        end_time = datetime.datetime.now()
        time_taken = end_time - start_game_timer

        count = 0
        while count < 70:

            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit(0)
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        pygame.quit()
                        sys.exit(0)
                    if event.key == 32:
                        want_to_try_again = True
                        count = 71

            greyed_out.display()

            # Display this message first
            if count < 30:
                Message("Game Completed!", (130, 250), 95).display_shadow()

            # Then this
            if count > 30:
                Message("You completed the game", (190,250), 65)\
                                                            .display_shadow()
                Message("In: {0} seconds".format(time_taken.seconds),\
                                                (230,350), 95).display_shadow()

            pygame.display.flip()
            count += 1
Exemplo n.º 12
0
def main():

    pygame.init()
    pygame.display.set_caption("Balls and Lines")
    screen = pygame.display.set_mode((600, 600))
    clock = pygame.time.Clock()
    running = True

    ### Physics stuff
    space = pymunk.Space()
    space.gravity = 0.0, -900.0

    ## Balls
    balls = []

    ### Mouse
    mouse_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    mouse_shape = pymunk.Circle(mouse_body, 3, (0, 0))
    mouse_shape.collision_type = COLLTYPE_MOUSE
    space.add(mouse_shape)

    ch = space.add_collision_handler(COLLTYPE_MOUSE, COLLTYPE_BALL)
    ch.data["surface"] = screen
    ch.pre_solve = mouse_coll_func
    ch.post_solve = draw_collision

    ### Static line
    line_point1 = None
    static_lines = []
    run_physics = True

    isElastic = False
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
                pygame.quit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                running = False
            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, "balls_and_lines.png")
            elif event.type == KEYDOWN and event.key == K_e:
                isElastic = not isElastic

            elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                p = event.pos[X], flipy(event.pos[Y])

                body = pymunk.Body(10, 100)
                body.position = p
                shape = pymunk.Circle(body, 10, (0, 0))
                shape.elasticity = 0.85 if isElastic else 0.0
                shape.friction = 0.5
                shape.collision_type = COLLTYPE_BALL
                space.add(body, shape)
                balls.append(shape)

            elif event.type == MOUSEBUTTONDOWN and event.button == 3:
                if line_point1 is None:
                    line_point1 = Vec2d(event.pos[X], flipy(event.pos[Y]))
            elif event.type == MOUSEBUTTONUP and event.button == 3:
                if line_point1 is not None:

                    line_point2 = Vec2d(event.pos[X], flipy(event.pos[Y]))
                    body = pymunk.Body(body_type=pymunk.Body.STATIC)
                    shape = pymunk.Segment(body, line_point1, line_point2, 0.0)
                    shape.friction = 0.99
                    space.add(shape)
                    static_lines.append(shape)
                    line_point1 = None

            elif event.type == KEYDOWN and event.key == K_SPACE:
                run_physics = not run_physics

        p = pygame.mouse.get_pos()
        mouse_pos = Vec2d(p[X], flipy(p[Y]))
        mouse_body.position = mouse_pos

        if pygame.key.get_mods() & KMOD_SHIFT and pygame.mouse.get_pressed(
        )[0]:
            body = pymunk.Body(10, 10)
            body.position = mouse_pos
            shape = pymunk.Circle(body, 10, (0, 0))

            shape.collision_type = COLLTYPE_BALL
            space.add(body, shape)
            balls.append(shape)

        ### Update physics
        if run_physics:
            dt = 1.0 / 60.0
            for x in range(1):
                space.step(dt)

        ### Draw stuff
        screen.fill(THECOLORS["white"])

        # Display some text
        font = pygame.font.SysFont("Helvetica", 16)
        text = """LMB: Create ball
LMB + Shift: Create many balls
RMB: Drag to create wall, release to finish
B: Toggle Elasticity
Space: Pause physics simulation"""
        y = 5
        for line in text.splitlines():
            text = font.render(line, 1, THECOLORS["black"])
            screen.blit(text, (5, y))
            y += 15

        for ball in balls:
            r = ball.radius
            v = ball.body.position
            rot = ball.body.rotation_vector
            p = int(v.x), int(flipy(v.y))
            p2 = Vec2d(rot.x, -rot.y) * r * 0.9
            pygame.draw.circle(screen, THECOLORS["blue"], p, int(r), 2)
            pygame.draw.line(screen, THECOLORS["red"], p, p + p2)

        if line_point1 is not None:
            p1 = line_point1.x, flipy(line_point1.y)
            p2 = mouse_pos.x, flipy(mouse_pos.y)
            pygame.draw.lines(screen, THECOLORS["black"], False, [p1, p2])

        for line in static_lines:
            body = line.body
            line.elasticity = 0.95
            pv1 = body.position + line.a.rotated(body.angle)
            pv2 = body.position + line.b.rotated(body.angle)
            p1 = pv1.x, flipy(pv1.y)
            p2 = pv2.x, flipy(pv2.y)
            pygame.draw.lines(screen, THECOLORS["black"], False, [p1, p2])

        ### Flip screen
        pygame.display.flip()
        clock.tick(50)
Exemplo n.º 13
0
    def _initialize_space(self):
        space = pymunk.Space()
        space.gravity = (0.0, -900)

        return space
def main(win, width, height):

    pygame.init()
    space = pm.Space()
    space.gravity = (0.0, 0.0)
    clock = pygame.time.Clock()
    fps = 120

    ROWS = 100
    grid = make_grid(ROWS, width)

    start = None
    end = None

    run = True
    while run:
        draw(win, grid, ROWS, width, height)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if pygame.mouse.get_pressed()[0]:  # LEFT
                pos = pygame.mouse.get_pos()
                row, col = get_clicked_pos(pos, ROWS, width)
                spot = grid[row][col]
                if not start and spot != end:
                    start = spot
                    start.make_start()

                elif not end and spot != start:
                    end = spot
                    end.make_end()

                elif spot != end and spot != start:
                    spot.make_barrier()

            elif pygame.mouse.get_pressed()[2]:  # RIGHT
                pos = pygame.mouse.get_pos()
                row, col = get_clicked_pos(pos, ROWS, width)
                spot = grid[row][col]
                spot.reset()
                if spot == start:
                    start = None
                elif spot == end:
                    end = None

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and start and end:
                    for row in grid:
                        for spot in row:
                            spot.update_neighbors(grid)

                    algorithm(lambda: draw(win, grid, ROWS, width, height),
                              grid, start, end)

                if event.key == pygame.K_c:
                    start = None
                    end = None
                    grid = make_grid(ROWS, width)

        space.step(1. / fps)

        clock.tick(fps)

        pygame.display.set_caption("fps: " + str(clock.get_fps()))

    pygame.quit()
Exemplo n.º 15
0
def main():
    if viz:
        pygame.init()
        screen = pygame.display.set_mode((1000, 1000))
        pygame.display.set_caption("Ball moving")
        clock = pygame.time.Clock()
        print(clock)
        draw_options = pymunk.pygame_util.DrawOptions(screen)

    space = pymunk.Space()
    space.gravity = (0.0, 0.0)

    objects = []

    # ticks_to_next_ball = 10

    if simtype == 'inertial':
        x_pos = random.randint(200, 800)
        y_pos = random.randint(200, 800)
        x_vel = random.randint(-500, 500)
        y_vel = random.randint(-500, 500)
        shape = add_ball(space, 1, 20, (x_pos, y_pos), (x_vel, y_vel), 0)

        objects.append(shape)

    elif simtype == 'circular':
        rotation_center_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        joint_x = random.randint(300, 700)
        joint_y = random.randint(300, 700)
        rotation_center_body.position = (joint_x, joint_y)

        x_pos = random.randint(200, 800)
        y_pos = random.randint(200, 800)
        vel = random.randint(200, 1200)

        string = (joint_x - x_pos, joint_y - y_pos)
        mag = math.sqrt(string[0]**2 + string[1]**2)
        velocity = (string[1] / mag * vel, string[0] / mag * vel)
        shape = add_ball(space, 1, 20, (x_pos, y_pos), velocity, 0)

        rotation_center_joint = pymunk.PinJoint(shape.body,
                                                rotation_center_body, (0, 0),
                                                (0, 0))
        space.add(rotation_center_joint)

        objects.append(shape)

    elif simtype == 'harmonic':
        harmonic_center_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        joint_x = random.randint(300, 700)
        joint_y = random.randint(300, 700)
        harmonic_center_body.position = (joint_x, joint_y)

        x_pos = random.randint(300, 700)
        y_pos = random.randint(300, 700)
        vel = random.randint(2, 20)

        string = (joint_x - x_pos, joint_y - y_pos)
        mag = math.sqrt(string[0]**2 + string[1]**2)
        velocity = (string[1] / mag * vel, string[0] / mag * vel)
        shape = add_ball(space, 1, 20, (x_pos, y_pos), velocity, 0)

        stiffness = random.randint(10, 120)
        harmonic_center_joint = pymunk.DampedSpring(shape.body,
                                                    harmonic_center_body,
                                                    (0, 0), (0, 0), 0,
                                                    stiffness, 0)
        space.add(harmonic_center_joint)

        objects.append(shape)

    else:
        sys.exit("ERROR: non-valid simulation type")

    locations = []
    timestep = 0
    while True:
        if not viz and timestep >= 100:
            break
        timestep += 1
        if viz:
            screen.fill((255, 255, 255))
            for event in pygame.event.get():
                if event.type == QUIT:
                    sys.exit(0)
                elif event.type == KEYDOWN and event.key == K_ESCAPE:
                    sys.exit(0)

        space.step(1 / 50.0)
        locations.append([obj.copy() for obj in objects])

        # objects_to_remove = []
        # for obj in objects:
        #     print (obj)
        #     if obj.body.position.y > 150:
        #         objects_to_remove.append(obj)

        # for obj in objects_to_remove:
        #     space.remove(obj, obj.body)
        #     objects.remove(obj)
        if viz:
            space.debug_draw(draw_options)
            pygame.display.flip()
            clock.tick(50)

    with open(os.path.join(data_folder, simtype + '_' + str(now) + '.pkl'),
              'wb') as f:
        pickle.dump(locations, f)
    def __init__(self, display_hidden=False):

        # Load sprite
        sprite = pygame.image.load("../ar19_q.png")
        self.sprite_img = pygame.transform.scale(sprite, (50, 50))
        self.sprites = []

        # Hide display
        self.show_sensors = not display_hidden
        self.draw_screen = not display_hidden

        # Physics stuff.
        self.space = pymunk.Space()
        self.space.gravity = pymunk.Vec2d(0., 0.)

        # Create the car.
        self.create_car(150, coordfix(600), 1.57)

        # This is all a mess of markers
        o1 = self.create_marker(100, coordfix(500), 10, THECOLORS["blue"])
        o2 = self.create_marker(200, coordfix(200), 10, THECOLORS["blue"])
        o3 = self.create_marker(400, coordfix(100), 10, THECOLORS["blue"])
        o4 = self.create_marker(600, coordfix(200), 10, THECOLORS["blue"])
        o5 = self.create_marker(700, coordfix(500), 10, THECOLORS["blue"])
        o6 = self.create_marker(950, coordfix(500), 10, THECOLORS["blue"])
        o7 = self.create_marker(1000, coordfix(200), 10, THECOLORS["blue"])
        o8 = self.create_marker(1400, coordfix(100), 10, THECOLORS["blue"])
        o9 = self.create_marker(1800, coordfix(200), 10, THECOLORS["blue"])
        o10 = self.create_marker(1800, coordfix(900), 10, THECOLORS["blue"])
        o11 = self.create_marker(1650, coordfix(1000), 10, THECOLORS["blue"])
        o12 = self.create_marker(1500, coordfix(900), 10, THECOLORS["blue"])
        o13 = self.create_marker(1500, coordfix(500), 10, THECOLORS["blue"])
        o14 = self.create_marker(1400, coordfix(400), 10, THECOLORS["blue"])
        o15 = self.create_marker(1300, coordfix(500), 10, THECOLORS["blue"])
        o16 = self.create_marker(1300, coordfix(700), 10, THECOLORS["blue"])
        o17 = self.create_marker(1100, coordfix(800), 10, THECOLORS["blue"])
        o18 = self.create_marker(825, coordfix(850), 10, THECOLORS["blue"])
        o19 = self.create_marker(500, coordfix(850), 10, THECOLORS["blue"])
        o20 = self.create_marker(100, coordfix(900), 10, THECOLORS["blue"])

        i1 = self.create_marker(500, coordfix(700), 10, THECOLORS["yellow"])
        i2 = self.create_marker(250, coordfix(700), 10, THECOLORS["yellow"])
        i3 = self.create_marker(250, coordfix(500), 10, THECOLORS["yellow"])
        i4 = self.create_marker(300, coordfix(300), 10, THECOLORS["yellow"])
        i5 = self.create_marker(400, coordfix(250), 10, THECOLORS["yellow"])
        i6 = self.create_marker(500, coordfix(300), 10, THECOLORS["yellow"])
        i7 = self.create_marker(550, coordfix(600), 10, THECOLORS["yellow"])
        i8 = self.create_marker(825, coordfix(700), 10, THECOLORS["yellow"])
        i9 = self.create_marker(1150, coordfix(600), 10, THECOLORS["yellow"])
        i10 = self.create_marker(1150, coordfix(300), 10, THECOLORS["yellow"])
        i11 = self.create_marker(1400, coordfix(250), 10, THECOLORS["yellow"])
        i12 = self.create_marker(1650, coordfix(300), 10, THECOLORS["yellow"])
        i13 = self.create_marker(1650, coordfix(800), 10, THECOLORS["yellow"])

        # Create lines
        self.static = [
            # Walls
            pymunk.Segment(self.space.static_body, (0, 1), (0, height), 1),
            pymunk.Segment(self.space.static_body, (1, height),
                           (width, height), 1),
            pymunk.Segment(self.space.static_body, (width - 1, height),
                           (width - 1, 1), 1),
            pymunk.Segment(self.space.static_body, (1, 1), (width, 1), 1),

            # Outer boundary
            pymunk.Segment(self.space.static_body, (o1.position),
                           (o2.position), 2),
            pymunk.Segment(self.space.static_body, (o2.position),
                           (o3.position), 2),
            pymunk.Segment(self.space.static_body, (o3.position),
                           (o4.position), 2),
            pymunk.Segment(self.space.static_body, (o4.position),
                           (o5.position), 2),
            pymunk.Segment(self.space.static_body, (o5.position),
                           (o6.position), 2),
            pymunk.Segment(self.space.static_body, (o6.position),
                           (o7.position), 2),
            pymunk.Segment(self.space.static_body, (o7.position),
                           (o8.position), 2),
            pymunk.Segment(self.space.static_body, (o8.position),
                           (o9.position), 2),
            pymunk.Segment(self.space.static_body, (o9.position),
                           (o10.position), 2),
            pymunk.Segment(self.space.static_body, (o10.position),
                           (o11.position), 2),
            pymunk.Segment(self.space.static_body, (o11.position),
                           (o12.position), 2),
            pymunk.Segment(self.space.static_body, (o12.position),
                           (o13.position), 2),
            pymunk.Segment(self.space.static_body, (o13.position),
                           (o14.position), 2),
            pymunk.Segment(self.space.static_body, (o14.position),
                           (o15.position), 2),
            pymunk.Segment(self.space.static_body, (o15.position),
                           (o16.position), 2),
            pymunk.Segment(self.space.static_body, (o16.position),
                           (o17.position), 2),
            pymunk.Segment(self.space.static_body, (o17.position),
                           (o18.position), 2),
            pymunk.Segment(self.space.static_body, (o18.position),
                           (o19.position), 2),
            pymunk.Segment(self.space.static_body, (o19.position),
                           (o20.position), 2),
            pymunk.Segment(self.space.static_body, (o20.position),
                           (o1.position), 2),

            # Inner boundary
            pymunk.Segment(self.space.static_body, (i1.position),
                           (i2.position), 2),
            pymunk.Segment(self.space.static_body, (i2.position),
                           (i3.position), 2),
            pymunk.Segment(self.space.static_body, (i3.position),
                           (i4.position), 2),
            pymunk.Segment(self.space.static_body, (i4.position),
                           (i5.position), 2),
            pymunk.Segment(self.space.static_body, (i5.position),
                           (i6.position), 2),
            pymunk.Segment(self.space.static_body, (i6.position),
                           (i7.position), 2),
            pymunk.Segment(self.space.static_body, (i7.position),
                           (i8.position), 2),
            pymunk.Segment(self.space.static_body, (i8.position),
                           (i9.position), 2),
            pymunk.Segment(self.space.static_body, (i9.position),
                           (i10.position), 2),
            pymunk.Segment(self.space.static_body, (i10.position),
                           (i11.position), 2),
            pymunk.Segment(self.space.static_body, (i11.position),
                           (i12.position), 2),
            pymunk.Segment(self.space.static_body, (i12.position),
                           (i13.position), 2),
            pymunk.Segment(self.space.static_body, (i1.position),
                           (i8.position), 2),
        ]
        for s in self.static:
            #s.sensor = 1
            s.friction = 1
            s.collision_type = 1
            s.color = THECOLORS['red']
        self.space.add(self.static)

        # Create checkpoints for scoring
        self.checkpoint = [
            pymunk.Segment(self.space.static_body, (o1.position),
                           (i3.position), 5),
            pymunk.Segment(self.space.static_body, (o2.position),
                           (i4.position), 5),
            pymunk.Segment(self.space.static_body, (o3.position),
                           (i5.position), 5),
            pymunk.Segment(self.space.static_body, (o4.position),
                           (i6.position), 5),
            pymunk.Segment(self.space.static_body, (o5.position),
                           (i7.position), 5),
            pymunk.Segment(self.space.static_body, (o6.position),
                           (i9.position), 5),
            pymunk.Segment(self.space.static_body, (o7.position),
                           (i10.position), 5),
            pymunk.Segment(self.space.static_body, (o8.position),
                           (i11.position), 5),
            pymunk.Segment(self.space.static_body, (o9.position),
                           (i12.position), 5),
            pymunk.Segment(self.space.static_body, (o10.position),
                           (i13.position), 5),
            pymunk.Segment(self.space.static_body, (o11.position),
                           (i13.position), 5),
            pymunk.Segment(self.space.static_body, (o12.position),
                           (i13.position), 5),
            pymunk.Segment(self.space.static_body, (o13.position),
                           (i12.position), 5),
            pymunk.Segment(self.space.static_body, (o14.position),
                           (i11.position), 5),
            pymunk.Segment(self.space.static_body, (o15.position),
                           (i10.position), 5),
            pymunk.Segment(self.space.static_body, (o16.position),
                           (i9.position), 5),
            pymunk.Segment(self.space.static_body, (o18.position),
                           (i8.position), 5),
            pymunk.Segment(self.space.static_body, (o19.position),
                           (i1.position), 5),
            pymunk.Segment(self.space.static_body, (o20.position),
                           (i2.position), 5),
        ]

        for c in self.checkpoint:
            c.sensor = 1
            c.collision_type = 4
            c.color = THECOLORS['green']
        self.space.add(self.checkpoint[0])

        self.score = 0
        self.counter = 0

        def checkpoint_hit(space, arbiter,
                           data):  # Do this if called by collision handler
            if self.counter < 18:  # If less than 18, remove current and place next checkpoint
                self.space.remove(self.checkpoint[self.counter])
                self.score += 1
                self.counter += 1
                self.space.add(self.checkpoint[self.counter])
            else:  # If less than 18, remove current and place next checkpoint
                self.space.remove(self.checkpoint[self.counter])
                self.counter = 0
                self.space.add(self.checkpoint[self.counter])
            return True

        # Pymunk collision for car and checkpoints
        ht = self.space.add_collision_handler(2, 4)
        ht.pre_solve = checkpoint_hit
Exemplo n.º 17
0
import pymunk
from pymunk import Vec2d


def to_pygame(p):
    """Small hack to convert pymunk to pygame coordinates"""
    return int(p.x), int(-p.y + 600)


pygame.init()
g_screen = pygame.display.set_mode((600, 600))
clock = pygame.time.Clock()
running = True

### Physics stuff
space = pymunk.Space(50)
space.gravity = (0.0, -900.0)

## Balls
balls = []

### walls
static_body = pymunk.Body()
static_lines = [
    pymunk.Segment(static_body, (150, 100.0), (50.0, 550.0), 1.0),
    pymunk.Segment(static_body, (450.0, 100.0), (550.0, 550.0), 1.0),
    pymunk.Segment(static_body, (50.0, 550.0), (300.0, 600.0), 1.0),
    pymunk.Segment(static_body, (300.0, 600.0), (550.0, 550.0), 1.0),
    pymunk.Segment(static_body, (300.0, 420.0), (400.0, 400.0), 1.0)
]
for line in static_lines:
Exemplo n.º 18
0
def main():

    pygame.init()
    screen = pygame.display.set_mode(display_size, display_flags)
    width, height = screen.get_size()

    def to_pygame(p):
        """Small hack to convert pymunk to pygame coordinates"""
        return int(p.x), int(-p.y + height)

    def from_pygame(p):
        return to_pygame(p)

    clock = pygame.time.Clock()
    running = True
    font = pygame.font.Font(None, 16)

    ### Physics stuff
    space = pm.Space()
    space.gravity = (0.0, -1900.0)
    space.damping = 0.999  # to prevent it from blowing up.
    mouse_body = pm.Body(body_type=pm.Body.KINEMATIC)

    bodies = []
    for x in range(-100, 150, 50):
        x += width / 2
        offset_y = height / 2
        mass = 10
        radius = 25
        moment = pm.moment_for_circle(mass, 0, radius, (0, 0))
        body = pm.Body(mass, moment)
        body.position = (x, -125 + offset_y)
        body.start_position = Vec2d(body.position)
        shape = pm.Circle(body, radius)
        shape.elasticity = 0.9999999
        space.add(body, shape)
        bodies.append(body)
        pj = pm.PinJoint(space.static_body, body, (x, 125 + offset_y), (0, 0))
        space.add(pj)

    reset_bodies(space)
    selected = None

    if not is_interactive:
        pygame.time.set_timer(USEREVENT + 1, 70000)  # apply force
        pygame.time.set_timer(USEREVENT + 2, 120000)  # reset
        pygame.event.post(pygame.event.Event(USEREVENT + 1))
        pygame.mouse.set_visible(False)

    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, "newtons_cradle.png")

            if event.type == pygame.USEREVENT + 1:
                r = random.randint(1, 4)
                for body in bodies[0:r]:
                    body.apply_impulse_at_local_point((-6000, 0))
            if event.type == pygame.USEREVENT + 2:
                reset_bodies(space)

            elif event.type == KEYDOWN and event.key == K_r and is_interactive:
                reset_bodies(space)
            elif event.type == KEYDOWN and event.key == K_f and is_interactive:
                r = random.randint(1, 4)
                for body in bodies[0:r]:
                    body.apply_impulse_at_local_point((-6000, 0))

            elif event.type == MOUSEBUTTONDOWN and is_interactive:
                if selected != None:
                    space.remove(selected)
                p = from_pygame(Vec2d(event.pos))
                hit = space.point_query_nearest(p, 0, pm.ShapeFilter())
                if hit != None:
                    shape = hit.shape
                    rest_length = mouse_body.position.get_distance(
                        shape.body.position)
                    ds = pm.DampedSpring(mouse_body, shape.body, (0, 0),
                                         (0, 0), rest_length, 1000, 10)
                    space.add(ds)
                    selected = ds

            elif event.type == MOUSEBUTTONUP and is_interactive:
                if selected != None:
                    space.remove(selected)
                    selected = None

            elif event.type == KEYDOWN:
                running = False
            elif event.type == MOUSEBUTTONDOWN:
                running = False

        mpos = pygame.mouse.get_pos()
        p = from_pygame(Vec2d(mpos))
        mouse_body.position = p

        ### Clear screen
        screen.fill(THECOLORS["black"])

        ### Draw stuff
        for c in space.constraints:
            pv1 = c.a.position + c.anchor_a
            pv2 = c.b.position + c.anchor_b
            p1 = to_pygame(pv1)
            p2 = to_pygame(pv2)
            pygame.draw.aalines(screen, THECOLORS["lightgray"], False,
                                [p1, p2])

        for ball in space.shapes:
            p = to_pygame(ball.body.position)
            drawcircle(screen, ball.color, p, int(ball.radius), 0)
            #pygame.draw.circle(screen, ball.color, p, int(ball.radius), 0)

        ### Update physics
        fps = 50
        iterations = 25
        dt = 1.0 / float(fps) / float(iterations)
        for x in range(
                iterations):  # 10 iterations to get a more stable simulation
            space.step(dt)

        ### Flip screen
        if is_interactive:
            screen.blit(
                font.render("fps: " + str(clock.get_fps()), 1,
                            THECOLORS["white"]), (0, 0))
            screen.blit(
                font.render("Press left mouse button and drag to interact", 1,
                            THECOLORS["darkgrey"]), (5, height - 35))
            screen.blit(
                font.render("Press R to reset, any other key to quit", 1,
                            THECOLORS["darkgrey"]), (5, height - 20))

        pygame.display.flip()
        clock.tick(fps)
Exemplo n.º 19
0
    def __init__(self, window, level):
        super(Pymunk_Scene, self).__init__(window, level)
        self.screen_resolution = window.width, window.height
        self.window = window

        self.debug_batch = pyglet.graphics.Batch()
        self.normal_batch = pyglet.graphics.Batch()
        self.ui_batch = pyglet.graphics.Batch()

        # The common_group parent keeps groups from
        # overlapping on accident. Silly Pyglet!
        common_group = pyglet.graphics.OrderedGroup(1)
        self.ordered_group10 = pyglet.graphics.OrderedGroup(
            10, parent=common_group)
        self.ordered_group9 = pyglet.graphics.OrderedGroup(9,
                                                           parent=common_group)
        self.ordered_group8 = pyglet.graphics.OrderedGroup(8,
                                                           parent=common_group)
        self.ordered_group7 = pyglet.graphics.OrderedGroup(7,
                                                           parent=common_group)
        self.ordered_group6 = pyglet.graphics.OrderedGroup(6,
                                                           parent=common_group)
        self.ordered_group5 = pyglet.graphics.OrderedGroup(5,
                                                           parent=common_group)
        self.ordered_group4 = pyglet.graphics.OrderedGroup(4,
                                                           parent=common_group)
        self.ordered_group3 = pyglet.graphics.OrderedGroup(3,
                                                           parent=common_group)
        self.ordered_group2 = pyglet.graphics.OrderedGroup(2,
                                                           parent=common_group)
        self.ordered_group1 = pyglet.graphics.OrderedGroup(1,
                                                           parent=common_group)

        self.grav = (0, -600)

        self.space = pymunk.Space()
        self.space.sleep_time_threshold = 1
        self.space.gravity = self.grav

        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        glHint(GL_POINT_SMOOTH_HINT, GL_FASTEST)

        glPointSize(2)
        glLineWidth(1)  #(1.25)

        self.camera = camera.Camera(self.screen_resolution,
                                    pos_rate=(1, 1, 1),
                                    target_rate=(1, 1, 1),
                                    angle_rate=5,
                                    fov_rate=1)

        #### Level ####
        self.level = level
        self.level.define_level(self)
        #### Level ####

        self.pymunk_util = pyglet_util.PymunkUtil2(self)
        self.pymunk_util.setup()

        self.keys_held = []

        self.debug = True
Exemplo n.º 20
0
def main():
    # PyGame init
    pygame.init()
    started = False
    global numLives
    numLives = 2
    gameOver = False

    screen = pygame.display.set_mode((width, height), RESIZABLE)
    clock = pygame.time.Clock()
    running = True

    # Display some text
    font = pygame.font.SysFont("Arial", 30)
    text = ""
    score = 0

    # Physics stuff
    space = pymunk.Space()
    space.gravity = (0, -600)
    space.damping = 0.9

    intro = pygame.Surface((680, 910))

    intro.fill(transport_color)

    spring = add_spring(space)
    block_up = False

    global block
    block = spawn_block(space)
    rotary_spring, rotary_spring2 = add_paddles(space)

    image = pygame.image.load("background.jpg")

    # Start game

    global ballsinplay
    ballsinplay += 1

    setup_level(space)

    global temp_ballbody
    temp_ballbody = spawn_ball(space, (600, 300), (0, 0))
    while running:
        global score
        global gameOver
        check_powerup(space)
        check_block(temp_ballbody)
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):
                running = False
            elif event.type == KEYDOWN and event.key == K_SPACE:
                block_up = False
                spring.rest_length = 10

            elif event.type == KEYUP and event.key == K_SPACE:
                spring.rest_length = 150

                block_up = True

            if event.type == KEYDOWN and event.key == K_LEFT:
                rotary_spring.rest_angle = math.pi / 5
            if event.type == KEYUP and event.key == K_LEFT:
                rotary_spring.rest_angle = 3 * math.pi / 5
            if event.type == KEYDOWN and event.key == K_RIGHT:
                rotary_spring2.rest_angle = -6 * math.pi / 5
            if event.type == KEYUP and event.key == K_RIGHT:
                rotary_spring2.rest_angle = -8 * math.pi / 5
            if event.type == MOUSEBUTTONDOWN:
                started = True
                if gameOver:
                    gameOver = False
                    numLives = 2
                    space.add(lives[0])
                    space.add(lives[1])
                    space.add(lives[2])
                    score = 0

        if numLives <= -1:
            gameOver = True

        # Clear screen
        screen.fill(screen_color)

        # Draw stuff

        # Update physics
        fps = 60
        step = 1. / fps

        for x in range(5):
            space.step(step / 5)

        # Info and flip screen
        screen.blit(image, (0, 0))
        largeText = pygame.font.Font('freesansbold.ttf', 205)

        screen.blit(
            font.render("fps: " + str(clock.get_fps()), 1, THECOLORS["white"]),
            (0, height - 25))
        screen.blit(font.render("Score: " + str(score), 1, THECOLORS["white"]),
                    (0, 0))
        draw(space)
        if not started:
            screen.blit(intro, (0, 0))
            screen.blit(font.render("Pinball ", 1, THECOLORS["white"]),
                        (300, 455))
        if gameOver:
            screen.blit(intro, (0, 0))
            screen.blit(font.render("Game Over", 1, THECOLORS["white"]),
                        (300, 455))
            screen.blit(
                font.render("Score:  " + str(score), 1, THECOLORS["white"]),
                (300, 490))

        pygame.display.flip()
        clock.tick(fps)
Exemplo n.º 21
0
 def __init__(self, *args, **kwargs):
     self.space = pm.Space()
     super(SpaceWorld, self).__init__(*args, **kwargs)
Exemplo n.º 22
0
def main():
    global amountofballs
    global mass
    global radius
    global bodyheight
    global bodyradius

    amountofballs = 100
    bodyradius = 50
    bodyheight = 150
    mass = 50
    radius = 10

    pygame.init()
    screen = pygame.display.set_mode((600, 600))
    pygame.display.set_caption("Hourglass Simulation")
    clock = pygame.time.Clock()

    space = pymunk.Space()
    space.gravity = (0.0, -900.0)
    draw_options = pymunk.pygame_util.DrawOptions(screen)
    hg = add_hourglass(space)
    space.debug_draw(draw_options)
    balls = []
    ballsxposition = []
    ballsxposition.append(amountofballs * 325)
    ballstimeposition = []
    ballstimeposition.append(0.0)
    temp = 0
    balltimecount = 0
    firsttime = 0
    sleeptime = 5

    for i in range(amountofballs):
        ball_shape = add_ball(space)
        balls.append(ball_shape)
    space.debug_draw(draw_options)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                printballdata(ballsxposition, ballstimeposition)
                pygame.display.quit()
                pygame.quit()
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    printballdata(ballsxposition, ballstimeposition)
                    pygame.display.quit()
                    pygame.quit()

        sleeptime -= 1
        # body.position.x and .y give different results
        if sleeptime <= 0:
            for i in range(amountofballs):
                for j in range(amountofballs):
                    temp += balls[j].body.position.x
                if firsttime == 0 or ballstimeposition[
                        balltimecount] != pygame.time.get_ticks():
                    ballsxposition.append(temp)
                    ballstimeposition.append(pygame.time.get_ticks())
                    balltimecount += 1
                    firsttime += 1
                temp = 0
            sleeptime = 10

        space.step(1 / 80)
        screen.fill((255, 255, 255))
        space.debug_draw(draw_options)
        pygame.display.flip()
        clock.tick(25)
Exemplo n.º 23
0
    def do_init(self,
                寬=common.WIN_WIDTH,
                高=common.WIN_HEIGHT,
                title=common.TITLE):
        common.stage = self
        common.舞台 = self
        common.is_engine_created = True
        __main__.stage = self
        __main__.舞台 = self
        __main__.key = arcade.key

        self.pause_simulate = False
        self.slow_simulate = False

        if common.WIN_MIN_WIDTH < 寬 < common.WIN_MAX_WIDTH:
            self.win_width = round(寬, 0)
        elif 寬 < common.WIN_MIN_WIDTH:
            self.win_width = common.WIN_MIN_WIDTH
        elif 寬 > common.WIN_MAX_WIDTH:
            self.win_width = common.WIN_MAX_WIDTH

        if common.WIN_MIN_HEIGHT < 高 < common.WIN_MAX_HEIGHT:
            self.win_height = round(高, 0)
        elif 高 < common.WIN_MIN_HEIGHT:
            self.win_height = common.WIN_MIN_HEIGHT
        elif 高 > common.WIN_MAX_HEIGHT:
            self.win_height = common.WIN_MAX_HEIGHT

        #self.win_width = round(寬,0) if 寬 > common.MIN_WIDTH else common.MIN_WIDTH

        #self.win_height = round(高,0) if 高 > common.MIN_HEIGHT else common.MIN_HEIGHT

        #print('stage size: ', self.win_width, self.win_height)
        #__main__.中央座標 = (self.win_width, self.win_height//2)

        self.title = title
        self.set_update_rate(common.DT_UPDATE)
        self.circle_list = []
        self.poly_list = []
        self.segment_list = []
        self.is_engine_running = False

        # status line
        self.font = ('C:/Windows/Fonts/msjh.ttc', 'arial')

        if hasattr(__main__, '__file__'):
            self.terrain_filename = __main__.__file__ + '.地形'
        else:
            # in shell , do not save terrain
            self.terrain_filename = None

        # retain mouse postion while mouse motion event
        self.mouse_x = 0
        self.mouse_y = 0

        # pymunk space
        self.space = pymunk.Space()
        self.space.gravity = common.GRAVITY
        self.sleep_time_threshold = 1

        self.obj_filter = pymunk.ShapeFilter(mask=common.CATE_CIRCLE
                                             | common.CATE_BOX)

        # info
        # self.info = {}
        # self.info['gravity_x'] = 0
        # self.info['gravity_y'] = 0
        # self.info['mouse_x'] = 0
        # self.info['mouse_y'] = 0
        # self.info['obj_num'] = 0
        # self.info_text = ''
        #self.info_update()

        # infomation update (can't to fast because text create burden)
        #arcade.schedule(self.info_update, 0.4)

        # assist
        self.dot_mark = DotMark()
        self.seg_add_assist = SegmentAddAssist()
        self.seg_remove_assist = SegmentRemoveAssist()
        self.arrow_assist = ArrowAssist()
        self.coor_assist = CoordinateAssist()

        hole_handler = self.space.add_collision_handler(
            COLLITYPE_DEFAULT, COLLITYPE_HOLE)

        hole_handler.begin = self.hole_begin_callback
        hole_handler.pre_solve = self.hole_pre_solve_callback
        hole_handler.post_solve = self.hole_post_solve_callback
        hole_handler.separate = self.hole_separate_callback

        # custom event handler
        self.user_mouse_press_handler = None
        self.user_mouse_release_handler = None
        self.user_key_press_handler = None
        self.user_key_release_handler = None
        self.user_arrow_launch_handler = None
        self.user_mouse_drag_handler = None
        self.user_object_click_handler = None
        # self.user_mouse_press_handler = lambda x, y :  None
        # self.user_mouse_release_handler = lambda x, y: None
        # self.user_key_press_handler = lambda key: None
        # self.user_key_release_handler = lambda key: None
        # self.user_arrow_launch_handler = lambda vector,start_pos :  None

        print(f"建立舞台(寬{self.win_width}x高{self.win_height})")

        if not self.terrain_filename or not self.load_terrain():
            #default terrain
            self.新增線段((50, 50), (self.win_width - 50, 50), 6)
            print('使用預設地形')
Exemplo n.º 24
0
    def __init__(
        self,
        ind_reward=0.8,
        group_reward=0.1,
        other_group_reward=0.1,
        prospec_find_gold_reward=1,
        prospec_handoff_gold_reward=1,
        banker_receive_gold_reward=1,
        banker_deposit_gold_reward=1,
        max_frames=900,
    ):
        EzPickle.__init__(self, ind_reward, group_reward, other_group_reward,
                          prospec_find_gold_reward,
                          prospec_handoff_gold_reward,
                          banker_receive_gold_reward,
                          banker_deposit_gold_reward, max_frames)
        if ind_reward + group_reward + other_group_reward != 1.0:
            raise ValueError(
                "Individual reward, group reward, and other group reward should "
                "add up to 1.0")

        self.num_agents = const.NUM_AGENTS
        self.agents = []

        self.sprite_list = [
            "bankers/0.png",
            "bankers/1.png",
            "bankers/2.png",
            "prospector.png",
        ]
        self.max_frames = max_frames

        pg.init()
        self.seed()
        self.clock = pg.time.Clock()
        self.closed = False

        self.background = Background(self.rng)

        self.space = pm.Space()
        self.space.gravity = Vec2d(0.0, 0.0)
        self.space.damping = 0.0

        self.all_sprites = pg.sprite.RenderUpdates()
        self.gold = []

        self.water = Water(const.WATER_INFO[0], const.WATER_INFO[1],
                           self.space, self.rng)

        # Generate random positions for each prospector agent
        prospector_info = [(i, utils.rand_pos("prospector", self.rng))
                           for i in range(const.NUM_PROSPECTORS)]
        self.prospectors = {}
        for num, pos in prospector_info:
            prospector = Prospector(pos, self.space, num, self.all_sprites)
            identifier = f"prospector_{num}"
            self.prospectors[identifier] = prospector
            self.agents.append(identifier)

        banker_info = [(i, utils.rand_pos("banker", self.rng))
                       for i in range(const.NUM_BANKERS)]
        self.bankers = {}
        for num, pos in banker_info:
            banker = Banker(pos, self.space, num, self.all_sprites)
            identifier = f"banker_{num}"
            self.bankers[identifier] = banker
            self.agents.append(identifier)

        self.banks = []
        for pos, verts in const.BANK_INFO:
            self.banks.append(Bank(pos, verts, self.space, self.all_sprites))

        self.fences = []
        for w_type, s_pos, b_pos, verts in const.FENCE_INFO:
            f = Fence(w_type, s_pos, b_pos, verts, self.space)
            self.fences.append(f)

        self.metadata = {"render.modes": ["human"]}

        self.action_spaces = {}
        for p in self.prospectors:
            self.action_spaces[p] = spaces.Box(low=np.float32(-1.0),
                                               high=np.float32(1.0),
                                               shape=(3, ))

        for b in self.bankers:
            self.action_spaces[b] = spaces.Box(low=np.float32(-1.0),
                                               high=np.float32(1.0),
                                               shape=(2, ))

        self.observation_spaces = {}
        self.last_observation = {}

        for p in self.prospectors:
            self.last_observation[p] = None
            self.observation_spaces[p] = spaces.Box(
                low=0,
                high=255,
                shape=const.PROSPEC_OBSERV_SHAPE,
                dtype=np.uint8)

        for b in self.bankers:
            self.last_observation[b] = None
            self.observation_spaces[b] = spaces.Box(
                low=0,
                high=255,
                shape=const.BANKER_OBSERV_SHAPE,
                dtype=np.uint8)

        self._agent_selector = agent_selector(self.agents)
        self.agent_selection = self._agent_selector.next()
        self.reset()

        # Collision Handler Functions --------------------------------------------
        # Water to Prospector
        def add_gold(arbiter, space, data):
            prospec_shape = arbiter.shapes[0]
            prospec_body = prospec_shape.body

            position = arbiter.contact_point_set.points[0].point_a
            normal = arbiter.contact_point_set.normal

            prospec_body.position = position - (24 * normal)
            prospec_body.velocity = (0, 0)

            for k, v in self.prospectors.items():
                if v.body is prospec_body:
                    self.rewards[k] += ind_reward * prospec_find_gold_reward
                else:
                    self.rewards[k] += group_reward * prospec_find_gold_reward

            for k in self.bankers:
                self.rewards[
                    k] += other_group_reward * prospec_find_gold_reward

            if prospec_body.nugget is None:
                position = arbiter.contact_point_set.points[0].point_a

                gold = Gold(position, prospec_body, self.space,
                            self.all_sprites)
                self.gold.append(gold)
                prospec_body.nugget = gold

            return True

        # Prospector to banker
        def handoff_gold_handler(arbiter, space, data):
            banker_shape, gold_shape = arbiter.shapes[0], arbiter.shapes[1]

            gold_sprite = None
            for g in self.gold:
                if g.id == gold_shape.id:
                    gold_sprite = g

            # gold_sprite is None if gold was handed off to the bank right before
            # calling this collision handler
            # This collision handler is only for prospector -> banker gold handoffs
            if (gold_sprite is None
                    or gold_sprite.parent_body.sprite_type != "prospector"):
                return False

            banker_body = banker_shape.body
            prospec_body = gold_sprite.parent_body

            for k, v in self.prospectors.items():
                self.rewards[
                    k] += other_group_reward * banker_receive_gold_reward
                if v.body is prospec_body:
                    self.rewards[k] += prospec_handoff_gold_reward
                else:
                    self.rewards[
                        k] += group_reward * prospec_handoff_gold_reward

            for k, v in self.bankers.items():
                self.rewards[
                    k] += other_group_reward * prospec_handoff_gold_reward
                if v.body is banker_body:
                    self.rewards[k] += banker_receive_gold_reward
                else:
                    self.rewards[
                        k] += group_reward * banker_receive_gold_reward

            normal = arbiter.contact_point_set.normal
            # Correct the angle because banker's head is rotated pi/2
            corrected = utils.normalize_angle(banker_body.angle +
                                              (math.pi / 2))
            normalized_normal = utils.normalize_angle(normal.angle)
            if (corrected - const.BANKER_HANDOFF_TOLERANCE <= normalized_normal
                    <= corrected + const.BANKER_HANDOFF_TOLERANCE):
                gold_sprite.parent_body.nugget = None

                gold_sprite.parent_body = banker_body
                banker_body.nugget = gold_sprite
                banker_body.nugget_offset = normal.angle

            return True

        # Banker to bank
        def gold_score_handler(arbiter, space, data):
            gold_shape, _ = arbiter.shapes[0], arbiter.shapes[1]

            for g in self.gold:
                if g.id == gold_shape.id:
                    gold_class = g

            if gold_class.parent_body.sprite_type == "banker":
                self.space.remove(gold_shape, gold_shape.body)
                gold_class.parent_body.nugget = None
                banker_body = gold_class.parent_body

                for k, v in self.bankers.items():
                    if v.body is banker_body:
                        self.rewards[k] += banker_deposit_gold_reward
                    else:
                        self.rewards[
                            k] += group_reward * banker_deposit_gold_reward

                for k in self.prospectors:
                    self.rewards[
                        k] += other_group_reward * banker_deposit_gold_reward

                self.gold.remove(gold_class)
                self.all_sprites.remove(gold_class)

            return False

        # Prevent prospector motion lag from colliding with gold nugget
        def prospec_gold_handler(arbiter, space, data):
            return False

        def boundary_collision_handler(arbiter, space, data):
            ps = arbiter.contact_point_set
            arbiter.shapes[0].body.position += ps.normal * (
                ps.points[0].distance + 1)

        # Create the collision event generators
        gold_dispenser = self.space.add_collision_handler(
            CollisionTypes.PROSPECTOR, CollisionTypes.WATER)

        gold_dispenser.begin = add_gold

        handoff_gold = self.space.add_collision_handler(
            CollisionTypes.BANKER, CollisionTypes.GOLD)

        handoff_gold.begin = handoff_gold_handler

        gold_score = self.space.add_collision_handler(CollisionTypes.GOLD,
                                                      CollisionTypes.BANK)

        gold_score.begin = gold_score_handler

        prospec_gold_collision = self.space.add_collision_handler(
            CollisionTypes.PROSPECTOR, CollisionTypes.GOLD)

        prospec_gold_collision.begin = prospec_gold_handler

        pros_bound_coll = self.space.add_wildcard_collision_handler(
            CollisionTypes.PROSPECTOR)
        pros_bound_coll.post_solve = boundary_collision_handler

        bank_bound_coll = self.space.add_wildcard_collision_handler(
            CollisionTypes.BANKER)
        bank_bound_coll.post_solve = boundary_collision_handler
Exemplo n.º 25
0
            key.UP: 'p2Up',
            key.DOWN: 'p2Down',

            key.F: 'p3Left',
            key.H: 'p3Right',
            key.T: 'p3Up',
            key.G: 'p3Down',

            key.J: 'p4Left',
            key.L: 'p4Right',
            key.I: 'p4Up',
            key.K: 'p4Down'
        }
}

space = pm.Space()
#space.gravity = Vec2d(0.0, -900.0)

batch = pyglet.graphics.Batch()

# Controls movement
upForce = 10
upSpeed = 5
sideForce = 10
sideSpeed = 5
sideDirectionMult = 10
upDirectionMult = 10
wallImpactForce = 200 #4500
playerImpactForceMult = 300

playerCrownScale = 1.5
Exemplo n.º 26
0
def main():
    pygame.joystick.init()
    controller = pygame.joystick.Joystick(0)
    controller.init()
    global restart
    restart = True
    while restart:
        restart = False
        pygame.font.init()
        myfont = pygame.font.SysFont('Comic Sans MS', 30)
        textsurface = myfont.render('Some Text', False, (0, 0, 0))

        pygame.init()
        screen = pygame.display.set_mode((1200, 680))
        pygame.display.set_caption("Joints. Just wait and the L will tip over")
        clock = pygame.time.Clock()

        space = pymunk.Space()
        global is_end
        is_end = False

        def set_tru(a, b, c):
            global is_end
            is_end = True

        def set_tru2(a, b, c):
            global restart
            restart = True

        space.add_collision_handler(1, 2).begin = set_tru
        space.add_collision_handler(1, 9).begin = set_tru2
        space.gravity = (0.0, -900.0)
        space.sleep_time_threshold = 1

        balls = []
        draw_options = pymunk.pygame_util.DrawOptions(screen)

        body = pymunk.Body(mass=0, moment=0, body_type=pymunk.Body.STATIC)
        shape = pymunk.Segment(body, (0, 0), (2000, 0), 5)
        body.position = (0, 0)

        shape6 = pymunk.Segment(body, (500, 200), (900, 200), 5)
        shape6.friction = 0.9
        space.add(shape6)

        shape6 = pymunk.Segment(body, (500, 200), (500, 690), 5)
        shape6.friction = 0.9
        space.add(shape6)

        shape6 = pymunk.Segment(body, (1100, 0), (1200, 100), 5)
        shape6.friction = 0.9
        #space.add(shape6)
        shape6.color = (250, 0, 0)
        shape6.collision_type = 9

        shape6 = pymunk.Segment(body, (0, 0), (0, 800), 5)
        shape6.friction = 0.9
        space.add(shape6)
        shape6 = pymunk.Segment(body, (0, 0), (1200, 0), 5)
        shape6.friction = 0.9
        space.add(shape6)
        shape6 = pymunk.Segment(body, (1200, 0), (1200, 800), 5)
        shape6.friction = 0.9
        space.add(shape6)
        shape6 = pymunk.Segment(body, (0, 800), (1200, 800), 5)
        shape6.friction = 0.9
        space.add(shape6)

        segments = [(-10 / 2, 100 / 2), (10 / 2, 100 / 2), (-100 / 2, 0 / 2),
                    (100 / 2, 0 / 2)]
        body1 = pymunk.Body(mass=0, moment=0, body_type=pymunk.Body.DYNAMIC)
        shape1 = pymunk.Poly(body1, segments)
        shape1.density = 1
        shape1.collision_type = 1

        body2 = pymunk.Body(mass=0, moment=0, body_type=pymunk.Body.DYNAMIC)
        shape2 = pymunk.Poly(body2, segments)
        shape2.density = 1
        #shape2.color = (255, 0, 0)
        shape2.collision_type = 1

        shape1.friction = 1
        shape2.friction = 1
        shape.friction = 1

        body1.position = (200, 150)
        body2.position = (200, 100)
        body2.angle = 3.1415926535897932

        space.add(body1, shape1)
        space.add(body2, shape2)

        def add_circle(x, y):
            body3 = pymunk.Body(mass=1, moment=1, body_type=pymunk.Body.STATIC)
            body3.position = (x, y)
            crl = pymunk.Circle(body3, 80)
            crl.collision_type = 2
            space.add(body3, crl)

        add_circle(800, 400)

        #cs = pymunk.constraint.SlideJoint(body1, body2, (-10,0), (10,0), 0, 100)
        #cs4 = pymunk.constraint.SlideJoint(body1, body2, (10,0), (-10,0), 0, 100)
        spring_f = 100000 * 2 * 2 * 2 * 2 * 2
        spring_d = 10000 * 2
        cs2 = pymunk.constraint.DampedSpring(body1, body2, (-50, 0), (50, 0),
                                             30, spring_f, spring_d)
        cs3 = pymunk.constraint.DampedSpring(body1, body2, (50, 0), (-50, 0),
                                             30, spring_f, spring_d)
        cs5 = pymunk.constraint.GrooveJoint(body1, body2, (10, 0), (10, -100),
                                            (-10, 0))
        cs6 = pymunk.constraint.GrooveJoint(body1, body2, (-10, 0),
                                            (-10, -100), (10, 0))
        #space.add(cs, cs2)
        space.add(cs2, cs3, cs5, cs6)

        space.add(body, shape)

        ticks_to_next_ball = 10
        max_jump = 150

        start_time = time.time()
        game_time = 180
        while True:
            for event in pygame.event.get():
                if event.type == pc.QUIT:
                    sys.exit(0)
                elif event.type == pc.KEYDOWN and event.key == pc.K_ESCAPE:
                    sys.exit(0)

                elif event.type == pc.KEYDOWN and event.key == 97:
                    cs2.rest_length = 15
                elif event.type == pc.KEYDOWN and event.key == 100:
                    cs3.rest_length = 15
                elif event.type == pc.KEYUP and event.key == 97:
                    cs2.rest_length = 50 + 10
                elif event.type == pc.KEYUP and event.key == 100:
                    cs3.rest_length = 50 + 10
                elif event.type == pc.KEYDOWN and event.key == 98:
                    cs3.rest_length = 50 + 30
                    cs2.rest_length = 50 + 30
                elif event.type == pc.KEYDOWN and event.key == 114:
                    restart = True
                    break
                elif event.type == 7 and event.axis == 5:
                    #right
                    jv = 1 - (event.value + 1) / 2
                    cs2.rest_length = 15 + jv * 65
                elif event.type == 7 and event.axis == 2:
                    #left
                    jv = 1 - (event.value + 1) / 2
                    cs3.rest_length = 15 + jv * 65
                else:
                    pass
                    #print(event.type)
                    #print(event.value)
            if restart:
                break
            #if event.type == pc
            #print(pc.JOYAXISMOTION)
            #print(event)
            #print(event.type)
            #print(event.value)
            #print(event.axis)
            #5/3

            space.step(1 / 50.0)
            #space.step(1/500.0)
            cur_max = max(body1.position[1], body2.position[1])
            #if  cur_max > max_jump:
            #print("NEW MAX JUMP:", cur_max)
            #max_jump = cur_max

            screen.fill((255, 255, 255))
            space.debug_draw(draw_options)
            finished_time = time.time()
            time_left = game_time - (finished_time - start_time)

            textsurface = myfont.render(f"TIME: {time_left:.3f}", False,
                                        (0, 0, 0))
            screen.blit(textsurface, (0, 0))
            pygame.display.flip()
            clock.tick(50)
            if is_end:
                print("end")
                break
    #finished_time = time.time()
    print("FINISHED FOR:", (finished_time - start_time))
Exemplo n.º 27
0
def main():
    ### PyGame init
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    clock = pygame.time.Clock()
    running = True
    font = pygame.font.SysFont("Arial", 16)

    ### Physics stuff
    space = pymunk.Space()
    space.gravity = 0, -1000
    # walls - the left-top-right walls
    static = [
        pymunk.Segment(space.static_body, (50, 50), (50, 550), 5),
        pymunk.Segment(space.static_body, (50, 550), (650, 550), 5),
        pymunk.Segment(space.static_body, (650, 550), (650, 50), 5),
        pymunk.Segment(space.static_body, (50, 50), (650, 50), 5)
    ]

    b2 = pymunk.Body()
    static.append(pymunk.Circle(b2, 30))
    b2.position = 300, 400

    for s in static:
        s.friction = 1.
        s.group = 1
    space.add(static)

    # "Cannon" that can fire arrows
    cannon_body = pymunk.Body(pymunk.inf, pymunk.inf)
    cannon_shape = pymunk.Circle(cannon_body, 25)
    cannon_shape.sensor = True
    cannon_body.position = 100, 100
    space.add(cannon_shape)

    arrow_body, arrow_shape = create_arrow()
    space.add(arrow_shape)

    space.add_collision_handler(0, 1, post_solve=post_solve_arrow_hit)

    flying_arrows = []

    while running:
        for event in pygame.event.get():
            if event.type == QUIT or \
                event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                start_time = pygame.time.get_ticks()
            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, "arrows.png")
            elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
                end_time = pygame.time.get_ticks()

                diff = end_time - start_time
                power = max(min(diff, 1000), 10) * 1.5
                impulse = power * Vec2d(1, 0)
                arrow_body.apply_impulse(impulse.rotated(arrow_body.angle))

                space.add(arrow_body)
                flying_arrows.append(arrow_body)

                arrow_body, arrow_shape = create_arrow()
                space.add(arrow_shape)

        keys = pygame.key.get_pressed()

        speed = 2.5
        if (keys[K_UP]):
            cannon_body.position += Vec2d(0, 1) * speed
        if (keys[K_DOWN]):
            cannon_body.position += Vec2d(0, -1) * speed
        if (keys[K_LEFT]):
            cannon_body.position += Vec2d(-1, 0) * speed
        if (keys[K_RIGHT]):
            cannon_body.position += Vec2d(1, 0) * speed

        mouse_position = from_pygame(Vec2d(pygame.mouse.get_pos()), screen)
        cannon_body.angle = (mouse_position - cannon_body.position).angle
        # move the unfired arrow together with the cannon
        arrow_body.position = cannon_body.position + Vec2d(
            cannon_shape.radius + 40, 0).rotated(cannon_body.angle)
        arrow_body.angle = cannon_body.angle

        for flying_arrow in flying_arrows:
            drag_constant = 0.0002
            pointing_direction = Vec2d(1, 0).rotated(flying_arrow.angle)
            flight_direction = Vec2d(flying_arrow.velocity)
            flight_speed = flight_direction.normalize_return_length()
            dot = flight_direction.dot(pointing_direction)
            # (1-abs(dot)) can be replaced with (1-dot) to make arrows turn around even when fired straight up.
            # Might not be as accurate, but maybe look better.
            drag_force_magnitude = (
                1 -
                abs(dot)) * flight_speed**2 * drag_constant * flying_arrow.mass

            arrow_tail_position = Vec2d(-50, 0).rotated(flying_arrow.angle)
            flying_arrow.apply_impulse(
                drag_force_magnitude * -flight_direction, arrow_tail_position)

            flying_arrow.angular_velocity *= 0.9

        ### Clear screen
        screen.fill(pygame.color.THECOLORS["black"])

        ### Draw stuff
        draw(screen, space)

        # Power meter
        if pygame.mouse.get_pressed()[0]:
            current_time = pygame.time.get_ticks()
            diff = current_time - start_time
            power = max(min(diff, 1000), 10)
            h = power / 2
            pygame.draw.line(screen, pygame.color.THECOLORS["red"], (30, 550),
                             (30, 550 - h), 10)

        # Info and flip screen
        screen.blit(
            font.render("fps: " + str(clock.get_fps()), 1, THECOLORS["white"]),
            (0, 0))
        screen.blit(
            font.render("Aim with mouse, hold LMB to powerup, release to fire",
                        1, THECOLORS["darkgrey"]), (5, height - 35))
        screen.blit(
            font.render("Press R to reset, ESC or Q to quit", 1,
                        THECOLORS["darkgrey"]), (5, height - 20))

        pygame.display.flip()

        ### Update physics
        fps = 60
        dt = 1. / fps
        space.step(dt)

        clock.tick(fps)
Exemplo n.º 28
0
def run_world():
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("Crude Oil Pretreatment Unit")
    clock = pygame.time.Clock()
    running = True


    # Create game space (world) and set gravity to normal
    space = pymunk.Space() #2
    space.gravity = (0.0, -900.0)
    
    # When oil collides with tank_level, call level_reached
    space.add_collision_handler(tank_level_collision, ball_collision, begin=level_reached)
    # When oil touches the oil_spill marker, call oil_spilled
    space.add_collision_handler(oil_spill_collision, ball_collision, begin=oil_spilled)
    # When oil touches the oil_process marker, call oil_processed
    space.add_collision_handler(oil_processed_collision, ball_collision, begin=oil_processed)
    # Initial outlet valve condition is turned off
    space.add_collision_handler(outlet_valve_collision, ball_collision, begin=no_collision)
    # Initial sep valve condition is turned off
    space.add_collision_handler(sep_valve_collision, ball_collision, begin=no_collision)
    # Initial waste valve condition is turned off
    space.add_collision_handler(waste_valve_collision, ball_collision, begin=no_collision)
    
    # Add the objects to the game world
    pump = add_pump(space)
    lines = add_oil_unit(space)
    tank_level = tank_level_sensor(space)
    sep_valve_obj = sep_valve(space)
    oil_spill = oil_spill_sensor(space)
    oil_process = oil_processed_sensor(space)
    outlet = outlet_valve(space)
    waste_valve_obj = waste_valve(space)
    

    balls = []
    ticks_to_next_ball = 1

    # Set font settings
    fontBig = pygame.font.SysFont(None, 40)
    fontMedium = pygame.font.SysFont(None, 26)
    fontSmall = pygame.font.SysFont(None, 18)

    while running:
        # Advance the game clock
        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                running = False

        # Load the background picture for the pipe images
        bg = pygame.image.load("oil_unit.png")
        # Background color
        screen.fill(THECOLORS["grey"])

        # If the feed pump is on
        if PLCGetTag(PLC_FEED_PUMP) == 1:
            # Draw the valve if the pump is on
            # If the oil reaches the level sensor at the top of the tank
            if (PLCGetTag(PLC_TANK_LEVEL) == 1):
                PLCSetTag(PLC_FEED_PUMP, 0)

        # Oil Tank outlet valve open/closed collision handler
        if PLCGetTag(PLC_OUTLET_VALVE) == 1:
            space.add_collision_handler(outlet_valve_collision, ball_collision, begin=outlet_valve_open)
        elif PLCGetTag(PLC_OUTLET_VALVE) == 0: # Valve is closed
            space.add_collision_handler(outlet_valve_collision, ball_collision, begin=outlet_valve_closed)
       
        # Separator valve open/closed collision handler
        if PLCGetTag(PLC_SEP_VALVE) == 1:
            space.add_collision_handler(sep_valve_collision, ball_collision, begin=sep_open)
        else:
            space.add_collision_handler(sep_valve_collision, ball_collision, begin=sep_closed)
            
        # Waste water valve open/closed collision handler
        if PLCGetTag(PLC_WASTE_VALVE) == 1:
            space.add_collision_handler(waste_valve_collision, ball_collision, begin=waste_valve_open)
        else:
            space.add_collision_handler(waste_valve_collision, ball_collision, begin=waste_valve_closed)
            
            
        ticks_to_next_ball -= 1

        if ticks_to_next_ball <= 0 and PLCGetTag(PLC_FEED_PUMP) == 1:
            ticks_to_next_ball = 1
            ball_shape = add_ball(space)
            balls.append(ball_shape)
            
        balls_to_remove = []
        for ball in balls:
            if ball.body.position.y < 0 or ball.body.position.x > SCREEN_WIDTH+150:
                balls_to_remove.append(ball)

            draw_ball(bg, ball)

        for ball in balls_to_remove:
            space.remove(ball, ball.body)
            balls.remove(ball)

        draw_polygon(bg, pump)
        draw_lines(bg, lines)
        draw_ball(bg, tank_level, THECOLORS['black'])
        draw_line(bg, sep_valve_obj)
        draw_line(bg, outlet)
        draw_line(bg, waste_valve_obj)
        draw_line(bg, oil_spill, THECOLORS['red'])
        draw_line(bg, oil_process, THECOLORS['red'])

        #draw_ball(screen, separator_feed, THECOLORS['red'])
        title = fontMedium.render(str("Crude Oil Pretreatment Unit"), 1, THECOLORS['blue'])
        name = fontBig.render(str("VirtuaPlant"), 1, THECOLORS['gray20'])
        instructions = fontSmall.render(str("(press ESC to quit)"), 1, THECOLORS['gray'])
        feed_pump_label = fontMedium.render(str("Feed Pump"), 1, THECOLORS['blue'])
        oil_storage_label = fontMedium.render(str("Oil Storage Unit"), 1, THECOLORS['blue'])
        separator_label = fontMedium.render(str("Separator Vessel"), 1, THECOLORS['blue'])
        waste_water_label = fontMedium.render(str("Waste Water Treatment Unit"), 1, THECOLORS['blue'])
        tank_sensor = fontSmall.render(str("Tank Level Sensor"), 1, THECOLORS['blue'])
        separator_release = fontSmall.render(str("Separator Vessel Valve"), 1, THECOLORS['blue'])
        waste_sensor = fontSmall.render(str("Waste Water Valve"), 1, THECOLORS['blue'])
        outlet_sensor = fontSmall.render(str("Outlet Valve"), 1, THECOLORS['blue'])
        
        bg.blit(title, (300, 40))
        bg.blit(name, (347, 10))
        bg.blit(instructions, (SCREEN_WIDTH-115, 0))
        bg.blit(feed_pump_label, (80, 0))
        bg.blit(oil_storage_label, (125, 100))
        bg.blit(separator_label, (385,275))
        screen.blit(waste_water_label, (265, 490))
        bg.blit(tank_sensor, (125, 50))
        bg.blit(outlet_sensor, (90, 195))
        bg.blit(separator_release, (350, 375))
        bg.blit(waste_sensor, (90, 375))
        screen.blit(bg, (0, 0))

        space.step(1/FPS) 
        pygame.display.flip()

    if reactor.running:
        reactor.callFromThread(reactor.stop)
Exemplo n.º 29
0
    def __init__(self, weights, indicator):
        # Global-ish.
        self.crashed = False

        # Physics stuff.
        self.space = pymunk.Space()
        self.space.gravity = pymunk.Vec2d(0., 0.)
        self.W = weights #weights for the reward function
        self.indicator = indicator #for the specific task

        # Create the car.
        self.create_car(150, 20, 15)

        # Record steps.
        self.num_steps = 0
        self.num_obstacles_type = 4

        # Create walls.
        static = [
            pymunk.Segment(
                self.space.static_body,
                (0, 1), (0, height), 1),
            pymunk.Segment(
                self.space.static_body,
                (1, height), (width, height), 1),
            pymunk.Segment(
                self.space.static_body,
                (width-1, height), (width-1, 1), 1),
            pymunk.Segment(
                self.space.static_body,
                (1, 1), (width, 1), 1)
        ]
        for s in static:
            s.friction = 1.
            s.group = 1
            s.collision_type = 1
            s.color = THECOLORS['red']
        self.space.add(static)

        # Create some obstacles, semi-randomly.
        # We'll create three and they'll move around to prevent over-fitting.
        self.obstacles = []
        #self.obstacles.append(self.create_obstacle(380, 220, 70, "yellow"))
        #self.obstacles.append(self.create_obstacle(250, 500, 70, "yellow"))
        #self.obstacles.append(self.create_obstacle(780, 330, 70, "brown"))
        #self.obstacles.append(self.create_obstacle(530, 500, 70, "brown"))

        self.obstacles.append(self.create_obstacle([100, 100], [100, 585] , 7, "yellow"))
        self.obstacles.append(self.create_obstacle([450, 600], [100, 600] , 7, "yellow"))
        self.obstacles.append(self.create_obstacle([900, 100], [900, 585] , 7, "yellow"))
        self.obstacles.append(self.create_obstacle([900, 600], [550, 600] , 7, "yellow"))

        self.obstacles.append(self.create_obstacle([200, 100], [200, 480] , 7, "yellow"))
        self.obstacles.append(self.create_obstacle([450, 500], [200, 500] , 7, "yellow"))
        self.obstacles.append(self.create_obstacle([800, 100], [800, 480] , 7, "yellow"))
        self.obstacles.append(self.create_obstacle([800, 500], [550, 500] , 7, "yellow"))

        self.obstacles.append(self.create_obstacle([300, 100], [300, 350] , 7, "yellow"))
        self.obstacles.append(self.create_obstacle([700, 380], [300, 380] , 7, "yellow"))
        self.obstacles.append(self.create_obstacle([700, 100], [700, 350] , 7, "yellow"))

        self.obstacles.append(self.create_obstacle([400, 100], [600, 100] , 7, "brown"))
        self.obstacles.append(self.create_obstacle([400, 200], [600, 200] , 7, "brown"))
        self.obstacles.append(self.create_obstacle([400, 300], [600, 300] , 7, "brown"))

        self.obstacles.append(self.create_obstacle([700, 370], [300, 370] , 7, "brown"))
        self.obstacles.append(self.create_obstacle([310, 100], [310, 350] , 7, "brown"))
        self.obstacles.append(self.create_obstacle([690, 100], [690, 350] , 7, "brown"))
Exemplo n.º 30
0
def main():
    shadowCapture = VectorShadowCapture()
    pygame.init()
    screen = pygame.display.set_mode([1280, 960])
    pygame.display.set_caption("Shadow Caster Level 2")
    clock = pygame.time.Clock()
    draw_options = pymunk.pygame_util.DrawOptions(screen)
    space = pymunk.Space(threaded=True)
    space.gravity = (0.0, -1500.0)
    static = [
        pymunk.Segment(space.static_body, (0, 0), (1280, 0), 3),
        pymunk.Segment(space.static_body, (1280, 0), (1280, 960), 3),
        pymunk.Segment(space.static_body, (1280, 960), (0, 960), 3),
        pymunk.Segment(space.static_body, (0, 960), (0, 0), 3)
    ]
    for segment in static:
        segment.friction = 1.
        space.add(segment)

    #create pendulum
    mass = 1
    radius = 60
    inertia = pymunk.moment_for_circle(mass, 0, radius, (0, 0))
    body = pymunk.Body(mass, inertia)
    body.position = (440, 430)
    body.start_position = Vec2d(body.position)
    objective = pymunk.Circle(body, radius)
    objective.elasticity = 0.75
    space.add(body, objective)
    pj = pymunk.PinJoint(space.static_body, body, (640, 960), (0, 0))
    space.add(pj)
    objectiveRegion = [1180, 960, 1280, 860]
    finished = False
    forbiddenRegion = [[800, 960], [1200, 960], [1300, 0], [700, 0]]
    cvForbiddenRegion = [[500, -100], [250, 480],
                         [750, 480]]  # Using 640x480 image at this point
    while not finished:
        finished = inRegion(objectiveRegion, objective.body)
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit(0)
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                sys.exit(0)
            elif event.type == KEYDOWN and event.key == K_SPACE:
                shadowCapture.resetBackground()
        surface = shadowCapture.updateWithBlocking(
            space, cvForbiddenRegion
        )  # Update the space with what's captured in the camera. Return a pygame image of the silhouette.
        screen.fill((255, 255, 255))
        pygame.draw.polygon(surface, (93, 0, 166),
                            [[1000, -100], [500, 960], [1500, 960]], 0)
        pygame.draw.circle(surface, (255, 0, 0), (1210, 70), 70, 3)
        screen.blit(surface, surface.get_rect())
        space.debug_draw(draw_options)
        space.step(1 / 50.0)
        pygame.display.flip()
        clock.tick(50)

    #Final screen
    screen.fill((225, 255, 255))
    font = pygame.font.SysFont("Arial", 32)
    screen.blit(
        font.render("Level 2 Complete! Esc to close window", 1, (0, 0, 0)),
        (480, 480))
    pygame.display.flip()
    #Wait for them to close the game
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit(0)
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                sys.exit(0)