def preproc(self, world, game):
     print 'world %d x %d' % (world.width, world.height)
     pprint(map(list, zip(*world.tiles_x_y)))
     print world.waypoints
     print '====================='
     self.navigator = Navigator(world)
     self.physics = Physics(world, game)
Esempio n. 2
0
    def __init__(self, screen, imgPath=None, name=None, highlight=False):
        self.screen = screen
        self.name = name or f'Name {random.randint(1111, 9999)}'
        self.highlight = highlight

        Physics.__init__(
            self,
            rect=(0, 0, 100, 100),
            initAngularVelocity=3000,
            friction=0,  # acceleration in  per second
            angularFriction=100,  # acceleration in degrees per second
        )
        if isinstance(imgPath, str):
            self.imgBase = pygame.image.load(imgPath or r'parts\1.png')
        else:
            self.imgBase = imgPath
        self.imgBase = self.imgBase.convert_alpha()
        self.imgBase = pygame.transform.scale(self.imgBase, self.size)
        self.image = self.imgBase

        self.edgeFriction = 100

        self._mask = None
        self.angVelocityLimit = 500
        self._UpdateMask()

        self.font = pygame.font.Font(
            None, 16) if not self.highlight else pygame.font.Font(None, 32)
        self.fontColor = pygame.color.Color(
            'white') if not self.highlight else pygame.color.Color('cyan')

        avgColor = pygame.transform.average_color(self.imgBase)
        font = pygame.font.Font(None, int(self.height / 3))
        self.surfTitle = font.render(self.name, True, avgColor)
Esempio n. 3
0
    def __init__(self, screen):
        self.screen = screen
        self.physics = Physics(
            (0, 0, 1, 1),
            friction=5000,
        )
        self.imgSize = int(self.screen.get_width() / 4)
        self.images = [
            pygame.transform.scale(pygame.image.load(IMG_DIR + '/' + path),
                                   (self.imgSize, self.imgSize))
            for path in os.listdir(IMG_DIR)
        ]
        # self.currentSelection = int(len(self.images) / 2)
        self.currentSelection = random.choice(list(range(len(self.images))))
        self.surfName = None

        self.stats = ['attack', 'defense', 'spin']
        self.statSurf = pygame.Surface((
            int(self.screen.get_width()),
            int((self.screen.get_height() - self.imgSize) / 2),
        ))

        self.startGameWith = None

        self.UpdateTextSurfaces()
        self.startTime = time.time()
Esempio n. 4
0
 def __init__(self,
              init_eta=None,
              init_upsilon=None,
              runtime=None,
              results_interval=300,
              random_eta_limits=None,
              random_upsilon_limits=None):
     '''Initialize parameters
     Params
     ======
         init_position: 1D numpy array, initial position in x-y-z coordinates (w.r.t. inertial frame)
         init_orientation: 1D numpy array, initial orientation in phi-theta-psi angles (Z-Y-X Tait-Bryan angles)
         init_vel: 1D numpy array, initial velocities in x-y-z components (w.r.t. body frame)
         init_ang_vel: 1D numpy array, initial angle velocities in x-y-z components (w.r.t. body frame)
         runtime: float, limit simulation time in seconds
         results_interval: int, iterations between saving results
         random_position_limits: float list, limits of random position generator
         random_state_limits: float list, limits of random state generator (orientation, vel and ang_vel)
     '''
     self.labels = [
         'time', 'x', 'y', 'psi', 'x_velocity', 'y_velocity',
         'z_angular_velocity', 'Tport', 'Tstbd'
     ]
     self.physics = Physics(init_eta, init_upsilon, runtime)
     self.results_interval = results_interval
     self.random_eta_limits = [[-2.5, 2.5], [-2.5, 2.5], [
         -np.pi, np.pi
     ]] if random_eta_limits is None else random_eta_limits
     self.random_upsilon_limits = [[0.0, 0.0], [0.0, 0.0], [
         0.0, 0.0
     ]] if random_upsilon_limits is None else random_upsilon_limits
     self.reset()
Esempio n. 5
0
    def __init__(self, _main):

        self.main = _main

        ## PHYSICS HANDLER ##
        self.physics = Physics(self)

        ## LEVEL LOADER ##
        self.currentLevelName = None
        self.levelloader = LevelLoader(self)
        self.currentLevelName = "startLevel2-extra"

        ## INPUT HANDLER
        self.input = Input(self)
        self.movementOption = '1'

        ## HANDLE PLAYER ##
        self.isPlayerActive = False
        self.player = {}
        self.activePlayerName = "player2"

        ## Start GuI ##
        self.gui = Gui(self)

        self.accept("doStart", self.startGame)

        ## GAME STATE VARIABLES ##
        self.isMoving = False
        self.isFloating = False
Esempio n. 6
0
    def __init__(self, screen_rect):

        self.wall_group = list()

        rect = pygame.rect.Rect((0, 0), (10, screen_rect.h))
        rect.topright = screen_rect.topright
        self.wall_group.append(Wall(rect))

        rect = pygame.rect.Rect((0, 0), (screen_rect.w, 10))
        rect.bottomleft = screen_rect.bottomleft
        self.wall_group.append(Wall(rect))

        rect = pygame.rect.Rect((0, 0), (10, screen_rect.h))
        rect.topleft = screen_rect.topleft
        self.wall_group.append(Wall(rect))

        rect = pygame.rect.Rect((0, 0), (screen_rect.w, 10))
        rect.topleft = screen_rect.topleft
        self.wall_group.append(Wall(rect))

        self.ball_group = list()
        for i in range(50):
            b = Ball((random.randint(0, screen_rect.w), random.randint(0, screen_rect.h)))
            if not any(Physics.is_circle_collision(b, ball) for ball in self.ball_group):
                self.ball_group.append(b)

        self.physics = Physics()
        self.physics.solids.extend(self.wall_group)
        self.physics.mobiles.extend(self.ball_group)
Esempio n. 7
0
 def __init__(self,
              pars,
              is_kinetic=False,
              acc=0,
              ang_acc=0,
              fr=0,
              lives=0,
              life=0):
     self.image = pars["image"]
     self.image_center = pars["info"].get_center()
     self.image_size = pars["info"].get_size()
     radius = pars["info"].get_radius()
     self.up_key_down = False
     self.left_key_down = False
     self.right_key_down = False
     self.missile_image = pars["missile_image"]
     self.missile_info = pars["missile_info"]
     self.missile_sound = pars["missile_sound"]
     self.ship_thrust_sound = pars["ship_thrust_sound"]
     self.missile_group = set([])
     self.lives = lives
     self.life = life
     self.score = 0
     if is_kinetic:
         self.physics = Physics(radius, pars["WIDTH"], pars["HEIGHT"], None,
                                is_kinetic, fr)
         self.physics.set_ang_acc(ang_acc)
         self.physics.set_acc(acc)
     else:
         self.physics = Physics(radius, WIDTH, HEIGHT)
     self.physics.set_pos(pars["pos"])
     self.physics.set_vel(pars["vel"])
     self.physics.set_ang(pars["ang"])
     self.physics.set_ang_vel(pars["ang_vel"])
    def test_straight_movement(self):
        me, world, game = load_objects()

        phys = Physics(world, game)
        me.speed_x = me.speed_y = 0.0
        me.x = 6800.0
        me.y = 7834.0
        car_state = CarState.from_car(me)
        car_state.brake = False
        car_state.engine_power = 1.0
        car_state.wheel_turn = 0.0

        car_state_350 = CarState(
            3.1415926535897931,
            np.array([-23.8683149170807631, 0.0000000000000029]), 0.0,
            np.array([4351.0112134403343589, 7834.0000000000000000]))

        car_state_474 = CarState(
            3.1415926535897931,
            np.array([-29.4477720000775669, 0.0000000000000036]), 0.0,
            np.array([992.6379800312042789, 7834.0000000000000000]))

        for i in xrange(181, 475):
            car_state = phys.calc(car_state)
            car_state.update_car(car_state)
            if i == 350:
                self.assertEqual(car_state, car_state_350)
            elif i == 474:
                self.assertEqual(car_state, car_state_474)
Esempio n. 9
0
    def __init__(self,
                 file_root,
                 physics=None,
                 smoothing=0.0,
                 degree=3,
                 SET_GLOBAL_EVOL=True):
        if physics is None:
            self.__phys = Physics()
        else:
            self.__phys = physics

        self.__f_data = np.loadtxt(file_root + '_devolution.dat')
        self.__delta_data = np.loadtxt(file_root + '_evolution.dat')
        a_data = np.loadtxt(file_root + '_a_vals.dat')
        self.__a_vals = a_data[:, 0]
        assert (a_data[-1, 0] == 1.0)
        self.__k_vals = np.loadtxt(file_root +
                                   '_matterpower_out.dat')[:,
                                                           0] * self.__phys.h

        if SET_GLOBAL_EVOL:
            physics.read_in_H(self.__a_vals, a_data[:, 1] / a_data[-1, 1])

        normalized_dataset = self.__delta_data / np.meshgrid(
            self.__a_vals, self.__delta_data[:, -1])[1]

        G_interpolation = RectBivariateSpline(np.log10(self.__k_vals),
                                              np.log10(self.__a_vals),
                                              normalized_dataset,
                                              bbox=[
                                                  min(np.log10(self.__k_vals)),
                                                  max(np.log10(self.__k_vals)),
                                                  min(np.log10(self.__a_vals)),
                                                  max(np.log10(self.__a_vals))
                                              ],
                                              kx=degree,
                                              ky=degree,
                                              s=smoothing)
        self.__G_func = lambda a, k: np.squeeze(
            G_interpolation.ev(np.log10(k), np.log10(a)))

        f_interpolation = RectBivariateSpline(np.log10(self.__k_vals),
                                              np.log10(self.__a_vals),
                                              self.__f_data,
                                              bbox=[
                                                  min(np.log10(self.__k_vals)),
                                                  max(np.log10(self.__k_vals)),
                                                  min(np.log10(self.__a_vals)),
                                                  max(np.log10(self.__a_vals))
                                              ],
                                              kx=degree,
                                              ky=degree,
                                              s=smoothing)
        self.__f_func = lambda a, k: np.squeeze(
            f_interpolation.ev(np.log10(k), np.log10(a)))

        self.__dG_dt = lambda a, k: self.__phys.da_over_a(
            (1 - a) / a) * np.squeeze(
                f_interpolation.ev(np.log10(a), np.log10(k))) * self.__G_func(
                    a, k)
Esempio n. 10
0
 def __init__(self, _id, pos=[0, 0], color='#27ae60'):
     # essentials
     super(Angel, self).__init__()
     # import settings
     self.settings = Settings()
     # set id
     self.id = _id
     # surface and rect
     self.image = pygame.Surface((200, 200))
     pygame.draw.circle(self.image, color, (100, 100), 99)
     self.image = pygame.transform.scale(self.image, (30, 30))
     self.image.fill(color)
     self.rect = self.image.get_rect()
     self.rect.x, self.rect.y = pos
     self.image.set_colorkey('#000000')
     # movement
     self.controls = controls[0]
     self.physics = Physics(self.rect, 1)
     self.last_state = None
     self.jumping = False
     self.air_timer = 0
     self.colliding = {
         'top': False,
         'bottom': False,
         'left': False,
         'right': False
     }
     self.wall = False
     # additional features
     self.lives = 3
     self.stamina = 10.0
     self.capJump = 12
Esempio n. 11
0
    def __init__(self, simVars, delta=50, tick=0):
        self.delta = delta
        self.simVars = simVars
        self.map = Map(simVars)
        self.spawner = Spawner(self)
        self.tick = tick

        self.physics = Physics()
 def update(self):
     Physics.instance().update()
     if not self.is_updating:
         pass
     index = 0
     self._update_list_game_object()
     for game_object in self._game_objects.values():
         if not game_object.is_updating:
             continue
         try:
             game_object.update()
         except:
             errorutils.handle_exception()
         index += 1
Esempio n. 13
0
 def step(self):
     if not self.ant.settled:
         try:
             self.ant.move()
         except Error as e:
             raise e
     else:
         if self.ant.y > self.maxHeight:
             self.maxHeight = self.ant.y
         if self.checkBridge():
             return False
         self.addJoints(self.ant)
         self.antId = self.antId + 1
         self.numAnts += 1
         if G.DeterministicAnts:
             self.ant = Pyramid(self.antId)
             self.oldy = self.y
             self.y = self.ant.y
             if self.y != self.oldy:
                 Physics.resetPhysics()
                 Physics.checkPhysics()
         else:
             self.ant = Ant(self.antId)
             Physics.resetPhysics()
             Physics.checkPhysics()
         self.updateShaking()
     return True
Esempio n. 14
0
class Element(object):
	__metaclass__ = ABCMeta

	color = ""
	ORIGINAL_WIDTH = 0
	width = 0
	ORIGINAL_HEIGHT = 0
	height = 0

	ORIGINAL_X = 0
	startX = 0
	ORIGINAL_Y = 0
	startY = 0

	canvasItem = None
	physics = None

	def resetElementForNewGame(self):
		self.physics = Physics(self.startX, self.startY)
		self.drawShip()

	def scale(self, horizontalScale, verticalScale):
		self.physics.scale(horizontalScale, verticalScale)
		self.width = self.ORIGINAL_WIDTH * horizontalScale
		self.height = self.ORIGINAL_HEIGHT * verticalScale
		self.startX = self.ORIGINAL_X * horizontalScale
		self.startY = self.ORIGINAL_Y * verticalScale
		self.drawElement()

	def executeAction(self, requestedActions):
		newLocationBasedOnActions = self.calculateNewLocationBasedOnActions(requestedActions)
		self.physics.updateForNewLocation(newLocationBasedOnActions)
		self.drawElement()

	def calculateNewLocationBasedOnActions(self, requestedActions):
		newLocationBasedOnActions = self.physics.location.getCopy()
		if requestedActions[Actions.UP]:
			newLocationBasedOnActions.y -= self.physics.maxSpeed.y
		if requestedActions[Actions.DOWN]:
			newLocationBasedOnActions.y += self.physics.maxSpeed.y
		if requestedActions[Actions.LEFT]:
			newLocationBasedOnActions.x -= self.physics.maxSpeed.x
		if requestedActions[Actions.RIGHT]:
			newLocationBasedOnActions.x += self.physics.maxSpeed.x

		return newLocationBasedOnActions

	def drawElement(self):
		pass
Esempio n. 15
0
    def __init__(self, _main):

        self.main = _main

        # Physics
        self.physics = Physics(self)
        # Level
        self.levelloader = LevelLoader(self)
        # Input
        # Player
        self.player = Player(self)
        # GUI

        # STATE
        self.isFloating = False
Esempio n. 16
0
 def update_objects(self):
     for i in self.objects:
         force = Vector(0, 0, 0)
         for j in self.objects:
             if i != j:
                 force.add(Physics.Force(i, j))
                 if i.get_location().distance(j.get_location()) <= i.get_diameter()/2 + j.get_diameter()/2:
                     self.collision = True
                     self.dt = 0
             
         acceleration = Physics.acc(i, force)
         
         i.update(acceleration, self.dt)
         
         
Esempio n. 17
0
 def __init__(self, _main):
     
     self.main = _main
     
     ## PHYSICS HANDLER ##
     self.physics = Physics(self)
     
     ## LEVEL LOADER ##
     self.currentLevelName = None
     self.levelloader = LevelLoader(self)
     self.currentLevelName = "startLevel2-extra"
     
     ## INPUT HANDLER
     self.input = Input(self)
     self.movementOption = '1'
     
     ## HANDLE PLAYER ##
     self.isPlayerActive = False
     self.player = {}
     self.activePlayerName = "player2"
     
     ## Start GuI ##
     self.gui = Gui(self)
     
     self.accept("doStart", self.startGame)
     
     ## GAME STATE VARIABLES ##
     self.isMoving = False
     self.isFloating = False
Esempio n. 18
0
    def build_level(self, level_file='lvl/level1.lvl'):
        lvl = Level(level_file)
        w, h = 100., 100.
        self.physics = Physics(w, h)

        # build units
        hero = self.add_hero(*lvl.units['h'][0])
        ball = self.add_ball(*lvl.units['b'][0])
        goal = self.add_goal(*lvl.units['g'][0])
        units = [hero, ball, goal]
        self.hero, self.ball, self.goal = hero, ball, goal
        for sym, target, anim in [('h', hero, 'type1'), ('b', ball, 'type2'),
                                  ('g', goal, 'type3')]:
            for (x, y) in lvl.units['e%s' % sym]:
                u = self.add_enemy_following_target(x, y, target)
                u.set_animation(anim)
                units.append(u)

        self.units = units

        # build physics space
        self.physics.space.add_collision_handler(
            3,  # goal
            4,  # ball
            post_solve=self.game_rules.collision_ball_border,
        )

        # Bind events to actions
        def on_double_tap(dt, pos):
            if not self.is_paused:
                self.add_explosion(hero.get_position())

        def on_key_down(dt, key):
            actions = {
                'w': self.hero.move_up,
                's': self.hero.move_down,
                'a': self.hero.move_left,
                'd': self.hero.move_right,
                'o': lambda _: self.add_explosion(hero.get_position()),
            }
            if key in actions:
                actions[key](dt)

        self.event_manager.register_action('double tap', on_double_tap)
        self.event_manager.register_action('swipe', self.hero.move)
        self.event_manager.register_action('key down', on_key_down)
Esempio n. 19
0
class Simulation:

    def __init__(self, screen_rect):

        self.wall_group = list()

        rect = pygame.rect.Rect((0, 0), (10, screen_rect.h))
        rect.topright = screen_rect.topright
        self.wall_group.append(Wall(rect))

        rect = pygame.rect.Rect((0, 0), (screen_rect.w, 10))
        rect.bottomleft = screen_rect.bottomleft
        self.wall_group.append(Wall(rect))

        rect = pygame.rect.Rect((0, 0), (10, screen_rect.h))
        rect.topleft = screen_rect.topleft
        self.wall_group.append(Wall(rect))

        rect = pygame.rect.Rect((0, 0), (screen_rect.w, 10))
        rect.topleft = screen_rect.topleft
        self.wall_group.append(Wall(rect))

        self.ball_group = list()
        for i in range(50):
            b = Ball((random.randint(0, screen_rect.w), random.randint(0, screen_rect.h)))
            if not any(Physics.is_circle_collision(b, ball) for ball in self.ball_group):
                self.ball_group.append(b)

        self.physics = Physics()
        self.physics.solids.extend(self.wall_group)
        self.physics.mobiles.extend(self.ball_group)

    def compute(self, delta_time):
        for ball in self.ball_group:
            ball.compute(delta_time)

        self.physics.compute()

    def render(self, surface):
        surface.fill(color.WHITE)

        for wall in self.wall_group:
            wall.render(surface)

        for ball in self.ball_group:
            ball.render(surface)
Esempio n. 20
0
 def __init__(self,pos_x,pos_y,width = 100,height=20):
     super().__init__()
     self.settings = Settings()
     self.image = pygame.Surface((width,height))
     self.image.fill('orange')
     self.rect = self.image.get_rect()
     self.rect.x, self.rect.y = pos_x, pos_y
     self.physics = Physics(self.rect,1000)
def selfControlFunction(physics: Physics, logging: Logging,
                        regulator: Regulator, coeffs: dict, target: dict):
    nst = new_state_vector = physics.getStatus()
    fst = full_state_vector = logging.last()

    dt = fst["dt"] = nst["t"] - fst[
        "t"]  #ибо используем много, а каждый раз прописывать лень

    fst["tetaL1"] = (nst["tetaL"] - fst["tetaL"]) / dt
    fst["tetaR1"] = (nst["tetaR"] - fst["tetaR"]) / dt
    new_teta = (nst["tetaL"] + nst["tetaR"]) / 2
    fst["teta1"] = (new_teta - fst["teta"]) / dt
    fst["teta"] = new_teta

    dxl = fst["teta1"] * coeffs["r"]
    fst["xl"] += dxl
    fst["xl1"] = dxl / dt

    beta1 = coeffs["r"] / coeffs["B"] * (fst["tetaR1"] - fst["tetaL1"])
    fst["beta"] += beta1 * dt
    x1 = math.cos(fst["beta"]) * fst["xl1"]
    y1 = math.sin(fst["beta"]) * fst["xl1"]
    fst["x"] += x1 * dt
    fst["y"] += y1 * dt

    ex = target["xT"] - fst["x"]
    ey = target["yT"] - fst["y"]

    fst["gamma"] = math.atan2(ey, ex)
    fst["alpha"] = fst["gamma"] - fst["beta"]  # угол ошибки
    if (abs(fst["alpha"]) > math.pi
        ):  # не забываем про выход за границы множества углов [-pi; pi)
        fst["alpha"] = fst["alpha"] - math.copysign(1,
                                                    fst["alpha"]) * 2 * math.pi

    fst["ro"] = math.sqrt(ey**2 + ex**2)
    fst["tetaT"] = fst["teta"] + fst["ro"] * math.cos(
        fst["alpha"]) / coeffs["r"]

    #обновляем все остальные базовые характеристики
    full_state_vector.update(new_state_vector)

    logging.add(full_state_vector)
    power_vector = regulator.regulate(full_state_vector)
    physics.setRegulation(power_vector)
Esempio n. 22
0
class Entity:
	def __init__(self, sceneManager, name, mesh = "", pos = ogre.Vector3(0,0,0), vel = ogre.Vector3(0,0,0), heading = 0, speed = 0, desiredSpeed = 0, desiredHeading = 0, turningRate = 0):
		self.name = name
		self.mesh = mesh
		self.pos = pos
		self.vel = vel
		self.heading = heading
		self.speed = speed
		self.desiredSpeed = desiredSpeed
		self.desiredHeading = desiredHeading
		self.turningRate = turningRate
		self.sceneManager = sceneManager
		self.physics = Physics(self)
		self.renderable = Renderable(self, self.sceneManager)

	def tick(self, time):
		self.physics.tick(time)
		self.renderable.tick()
 def test_calc_brake_distance(self):
     me, world, game = load_objects()
     phys = Physics(world, game)
     car_state = CarState.from_car(me)
     car_state.wheel_turn = 0.0
     car_state.speed = np.array([-27.0311463976256405, 0.0])
     speed_limit = 1.8195814109630735
     ticks, brake_dist, car_state = phys.calc_brake_distance(
         car_state, speed_limit)
     self.assertEqual(ticks, 72)
     self.assertAlmostEquals(brake_dist,
                             958.2923150089691262,
                             delta=TestPhysics.EPSILON)
     self.assertTrue(
         np.allclose(car_state.speed,
                     np.array([-1.8195814109630735, 0.0]),
                     rtol=0,
                     atol=TestPhysics.EPSILON))
Esempio n. 24
0
 def __init__(self, location, speed):
     """
     The location is an (x,y) coordinate pair, and speed is the player's
     speed in pixels per frame. Speed should be an integer.
     """
     Physics.__init__(self)
     pg.sprite.Sprite.__init__(self)
     self.image = pg.Surface((30, 55)).convert()
     self.image.fill(pg.Color("red"))
     self.rect = self.image.get_rect(topleft=location)
     self.speed = speed
     self.jump_power = -9.0
     self.jump_cut_magnitude = -3.0
     self.on_moving = False
     self.collide_below = False
     self.weapons = {
         1: MachineGun(),
     }
     self.weapon = self.weapons[1]
Esempio n. 25
0
    def add_type(self,
                 name,
                 drawn_type=None,
                 res_asset_path=None,
                 full_asset_path=None,
                 meta_path=None):
        # make asset path safe
        if res_asset_path is not None:
            res_asset_path = res_asset_path.replace('\\', '/')

        add_type = DrawnType(name,
                             start_ext_id=self.curr_ext_resource_id,
                             start_sub_id=self.curr_sub_resource_id)
        # break out for specific node types
        if drawn_type is not None and drawn_type in self.TYPES:
            if drawn_type == 'sprite':
                add_type = Sprite(name,
                                  res_asset_path,
                                  meta_path=meta_path,
                                  start_ext_id=self.curr_ext_resource_id,
                                  start_sub_id=self.curr_sub_resource_id)
            elif drawn_type == 'static':
                add_type = Static(name,
                                  res_asset_path,
                                  full_asset_path,
                                  self.curr_ext_resource_id,
                                  self.curr_sub_resource_id,
                                  meta_path=meta_path)
            elif drawn_type == 'platforms':
                add_type = Static(name,
                                  res_asset_path,
                                  full_asset_path,
                                  self.curr_ext_resource_id,
                                  self.curr_sub_resource_id,
                                  meta_path=meta_path,
                                  one_way=True)
            elif drawn_type == 'physics' or drawn_type == 'items':
                add_type = Physics(name, res_asset_path, meta_path,
                                   self.curr_ext_resource_id,
                                   self.curr_sub_resource_id)
        elif res_asset_path is not None:
            # use sprites, if asset path exists
            add_type = Sprite(name,
                              res_asset_path,
                              meta_path=meta_path,
                              start_ext_id=self.curr_ext_resource_id,
                              start_sub_id=self.curr_sub_resource_id)

        # add node, external, sub content
        self.nodes += add_type.get_node_string() + '\n'
        self.ext_resources += add_type.get_ext_resources_string()
        self.sub_resources += add_type.get_sub_resources_string()
        # update id's
        self.curr_ext_resource_id = add_type.get_last_ext_id()
        self.curr_sub_resource_id = add_type.get_last_sub_id()
Esempio n. 26
0
    def __init__(self, config_file=None):
        """
            Method to initialize the Engine class.
        """
        pygame.init()
        self.running = True
        self.icon = pygame.image.load("assets/icon.png")
        self.background = pygame.image.load("assets/background.png")

        self.score_value = 0
        self.screen_text = pygame.font.Font('freesansbold.ttf', 32)

        self.screen = pygame.display.set_mode((800, 600))
        pygame.display.set_caption("Space Invaders")
        pygame.display.set_icon(self.icon)

        self.player = Player()
        self.enemy_fleet = EnemyFleet(16)
        self.enemy_fleet.create_fleet()
        self.game_physics = Physics()
Esempio n. 27
0
 def __init__(self):
     Physics.__init__(self)
     pg.sprite.Sprite.__init__(self)
     self.width = con.RUNNER_WIDTH
     self.height = con.RUNNER_HEIGHT
     self.right_image = setup.GFX['knightsprite_right']
     self.right_image = pg.transform.scale(self.right_image, (80, 80)).convert_alpha()
     self.left_image = setup.GFX['knightsprite_left']
     self.left_image = pg.transform.scale(self.left_image, (80, 80)).convert_alpha()
     self.image = self.right_image
     self.rect = self.image.get_rect()
     self.rect.width *= .75
     self.name = con.RUNNER_NAME
     self.speed = con.RUNNER_SPEED
     self.jump_power = con.JUMP_POWER
     self.moving_right = True
     self.ok_to_jump = True
     self.dead = False
     self.on_mover = False
     self.mover = None
Esempio n. 28
0
    def __init__(self, period=0.05):
        """Setup the world, physics and viewer for the simulation."""
        # bind the world step rate
        # - seconds, passed to gui loop
        self.period = period
        # - ideal step length, but procees time will vary
        self.current_dt_target = period

        # setup the size of the world
        self.width = DEFAULT_WORLD_M_W
        self.height = DEFAULT_WORLD_M_H

        # initialize physics engine
        self.physics = Physics(self)

        # create the map manager
        self.map_manager = MapManager(self)

        # create the GUI
        self.viewer = Viewer(self, self.period, DEFAULT_ZOOM, RANDOM)
        self.viewer.initialise_viewer()
    def velocity(self):
        """ updates velocity """
        for i, body in enumerate(self._body_list):
            v = Physics.velocity(body.get_velocity(), self.dt,
                                 self.a_matrix[:, i])
            body.set_position(v, self.dt)

            if i == 1:
                self._velocity_analytics.add_data(self._t, la.norm(v))

        self._t += self.dt
        self.render()
Esempio n. 30
0
 def __init__( self, surface ):
     self.surface = surface
     self.points = 8
     self.segments = 20
     #
     self.world = Physics()
     self.world.set_world( self.surface.get_size() )
     self.world.set_repulsive_threshold( 100.0 )
     self.world.set_viscosity( 0.85 )
     #
     vertex_ring = create_initial_ring( self.surface, self.points, 10 )
     self.colour = ColourGen()
     self.polygon_chain = PolygonShapeChain( self.segments, vertex_ring, self.colour.current(), GlowingBallShape )
Esempio n. 31
0
class Game():
    def __init__(self, _main):

        self.main = _main

        # Physics
        self.physics = Physics(self)
        # Level
        self.levelloader = LevelLoader(self)
        # Input
        # Player
        self.player = Player(self)
        # GUI

        # STATE
        self.isFloating = False

    def start_game(self):
        self.physics.start()

    def stop_game(self):
        self.physics.stop()
Esempio n. 32
0
 def __init__(self,
              name='untiled',
              pos=MyVector(0, 0, 0),
              vel=MyVector(0, 0, 0),
              mesh='untiled.mesh',
              yaw=0):
     self.name = name
     self.pos = pos
     self.vel = vel
     self.mesh = mesh
     self.yaw = yaw
     self.aspectTypes = ['Physics']
     self.aspects = [Physics(self)]
Esempio n. 33
0
def run_game():
    pygame.init()

    screen_size = (600, 385)
    screen = pygame.display.set_mode(screen_size)
    mario = Mario(screen)
    background = Background(screen, './mario_pics/full_background_no_sky.png',
                            mario)
    question_block = Block(screen, 300)
    physics = Physics()
    # first_goomba = Goomba(screen)
    enemies = Group()
    game_on = True
    tick = 0
    background_color = (93, 148, 251)
    # r = randint(0, 255)
    # g = randint(0,255)
    # b = randint(0,255)

    while game_on == True:
        # tick += 1
        # background_color = (r, g, b)
        # if tick % 5 == 0:
        # 	r += 10
        # 	g += 15
        # 	b += 16
        # if r > 230:
        # 	r -= 150
        # if g > 230:
        # 	g -= 150
        # if b > 230:
        # 	b -= 150

        # print tick
        for i in background.goomba_spawn_points:
            if background.x == i:
                enemies.add(Goomba(screen))
        check_events(background, mario, question_block, screen)
        screen.fill(background_color)
        background.draw_background(mario)
        mario.draw_mario(physics, background)
        question_block.draw_block(mario)
        print enemies
        for enemy in enemies:
            enemy.draw_goomba(mario, physics, background)
            mario.check_mario_is_alive(background, enemy)
        # first_goomba.draw_goomba(mario)

        pygame.display.flip()
Esempio n. 34
0
 def __init__(self,
              pos,
              vel,
              angle,
              angle_vel,
              image,
              info,
              WIDTH,
              HEIGHT,
              sound=None,
              is_kinetic=False,
              acc=0,
              ang_acc=0,
              fr=0):
     self.pos = [pos[0], pos[1]]
     self.vel = [vel[0], vel[1]]
     self.angle = angle
     self.angle_vel = angle_vel
     self.image = image
     self.image_center = info.get_center()
     self.image_size = info.get_size()
     radius = info.get_radius()
     self.lifespan = info.get_lifespan()
     self.animated = info.get_animated()
     #self.age = 0
     if sound:
         sound.rewind()
         sound.play()
     if is_kinetic:
         if self.lifespan == None:
             self.physics = Physics(radius, WIDTH, HEIGHT, None, is_kinetic,
                                    fr)
         else:
             self.physics = Physics(radius, WIDTH, HEIGHT, self.lifespan,
                                    is_kinetic, fr)
         self.physics.set_ang_acc(ang_acc)
         self.physics.set_acc(acc)
     else:
         if self.lifespan == None:
             self.physics = Physics(radius, WIDTH, HEIGHT)
         else:
             self.physics = Physics(radius, WIDTH, HEIGHT, self.lifespan)
     self.physics.set_pos(pos)
     self.physics.set_vel(vel)
     self.physics.set_ang(angle)
     self.physics.set_ang_vel(angle_vel)
Esempio n. 35
0
    def build_level(self, level_file='lvl/level1.lvl'):
        lvl = Level(level_file)
        w, h = 100., 100.
        self.physics = Physics(w, h)

        # build units
        hero = self.add_hero(*lvl.units['h'][0])
        ball = self.add_ball(*lvl.units['b'][0])
        goal = self.add_goal(*lvl.units['g'][0])
        units = [hero, ball, goal]
        self.hero, self.ball, self.goal = hero, ball, goal
        for sym, target, anim in [('h', hero, 'type1'), ('b', ball, 'type2'), ('g', goal, 'type3')]:
            for (x, y) in lvl.units['e%s' % sym]:
                u = self.add_enemy_following_target(x, y, target)
                u.set_animation(anim)
                units.append(u)

        self.units = units

        # build physics space
        self.physics.space.add_collision_handler(
            3,  # goal
            4,  # ball
            post_solve=self.game_rules.collision_ball_border,
        )

        # Bind events to actions
        def on_double_tap(dt, pos):
            if not self.is_paused:
                self.add_explosion(hero.get_position())

        def on_key_down(dt, key):
            actions = {
                'w': self.hero.move_up,
                's': self.hero.move_down,
                'a': self.hero.move_left,
                'd': self.hero.move_right,
                'o': lambda _: self.add_explosion(hero.get_position()),
            }
            if key in actions:
                actions[key](dt)

        self.event_manager.register_action('double tap', on_double_tap)
        self.event_manager.register_action('swipe', self.hero.move)
        self.event_manager.register_action('key down', on_key_down)
Esempio n. 36
0
class Game():
    physics = Physics()

    def __init__(self):
        self.artifact_manager = ArtifactManager()
        self.hero_manager = HeroManager()

    def connect_new_gamer(self, id, name):
        self.hero_manager.add(id, name)
        return self.hero_manager.get(id)

    def disconnect_gamer(self, id):
        self.hero_manager.delete(id)

    def get_all_artifacts(self):
        all = []
        for a in self.artifact_manager.get_all():
            a = a.__dict__
            all.append(a)
        return all

    def get_all_heroes(self):
        all = []
        for a in self.hero_manager.get_all():
            a = a.__dict__
            all.append(a)
        return all

    def move(self, id, direction):
        self.hero_manager.move(id, direction)
        hero = self.hero_manager.get(id)
        r = {'x': hero.x, 'y': hero.y, 'diameter': hero.diameter, 'eat': None}
        for artifact in self.artifact_manager.get_all():
            if self.physics.object_on_object(hero, artifact):
                self.hero_manager.eat_artifact(id, artifact)
                self.artifact_manager.delete(artifact.id)
                r['eat'] = artifact
        for another_hero in self.hero_manager.get_all():
            if self.physics.object_on_object(
                    hero, another_hero) and another_hero.id != hero.id:
                self.hero_manager.eat_hero(id, another_hero)
                self.hero_manager.delete(another_hero.id)
                r['eat'] = another_hero
        return r
Esempio n. 37
0
    def __init__(self, period=0.05):
        """Setup the world, physics and viewer for the simulation."""
        # bind the world step rate
        # - seconds, passed to gui loop
        self.period = period
        # - ideal step length, but procees time will vary
        self.current_dt_target = period

        # setup the size of the world
        self.width = DEFAULT_WORLD_M_W
        self.height = DEFAULT_WORLD_M_H

        # initialize physics engine
        self.physics = Physics(self)

        # create the map manager
        self.map_manager = MapManager(self)

        # create the GUI
        self.viewer = Viewer(self, self.period, DEFAULT_ZOOM, RANDOM)
        self.viewer.initialise_viewer()
Esempio n. 38
0
 def run(self):
     # Initialise variables
     self.physics = False
     self.physics_engine = Physics(self)
     self.raw_blocks = None
     self.running = True
     self.unflooding = False
     self.finite_water = False
     self.queued_blocks = {} # Blocks which need to be flushed into the file.
     self.create_raw_blocks()
     # Start physics engine
     self.physics_engine.start()
     # Main eval loop
     while self.running:
         try:
             # Pop something off the queue
             task = self.in_queue.get()
             # If we've been asked to flush, do so, and say we did.
             if task[0] is TASK_FLUSH:
                 self.flush()
                 self.out_queue.put([TASK_FLUSH])
             # New block?
             elif task[0] is TASK_BLOCKSET:
                 try:
                     self[task[1]] = task[2]
                 except AssertionError:
                     logging.log("Tried to set a block at %s in %s!" % (task[1], self.blocks_path), logging.WARN)
             # Asking for a block?
             elif task[0] is TASK_BLOCKGET:
                 self.out_queue.put([TASK_BLOCKGET, task[1], self[task[1]]])
             # Perhaps physics was enabled?
             elif task[0] is TASK_PHYSICSOFF:
                 logging.log(logging.DEBUG, "Disabling physics on '%s'..." % self.blocks_path)
                 self.disable_physics()
             # Or disabled?
             elif task[0] is TASK_PHYSICSON:
                 logging.log(logging.DEBUG, "Enabling physics on '%s'..." % self.blocks_path)
                 self.enable_physics()
             # I can haz finite water tiem?
             elif task[0] is TASK_FWATERON:
                 logging.log(logging.DEBUG, "Enabling finite water on '%s'..." % self.blocks_path)
                 self.finite_water = True
             # Noes, no more finite water.
             elif task[0] is TASK_FWATEROFF:
                 logging.log(logging.DEBUG, "Disabling finite water on '%s'..." % self.blocks_path)
                 self.finite_water = False
             # Do they need to do a Moses?
             elif task[0] is TASK_UNFLOOD:
                 logging.log(logging.DEBUG, "Unflood started on '%s'..." % self.blocks_path)
                 self.unflooding = True
             # Perhaps that's it, and we need to stop?
             elif task[0] is TASK_STOP:
                 logging.log(logging.DEBUG, "Stopping block store '%s'..." % self.blocks_path)
                 self.physics_engine.stop()
                 self.flush()
                 logging.log(logging.DEBUG, "Stopped block store '%s'." % self.blocks_path)
                 return
             # ???
             else:
                 raise ValueError("Unknown BlockStore task: %s" % task)
         except (KeyboardInterrupt, IOError):
             pass
Esempio n. 39
0
class BlockStore(Thread):
    """
    A class which deals with storing the block worlds, flushing them, etc.
    """
    
    def __init__(self, blocks_path,  sx, sy, sz):
        Thread.__init__(self)
        self.x, self.y, self.z = sx, sy, sz
        self.blocks_path = blocks_path
        self.in_queue = Queue()
        self.out_queue = Queue()
        self.saving = False

    def run(self):
        # Initialise variables
        self.physics = False
        self.physics_engine = Physics(self)
        self.raw_blocks = None
        self.running = True
        self.unflooding = False
        self.finite_water = False
        self.queued_blocks = {} # Blocks which need to be flushed into the file.
        self.create_raw_blocks()
        # Start physics engine
        self.physics_engine.start()
        # Main eval loop
        while self.running:
            try:
                # Pop something off the queue
                task = self.in_queue.get()
                # If we've been asked to flush, do so, and say we did.
                if task[0] is TASK_FLUSH:
                    self.flush()
                    self.out_queue.put([TASK_FLUSH])
                # New block?
                elif task[0] is TASK_BLOCKSET:
                    try:
                        self[task[1]] = task[2]
                    except AssertionError:
                        logging.log("Tried to set a block at %s in %s!" % (task[1], self.blocks_path), logging.WARN)
                # Asking for a block?
                elif task[0] is TASK_BLOCKGET:
                    self.out_queue.put([TASK_BLOCKGET, task[1], self[task[1]]])
                # Perhaps physics was enabled?
                elif task[0] is TASK_PHYSICSOFF:
                    logging.log(logging.DEBUG, "Disabling physics on '%s'..." % self.blocks_path)
                    self.disable_physics()
                # Or disabled?
                elif task[0] is TASK_PHYSICSON:
                    logging.log(logging.DEBUG, "Enabling physics on '%s'..." % self.blocks_path)
                    self.enable_physics()
                # I can haz finite water tiem?
                elif task[0] is TASK_FWATERON:
                    logging.log(logging.DEBUG, "Enabling finite water on '%s'..." % self.blocks_path)
                    self.finite_water = True
                # Noes, no more finite water.
                elif task[0] is TASK_FWATEROFF:
                    logging.log(logging.DEBUG, "Disabling finite water on '%s'..." % self.blocks_path)
                    self.finite_water = False
                # Do they need to do a Moses?
                elif task[0] is TASK_UNFLOOD:
                    logging.log(logging.DEBUG, "Unflood started on '%s'..." % self.blocks_path)
                    self.unflooding = True
                # Perhaps that's it, and we need to stop?
                elif task[0] is TASK_STOP:
                    logging.log(logging.DEBUG, "Stopping block store '%s'..." % self.blocks_path)
                    self.physics_engine.stop()
                    self.flush()
                    logging.log(logging.DEBUG, "Stopped block store '%s'." % self.blocks_path)
                    return
                # ???
                else:
                    raise ValueError("Unknown BlockStore task: %s" % task)
            except (KeyboardInterrupt, IOError):
                pass
    
    def enable_physics(self):
        "Turns on physics"
        self.flush()
        self.physics = True
    
    def disable_physics(self):
        "Disables physics, and clears the in-memory store."
        self.physics = False
    
    def create_raw_blocks(self):
        "Reads in the gzipped data into a raw array"
        # Open the blocks file
        fh = gzip.GzipFile(self.blocks_path)
        self.raw_blocks = array('c')
        # Read off the size header
        fh.read(4)
        # Copy into the array in chunks
        chunk = fh.read(2048)
        while chunk:
            self.raw_blocks.extend(chunk)
            chunk = fh.read(2048)
        fh.close()
    
    def get_offset(self, x, y, z):
        "Turns block coordinates into a data offset"
        assert 0 <= x < self.x
        assert 0 <= y < self.y
        assert 0 <= z < self.z
        return y*(self.x*self.z) + z*(self.x) + x

    def get_coords(self, offset):
        "Turns a data offset into coordinates"
        x = offset % self.x
        z = (offset // self.x) % self.z
        y = offset // (self.x * self.z)
        return x, y, z

    def world_message(self, message):
        "Sends a message out to users about this World."
        self.out_queue.put([TASK_WORLDMESSAGE, message])
    
    def admin_message(self, message):
        "Sends a message out to admins about this World."
        self.out_queue.put([TASK_ADMINMESSAGE, message])

    def send_block(self, x, y, z):
        "Tells the server to update the given block for clients."
        self.out_queue.put([TASK_BLOCKSET, (x, y, z, self[x, y, z])])
    
    def __setitem__(self, (x, y, z), block):
        "Set a block in this level to the given value."
        assert isinstance(block, str) and len(block) == 1
        # Save to queued blocks
        offset = self.get_offset(x, y, z)
        self.queued_blocks[offset] = block
        # And directly to raw blocks, if we must
        if self.raw_blocks:
            self.raw_blocks[offset] = block
        # Ask the physics engine if they'd like a look at that
        self.physics_engine.handle_change(offset, block)
Esempio n. 40
0
	def resetElementForNewGame(self):
		self.physics = Physics(self.startX, self.startY)
		self.drawShip()
Esempio n. 41
0
def game():
    screen.fill(black)
    running = True
    keyboard = Keyboard()
    world = World(32, 32)
    off = ((WIDTH - world.get_render_width()) / 2,
           (HEIGHT - world.get_render_height()) / 2)
    world.offX = off[0]
    world.offY = off[1]
    ply = Player(0, 0, world)
    ply.x = random.randint(0, WIDTH - ply.w)
    ply.y = random.randint(0, HEIGHT - ply.h)
    while world.entity_hitpos(ply):
        ply.x = random.randint(0, WIDTH - ply.w)
        ply.y = random.randint(0, HEIGHT - ply.h)
    physics = Physics(world, (WIDTH, HEIGHT))
    physics.watch(ply)
    clock = pygame.time.Clock()
    last = pygame.time.get_ticks()
    ticks = 0
    plydeathtimer = 0
    lastrect = pygame.Rect(0, 0, 0, 0)

    while running:
        ticks += 1
        clock.tick(0)
        for ev in pygame.event.get():
            if ev.type == QUIT:
                running = False
                break
            elif ev.type == FRAMECOUNTER:
                print clock.get_fps()
            elif ev.type == WORLDREGEN:
                world.regen_once()
            elif ev.type == ENTITYGEN:
                x = random.randint(0, WIDTH)
                y = random.randint(0, HEIGHT)
                physics.watch(Enemy(x, y, world, physics))
            elif ev.type == MOUSEBUTTONDOWN:
                if ev.button == 0 and plydeathtimer == 0:
                    mpos = ev.pos
                    center = ply.get_center()
                    a = mpos[0] - center[0]
                    b = mpos[1] - center[1]
                    # tan(ang) = b / a
                    ang = math.atan2(b, a)

                    # Calculate bullet pos
                    pos = [math.cos(ang) * ply.w + center[0],
                           math.sin(ang) * ply.h + center[1]]

                    bull = Bullet(pos[0], pos[1], world)
                    speed = 2
                    bull.vx = speed * math.cos(ang)
                    bull.vy = speed * math.sin(ang)
                    physics.watch(bull)
                    shootsound.play()

            elif ev.type == KEYDOWN:
                keyboard.keydown(ev.key)
            elif ev.type == KEYUP:
                keyboard.keyup(ev.key)

        # Handle movement
        if plydeathtimer == 0:
            if keyboard.is_down(K_w):
                ply.vy = -1
            elif keyboard.is_down(K_s):
                ply.vy = 1
            else:
                ply.vy = 0
            if keyboard.is_down(K_a):
                ply.vx = -1
            elif keyboard.is_down(K_d):
                ply.vx = 1
            else:
                ply.vx = 0

        # Shooting repeat
        if ticks % 10 == 0 and pygame.mouse.get_pressed()[0]:
            mpos = pygame.mouse.get_pos()
            center = ply.get_center()
            a = mpos[0] - center[0]
            b = mpos[1] - center[1]
            # tan(ang) = b / a
            ang = math.atan2(b, a)

            # Calculate bullet pos
            pos = [math.cos(ang) * ply.w + center[0],
                   math.sin(ang) * ply.h + center[1]]

            bull = Bullet(pos[0], pos[1], world)
            speed = 2
            bull.vx = speed * math.cos(ang)
            bull.vy = speed * math.sin(ang)
            physics.watch(bull)
            shootsound.play()


        for ent in physics.entities:
            if isinstance(ent, Enemy):
                ent.think(ply)

        if world.win():
            win()
            running = False
        if ply.lives == 0:
            lose()
            running = False
        elif ply.removeme:
            ply.removeme = False
            plydeathtimer = 180
        if plydeathtimer > 0:
            if plydeathtimer == 1:
                ply.x = random.randint(0, WIDTH - ply.w)
                ply.y = random.randint(0, HEIGHT - ply.h)
                while world.entity_hitpos(ply):
                    ply.x = random.randint(0, WIDTH - ply.w)
                    ply.y = random.randint(0, HEIGHT - ply.h)
                physics.watch(ply)
            plydeathtimer -= 1

        # Clear previous font
        screen.fill(black, lastrect)

        # Render
        physics.renderclear(screen)
        world.render(screen)
        physics.tick()
        physics.render(screen)

        # Display health
        msg = "Lives: %d | Health: %d" % (ply.lives, ply.health)
        text = bigfont.render(msg, 1, white)
        lastrect = pygame.Rect(0, 0, text.get_width(), text.get_height())
        screen.blit(text, (0, 0))
        pygame.display.flip()


        dt = pygame.time.get_ticks() - last
        if dt < (1000 / 60):
            pygame.time.delay((1000 / 60) - dt)
        last = pygame.time.get_ticks()
Esempio n. 42
0
					gingerbreadIntelligenceThread

			objects.append(gingerbreadMonster)
		elif object[0] == "some other monster":
			pass


if __name__ == '__main__':
	Network.Listen('0.0.0.0', 30000)

	startTime = time.time()

	objdata = []
	players = []

	physics = Physics(objects)
	physics.isClient = False

	spawnMonsters()

	physics.updateObjects(objects)

	try:
		lastSend = 0
		while True:
			objects = physics.update()

			sendObjdata = False

			read_sockets, write_sockets, error_sockets = \
					select.select(
Esempio n. 43
0
class Game(DirectObject):
    
    def __init__(self, _main):
        
        self.main = _main
        
        ## PHYSICS HANDLER ##
        self.physics = Physics(self)
        
        ## LEVEL LOADER ##
        self.currentLevelName = None
        self.levelloader = LevelLoader(self)
        self.currentLevelName = "startLevel2-extra"
        
        ## INPUT HANDLER
        self.input = Input(self)
        self.movementOption = '1'
        
        ## HANDLE PLAYER ##
        self.isPlayerActive = False
        self.player = {}
        self.activePlayerName = "player2"
        
        ## Start GuI ##
        self.gui = Gui(self)
        
        self.accept("doStart", self.startGame)
        
        ## GAME STATE VARIABLES ##
        self.isMoving = False
        self.isFloating = False
    
    def startGame(self):
        self.gui.hideMenu()
        self.levelloader.newLevel(self.currentLevelName)
        self.createPlayer(self.activePlayerName)
        self.gui.showGameGui()
        self.levelloader.startCounter()
        
        ## HANDLE CAMERA ##
        self.camera = Camera(self)
        
        ## START PHYSICS ##
        self.physics.start()
        
    def stopGame(self):
        self.gui.hideGameGui()
        
        for object in self.levelloader.levelObjects:
            object.remove()
        
        for stateCoin in self.levelloader.levelStateCoins.keys():
            self.levelloader.levelStateCoins["exit"].exitModel.remove()
            self.levelloader.levelStateCoins["exit"] = None
            
        for coin in self.levelloader.levelCoins.keys():
            self.levelloader.levelCoins[coin].coinModel.remove()
            self.levelloader.levelCoins[coin] = None

        for node in self.physics.World.getRigidBodies():
            self.physics.World.removeRigidBody(node)
            
        for node in self.physics.World.getGhosts():
            self.physics.World.removeGhost(node)
            
        #self.levelloader.level = None
        self.levelloader.stopCounter()
        
        self.player[self.activePlayerName].removePlayer()
        self.player = None
        
        self.camera.stopCamTask()
        # Reset Cursor
        winProps = WindowProperties()
        winProps.setCursorHidden(False)
        base.win.requestProperties(winProps)
        self.camera = None
        
        self.physics.stop()
        
        self.gui.showMenu()
        
    
    def createPlayer(self, name):
        self.player = {}
        self.player[name] = Player(self, name)
Esempio n. 44
0
class GameLogic(State):

    time = 0

    def __init__(self):
        self.game_ended = False
        self.stop_when_unpaused = False
        self.explosions_left = 3
        self.game_rules = GameRules(self)
        self.i = 0

    def build_widget(self):
        self.game_interface = GameInterface()
        return self.game_interface

    def update(self, dt):
        # continue animation when the game has ended
        if self.is_paused and not self.stop_when_unpaused:
            return True

        self.time += dt
        self.game_interface.score = self.game_state.score
        self.game_interface.time = self.time
        self.game_interface.explosions_left = self.explosions_left
        if self.i % 100 == 0:
            self.game_interface.fps = int((self.i/self.time + 9/dt)/10)
        self.i += 1

        self.physics.update(dt)
        for u in self.units:
            u.update(dt)

        if self.is_paused:
            return True

        if self.stop_when_unpaused:
            self.stop()
        return super(GameLogic, self).update(dt=dt)

    def build_level(self, level_file='lvl/level1.lvl'):
        lvl = Level(level_file)
        w, h = 100., 100.
        self.physics = Physics(w, h)

        # build units
        hero = self.add_hero(*lvl.units['h'][0])
        ball = self.add_ball(*lvl.units['b'][0])
        goal = self.add_goal(*lvl.units['g'][0])
        units = [hero, ball, goal]
        self.hero, self.ball, self.goal = hero, ball, goal
        for sym, target, anim in [('h', hero, 'type1'), ('b', ball, 'type2'), ('g', goal, 'type3')]:
            for (x, y) in lvl.units['e%s' % sym]:
                u = self.add_enemy_following_target(x, y, target)
                u.set_animation(anim)
                units.append(u)

        self.units = units

        # build physics space
        self.physics.space.add_collision_handler(
            3,  # goal
            4,  # ball
            post_solve=self.game_rules.collision_ball_border,
        )

        # Bind events to actions
        def on_double_tap(dt, pos):
            if not self.is_paused:
                self.add_explosion(hero.get_position())

        def on_key_down(dt, key):
            actions = {
                'w': self.hero.move_up,
                's': self.hero.move_down,
                'a': self.hero.move_left,
                'd': self.hero.move_right,
                'o': lambda _: self.add_explosion(hero.get_position()),
            }
            if key in actions:
                actions[key](dt)

        self.event_manager.register_action('double tap', on_double_tap)
        self.event_manager.register_action('swipe', self.hero.move)
        self.event_manager.register_action('key down', on_key_down)

    def on_game_end(self, player_won):
        self.game_ended = True
        if player_won:
            self.game_state.score += 1
        else:
            self.game_state.score -= 1
        self.game_state.player_won = player_won
        self.goal.set_animation('happy', 2)

    def stop(self):
        self.on_quit()
        super(GameLogic, self).stop()

    # function for building units
    def add_unit(self, unit_factory, x, y):
        size = config.get_sprite_size()
        u = unit_factory(size)
        u.set_position(x, y)
        self.physics.add_body(u)
        self.game_interface.add_widget(u.gfx)
        return u

    def add_hero(self, x, y):
        return self.add_unit(Hero, x, y)

    def add_ball(self, x, y):
        return self.add_unit(Brick, x, y)

    def add_goal(self, x, y):
        return self.add_unit(Goal, x, y)

    def add_enemy_following_target(self, x, y, hero):
        enemy = self.add_unit(Enemy,  x, y)
        ai = EnemyFollowingTargetAi(hero)
        enemy.add_ai(ai)
        return enemy

    # Actions

    def add_explosion(self, center):
        if self.explosions_left <= 0:
            return

        self.explosions_left -= 1
        for u in self.units:
            r = 2e-2 * max(1, (u.get_position() - center).length())
            u.apply_force((u.get_position() - center).normalize() / r)
        self.game_interface.activate_shader_effect(center)
        self.hero.set_animation('special', 3)
        self.goal.set_animation('unhappy', 2)

    def move_hero(self, dt, direction):
        self.hero.move(dt, directly)
Esempio n. 45
0
 def test_displacement(self):
   object = Physics()
   self.assertEqual(6.890165, object.displacement(1, 1, 1))
Esempio n. 46
0
class World(object):
    """Sets up a world in the simulation with robots, obstacles and a goal.

    Attributes:
        period -> float
        current_dt_target -> float
        width -> int
        height -> int
        physics -> Physics object
        map_manger -> MapManger object
        viewer -> Viewer object
        world_time -> float
        prev_absolute_time -> float
        supervisors -> list
        robots -> list
        obstacles -> list
        world_view -> WorldView object

    Methods:
        __init__(period=0.05)
        initialise_world(random=False, loading=False)
        draw_world()
        step()
        add_robot(robot)
        add_obstacle(obstacle)
        colliders()
        solids()
        stop_robots()
    """
    def __init__(self, period=0.05):
        """Setup the world, physics and viewer for the simulation."""
        # bind the world step rate
        # - seconds, passed to gui loop
        self.period = period
        # - ideal step length, but procees time will vary
        self.current_dt_target = period

        # setup the size of the world
        self.width = DEFAULT_WORLD_M_W
        self.height = DEFAULT_WORLD_M_H

        # initialize physics engine
        self.physics = Physics(self)

        # create the map manager
        self.map_manager = MapManager(self)

        # create the GUI
        self.viewer = Viewer(self, self.period, DEFAULT_ZOOM, RANDOM)
        self.viewer.initialise_viewer()

    def initialise_world(self, random=False, loading=False):
        """Generate the world in the simulation gui.

        This function sets up (or resets) the robots, their supervisors,
        the obstacles and goal and draws this to the gui."""
        # initialize world time
        self.world_time = 0.0  # seconds
        self.prev_absolute_time = time()

        # initialize lists of world objects
        self.supervisors = []
        self.robots = []
        self.obstacles = []

        # create the robot
        robot_1 = Robot(1, self.viewer, -0.5, -0.5, 270)
        #robot_2 = Robot(2, self.viewer, -1.0, 0.5, 270)

        self.add_robot(robot_1)
        #self.add_robot(robot_2)

        # generate a random environment
        if random:
            self.map_manager.random_map()
            print("Random Map")
        elif loading:
            self.map_manager.apply_to_world()
            print("Loading Map")
        else:
            self.map_manager.custom_map()
            print("Custom Map")

        # create the world view
        self.world_view = WorldView(self, self.viewer)

        # render the initial world
        self.draw_world()

    def reset_world(self):
        # initialize world time
        self.world_time = 0.0  # seconds
        self.prev_absolute_time = time()

        # initialize lists of world objects
        for robot in self.robots:
            robot.setup_robot(robot.x, robot.y, robot.deg)

        # render the initial world
        self.draw_world()

    def draw_world(self):
        """Refreshes the gui with the newly setup world."""
        self.viewer.new_frame()                 # start a fresh frame
        self.world_view.draw_world_to_frame()   # draw the world onto the frame
        self.viewer.draw_frame()                # render the frame

    # step the simulation through one time interval
    def step(self):
        """Main step function of simulation, to step through time in world.

        This function first checks if the simulation is lagging or not by
        comparing the time passed since last called to the ideal time that
        should be taken between steps. An alarm is printed if lag occurs.

        The robot is first stepped in time to it's new position.

        Then physics are applied to these new robot positions to check
        for collisions and if obstacles are in range of the proximity sensors.

        The supervisors are then updated with the results of the physics test
        so controllers can be updated accordingly
        """
        # calculate time since last step iteration
        time_now = time()
        self.current_dt = time_now - self.prev_absolute_time

        # update world_time to the current time
        self.prev_absolute_time = time_now

        # increment world time
        self.world_time += self.current_dt

        self.viewer._label_world_time.set_text('{0:.2f}'.format(
            self.world_time))

        # Flag if current_dt is lagging by more than 5%
        if (self.current_dt > (self.current_dt_target * 1.05) or
                self.current_dt < (self.current_dt_target * 0.95)):
            print("Simulation lagging: {:.4f}").format(self.current_dt -
                self.current_dt_target)

        # read sensor values from all the robots
        for robot in self.robots:
            # read encoder values
            robot.read_encoders()

        # calculate the appropriate wheel velocities and control state
        for supervisor in self.supervisors:
            supervisor.step(self.current_dt)

        # step all the robots with the wheel velocities received from their
        # supervisors
        for robot in self.robots:
            # step robot motion
            robot.step_motion(self.current_dt)

        # check for interactions of robot with obstacles
        self.physics.apply_physics()

    def add_robot(self, robot):
        """Adds new robot to the robot list."""
        self.robots.append(robot)
        self.supervisors.append(robot.supervisor)

    def add_obstacle(self, obstacle):
        """Adds new obstacle to the obstacle list."""
        self.obstacles.append(obstacle)

    # return all objects in the world that might collide with other objects
    #    in the world during simulation
    def colliders(self):
        """Returns a list of any moving objects in the simulation."""
        # moving objects only
        return self.robots  # as obstacles are static we should not test them
                            #    against each other

    # return all solids in the world
    def solids(self):
        """Returns a list of any solid objects in the world."""
        return self.robots + self.obstacles

    def stop_robots(self):
        """Sends command to robot object to cease any motion.

        This is for sending a stop command to any connected physical robots.
        """
        # stop all the robots
        for robot in self.robots:
            # stop robot motion
            robot.stop_motion()