def __init__(self, definition, properties=None, components=None): def flatten_includes(definition, flattened=None): if flattened == None: flattened = [] flattened.append(definition) def_map = game.get_game().resource_manager.get('definition', definition) if 'includes' in def_map: for include in def_map['includes']: flattened = flatten_includes(include, flattened=flattened) return flattened definitions = flatten_includes(definition) self.props = EntityProperties(definitions) self.handlers = {} for defn in definitions: for component in game.get_game().resource_manager.get('definition', defn)['components']: game.get_game().component_manager.add(component, self) if properties: for key, value in properties.items(): setattr(self.props, key, value) if components: for component in components: game.get_game().component_manager.add(component, self)
def enter(self): self.music = game.get_game().resource_manager.get( 'sound', 'Main Body.ogg') self.music.play(loops=-1) game.get_game().renderer.cleanup() game.get_game().entity_manager.add_entity( entity.Entity("vortexspawner"))
def handle_day(self, entity): if entity.humans: h = entity.humans[0] energy_needed = mid() if h.energy >= energy_needed: h.energy -= energy_needed num = random.randrange(0, 100) if num < 15: food_found = min(big(),100 - camp().food) camp().food += food_found report('Explore','%s found %s food.' % (h.name, food_found)) elif num < 30: water_found = min(big(),100 - camp().water) camp().water += water_found report('Explore','%s found %s water.' % (h.name, water_found)) elif num < 45: medicine_found = min(big(),100 - camp().medicine) camp().medicine += medicine_found report('Explore','%s found %s medicine.' % (h.name, medicine_found)) else: report('Explore',"%s couldn't find anything." % h.name) else: report('Explore',"%s did not have the energy to go exploring." % h.name) if entity.humans: entity.humans[0].energy -= 10 game.get_game().entity_manager.get_by_name('camp').medicine += 10 game.get_game().entity_manager.get_by_name('report').handle('record_update', 'Explore', '%s found 10 medicine but lost 10 energy.' % entity.humans[0].name)
def leave(self): self.music.stop() for location in game.get_game().entity_manager.get_by_tag('location'): location.handle('day') for location in game.get_game().entity_manager.get_by_tag('human'): location.handle('day') game.get_game().entity_manager.get_by_name('mouse').grab = True
def handle_draw(self, entity): ratio = entity.time_remaining / entity.time_limit x, y = get_midpoint(entity) game.get_game().renderer.appendCircle((50, 50, 50), x, y, entity.width / 2) game.get_game().renderer.appendFan((200, 200, 200), x, y, entity.width / 2, ratio)
def handle_action(self, entity, action): if action == 'CREATE_DECOY' and entity.decoy_cooldown <= 0: if entity.dx or entity.dy: d = (entity.dx,entity.dy) else: d = (1,0) game.get_game().entity_manager.add_entity(Entity("decoy",follow_entity = entity, color = entity.color, mirror_dir = d, x = entity.x, y = entity.y)) entity.decoy_cooldown = entity.decoy_cooldown_time
def handle_draw(self, entity): # print entity.x,entity.y # screen_x, screen_y = transform(entity.x, entity.y) # r = pygame.Rect(int(screen_x), int(screen_y), entity.height, entity.width) # pygame.draw.ellipse(surface, entity.color, r) if entity.visible: p = get_midpoint(entity) game.get_game().renderer.appendPlayerCircle( entity.color,p.x,p.y, entity.height/2)
def handle_action(self, entity, action): if action == 'SMOKE_SCREEN' and entity.smoke_screen_cooldown <= 0: p = get_midpoint(entity) game.get_game().renderer.appendCircle( entity.color,int(p[0]), int(p[1]), entity.smoke_screen_rad ) #pygame.draw.circle(game.get_game().screen, entity.color, (int(p[0]), int(p[1])), entity.smoke_screen_rad) entity.smoke_screen_cooldown = entity.smoke_screen_cooldown_time
def handle_action(self, entity, action): if action == 'TRAP' and entity.trap_cooldown <= 0: p = get_midpoint(entity) game.get_game().renderer.appendRing(entity.color, int(p[0]), int(p[1]), entity.trap_out_rad, entity.trap_in_rad) #pygame.draw.circle(game.get_game().screen, entity.color, (int(p[0]), int(p[1])), entity.smoke_screen_rad) entity.trap_cooldown = entity.trap_cooldown_time
def handle_action(self, entity, action): if action == 'TRAP' and entity.trap_cooldown <= 0: p = get_midpoint(entity) game.get_game().renderer.appendRing( entity.color,int(p[0]), int(p[1]), entity.trap_out_rad, entity.trap_in_rad ) #pygame.draw.circle(game.get_game().screen, entity.color, (int(p[0]), int(p[1])), entity.smoke_screen_rad) entity.trap_cooldown = entity.trap_cooldown_time
def handle_action(self, entity, action): if action == 'SMOKE_SCREEN' and entity.smoke_screen_cooldown <= 0: p = get_midpoint(entity) game.get_game().renderer.appendCircle(entity.color, int(p[0]), int(p[1]), entity.smoke_screen_rad) #pygame.draw.circle(game.get_game().screen, entity.color, (int(p[0]), int(p[1])), entity.smoke_screen_rad) entity.smoke_screen_cooldown = entity.smoke_screen_cooldown_time
def handle_update(self, entity, dt): mouse_entity = game.get_game().entity_manager.get_by_name('mouse') if not mouse_entity.dragging and get_box(entity).collidepoint(mouse_entity.x, mouse_entity.y): info_entity = game.get_game().entity_manager.get_by_name('info-window') info_entity.text = entity.name for attr in ['health', 'hunger', 'thirst', 'energy', 'strength']: amount = getattr(entity, attr) info_entity.text += '\n' + attr + ' ' + str(amount) + "/100"
def update(self, dt): entities_to_update = set() for player in game.get_game().entity_manager.get_by_tag('player'): update_area = pygame.Rect(0, 0, 800, 800) update_area.center = (player.x, player.y) entities_to_update.update(game.get_game().entity_manager.get_in_area('update', update_area, precise=False)) for entity in entities_to_update: entity.handle('update', dt)
def handle_draw(self, entity): # print entity.x,entity.y # screen_x, screen_y = transform(entity.x, entity.y) # r = pygame.Rect(int(screen_x), int(screen_y), entity.height, entity.width) # pygame.draw.ellipse(surface, entity.color, r) if entity.visible: p = get_midpoint(entity) game.get_game().renderer.appendPlayerCircle( entity.color, p.x, p.y, entity.height / 2)
def __init__(self, static_data_name, **kwargs): self._static_data_name = static_data_name self._handlers = {} for attribute, value in kwargs.items(): setattr(self, attribute, value) if 'components' in self.__dict__ or 'components' in self.static._fields: for component in self.components: game.get_game().component_manager.add(component, self)
def handle_update(self, entity, dt): entity.spawn_timer += dt if entity.spawn_timer > entity.spawn_period: entity.spawn_timer -= entity.spawn_period x = random.randrange(0, game.get_game().screen.get_width()) y = random.randrange(0, game.get_game().screen.get_height()) color = random.choice([(255,0,0), (0,255,0)]) vortex = Entity("vortex", x=x, y=y, color=color) game.get_game().entity_manager.add_entity(vortex)
def handle_update(self, entity, dt): if entity.dx or entity.dy: entity.last_good_x = entity.x entity.last_good_y = entity.y entity.x += entity.dx * dt entity.y += entity.dy * dt game.get_game().entity_manager.update_position(entity) collisions = game.get_game().entity_manager.get_in_area('collide', (entity.x, entity.y, entity.width, entity.height)) - {entity} for collided_entity in collisions: collided_entity.handle('collision', entity) entity.handle('collision', collided_entity)
def handle_collision(self, entity, colliding_entity): # zombies can't collide with other zombies if not 'zombie' in colliding_entity.tags and not 'item' in colliding_entity.tags: y_axis_collisions = game.get_game().entity_manager.get_in_area('collide', (entity.last_good_x, entity.y, entity.width, entity.height)) - {entity} x_axis_collisions = game.get_game().entity_manager.get_in_area('collide', (entity.x, entity.last_good_y, entity.width, entity.height)) - {entity} if len(x_axis_collisions) > 0: entity.x = entity.last_good_x if len(y_axis_collisions) > 0: entity.y = entity.last_good_y game.get_game().entity_manager.update_position(entity)
def handle_use(self, entity, item, player): CAR_IMAGES = ["items/car/Car-empty.png", "items/car/Car-rear-wheel.png", "items/car/Car-front-rear.png", "items/car/Car-engine-front.png", "items/car/Car-engine-rear.png", "items/car/Car-full.png"] if item: if item.item_type not in entity.item_types: item.handle('drop', player) entity.items.append(item) entity.item_types.append(item.item_type) game.get_game().entity_manager.remove_entity(item) game.get_game().component_manager.remove('DrawComponent', item) game.get_game().component_manager.remove('ItemComponent', item) entity.image = CAR_IMAGES[len(entity.items)] elif player and set(entity.item_types).issuperset(entity.needed_item_types): if entity.driver is None: game.get_game().component_manager.remove("StaticCollisionComponent", entity) entity.driver = player player.draw = False player.x, player.y = entity.x, entity.y entity.dx, entity.dy = -200, 2 player.handle('dead', True)
def handle_action(self, entity, action): if action == 'CREATE_DECOY' and entity.decoy_cooldown <= 0: if entity.dx or entity.dy: d = (entity.dx, entity.dy) else: d = (1, 0) game.get_game().entity_manager.add_entity( Entity("decoy", follow_entity=entity, color=entity.color, mirror_dir=d, x=entity.x, y=entity.y)) entity.decoy_cooldown = entity.decoy_cooldown_time
def handle_action(self, entity, action): if action == 'PLACE_MINEFIELD' and entity.minefield_cooldown <= 0: m = get_midpoint(entity) for r in range(entity.minefield_min_rad, entity.minefield_max_rad, entity.minefield_rad_density): anglestart = 0 angleend = 360 for a in xrange(anglestart, angleend, entity.minefield_ang_density): v = Vec2d(0, 1) v.length = r v.angle = a p = m + v #pygame.draw.circle(game.get_game().screen, entity.color, (int(p[0]), int(p[1])), 5) game.get_game().renderer.appendPlayerCircle( entity.color,int(p[0]), int(p[1]), 5) entity.minefield_cooldown = entity.minefield_cooldown_time
def __init__(self, definition, properties=None, components=None): self.props = EntityProperties(definition) self.handlers = {} for component in get_game().resource_manager.get('definition', definition)[components]: get_game().component_manager.add(component, self) if properties: for key, value in properties.items(): setattr(self.props, key, value) if components: for component in components: get_game().component_manager.add(component, self)
def handle_update(self, entity, dt): if entity.dx or entity.dy: entity.last_good_x = entity.x entity.last_good_y = entity.y entity.x += entity.dx * dt * entity.speed entity.y += entity.dy * dt * entity.speed bound = lambda a,b,x : min(b,max(a,x)) res = game.get_game().screen_size entity.x = bound(0, res[0] - entity.width, entity.x) entity.y = bound(0, res[1] - entity.height, entity.y) game.get_game().entity_manager.update_position(entity) collisions = game.get_game().entity_manager.get_in_area('collision', (entity.x, entity.y, entity.width, entity.height)) - {entity} for collided_entity in collisions: entity.handle('collision', collided_entity)
def LoadEntityData(prefix, key): with open(os.path.join(prefix, 'entities', key + '.json')) as in_file: definition = json.load(in_file) if 'animations' in definition: for animation in definition['animations'].values(): if 'frame_dir' in animation: frame_dir = os.path.join(prefix, 'images', animation['frame_dir']) frames = sorted(os.listdir(frame_dir)) animation['frames'] = [] for frame in frames: animation['frames'].append(os.path.join(frame_dir, frame)) if 'includes' in definition: flattened = {} for include_name in definition['includes']: include = game.get_game().resource_manager.get('entity', include_name) for field in include._fields: flattened[field] = getattr(include, field) for key, value in definition.iteritems(): if key.endswith('+'): base_key = key[:-1] flattened[base_key] = flattened.get(base_key, tuple()) + tuple(value) else: flattened[key] = value definition = flattened return freezejson.freeze_value(definition)
def draw_rover_ground(self): wheel_size = WHEEL_SIZE / 2 wheels_pos_x = [ wheel_size / 2, wheel_size + 4 + wheel_size / 2, ROVER_SIZE - 4 - wheel_size / 2 ] wheels_pos_y = [ game.get_game().terrain.get_y_at(self.x_pos + x) for x in wheels_pos_x ] average_wheel_pos = sum(wheels_pos_y) / 3 wheels_pos_y = [ max(min(y, average_wheel_pos + 10), average_wheel_pos - 10) for y in wheels_pos_y ] player_height = average_wheel_pos - 110 self.y_pos = player_height + 110 wheel_num = int(self.wheel_animation) self.rect = (self.x_pos, player_height, ROVER_SIZE, ROVER_SIZE) self.image = self.chassis_images[0].copy() self.image.blit(self.big_wheels_images[wheel_num], (wheels_pos_x[0] - wheel_size / 2, wheels_pos_y[0] - player_height - wheel_size)) self.image.blit(self.big_wheels_images[wheel_num], (wheels_pos_x[1] - wheel_size / 2, wheels_pos_y[1] - player_height - wheel_size)) self.image.blit(self.small_wheel_images[wheel_num], (wheels_pos_x[2] - wheel_size / 2, wheels_pos_y[2] - player_height - wheel_size))
def LoadEntityData(prefix, key): with open(os.path.join(prefix, 'data', key + '.json')) as in_file: definition = json.load(in_file) if 'animations' in definition: for animation in definition['animations'].values(): if 'frame_dir' in animation: frame_dir = os.path.join(prefix, 'images', animation['frame_dir']) frames = sorted(os.listdir(frame_dir)) animation['frames'] = [] for frame in frames: animation['frames'].append(os.path.join(frame_dir, frame)) if 'includes' in definition: flattened = {} for include_name in definition['includes']: include = game.get_game().resource_manager.get( 'data', include_name) for field in include._fields: flattened[field] = getattr(include, field) for key, value in definition.iteritems(): if key.endswith('+'): base_key = key[:-1] flattened[base_key] = flattened.get(base_key, tuple()) + tuple(value) else: flattened[key] = value definition = flattened return freezejson.freeze_value(definition)
def handle_input(self, entity, event): if not entity.grab: return if event.action == 'CLICK': if event.value == 1: humans = game.get_game().entity_manager.get_by_tag('human') my_pos = Vec2d(entity.x, entity.y) closest = None distance = 0 for h in humans: other_pos = get_midpoint(h) if closest == None: closest = h distance = my_pos.get_distance(other_pos) else: new_distance = my_pos.get_distance(other_pos) if new_distance < distance: closest = h distance = new_distance if distance < entity.grab_range: entity.grabbed_human = closest closest.handle('grabbed', entity) entity.dragging = True elif event.value == 0: if entity.grabbed_human: entity.grabbed_human.handle('released', entity) entity.grabbed_human = None entity.dragging = False
def get_entities_in_front(entity): COLLIDE_BOX_WIDTH = 100 COLLIDE_BOX_HEIGHT = 100 collision_box = get_box_in_front(entity, COLLIDE_BOX_WIDTH, COLLIDE_BOX_HEIGHT) return game.get_game().entity_manager.get_in_area('collide', collision_box)
def draw(self, view): r = pygame.Rect(view.area) p = 1 for x in xrange(0, view.area.width, 100): r.left = x pygame.draw.rect(view.surface, game.get_game().entity_manager.get_by_name('player' + str(1+p)).color, r) p = (p + 1) % 2
def process_events(self): self._input_map = game.get_game().resource_manager.get( 'inputmap', 'default') processed_events = [] for e in pygame.event.get(): if e.type == pygame.QUIT: processed_events.append(InputEvent('GAME', 'QUIT', 1)) elif e.type == pygame.VIDEORESIZE: game.get_game().renderer.resize(e.dict['size']) elif e.type == pygame.JOYAXISMOTION: control_type = 'AXIS' device_id = e.joy value, _ = self._normalize_axis(e.value, 0) if value >= 0: event = self._new_event(device_id, control_type, "+%d" % e.axis, value) if value <= 0: value = -1 * value event = self._new_event(device_id, control_type, "-%d" % e.axis, value) if event != None: processed_events.append(event) elif e.type == pygame.JOYBUTTONDOWN: event = self._new_event(e.joy, 'BUTTON', e.button, 1) if event != None: processed_events.append(event) elif e.type == pygame.JOYBUTTONUP: event = self._new_event(e.joy, 'BUTTON', e.button, 0) if event != None: processed_events.append(event) elif e.type == pygame.KEYDOWN: event = self._new_event(None, 'KEY', e.key, 1) if event != None: processed_events.append(event) elif e.type == pygame.KEYUP: event = self._new_event(None, 'KEY', e.key, 0) if event != None: processed_events.append(event) elif e.type == pygame.JOYHATMOTION: pass # TODO: this is going to get complicated else: pass return processed_events
def handle_action(self, entity, action): if action == 'PLACE_MINEFIELD' and entity.minefield_cooldown <= 0: m = get_midpoint(entity) for r in range(entity.minefield_min_rad, entity.minefield_max_rad, entity.minefield_rad_density): anglestart = 0 angleend = 360 for a in xrange(anglestart, angleend, entity.minefield_ang_density): v = Vec2d(0, 1) v.length = r v.angle = a p = m + v #pygame.draw.circle(game.get_game().screen, entity.color, (int(p[0]), int(p[1])), 5) game.get_game().renderer.appendPlayerCircle( entity.color, int(p[0]), int(p[1]), 5) entity.minefield_cooldown = entity.minefield_cooldown_time
def handle_collision(self, entity, colliding_entity): if colliding_entity == entity.carrying_item: return if 'car' in colliding_entity.tags: colliding_entity.handle('use', entity.carrying_item, entity) y_axis_collisions = game.get_game().entity_manager.get_in_area('collide', (entity.last_good_x, entity.y, entity.width, entity.height)) - {entity} x_axis_collisions = game.get_game().entity_manager.get_in_area('collide', (entity.x, entity.last_good_y, entity.width, entity.height)) - {entity} if len(x_axis_collisions) > 0: entity.x = entity.last_good_x if len(y_axis_collisions) > 0: entity.y = entity.last_good_y game.get_game().entity_manager.update_position(entity)
def handle_update(self, entity, dt): if entity.dx or entity.dy: entity.last_good_x = entity.x entity.last_good_y = entity.y entity.x += entity.dx * dt * entity.speed entity.y += entity.dy * dt * entity.speed bound = lambda a, b, x: min(b, max(a, x)) res = game.get_game().screen_size entity.x = bound(0, res[0] - entity.width, entity.x) entity.y = bound(0, res[1] - entity.height, entity.y) game.get_game().entity_manager.update_position(entity) collisions = game.get_game().entity_manager.get_in_area( 'collision', (entity.x, entity.y, entity.width, entity.height)) - {entity} for collided_entity in collisions: entity.handle('collision', collided_entity)
def __init__(self, parent=None): self.parent = parent self.x = 0 self.y = 0 self.z = 1 self.angle = 0.0 self.scale = (1.0, 1.0) self._current_frame = 0 self.current_order = 0 self._current_anim = None self.hotspot = (0, 0) self.fading = False self.fade_time = 0.0 self.fade_delay = 0.0 self.set_to_zero = False self.last_time = self.update_time = clock() self.is_play_loop = True self.is_play_backward = False self.is_play_pingpong = False self.playing = False self.delta = 1 self._alpha = 1.0 self._Alpha = 1.0 self.children = [] self.visible = True self.size = (0, 0) self.color = (255, 255, 255, 255) self.regions = [] self.track_position = False self.transparent = False if parent == None: if get_game(): get_game().screen.children.append(self) else: self.alpha = parent.alpha parent.children.append(self) if hasattr(self, "autos"): for j, i in self.autos: klass = wx.GetApp().gns.getattr(i) if not issubclass(klass, Animation): obj = klass(self) self.__dict__[j] = obj self.children.append(obj) p = getattr(self, "animation", None) if p: self.current_anim = p() else: self._current_anim = None
def enter(self): self.music = game.get_game().resource_manager.get( 'sound', 'Prelude.ogg') self.music.play() game.get_game().entity_manager.add_entity(Entity('aiplayer1')) game.get_game().entity_manager.add_entity(Entity('aiplayer2')) game.get_game().renderer.cleanup()
def process_events(self): self._input_map = game.get_game().resource_manager.get('inputmap', 'default') processed_events = [] for e in pygame.event.get(): if e.type == pygame.QUIT: processed_events.append(InputEvent('GAME', 'QUIT', 1)) elif e.type == pygame.VIDEORESIZE: game.get_game().renderer.resize(e.dict['size']) elif e.type == pygame.JOYAXISMOTION: control_type = 'AXIS' device_id = e.joy value, _ = self._normalize_axis(e.value, 0) if value >= 0: event = self._new_event(device_id, control_type, "+%d" % e.axis, value) if value <= 0: value = -1 * value event = self._new_event(device_id, control_type, "-%d" % e.axis, value) if event != None: processed_events.append(event) elif e.type == pygame.JOYBUTTONDOWN: event = self._new_event(e.joy, 'BUTTON', e.button, 1) if event != None: processed_events.append(event) elif e.type == pygame.JOYBUTTONUP: event = self._new_event(e.joy, 'BUTTON', e.button, 0) if event != None: processed_events.append(event) elif e.type == pygame.KEYDOWN: event = self._new_event(None, 'KEY', e.key, 1) if event != None: processed_events.append(event) elif e.type == pygame.KEYUP: event = self._new_event(None, 'KEY', e.key, 0) if event != None: processed_events.append(event) elif e.type == pygame.JOYHATMOTION: pass # TODO: this is going to get complicated else: pass return processed_events
def __init__(self, parent = None): self.parent = parent self.x = 0 self.y = 0 self.z = 1 self.angle = 0.0 self.scale = (1.0, 1.0) self._current_frame = 0 self.current_order = 0 self._current_anim = None self.hotspot = (0, 0) self.fading = False self.fade_time = 0.0 self.fade_delay = 0.0 self.set_to_zero = False self.last_time = self.update_time = clock() self.is_play_loop = True self.is_play_backward = False self.is_play_pingpong = False self.playing = False self.delta = 1 self._alpha = 1.0 self._Alpha = 1.0 self.children = [] self.visible = True self.size = (0, 0) self.color = (255, 255, 255, 255) self.regions = [] self.track_position = False self.transparent = False if parent == None: if get_game(): get_game().screen.children.append(self) else: self.alpha = parent.alpha parent.children.append(self) if hasattr(self, "autos"): for j, i in self.autos: klass = wx.GetApp().gns.getattr(i) if not issubclass(klass, Animation): obj = klass(self) self.__dict__[j] = obj self.children.append(obj) p = getattr(self, "animation", None) if p: self.current_anim = p() else: self._current_anim = None
def move(): x = int(request.args.get("x")) y = int(request.args.get("y")) player = session["id"] game = get_game(player) set_tile(game, player, x, y) return jsonify(game)
def handle_update(self, entity, dt): if entity.attacking: entity.attack_time += dt if entity.attack_time >= entity.total_attack_time: entity.attacking = False entity.attack_time = 0 else: return mypos = get_midpoint(entity) in_range_player = None in_range_player_attack = [] mindist = entity.sight_distance for player in game.get_game().entity_manager.get_by_tag("player"): if player.health > 0: theirpos = get_midpoint(player) dist = (mypos-theirpos).length if dist <= entity.sight_distance : if mindist > dist: in_range_player = player if dist <= entity.attack_distance: in_range_player_attack.append(player) if in_range_player is not None: theirpos = get_midpoint(in_range_player) direction = entity.speed * (theirpos-mypos).normalized() entity.dx = direction.x entity.dy = direction.y else: direction = Vec2d(entity.dx,entity.dy) if direction.length < 1: ang = random.uniform(0,3.14159) direction = entity.speed * Vec2d(cos(ang),sin(ang)) else: ang = atan(direction.y/direction.x) ang += random.gauss(0,0.1) direction = direction.length * Vec2d(cos(ang),sin(ang)) entity.dx = direction.x entity.dy = direction.y if len(in_range_player_attack) > 0: entity.dx = 0 entity.dy = 0 entity.attacking = True #entity.attack_time = 0 for player in in_range_player_attack: player.handle('attack', entity, dt) entity.facing = int(((direction.get_angle() + 45) % 360) / 90) entity.handle('play-animation', 'walk_%s' % (FACING[entity.facing],), True)
def flatten_includes(definition, flattened=None): if flattened == None: flattened = [] flattened.append(definition) def_map = game.get_game().resource_manager.get('definition', definition) if 'includes' in def_map: for include in def_map['includes']: flattened = flatten_includes(include, flattened=flattened) return flattened
def handle_draw(self, entity, surface): fill = getattr(game.get_game().entity_manager.get_by_name(entity.tracking_entity), entity.tracking_resource)/100.0 r = pygame.Rect(entity.x, entity.y, entity.width, entity.height) fill_r = r.inflate(-5, -5) old_bottom = fill_r.bottom fill_r.h *= fill fill_r.bottom = old_bottom pygame.draw.rect(surface, entity.background_colour, r) pygame.draw.rect(surface, entity.colour, fill_r)
def __init__(self, size, tag): self.size = size self.tag = tag self.surface = pygame.Surface(self.size) self.surface.convert() transform = lambda x, y: (x, y) for entity in game.get_game().entity_manager.get_by_tag(tag): entity.handle('draw', self.surface, transform)
def __init__(self, size, tag): self.size = size self.tag = tag self.surface = pygame.Surface(self.size) self.surface.convert() transform = lambda x, y : (x, y) for entity in game.get_game().entity_manager.get_by_tag(tag): entity.handle('draw', self.surface, transform)
def draw(self, view): area_to_blit = pygame.Rect(view.area) area_to_blit.center = (view.entity.x, view.entity.y) entities_to_draw = sorted(game.get_game().entity_manager.get_in_area(self.tag, area_to_blit, precise=False), key=lambda entity: entity.y) transform = lambda x, y : (x - area_to_blit.x + view.area.x, y - area_to_blit.y + view.area.y) for entity in entities_to_draw: entity.handle('draw', view.surface, transform)
def move(data): x = int(data["x"]) y = int(data["y"]) player = request.sid game = get_game(player) set_tile(game, player, x, y) for player in game["players"]: socketio.emit("moved", game, room=player)
def move(): x = int(request.args.get("x")) y = int(request.args.get("y")) player = request.args.get("id") print(player) game = get_game(player) set_tile(game, player, x, y) response = jsonify(game) response.headers.add('Access-Control-Allow-Origin', 'localhost:3000') return response
def draw(self, view): r = pygame.Rect(view.area) p = 1 for x in xrange(0, view.area.width, 100): r.left = x pygame.draw.rect( view.surface, game.get_game().entity_manager.get_by_name('player' + str(1 + p)).color, r) p = (p + 1) % 2
def handle_released(self, entity, releaser): locations = game.get_game().entity_manager.get_in_area('location', (entity.x, entity.y, entity.width, entity.height)) location_found = False for location in locations: if not location.humans: location.handle('human_placed', entity) entity.location = location location_found = True break # Just send the event to the first location in the set if not location_found: entity.x = entity.home_x entity.y = entity.home_y
def draw(self): player1 = game.get_game().entity_manager.get_by_name('player1') player2 = game.get_game().entity_manager.get_by_name('player2') if player1.score > player2.score: game.get_game().renderer.render_game_end() else: game.get_game().renderer.render_game_end()
def draw(self, view): area_to_blit = pygame.Rect(view.area) area_to_blit.center = (view.entity.x, view.entity.y) entities_to_draw = sorted(game.get_game().entity_manager.get_in_area( self.tag, area_to_blit, precise=False), key=lambda entity: entity.y) transform = lambda x, y: (x - area_to_blit.x + view.area.x, y - area_to_blit.y + view.area.y) for entity in entities_to_draw: entity.handle('draw', view.surface, transform)
async def handler(websocket, path): logger.info(f"connected {websocket} {path}") consumer_task = asyncio.ensure_future(consumer_handler(websocket, path)) producer_task = asyncio.ensure_future(producer_handler(websocket, path)) done, pending = await asyncio.wait([consumer_task, producer_task], return_when=asyncio.FIRST_COMPLETED) for task in pending: game = get_game(path, False) if game is not None: game.disconnect(websocket) task.cancel() return None
async def producer_handler(websocket: WebSocketServerProtocol, path: str): game = get_game(path) while True: await sleep(0.1) for socket, message in game.message_queue: logger.info(f"sending message {message}") if not socket: for player in game.players.values(): if player.socket: await player.socket.send(message) else: await socket.send(message) game.message_queue = []
def drawBackground(self): return glUseProgram(self.player_shader) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) num_split = 10 dx = 1.0 / num_split color_location = glGetUniformLocation(self.player_shader, "color") for i in xrange(num_split): color = game.get_game().entity_manager.get_by_name( 'player' + str(2 - (i % 2))).color col = map(lambda x: x / 255.0, color) glUniform3f(color_location, col[0], col[1], col[2]) self.drawUVQuad(i * dx, 0, dx, 1) glUseProgram(0)
def load(self, path): with open(path) as in_file: definition = json.load(in_file) if 'includes' in definition: flattened = {} for include_path in definition['includes']: include = game.get_game().resource_manager.get(include_path) for field in include._fields: flattened[field] = getattr(include, field) for key, value in definition.iteritems(): if key.endswith('+'): base_key = key[:-1] flattened[base_key] = flattened.get(base_key, tuple()) + tuple(value) else: flattened[key] = value definition = flattened return freezejson.freeze_value(definition)
def update(self, dt): player1 = game.get_game().entity_manager.get_by_name('player1') player2 = game.get_game().entity_manager.get_by_name('player2') if player1.score == 3 or player2.score == 3: player1.score = 0 player2.score = 0 player1.chasing = True player2.chasing = False game.get_game().change_mode(GameEndMode()) self.ttl -= dt if self.ttl < 0: game.get_game().change_mode(PlayMode())
def update(self, *args, **kwargs): if not self.on_ground and self.y_vel > 0: height_below = game.get_game().terrain.get_y_at(self.x_pos + 100) if height_below < self.y_pos: self.on_ground = True self.y_vel = 0 if self.on_ground: self.x_pos += self.x_vel if self.on_ground: self.wheel_animation += WHEEL_SPEED self.wheel_animation %= 2 self.draw_rover_ground() else: if self.jumping: self.jump(None) else: self.y_vel += G / 60 self.y_pos += self.y_vel self.draw_rover_air()
def handle_draw(self, entity): player = game.get_game().entity_manager.get_by_name(entity.target) radius = entity.height / 2 if player.chasing: game.get_game().renderer.appendRect((200, 200, 200), entity.x, entity.y, entity.width, entity.height) else: game.get_game().renderer.appendRect( (50, 50, 50), entity.x, entity.y, entity.width, entity.height) for i in range(player.score): if entity.direction == 1: start_x = entity.x + radius else: start_x = entity.x + entity.width - radius pos = (start_x + (i * radius * 2 * entity.direction), entity.y + radius) game.get_game().renderer.appendCircle(player.color, pos[0], pos[1], radius)