def __init__(self): """sets up the game variables and then initializes its employee agents""" super(GameManager, self).__init__("game_manager") self.house = Environment() self.screen = None # screen size self.screen_height = 444 self.screen_width = 1116 self.running_game = True # player list self.player_list = pygame.sprite.Group() self.house.add_object("player_list", self.player_list) # holds bullet list self.bullet_list = pygame.sprite.Group() self.house.add_object("bullet_list", self.bullet_list) # holds the sprites that make up the wall self.wall_list = pygame.sprite.Group() self.house.add_object("wall_list", self.wall_list) # holds the objects that are placed in the environment for Neo to interact with self.object_list = pygame.sprite.Group() self.house.add_object("object_list", self.object_list) # this holds the awesome laser beams that Neo shoots from his face self.raycast_list = pygame.sprite.Group() self.house.add_object("raycast_list", self.raycast_list) # initialize agents and place them in the environment self.map_builder = MapBuilder(self.house) self.neo = NEO(self.house) self.blue_player_pilot = BluePlayerPilot(self.house)
def __init__(self): """sets up the game variables and then initializes its employee agents""" super(GameManager, self).__init__("game_manager") self.play_window = Environment() self.screen = None # screen size self.screen_height = 444 self.screen_width = 1116 self.running_game = True # player list self.player_list = pygame.sprite.Group() self.play_window.add_object("player_list", self.player_list) # holds bullet list self.bullet_list = pygame.sprite.Group() self.play_window.add_object("bullet_list", self.bullet_list) # holds the sprites that make up the wall self.wall_list = pygame.sprite.Group() self.play_window.add_object("wall_list", self.wall_list) # initialize agents and place them in the environment self.map_builder = MapBuilder(self.play_window) self.red_ai_pilot = RedAiPilot(self.play_window) self.blue_player_pilot = BluePlayerPilot(self.play_window)
def __init__(self, map_name): ShowBase.__init__(self) self.disableMouse() self.map_name = map_name self.stop_loop = False self.current_group = None self._group_markers = set() self.map = Map(map_name) self.map_builder = MapBuilder(self.map, render) self.map_builder.build() self.edit_panel = EditPanel(self) self.pointer = Pointer(self) taskMgr.add(self.pointer.update, 'update_pointer') self.camera_node = render.attachNewNode('camera_node') self.set_camera_control() base.accept(ES.control_keys['cancel_selection'], self.cancel_selection) base.accept(ES.control_keys['close_window'], self.close_window) base.accept(ES.control_keys['save'], self.save) base.accept(ES.control_keys['add_group'], self.add_group) base.accept(ES.control_keys['switch_transparency'], self.switch_transparency) if ES.show_control_keys: display_control_keys(ES) self.coordinate_text = OnscreenText(style=1, text='22', fg=(1, 1, 1, 1), pos=(-1, ES.text_scale - 1), align=TextNode.ALeft, scale=ES.text_scale) self.coordinate_text.reparentTo(render2d)
def __init__(self, map_name): self.main_node = render.attachNewNode('main_node') self.blocked_squares = set() self.bodies = {} self.map = Map(map_name) self.map_builder = MapBuilder(self.map, self.main_node) self.map_builder.build() self.map_builder.clear_map_textures() self.player = Player(self, self.map.start_pos) self.set_npcs() self.setup_graphics() if S.show_view_field: self.view_fields = defaultdict(set) taskMgr.doMethodLater(1, self.update_view_fields, 'fields') if S.show_pathes: self.pathes = defaultdict(set) taskMgr.doMethodLater(1, self.update_pathes, 'pathes')
class Editor(ShowBase): def __init__(self, map_name): ShowBase.__init__(self) self.disableMouse() self.map_name = map_name self.stop_loop = False self.current_group = None self._group_markers = set() self.map = Map(map_name) self.map_builder = MapBuilder(self.map, render) self.map_builder.build() self.edit_panel = EditPanel(self) self.pointer = Pointer(self) taskMgr.add(self.pointer.update, 'update_pointer') self.camera_node = render.attachNewNode('camera_node') self.set_camera_control() base.accept(ES.control_keys['cancel_selection'], self.cancel_selection) base.accept(ES.control_keys['close_window'], self.close_window) base.accept(ES.control_keys['save'], self.save) base.accept(ES.control_keys['add_group'], self.add_group) base.accept(ES.control_keys['switch_transparency'], self.switch_transparency) if ES.show_control_keys: display_control_keys(ES) self.coordinate_text = OnscreenText(style=1, text='22', fg=(1, 1, 1, 1), pos=(-1, ES.text_scale - 1), align=TextNode.ALeft, scale=ES.text_scale) self.coordinate_text.reparentTo(render2d) def set_camera_control(self, only_arrows=False): pitch = -ES.camera['horizontal_angle'] yaw = ES.camera['init_vertical_angle'] min_h = ES.camera['min_height'] max_h = ES.camera['max_height'] height = ES.camera['init_height'] pos = ES.camera['init_pos'] hstep = ES.camera['height_step'] camera_node = self.camera_node if not only_arrows: camera.reparentTo(camera_node) def init(): camera_node.setPosHpr(pos[0], pos[1], height, 90 + yaw, 0, 0) camera.setPosHpr(0, 0, 0, 0, pitch, 0) init() base.accept('home', init) def incr_angle(): camera_node.setH(camera_node, ES.camera['vertical_angle_step']) key = ES.control_keys['rotate_camera_counterclockwise'] base.accept(key, incr_angle) base.accept(key + '-repeat', incr_angle) def decr_angle(): camera_node.setH(camera_node, -ES.camera['vertical_angle_step']) key = ES.control_keys['rotate_camera_clockwise'] base.accept(key, decr_angle) base.accept(key + '-repeat', decr_angle) def incr_height(): camera_node.setZ(min(camera_node.getZ() + hstep, max_h)) key = ES.control_keys['increase_camera_height'] base.accept(key, incr_height) base.accept(key + '-repeat', incr_height) def decr_height(): camera_node.setZ(max(camera_node.getZ() - hstep, min_h)) key = ES.control_keys['decrease_camera_height'] base.accept(key, decr_height) base.accept(key + '-repeat', decr_height) def remove_arrow_handlers(self): key = ES.control_keys['rotate_camera_counterclockwise'] base.ignore(key) base.ignore(key + '-repeat') key = ES.control_keys['rotate_camera_clockwise'] base.ignore(key) base.ignore(key + '-repeat') key = ES.control_keys['increase_camera_height'] base.ignore(key) base.ignore(key + '-repeat') key = ES.control_keys['decrease_camera_height'] base.ignore(key) base.ignore(key + '-repeat') def cancel_selection(self): self.select_group(None) def select_group(self, ident): self.edit_panel.select_group(ident) def set_current_group(self, group): self.current_group = group self._mark_group() def _mark_group(self): for marker in self._group_markers: marker.removeNode() self._group_markers.clear() if self.current_group is None: return for pos in self.map.groups[self.current_group['ident']]: self.set_marker(pos) def set_marker(self, pos): marker = loader.loadModel(S.model('plane')) texture = loader.loadTexture(S.texture('black_pointer')) marker.setTexture(texture) marker.setTransparency(True) marker.setHpr(0, -90, 0) marker.reparentTo(render) marker.setPos(pos[0], pos[1], 0.1) marker.setBin("fixed", 40) marker.setDepthTest(False) marker.setDepthWrite(False) self._group_markers.add(marker) def add_group(self): letters = string.uppercase + string.lowercase while True: group_id = random.choice(letters) + random.choice(letters) if group_id not in self.map.definitions: break group = dict(ident=group_id, kind='empty', actions=[]) self.map.definitions[group_id] = group self.edit_panel.add_group(group_id) def save(self): map = self.map poses = [p for p, i in map] min_x = min(p[0] for p in poses) offset_x = -min_x min_y = min(p[1] for p in poses) offset_y = -min_y width = max(p[0] for p in poses) - min_x + 1 height = max(p[1] for p in poses) - min_y + 1 topology = [['..'] * width for _ in range(height)] for ident, gposes in map.groups.items(): for p in gposes: topology[p[1] + offset_y][p[0] + offset_x] = ident topology = [' '.join(row) for row in topology] topology.reverse() yaml_data = deepcopy(map.yaml_data) definitions = deepcopy(map.definitions) for info in tuple(definitions.values()): if not map.groups[info['ident']]: del definitions[info['ident']] del info['ident'] if info['kind'] == 'model_field': del info['actions'] yaml_data['topology'] = topology yaml_data['substrate_actions'] = definitions.pop('ss')['actions'] yaml_data['definitions'] = definitions if 'start_position' in yaml_data: st_pos = yaml_data['start_position'] st_pos = [st_pos[0] + offset_x, st_pos[1] + offset_y] yaml_data['start_position'] = st_pos if 'routes' in yaml_data: routes = yaml_data['routes'] for rname, route in routes.items(): for index, rpos in enumerate(tuple(route)): route[index] = [rpos[0] + offset_x, rpos[1] + offset_y] with open(S.map(self.map_name), 'w') as f: yaml.dump(yaml_data, f, default_flow_style=False, width=1000) def switch_transparency(self): if self.map_builder.models_transparency == 1: self.map_builder.set_models_transparency(ES.model_transparency) else: self.map_builder.set_models_transparency(1) def close_window(self): self.stop_loop = True def loop(self): while not self.stop_loop: taskMgr.step()
class GameManager(Agent): """The game_manager handles all agents responsible for making the game run""" def __init__(self): """sets up the game variables and then initializes its employee agents""" super(GameManager, self).__init__("game_manager") self.house = Environment() self.screen = None # screen size self.screen_height = 444 self.screen_width = 1116 self.running_game = True # player list self.player_list = pygame.sprite.Group() self.house.add_object("player_list", self.player_list) # holds bullet list self.bullet_list = pygame.sprite.Group() self.house.add_object("bullet_list", self.bullet_list) # holds the sprites that make up the wall self.wall_list = pygame.sprite.Group() self.house.add_object("wall_list", self.wall_list) # holds the objects that are placed in the environment for Neo to interact with self.object_list = pygame.sprite.Group() self.house.add_object("object_list", self.object_list) # this holds the awesome laser beams that Neo shoots from his face self.raycast_list = pygame.sprite.Group() self.house.add_object("raycast_list", self.raycast_list) # initialize agents and place them in the environment self.map_builder = MapBuilder(self.house) self.neo = NEO(self.house) self.blue_player_pilot = BluePlayerPilot(self.house) def build_environment(self): """calls the map builder agent to parse through the level file and create the map of the game""" self.map_builder.build_arena() self.map_builder.insert_objects() self.wall_list = self.house.get_object("wall_list") self.object_list = self.house.get_object("object_list") def check_bullet_collisions(self): """checks if any bullets have collided with objects and need to be removed""" for bullet in self.bullet_list: bullet.update_movement() self.check_if_bullet_is_in_boundaries(bullet) self.check_player_bullet_collision(bullet) self.check_wall_bullet_collision(bullet) self.check_object_ray_collision(bullet) def check_if_bullet_is_in_boundaries(self, bullet): """removes the bullet if it is no longer on the map""" if bullet.rect.x < 0 or bullet.rect.x > 1116 or bullet.rect.y < 0 or bullet.rect.y > 444: self.bullet_list.remove(bullet) def check_player_bullet_collision(self, bullet): """checks if the bullet has collided with a player""" # for player in self.player_list: # if bullet.rect.colliderect(player): # player.hit_points -= 10 # self.bullet_list.remove(bullet) pass def check_object_ray_collision(self, bullet): for object in self.object_list: if bullet.rect.colliderect(object): self.neo.mouth.stopSentence() sentence = object.name + " detected" _thread.start_new_thread(self.neo.mouth.identify_detected_object, (sentence,)) self.neo.object_coordinates = (object.rect.x, object.rect.y) self.neo.detected_objects.add(object) self.bullet_list.remove(bullet) def check_wall_bullet_collision(self, bullet): for wall_block in self.wall_list: if bullet.rect.colliderect(wall_block): self.bullet_list.remove(bullet) def check_pygame_events(self): """checks any for events such as keys pressed or A.I. actions that change the state of the game""" for e in pygame.event.get(): if e.type == pygame.QUIT: self.running_game = False if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE: self.running_game = False def draw(self): """displays the game images on the screen""" self.screen.fill((0, 0, 0)) self.object_list.draw(self.screen) self.player_list.draw(self.screen) self.wall_list.draw(self.screen) self.bullet_list.draw(self.screen) pygame.display.flip() def initialize_screen(self): # Set up the display pygame.display.set_caption("BOT ARENA 3.0!") self.screen = pygame.display.set_mode((self.screen_width, self.screen_height)) def run_game(self): """calls the player agent's to perform their moves and check's for bullet movement""" self.check_pygame_events() self.neo.make_decision() self.blue_player_pilot.check_input_for_actions() self.check_bullet_collisions() self.draw() def setup_players(self): """adds the player sprites to the list of players for reference and sets up the bots in their environment""" self.player_list.add(self.neo.bot, self.blue_player_pilot.bot) self.blue_player_pilot.setup_bot_map() self.neo.setup_bot_map()
class GameManager(Agent): """The game_manager handles all agents responsible for making the game run""" def __init__(self): """sets up the game variables and then initializes its employee agents""" super(GameManager, self).__init__("game_manager") self.play_window = Environment() self.screen = None # screen size self.screen_height = 444 self.screen_width = 1116 self.running_game = True # player list self.player_list = pygame.sprite.Group() self.play_window.add_object("player_list", self.player_list) # holds bullet list self.bullet_list = pygame.sprite.Group() self.play_window.add_object("bullet_list", self.bullet_list) # holds the sprites that make up the wall self.wall_list = pygame.sprite.Group() self.play_window.add_object("wall_list", self.wall_list) # initialize agents and place them in the environment self.map_builder = MapBuilder(self.play_window) self.red_ai_pilot = RedAiPilot(self.play_window) self.blue_player_pilot = BluePlayerPilot(self.play_window) def build_walls(self): """calls the map builder agent to parse through the level file and create the map of the game""" self.map_builder.build_arena() self.wall_list = self.play_window.get_object("wall_list") def check_bullet_collisions(self): """checks if any bullets have collided with objects and need to be removed""" for bullet in self.bullet_list: bullet.update_movement() self.check_if_bullet_is_in_boundaries(bullet) self.check_player_bullet_collision(bullet) self.check_wall_bullet_collision(bullet) def check_if_bullet_is_in_boundaries(self, bullet): """removes the bullet if it is no longer on the map""" if bullet.rect.x < 0 or bullet.rect.x > 1116 or bullet.rect.y < 0 or bullet.rect.y > 444: self.bullet_list.remove(bullet) def check_player_bullet_collision(self, bullet): """checks if the bullet has collided with a player""" for player in self.player_list: if bullet.rect.colliderect(player): player.hit_points -= 10 self.bullet_list.remove(bullet) def check_wall_bullet_collision(self, bullet): for wall_block in self.wall_list: if bullet.rect.colliderect(wall_block): self.bullet_list.remove(bullet) def check_pygame_events(self): """checks any for events such as keys pressed or A.I. actions that change the state of the game""" for e in pygame.event.get(): if e.type == pygame.QUIT: self.running_game = False if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE: self.running_game = False def draw(self): """displays the game images on the screen""" self.screen.fill((0, 0, 0)) self.player_list.draw(self.screen) self.wall_list.draw(self.screen) self.bullet_list.draw(self.screen) pygame.display.flip() def initialize_screen(self): # Set up the display pygame.display.set_caption("BOT ARENA 3.0!") self.screen = pygame.display.set_mode( (self.screen_width, self.screen_height)) def run_game(self): """calls the player agent's to perform their moves and check's for bullet movement""" self.check_pygame_events() self.red_ai_pilot.make_decision() self.blue_player_pilot.check_input_for_actions() self.check_bullet_collisions() self.draw() def setup_players(self): """adds the player sprites to the list of players for reference and sets up the bots in their environment""" self.player_list.add(self.red_ai_pilot.bot, self.blue_player_pilot.bot) self.blue_player_pilot.setup_bot_map() self.red_ai_pilot.setup_bot_map()
class Manager(object): def __init__(self, map_name): self.main_node = render.attachNewNode('main_node') self.blocked_squares = set() self.bodies = {} self.map = Map(map_name) self.map_builder = MapBuilder(self.map, self.main_node) self.map_builder.build() self.map_builder.clear_map_textures() self.player = Player(self, self.map.start_pos) self.set_npcs() self.setup_graphics() if S.show_view_field: self.view_fields = defaultdict(set) taskMgr.doMethodLater(1, self.update_view_fields, 'fields') if S.show_pathes: self.pathes = defaultdict(set) taskMgr.doMethodLater(1, self.update_pathes, 'pathes') def set_npcs(self): self.npcs = {} for data in self.map.npcs: for _ in range(data['count']): _data = data.copy() route = deque(self.map.routes[data['route']]) free = [i for i in route if i not in self.npcs] assert free, 'all postions are occupated' pos = choice(free) while pos != route[0]: route.rotate(1) _data['route'] = route NPC(self, **_data)#.dead = True # for debugging data = self.map.target_npc.copy() if not data: return route = deque(self.map.routes[data['route']]) data['route'] = route TargetNPC(self, **data) def is_available(self, pos): return (pos in self.map and (pos != self.player.pos or self.player.walking) and (pos not in self.npcs or self.npcs[pos].walking) and pos not in self.bodies) def __call__(self, task): self.player.update_action() for npc in tuple(self.npcs.values()): if not npc and npc.action is None: if isinstance(npc, TargetNPC): self.finish(True) del self.npcs[npc.pos] Body(npc, self) continue npc.update_action() if isinstance(npc, TargetNPC) and npc.pos == self.map.escape_position: self.finish(False) return task.cont def finish(self, win): base.finish_game(win) def on_player_moved(self, prev_pos, pos): map = self.map if prev_pos is None: prev_group = None elif map[prev_pos]['kind'] != 'model_field': prev_group = map[prev_pos]['ident'] else: prev_group = map[prev_pos]['group'] if map[pos]['kind'] != 'model_field': group = map[pos]['ident'] else: group = map[pos]['group'] if prev_group == group: return if prev_group is not None: for pos in map.groups[prev_group]: model = self.map_builder.get_model(pos) if model is None: continue model.setAlphaScale(1) for pos in map.groups[group]: model = self.map_builder.get_model(pos) if model is None: continue model.setAlphaScale(S.graphics['transparency']) def alert(self, pos, target=None): for npc in self.npcs.values(): if not npc: continue length = hypot(npc.pos[0] - pos[0], npc.pos[1] - pos[1]) if length <= S.npc['alert_radius']: if isinstance(npc, TargetNPC): npc.target = self.map.escape_position npc.speed = S.target_npc['escape_speed'] else: npc.set_alert_texture() #FIXME: don't set target if path to it doesn't exist npc.target = target or self.player npc.speed = S.npc['excited_speed'] npc.view_radius = S.npc['excited_view_radius'] npc.view_angle = S.npc['excited_view_angle'] def setup_graphics(self): angle = self.map.hour * 15 - 90 light_factor = max(sin(radians(angle)), 0) mnode = self.main_node alight = AmbientLight('alight') color = S.graphics['ambient_light_color'] + [light_factor] alight.setColor(VBase4(*color)) alnp = mnode.attachNewNode(alight) mnode.setLight(alnp) dlight = DirectionalLight('dlight') color = S.graphics['light_color'] + [light_factor] dlight.setColor(VBase4(*color)) dlnp = mnode.attachNewNode(dlight) dlnp.setHpr(0, -angle, 0) mnode.setLight(dlnp) if S.graphics['enable_shadows']: self.main_node.setShaderAuto() # doesn't work in multithreading mode lens = OrthographicLens() lens.setFilmSize(30, 30) lens.setNearFar(-1000, 1000) dlight.setLens(lens) ss = S.graphics['shadow_size'] dlight.setShadowCaster(True, ss, ss) dlnp.reparentTo(self.player.node) if S.graphics['enable_cartoon']: # set for models separately self.main_node.setShaderAuto() # doesn't work in multithreading mode def update_view_fields(self, task): """ It is a very expensive funciton. Use only for debugging """ for npc in self.npcs.values(): key = id(npc) for marker in self.view_fields[key]: marker.removeNode() del self.view_fields[key] radius, c_angle = npc.view_radius, npc.view_angle angle = int(npc.actor.getHpr()[0] - 90) % 360 pred = lambda pos: 'see' in self.map[pos]['actions'] field = self.map.view_field(npc.pos, angle, c_angle, radius, pred) for pos in field: marker = loader.loadModel(S.model('plane')) marker.setHpr(0, -90, 0) marker.reparentTo(self.main_node) marker.setPos(pos[0], pos[1], 0.1) self.view_fields[key].add(marker) return task.again def update_pathes(self, task): """ It is a very expensive funciton. Use only for debugging """ map = self.map for npc in self.npcs.values(): key = id(npc) for marker in self.pathes[key]: marker.removeNode() del self.pathes[key] target = npc.target end_pos = target if isinstance(target, tuple) else target.pos pred = lambda pos: ('walk' in map[pos]['actions'] and map.is_available(pos) and (pos not in self.npcs or self.npcs[pos].walking) and pos not in self.bodies) path = map.get_path(npc.pos, end_pos, pred) if path is None: continue for pos in path: marker = loader.loadModel(S.model('plane')) marker.setHpr(0, -90, 0) marker.reparentTo(self.main_node) marker.setPos(pos[0], pos[1], 0.1) self.pathes[key].add(marker) return task.again