示例#1
0
    def __init__(self, background=(240, 240, 240), resizable=False, vsync=False, debug=False, style=pyglet.window.Window.WINDOW_STYLE_DEFAULT):
        # type: (str) -> None
        pyglet.window.Window.__init__(self, resizable=resizable, vsync=vsync, style=style)
        self.debug = debug
        self.background = background
        self._resizeable = resizable
        self._vsync = vsync
        self._style = style

        self._title = ""
        self._icon = None
        self._fullscreen = False
        self._min_size = (0, 0)
        self._max_size = (0, 0)

        if self.debug:
            from pymunk.pyglet_util import DrawOptions

            self.options = DrawOptions()

        pyglet.gl.glClearColor(int(background[0]) / 255, int(background[1]) / 255, int(background[2]) / 255, 1)

        Globals.WINDOW = self

        self.keys = pyglet.window.key.KeyStateHandler()
        self.push_handlers(self.keys)

        self._loop = True

        self._middle = [self.width / 2, self.height / 2]

        self._mouse_x = 0
        self._mouse_y = 0
        
        self.scene_list = []
        self.active_scene = 0

        self.icon(pyglet.image.load(os.path.join(os.path.dirname(__file__), "swine.png")))

        self.clock = pyglet.clock.get_default()

        if Globals.FPS_LIMIT != -1:
            self.clock.set_fps_limit(Globals.FPS_LIMIT)

        if Globals.GUI_FPS != -1:
            self.clock.schedule_interval(self.gui_update, 1 / Globals.GUI_FPS)

        else:
            self.clock.schedule(self.gui_update)

        if Globals.PHYSICS_FPS != -1:
            self.clock.schedule_interval(self.physics_update, 1 / Globals.PHYSICS_FPS)

        else:
            self.clock.schedule(self.physics_update)

        self._benchmark_timer = 0
        self._benchmark_list = []

        self.register_event_type("on_update")
示例#2
0
    def __init__(self, window, debug=False):
        self.window = window
        self.background_colour = pyglet.image.SolidColorImagePattern((143, 187, 247, 255)).\
            create_image(window_width, window_height)

        self.world_batch = pyglet.graphics.Batch()
        self.background = pyglet.graphics.OrderedGroup(0)
        label_y_position = window_height - 35
        self.score_label = pyglet.text.Label(text="Score: 0",
                                             x=10,
                                             y=label_y_position,
                                             font_size=24,
                                             bold=True,
                                             color=(255, 255, 255, 255))
        self.lives_label = pyglet.text.Label(text="Lives: 0",
                                             x=200,
                                             y=label_y_position,
                                             font_size=24,
                                             bold=True,
                                             color=(255, 255, 255, 255))
        self.level_label = pyglet.text.Label(text="Level: 0",
                                             x=340,
                                             y=label_y_position,
                                             font_size=24,
                                             bold=True,
                                             color=(255, 255, 255, 255))

        self.fps_display = FPSDisplay(window)
        self.levels = [Level1(self), Level2(self)]
        self.on_new_level()
        self.draw_options = DrawOptions()
        self.debug = debug
示例#3
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.keysDown = []
        self.label = pyglet.text.Label("test",
                                       font_name='Times New Roman',
                                       font_size=36,
                                       x=self.width // 2,
                                       y=self.height // 2,
                                       anchor_x='center',
                                       anchor_y='center')

        self.space = pymunk.Space()
        self.options = DrawOptions()
        self.score = 0
        self.playerCar = car.Car(self.space)
        self.course = walls.Walls(self.space)
        self.coins = coins.Coins(self.space)
        self.fps = FPSDisplay(self)
        self.nearestCoinPos = self.coins.usedCoinPos[0]

        handler = self.space.add_collision_handler(1, 2)
        handler.begin = self.hitWall

        coinHandler = self.space.add_collision_handler(1, 3)
        coinHandler.begin = self.collectCoin
示例#4
0
    def __init__(self, space, update):
        super().__init__(*WINDOW_SIZE)
        self.space = space
        self.draw_option = DrawOptions()

        self.set_caption(CAPTION)
        self.set_fullscreen(FULLSCREEN)
        self.set_mouse_visible(MOUSE_VISIBLE)
        pyglet.clock.schedule_interval(update, 1 / FPS_MAX)
示例#5
0
    def __init__(self):
        self.width = 1280
        self.height = 720
        self.window = pyglet.window.Window(self.width,
                                           self.height,
                                           "Car Simulator",
                                           resizable=False)
        self.draw_options = DrawOptions()

        self.seed()
        self.action_space = spaces.Discrete(3)
        self.observation_space = spaces.Box(low=0.0,
                                            high=1.0,
                                            shape=(3, ),
                                            dtype=np.float32)

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

        self._create_boundaries()
        self.car = Car(self.space)

        Obstacle(self.space, (300, 300), 50)
        Obstacle(self.space, (250, 630), 80)
        Obstacle(self.space, (1200, 600), 90)

        FourLegsObstacle(self.space, (700, 400), 200, 200, 15)

        FourLegsObstacle(self.space, (800, 50), 100, 100, 10)
        FourLegsObstacle(self.space, (920, 50), 100, 100, 10)
        FourLegsObstacle(self.space, (1040, 50), 100, 100, 10)

        def on_key_press(symbol, modifiers):
            #if symbol == pyglet.window.key.LEFT:
            #    self.car.cmd(0)
            #elif symbol == pyglet.window.key.RIGHT:
            #    self.car.cmd(1)
            #elif symbol == pyglet.window.key.UP:
            #    self.car.cmd(2)
            if symbol == pyglet.window.key.ESCAPE:
                pyglet.app.exit()
                quit()
            #update(0.2)

        #def on_draw():
        #    self.window.clear()
        #    self.space.debug_draw(self.draw_options)

        #def update(dt):
        #    self.car.sensors[0]._clear_rays()
        #    self.space.step(dt)
        #    print(self.car.read_sensors())
        #    if self.car.is_crashed:
        #        self.reset_sim()

        self.window.push_handlers(on_key_press)  #,on_draw)
示例#6
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.set_location(300, 50)
     self.fps = FPSDisplay(self)
     self.space = pymunk.Space()
     self.options = DrawOptions()
     self.player = Player(self.space)
     self.ball = Ball(self.space, self.player.position)
     self.walls = Walls(self.space)
     self.bricks = Bricks(self.space)
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.set_location(500, 50)
        self.fps = FPSDisplay(self)

        self.space = pymunk.Space()
        self.options = DrawOptions()

        self.player = Player(self.space)
        self.puck = Puck(self.space)
        self.rail = Rail(self.space)
示例#8
0
 def __init__(self,*args,**kwargs):
     super().__init__(*args,**kwargs)
     self.space=pymunk.Space()
     self.set_caption("Bouncy Stack")
     self.space.gravity=0,-500
     self.add=False
     self.draw_options=DrawOptions()
     self.ground=Base(self.space)
     self.ground.draw()
     self.game_complete=False
     self.counter=0
     self.comp_lbl=pyglet.text.Label(text="Game Completed",font_size=40,bold=True,italic=True,color=(100,100,100,100),x=400,y=400,anchor_x='center',anchor_y='center')
示例#9
0
    def __init__(self):
        self.width = 1280
        self.height = 720
        self.window = pyglet.window.Window(self.width,
                                           self.height,
                                           "Car Simulator",
                                           resizable=False)
        self.draw_options = DrawOptions()

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

        self._create_boundaries()
        self.car = Car(self.space)

        Obstacle(self.space, (300, 300), 50)
        Obstacle(self.space, (250, 630), 80)
        Obstacle(self.space, (1200, 600), 90)

        FourLegsObstacle(self.space, (700, 400), 200, 200, 15)

        FourLegsObstacle(self.space, (800, 50), 100, 100, 10)
        FourLegsObstacle(self.space, (920, 50), 100, 100, 10)
        FourLegsObstacle(self.space, (1040, 50), 100, 100, 10)

        def on_draw():
            self.window.clear()
            self.space.debug_draw(self.draw_options)

        def on_key_press(symbol, modifiers):
            if symbol == pyglet.window.key.LEFT:
                self.car.cmd(0)
            elif symbol == pyglet.window.key.RIGHT:
                self.car.cmd(1)
            elif symbol == pyglet.window.key.UP:
                self.car.cmd(2)
            #update(0.2)

        def update(dt):
            self.car.sensors[0]._clear_rays()
            self.space.step(dt)
            dists = []
            for sensor in self.car.sensors:
                dists.append(sensor.sense())
            print(dists)
            if self.car.is_crashed:
                self.reset_sim()

        self.window.push_handlers(on_key_press, on_draw)
        pyglet.clock.schedule_interval(update, 1.0 / 30.0)
        pyglet.app.run()
示例#10
0
    def __init__(self, *args, **kwargs): #arguments and keyword arguments
        super().__init__(*args, **kwargs)
        pyg.gl.glClearColor(1000,1000,1000,1000) #background colour
        self.set_location(30, 50) #window position
        self.fps = FPSDisplay(self)

        self.space = pym.Space() #pymunk space
        self.options = DrawOptions() #pymunk + pyglet integration

        self.player = Player_Object(self.space, *object_types[0])
        self.ground = Game_Object(self.space, *object_types[2])
        self.enemy_list = []

        self.player_sprite_walking = Sprites(*sprite_types[0])
        self.player_sprite_jumping = Sprites(*sprite_types[1])
        self.player_sprite_ducking = Sprites(*sprite_types[2])
        self.player_sprite_dead = Sprites(*sprite_types[3])

        self.sleep = 30 #30 frames untill first enemy
        self.randomsleep_down = 90
        self.randomsleep_up = 150
        self.state = None #the players state
        self.running = True

        ground_handler = self.space.add_collision_handler(1, 2) #collision handler to know when player is on the ground
        ground_handler.begin = self.coll_ground

        end_handler = self.space.add_collision_handler(2, 3)
        end_handler.begin = self.coll_enemy
        
        self.counter_vel = 2
        self.enemy_velocity = -250

        self.points = 0
        self.scoreLabel = pyg.text.Label('',
                                 font_name='Press Start 2P',
                                 font_size=20,
                                 color=(83, 83, 83, 255),
                                 x=1180, y=700,
                                 anchor_x='center', anchor_y='center')
        self.highscoreLabel = pyg.text.Label('HI',
                                 font_name='Press Start 2P',
                                 font_size=20,
                                 color=(115, 115, 115, 255),
                                 x=980, y=700,
                                 anchor_x='center', anchor_y='center')
        self.counter_score = 0.1
        self.value_holder = 0.1
        self.speedup_score = 3
        self.highscore = self.load()
示例#11
0
    def __init__(self, aspect_ratio, dt_for_physicx):
        self.aspect_ratio = aspect_ratio
        self.dt_for_physicx = dt_for_physicx

        self.space = pymunk.Space()
        self.options = DrawOptions()

        self.nb_balls = 2
        self.nb_balls_in_game = self.nb_balls

        self._init_dynamic_body()
        self._add_collision_handler_for_paddle_ball()
        #
        self.walls = Walls(self.space, CollisionType.BALL,
                           CollisionType.BOTTOM, self.loose_ball, aspect_ratio)
        self.bricks = Bricks(self.space, CollisionType.BRICK,
                             CollisionType.BALL, aspect_ratio)
示例#12
0
    def __init__(self, cfg):
        # Set the window width and height from the config file
        self.winwidth = int(cfg['winwidth'])
        self.winheight = int(cfg['winheight'])
        # Boilerplate pyglet stuff, intialize the environment
        pyglet.window.Window.__init__(self,
                                      self.winheight,
                                      self.winwidth,
                                      fullscreen=False)
        self.options = DrawOptions()
        # Create the underlying pymunk engine
        self.pmSpace = norender.PymunkSpace(cfg)
        # Solid white background
        background = pyglet.image.SolidColorImagePattern(
            (255, 255, 255, 255)).create_image(self.winheight, self.winwidth)
        self.background_sprite = pyglet.sprite.Sprite(background, x=0, y=0)
        # At every 1.0/60 interval, call the update function (essentially render at 60 FPS)
        pyglet.clock.schedule_interval(self.update, 1.0 / 60)
        # This keeps track of if the agent is in the middle of a shot; the engine will not take another job off the job_queue until it finishes whatever it is doing
        self.doingAction = False

        # Load the net and ball images
        hoop_img = pyglet.image.load(dirname + "/../resource/hoop_resized.png")
        hoop_img.anchor_x = hoop_img.width // 2 - 1
        hoop_img.anchor_y = hoop_img.height // 2 - 1
        self.hoop_sprite = pyglet.sprite.Sprite(hoop_img, x=0, y=0)

        # Reset the pymunk space
        self.reset_space(True)

        basketball_img = pyglet.image.load(
            dirname + "/../resource/basketball_resized.png")
        basketball_img.anchor_x = basketball_img.width // 2 - 1
        basketball_img.anchor_y = basketball_img.height // 2 - 1
        self.basketball_sprite = pyglet.sprite.Sprite(
            basketball_img,
            x=self.pmSpace.basketball_body.position.x,
            y=self.pmSpace.basketball_body.position.y)
        done_queue.put(True)
    def __init__(self, game):
        super(CarScreen, self).__init__(game)

        pyglet.clock.schedule_interval(self.update, 1 / 60)
        #Pymunk specifications
        self.options = DrawOptions()
        self.options.collision_point_color = (0, 0, 0, 255)
        self.space = pymunk.Space()
        self.space.gravity = 0, 0
        self.space.idle_speed_threshold = 10
        self.space.sleep_time_threshold = 50
        # Pymunk Space
        self.car = Poly(100, ((0, 0), (80, 0), (80, 35), (65, 60), (15, 60),
                              (0, 35)), (game.width / 4, game.height / 2))
        self.car.body.elasticity = 0.1
        self.car.body.friction = 1
        self.space.add(self.car.existence)

        self.roda_traseira = Ball(30, 50,
                                  (game.width / 4 - 30, game.height / 2 - 30))
        self.roda_traseira.shape.elasticity = 0.1
        self.roda_dianteira = Ball(
            30, 50, (game.width / 4 + 110, game.height / 2 - 30))
        self.roda_dianteira.shape.elasticity = 0.1

        self.pino1 = pymunk.PinJoint(self.car.body, self.roda_traseira.body,
                                     (0, 0), (0, 0))
        self.guia1 = pymunk.SlideJoint(self.car.body, self.roda_traseira.body,
                                       (0, 30), (0, 0), 45, 59)
        self.mola1 = pymunk.DampedSpring(self.car.body,
                                         self.roda_traseira.body, (0, 30),
                                         (0, 0), 100, 1000, 65)

        self.pino2 = pymunk.PinJoint(self.car.body, self.roda_dianteira.body,
                                     (80, 0), (0, 0))
        self.guia2 = pymunk.SlideJoint(self.car.body, self.roda_dianteira.body,
                                       (80, 30), (0, 0), 45, 59)
        self.mola2 = pymunk.DampedSpring(self.car.body,
                                         self.roda_dianteira.body, (80, 30),
                                         (0, 0), 100, 1000, 65)

        self.space.add(self.roda_dianteira.existence,
                       self.roda_traseira.existence)

        self.space.add(self.pino1, self.guia1, self.mola1, self.pino2,
                       self.guia2, self.mola2)

        # ELEMENTOS ESTÁTICOS:
        self.segment1 = Segment((0, 4), (game.width, 4),
                                10)  # Limite de tela inferior
        self.segment1.shape.friction = 1  # Elasticidade borda inferior - Solo
        self.segment2 = Segment((0, 0), (0, game.height),
                                10)  # Limite de tela lateral esquerdo
        self.segment2.shape.friction = 0  # Elasticidade borda lateral esquerda
        self.segment3 = Segment((0, game.height), (game.width, game.height),
                                10)  # Limite de tela superior
        self.segment3.shape.friction = 0  # Elasticidade borda superior
        self.segment4 = Segment((game.width, 0), (game.width, game.height),
                                10)  # Limite de tela lateral direito
        self.segment4.shape.friction = 0  # Elasticidade borda lateral direita
        self.space.add(self.segment1.shape, self.segment2.shape,
                       self.segment3.shape, self.segment4.shape)
    def __init__(self, width=800, height=600, *args, **kwargs):
        super().__init__(self.SCREEN_WIDTH,
                         self.SCREEN_HEIGHT,
                         self.SCREEN_TITLE,
                         resizable=False,
                         fullscreen=False,
                         *args,
                         **kwargs)
        self.x, self.y = 0, 0

        # Pyglet   #style=pyglet.window.Window.WINDOW_STYLE_TOOL style=pyglet.window.Window.WINDOW_STYLE_BORDERLESS)
        self.options = DrawOptions()
        # Pymunk
        self.space = pymunk.Space()

        # type float in the range [0.0, 1.0], corresponding to the RGBA sequence (red, green, blue, and alpha).
        self.background_color = (.1, .5, .1, 1)  # green grass
        self.background_color2 = (.2, .75, .5, 1)  # light green grass
        # sets the background color
        glClearColor(*self.background_color)

        # Instances of classes
        self.population = Population()
        self.track_builder = TrackBuilder()
        self.track_settings = TrackSettings()

        self.track_creation_label = pyglet.text.Label(
            self.TRACK_MSG.format(len(self.track)),
            font_name='Times New Roman',
            font_size=20,
            x=self.SCREEN_WIDTH // 2,
            y=self.SCREEN_HEIGHT - 20,
            color=(255, 255, 0, 255),
            anchor_x='center',
            anchor_y='center')

        self.epoch_label = pyglet.text.Label(self.EPOCH_MSG.format(
            self.epoch, self.time_step),
                                             font_name='Times New Roman',
                                             font_size=16,
                                             x=0.8 * self.SCREEN_WIDTH // 10,
                                             y=self.SCREEN_HEIGHT - 20,
                                             color=(255, 255, 255, 255),
                                             anchor_x='center',
                                             anchor_y='center')

        self.best_car_info_label = pyglet.text.Label(
            self.COUNTER_MSG.format(self.time_counter),
            font_name='Times New Roman',
            font_size=16,
            x=4.4 * self.SCREEN_WIDTH // 10,
            y=self.SCREEN_HEIGHT - 20,
            color=(255, 255, 0, 255),
            anchor_x='center',
            anchor_y='center')

        self.current_best_car_info_label = pyglet.text.Label(
            self.CURRENT_BEST_CAR.format("None", "0"),
            font_name='Times New Roman',
            font_size=16,
            x=8.3 * self.SCREEN_WIDTH // 10,
            y=self.SCREEN_HEIGHT - 20,
            color=(255, 255, 0, 255),
            anchor_x='center',
            anchor_y='center')
示例#15
0
from simulator_tools import *
from input_tools import *

Tau = 2 * np.pi
Phi = 1.61803398874989

###
#  pyglet setup and calls
###

window_sx = 1000
window_sy = 1000
window = pyglet.window.Window(window_sx, window_sy, "Window", resizable=False)
pyglet.gl.glClearColor(0.0, 43 / 255.0, 54 / 255.0, 1)
options = DrawOptions()
options.flags = pymunk.SpaceDebugDrawOptions.DRAW_SHAPES
#options.flags |= pymunk.SpaceDebugDrawOptions.DRAW_COLLISION_POINTS

scale_wi = 0.2

# setup the reference lines
'''
cross_lines = pyglet.graphics.vertex_list(4,
('v2f', (400, 100, 400, 500, 100, 300, 700, 300)),
('c3B', (147, 161, 161, 147, 161, 161, 147, 161, 161, 147, 161, 161))
)
'''

bounding_hull = []
示例#16
0
 def on_draw(self) -> None:
     super().clear()
     self.universe.space.debug_draw(DrawOptions())
     self.label.draw()
示例#17
0
#%%
import pymunk as pm
from pymunk.pyglet_util import DrawOptions
import numpy as np
import math
from numba import njit
import cell_geometry
from Cell import Cell
import cell_physics
import matplotlib.pyplot as plt
import cell_drawing

## DEFINE SPACE
space = pm.Space()
space.iterations = 100
options = DrawOptions()
options.collision_point_color = (0, 0, 0, 0)
space.debug_draw(options)
space.gravity = 0, 0

## ADD INITIAL CELLS
cell_1 = Cell(length=15,
              width=7.5,
              x_pos=0,
              y_pos=0,
              angle=0,
              colour=(1, 0, 0, 1),
              perm_colour=(1, 0, 0, 1),
              space=space)
cell_2 = Cell(length=15,
              width=7.5,
    def __init__(self, game):
        super(AnotherScreen, self).__init__(game)

        pyglet.clock.schedule_interval(self.update, 1 / 60)
        #Pymunk specifications
        self.options = DrawOptions()
        self.options.collision_point_color = (0, 0, 0, 255)
        self.space = pymunk.Space()
        self.space.gravity = 0, -100
        self.space.idle_speed_threshold = 10
        self.space.sleep_time_threshold = 500
        # Pymunk Space

        self.player = Player(1350, ((0, 0), (171 / 5, 0), (171 / 10, 300 / 5)),
                             (game.width / 2, game.height / 2))
        self.player.body.center_of_gravity = ((0 + 171 / 5 + 171 / 10) / 3,
                                              300 / 15)
        self.player.body.elasticity = 0
        self.player.body.friction = 1
        self.player_image = pyglet.image.load("nave.png")
        self.player_sprite = pyglet.sprite.Sprite(
            self.player_image,
            x=self.player.body.position[0],
            y=self.player.body.position[1])
        self.player.combustivel = 3000
        self.space.add(self.player.existence)

        # ELEMENTOS ESTÁTICOS:
        # Limite da tela inferior
        self.segment1 = Segment((0, 4), (game.width, 4), 10)
        self.segment1.shape.friction = 1
        self.segment1.shape.elasticity = 0

        # Limite da tela lateral esquerda
        self.segment2 = Segment((0, 0), (0, game.height), 10)
        self.segment2.shape.friction = 0
        self.segment2.shape.elasticity = 0

        # Limite da tela superior
        self.segment3 = Segment((0, game.height), (game.width, game.height),
                                10)
        self.segment3.shape.friction = 0
        self.segment3.shape.elasticity = 0

        # Limite da tela lateral direita
        self.segment4 = Segment((game.width, 0), (game.width, game.height), 10)
        self.segment4.shape.friction = 0
        self.segment4.shape.elasticity = 0

        # Roxa esquerda
        self.triangulo1_r1 = Poly(1000, ((0, 0), (41, 0), (41, 105)),
                                  (52, 113))
        self.triangulo1_r1.body.body_type = pymunk.Body.STATIC
        self.triangulo1_r1.shape.elasticity = 0
        self.triangulo2_r1 = Poly(1000, ((0, 0), (90, 0), (0, 55)), (129, 0))
        self.triangulo2_r1.body.body_type = pymunk.Body.STATIC
        self.triangulo2_r1.shape.elasticity = 0
        self.triangulo3_r1 = Poly(1000, ((0, 0), (19, 0), (9, 10)), (98, 218))
        self.triangulo3_r1.body.body_type = pymunk.Body.STATIC
        self.triangulo3_r1.shape.elasticity = 0
        self.retangulo1_r1 = Poly(1000, ((0, 0), (96, 0), (96, 116), (0, 116)),
                                  (33, 0))
        self.retangulo1_r1.body.body_type = pymunk.Body.STATIC
        self.retangulo1_r1.shape.elasticity = 0
        self.retangulo2_r1 = Poly(1000, ((0, 0), (48, 0), (48, 73), (0, 73)),
                                  (81, 113))
        self.retangulo2_r1.body.body_type = pymunk.Body.STATIC
        self.retangulo2_r1.shape.elasticity = 0
        self.retangulo3_r1 = Poly(1000, ((0, 0), (28, 0), (28, 32), (0, 32)),
                                  (93, 186))
        self.retangulo3_r1.body.body_type = pymunk.Body.STATIC
        self.retangulo3_r1.shape.elasticity = 0

        # Roxa direita
        self.triangulo1_r2 = Poly(1000, ((0, 0), (29, 0), (29, 205)),
                                  (1210, 0))
        self.triangulo1_r2.body.body_type = pymunk.Body.STATIC
        self.triangulo1_r2.shape.elasticity = 0
        self.triangulo2_r2 = Poly(1000, ((0, 0), (58, 0), (0, 193)), (1263, 0))
        self.triangulo2_r2.body.body_type = pymunk.Body.STATIC
        self.triangulo2_r2.shape.elasticity = 0
        self.triangulo3_r2 = Poly(1000, ((0, 0), (39, 0), (0, 60)), (1277, 81))
        self.triangulo3_r2.body.body_type = pymunk.Body.STATIC
        self.triangulo3_r2.shape.elasticity = 0
        self.retangulo1_r2 = Poly(1000, ((0, 0), (26, 0), (26, 203), (0, 203)),
                                  (1238, 0))
        self.retangulo1_r2.body.body_type = pymunk.Body.STATIC
        self.retangulo1_r2.shape.elasticity = 0
        self.retangulo2_r2 = Poly(1000, ((0, 0), (39, 0), (39, 82), (0, 82)),
                                  (1277, 0))
        self.retangulo2_r2.body.body_type = pymunk.Body.STATIC
        self.retangulo2_r2.shape.elasticity = 0

        # Adicionando formas geométricas
        self.space.add(
            self.segment1.shape, self.segment2.shape, self.segment3.shape,
            self.segment4.shape, self.triangulo1_r1.existence,
            self.triangulo2_r1.existence, self.triangulo3_r1.existence,
            self.retangulo1_r1.existence, self.retangulo2_r1.existence,
            self.retangulo3_r1.existence, self.triangulo1_r2.existence,
            self.triangulo2_r2.existence, self.triangulo3_r2.existence,
            self.retangulo1_r2.existence, self.retangulo2_r2.existence)
        # IMAGENS
        self.background = pyglet.resource.image("Plano_Game1.png")
        self.solo = pyglet.resource.image("Solo.png")
        self.moldura = pyglet.resource.image("moldura.png")

        # TEXTOS
        self.texts = [
            self.player.body.position[0], self.player.body.position[1],
            self.player.body.velocity[0], self.player.body.velocity[1],
            self.player.combustivel
        ]

        self.status = [0] * len(self.texts)
        for i in range(len(self.texts)):
            self.status[i] = pyglet.text.Label("{}".format(self.texts[i]),
                                               font_name="Arial",
                                               font_size=10,
                                               color=(100, 255, 0, 255),
                                               x=game.width - 200,
                                               y=game.height - 50 - (15 * i),
                                               anchor_x="left",
                                               anchor_y="center",
                                               align="left")

        self.handler = self.space.add_default_collision_handler()
        self.handler.begin = self.coll_begin
        self.handler.pre_solve = self.coll_pre
        self.handler.post_solve = self.coll_post
        self.handler.separate = self.coll_separate
        self.player.vida = 1000
#!/usr/bin/env python
# Imports
import math
import time
import pyglet
import pymunk
from pymunk.pyglet_util import DrawOptions
import numpy as np
import matplotlib.pyplot as plt

options = DrawOptions()  # Initialise DrawOptions for Pymunk
key = pyglet.window.key

# Physical dimensions of swing
rod1_length = 400
rod2_length = 50
rod3_length = 20
seat_length = 30
torso_length = 100
legs_length = 60

#####################
### PYMUNK
#####################


class Angle:
    '''
    The 'Angle' class which converts an angle in degrees to
    absolute world positions for the swing simulation.
    '''
    def visualize(self, genome, game_id: int):
        """
        Visualize the performance of a single genome.
        
        :param genome: Tuple (genome_id, genome_class)
        :param game_id: ID of the game that will be used for evaluation
        """
        # Create the requested game
        game: Game = get_game(game_id, cfg=self.game_config)
        game.player.set_active_sensors(
            set(genome.get_used_connections().keys()))

        # Create space in which game will be played
        window = pyglet.window.Window(
            game.game_config.x_axis * game.game_config.p2m,
            game.game_config.y_axis * game.game_config.p2m,
            "Robot Simulator - Game {id:03d}".format(id=game_id),
            resizable=False,
            visible=True)
        window.set_location(100, 100)
        pyglet.gl.glClearColor(1, 1, 1, 1)

        # Setup the requested game
        self.state = game.reset()[D_SENSOR_LIST]
        self.finished = False

        # Make the network used during visualization
        net = self.make_net(
            genome=genome,
            genome_config=self.pop_config.genome,
            game_config=self.game_config,
            bs=1,
            initial_read=self.state,
        )

        # Create the visualize-environment
        space = pymunk.Space()
        options = DrawOptions()

        # Draw static objects - walls
        for wall in game.walls:
            wall_shape = pymunk.Segment(space.static_body,
                                        a=wall.x * game.game_config.p2m,
                                        b=wall.y * game.game_config.p2m,
                                        radius=0.05 *
                                        game.game_config.p2m)  # 5cm walls
            wall_shape.color = (0, 0, 0)
            space.add(wall_shape)

        # Draw static objects - target
        target_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
        target_body.position = game.target * game.game_config.p2m
        target_shape = pymunk.Circle(body=target_body,
                                     radius=game.bot_config.radius *
                                     game.game_config.p2m)
        target_shape.sensor = True
        target_shape.color = (0, 128, 0)
        space.add(target_body, target_shape)

        # Init player²
        m = pymunk.moment_for_circle(mass=2,
                                     inner_radius=0,
                                     outer_radius=game.bot_config.radius *
                                     game.game_config.p2m)
        player_body = pymunk.Body(mass=1, moment=m)
        player_body.position = game.player.pos * game.game_config.p2m
        player_body.angle = game.player.angle
        player_shape = pymunk.Circle(body=player_body,
                                     radius=game.bot_config.radius *
                                     game.game_config.p2m)
        player_shape.color = (255, 0, 0)
        space.add(player_body, player_shape)
        label = pyglet.text.Label(
            f'{self.time}',  # TODO: Creates error in WeakMethod after run (during termination)
            font_size=16,
            color=(100, 100, 100, 100),
            x=window.width - 20,
            y=window.height - 20,
            anchor_x='center',
            anchor_y='center')

        # Draw the robot's sensors
        def draw_sensors():
            [
                space.remove(s) for s in space.shapes
                if s.sensor and type(s) == pymunk.Segment
            ]
            for key in game.player.active_sensors:
                s = game.player.sensors[key]
                if type(s) == ProximitySensor:
                    line = pymunk.Segment(space.static_body,
                                          a=s.start_pos * game.game_config.p2m,
                                          b=s.end_pos * game.game_config.p2m,
                                          radius=0.5)
                    line.sensor = True
                    touch = ((s.start_pos - s.end_pos).get_length() <
                             game.bot_config.ray_distance - 0.05)
                    line.color = (100, 100, 100) if touch else (
                        200, 200, 200)  # Brighten up ray if it makes contact
                    space.add(line)

        @window.event
        def on_draw():
            window.clear()
            draw_sensors()
            label.draw()
            space.debug_draw(options=options)

        def update_method(_):  # Input dt ignored
            dt = 1 / game.game_config.fps
            self.time += dt
            label.text = str(int(self.time))

            # Stop when target is reached
            if not self.finished:
                # Query the game for the next action
                action = self.query_net(net, [self.state])
                if self.debug:
                    print("Passed time:", round(dt, 3))
                    print("Location: x={}, y={}".format(
                        round(player_body.position.x / game.game_config.p2m,
                              2),
                        round(player_body.position.y / game.game_config.p2m,
                              2)))
                    print("Action: lw={l}, rw={r}".format(
                        l=round(action[0][0], 3), r=round(action[0][1], 3)))
                    print("Observation:", [round(s, 3) for s in self.state])

                # Progress game by one step
                obs = game.step_dt(dt=dt, l=action[0][0], r=action[0][1])
                self.finished = obs[D_DONE]
                self.state = obs[D_SENSOR_LIST]

                # Update space's player coordinates and angle
                player_body.position = game.player.pos * game.game_config.p2m
                player_body.angle = game.player.angle
            space.step(dt)

        # Run the game
        pyglet.clock.schedule_interval(
            update_method, 1.0 / (game.game_config.fps * self.speedup))
        pyglet.app.run()
示例#21
0
def live_visualisation(agent: Agent = Empty(), game: Game = None):
    """Visualise the performance of the given agent."""
    if not game: game = Game()

    # Regularly used constants
    width = game.width * game.pixels
    height = game.height * game.pixels

    # Initialise the Pyglet instance
    window = pyglet.window.Window(width,
                                  height,
                                  "PySnake",
                                  resizable=False,
                                  visible=True)
    window.set_location(100, 100)
    pyglet.gl.glClearColor(1, 1, 1, 1)

    # Draw the environment
    space = pymunk.Space()
    options = DrawOptions()

    # Label for the score
    label = pyglet.text.Label(f'{game.score}',
                              font_size=12,
                              color=(100, 100, 100, 100),
                              x=window.width - 30,
                              y=window.height - 30,
                              anchor_x='center',
                              anchor_y='center')

    # Draw a square in the environment
    def draw_segment(pos, i=None, color=(0, 128, 0)):
        """Draw square segment at position p."""
        target_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
        target_body.position = (pos[0] * game.pixels + game.pixels / 2,
                                pos[1] * game.pixels + game.pixels / 2)
        target_shape = pymunk.Poly.create_box(body=target_body,
                                              size=(game.pixels * 0.9,
                                                    game.pixels * 0.9))
        target_shape.sensor = True
        if i is not None: target_shape.id = i
        target_shape.color = color
        space.add(target_body, target_shape)

    # Draw the walls
    for i in range(game.height):
        draw_segment((0, i), color=(0, 0, 0))
        draw_segment((game.width - 1, i), color=(0, 0, 0))
    for i in range(game.width):
        draw_segment((i, 0), color=(0, 0, 0))
        draw_segment((i, game.height - 1), color=(0, 0, 0))

    # Draw the apple
    draw_segment(game.apple, i=-1, color=(128, 0, 0))

    # Create the Snake instance
    snake_i = IntegerGenerator()  # Iterator for the snake segments
    agent.training = False
    agent.reset(n_envs=1, sample_game=game)

    def draw_snake(init=False):
        """Draw the snake."""
        if init:
            for p in reversed(game.snake.body):
                draw_segment(p, i=snake_i())
        else:
            draw_segment(game.snake.body[0], i=snake_i())

    # Initialise the snake
    draw_snake(init=True)

    @window.event
    def on_draw():
        window.clear()
        label.text = str(game.score)
        label.draw()
        space.debug_draw(options=options)

    # Make game keyboard sensitive
    if type(agent) == Empty:

        @window.event
        def on_key_press(key, _):
            """Called whenever a key is pressed to record manual input."""
            if key == arcade.key.LEFT and game.snake.direction != RIGHT:
                game.snake.direction = LEFT
            elif key == arcade.key.RIGHT and game.snake.direction != LEFT:
                game.snake.direction = RIGHT
            elif key == arcade.key.UP and game.snake.direction != DOWN:
                game.snake.direction = UP
            elif key == arcade.key.DOWN and game.snake.direction != UP:
                game.snake.direction = DOWN

    def update_method(dt):
        """Update the game environment."""
        # Query brain to get action for current state
        a = agent([game])[0]

        # Progress the game
        score_pre = game.score
        alive = game.step(a=a)
        if not alive: pyglet.app.exit()
        score_post = game.score
        eaten = score_pre != score_post

        # Remove the oldest added shape
        for shape in space.shapes:
            if hasattr(shape, 'id') and shape.id <= len(snake_i) - (
                    game.snake.length - 1):
                if eaten:
                    space.remove(shape.body, shape)
                    draw_segment(game.apple, i=-1, color=(128, 0, 0))
                elif shape.id >= 0:
                    space.remove(shape.body, shape)

        # Proceed the snake
        draw_snake()

        # Perform required action
        space.step(dt)

    # Run the game
    pyglet.clock.schedule_interval(update_method, .1)
    pyglet.app.run()
示例#22
0
#print_options = pymunk.SpaceDebugDrawOptions() # For easy printing
#while True:                 # Infinite loop simulation
#space.step(0.02)        # Step the simulation one step forward
#space.debug_draw(print_options) # Print the state of the simulation

import pyglet
import pymunk
from pymunk.pyglet_util import DrawOptions
import time

#seting up pyglet
window = pyglet.window.Window(1280, 720, "MyMunk", resizable=True)
option = DrawOptions()

space = pymunk.Space()
space.gravity = 0, -1000

body = pymunk.Body(1, 1666)
body.position = 600, 700

poly = pymunk.Poly.create_box_bb(body, bb, radius=25)
space.add(body, poly)


@window.event
def on_draw():
    window.clear()
    space.debug_draw(option)


def update(dt):  #dt==date_time
示例#23
0
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 01:49:25 2021

@author: ACER
"""
import pyglet
import pymunk
from pymunk.pyglet_util import DrawOptions

window = pyglet.window.Window(
    1280, 720, "Pymunk Tester",
    resizable=False)  # width,height,title,not resizble
options = DrawOptions()

space = pymunk.Space()
space.gravity = 0, 0  #gravity for x and y directions
'''Body types: (default is DYNAMIC)
    DYNAMIC: affected by gravity and other forces (ball,player,enemies etc)
    KINEMATIC: Not affected by gravity or other forces, but can be moved (platforms,doors)
    STATIC: Not affected by gravity or other forces, and cannot be moved (ground,building, immovable object)

   Moment of Inertia: How much a body will resist rotation. Large value: resists rotation/angular acceleration more'''

poly = pymunk.Poly.create_box(None, size=(50, 50))
moment = pymunk.moment_for_poly(1, vertices=poly.get_vertices())

body = pymunk.Body(1, moment, pymunk.Body.DYNAMIC
                   )  #rigid body (without shape right now); params: mass, MOI
poly.body = body
body.position = 640, 700
    def visualize(self, genome, game_id: int):
        """
        Visualize the performance of a single genome.
        
        :param genome: Tuple (genome_id, genome_class)
        :param game_id: ID of the game that will be used for evaluation
        """
        # Create the requested game
        game: Game = get_game(game_id, cfg=self.game_config)
        self.p2m = game.game_config.p2m

        # Create space in which game will be played
        window = pyglet.window.Window(
            game.x_axis * self.p2m,
            game.y_axis * self.p2m,
            "Robot Simulator - Game {id:03d}".format(id=game_id),
            resizable=False,
            visible=True)
        window.set_location(100, 100)
        pyglet.gl.glClearColor(1, 1, 1, 1)

        # Setup the requested game
        self.state = game.reset()[D_SENSOR_LIST]
        self.finished = False
        self.score = 0

        # Make the network used during visualization
        net = make_net(
            genome=genome,
            genome_config=self.pop_config.genome,
            batch_size=1,
            initial_read=self.state,
        )

        # Create the visualize-environment
        space = pymunk.Space()
        options = DrawOptions()

        # Draw static objects - walls
        if game.wall_bound:
            x_axis = game.x_axis
            y_axis = game.y_axis
            corners = [(0, 0), (0, y_axis * self.p2m),
                       (x_axis * self.p2m, y_axis * self.p2m),
                       (x_axis * self.p2m, 0)]
            for c in range(4):
                wall_shape = pymunk.Segment(space.static_body,
                                            a=corners[c],
                                            b=corners[(c + 1) % 4],
                                            radius=0.1 * self.p2m)  # 5cm walls
                wall_shape.color = (0, 0, 0)
                space.add(wall_shape)

        # Draw static objects - target
        target_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
        target_body.position = game.target * self.p2m
        target_shape = pymunk.Circle(body=target_body,
                                     radius=game.bot_config.radius * self.p2m *
                                     3)  # TODO: Thick boi
        target_shape.sensor = True
        target_shape.color = (0, 128, 0)
        space.add(target_body, target_shape)

        # Init player
        m = pymunk.moment_for_circle(mass=2,
                                     inner_radius=0,
                                     outer_radius=game.bot_config.radius *
                                     self.p2m)
        player_body = pymunk.Body(mass=1, moment=m)
        player_body.position = game.player.pos * self.p2m
        player_body.angle = game.player.angle
        player_shape = pymunk.Circle(body=player_body,
                                     radius=game.bot_config.radius * self.p2m *
                                     3)  # TODO: Thick boi
        player_shape.color = (255, 0, 0)
        space.add(player_body, player_shape)
        label = pyglet.text.Label(f'{self.time}',
                                  font_size=16,
                                  color=(100, 100, 100, 100),
                                  x=window.width - 20,
                                  y=window.height - 20,
                                  anchor_x='center',
                                  anchor_y='center')

        @window.event
        def on_draw():
            window.clear()
            label.draw()
            space.debug_draw(options=options)

        if self.mouse_enabled:

            @window.event
            def on_mouse_press(x, y, *_):
                # Add new circle on mouse-clicked position
                game.target.x = x / game.game_config.p2m
                game.target.y = y / game.game_config.p2m
                target_body.position = game.target * self.p2m

        def update_method(_):  # Input dt ignored
            dt = 1 / game.game_config.fps
            self.time += dt
            label.text = str(int(self.time))

            # Stop when target is reached
            if not self.finished:
                # Query the game for the next action
                action = net(np.asarray([self.state]))
                if self.debug:
                    print(f"Passed time: {round(dt, 3)}")
                    print(
                        f"Location: x={round(player_body.position.x / self.p2m, 2)}, "
                        f"y={round(player_body.position.y / self.p2m, 2)}")
                    print(f"Orientation: {round(player_body.angle, 2)}")
                    print("Action: lw={l}, rw={r}".format(
                        l=round(action[0][0], 3), r=round(action[0][1], 3)))
                    print("Observation:", [round(s, 3) for s in self.state])

                # Progress game by one step
                obs = game.step_dt(dt=dt, l=action[0][0], r=action[0][1])
                self.finished = obs[D_DONE]
                self.state = obs[D_SENSOR_LIST]

                # Update space's player coordinates and angle
                player_body.position = game.player.pos * self.p2m
                player_body.angle = game.player.angle

                # Check if score has increased
                if game.score > self.score:
                    self.score = game.score
                    target_body.position = game.target * self.p2m
            space.step(dt)

        # Run the game
        time.sleep(5)  # TODO: Waiting time to start recording
        pyglet.clock.schedule_interval(
            update_method, 1.0 / (game.game_config.fps * self.speedup))
        pyglet.app.run()