def __init__(self, map_name): # Local copy of Player self._players = {} self._map = Map(map_name) self._player_height = 20 self._player_width = 10 self._player_color = 'red'
class GameGuide(AbstractGame): def __init__(self, screen, server): self.server = server super(GameGuide, self).__init__(screen) def _load_map(self, screen): """ Load the map :param screen: pygame.Screen object """ # Wait for map to be loaded on blind and sent here while not self.server.map: self.server.listen() map_path = self.server.map # Load the map self.map = Map(self, screen, map_path, self.server.map_timer) self.map.draw_static_sprites() super(GameGuide, self)._load_map(screen) def _run_game(self): """ Inherit run game to add the listening for the server on each iteration """ super(GameGuide, self)._run_game() if self.server: self.server.blind = self.blind self.server.game = self self.server.listen() self._check_keys() def _check_keys(self): keys = pygame.key.get_pressed() if keys[pygame.K_ESCAPE]: self.server.send_pause_game() PauseMenu(self.screen) self.server.check_client_ready() def reload_game(self, from_game_over=False): """ Reload a new game Delete the old instance of the game and start a new one from_game_over : from_game_over is True we load the current map, otherwise we load the next map """ # Wait for the blind to be ready self.server.check_client_ready() screen = self.map.screen self.server.map = False # Reset the map so we always get the one from the blind server = self.server del self GameGuide(screen, server) def pause_game(self): PauseMenu(self.screen) self.server.check_client_ready() def exit_game(self): self.server.release() super(GameGuide, self).exit_game()
def loadLevel(self, file): self.pressed = [] for key in pygame.key.get_pressed(): self.pressed.append( False ) if file in self.loaded_maps: self.current_map = self.loaded_maps[file] self.current_map.reset() else: self.current_map = Map(file, self.screen, self) self.loaded_maps[file] = self.current_map self.current_map.intialize()
def _load_map(self, screen): """ Load the map :param screen: pygame.Screen object """ # Wait for map to be loaded on blind and sent here while not self.server.map: self.server.listen() map_path = self.server.map # Load the map self.map = Map(self, screen, map_path, self.server.map_timer) self.map.draw_static_sprites() super(GameGuide, self)._load_map(screen)
def __init__(self, enable_no_resp_die=True, map=None): self.enable_no_resp_die = enable_no_resp_die if not map: m = Map.loadfile(DEFAULT_MAP) else: m = Map.loadfile(map) self.set_map(m) self.start()
def _deploySquare(self): min_y = 0 max_y = Map.getMap().height min_x = 0 max_x = Map.getMap().width if self._clan_id == Clan.RED: min_x = 0 max_x = Map.getMap().width / 3 min_y = 0 max_y = Map.getMap().height / 3 else: min_x = (Map.getMap().width / 3) * 2 max_x = Map.getMap().width min_y = (Map.getMap().height / 3) * 2 max_y = Map.getMap().height pos_y = min_y dimensions = int(math.sqrt(self._size)) self._size = dimensions ** 2 for p in range(dimensions): pos_x = min_x pos_y += 1 for q in range(dimensions): pos_x += 1 self._addElement(pos_x, pos_y)
def user_set_map(self, data): if self.status != WAITFORPLAYER: return "only can set map when the game state is waitforplayer" try: m = Map.loaddata(data) self.set_map(m) self.start() return 'ok' except Exception as e: # if error, fall back to default map self.set_map(Map.loadfile(DEFAULT_MAP)) self.start() return 'setmap error: ', str(e)
def __init__(self, enable_no_resp_die=True, map=None): self.enable_no_resp_die = enable_no_resp_die if not map: m = Map.loadfile(DEFAULT_MAP) else: m = Map.loadfile(map) self.set_map(m) self.map_max_units = m.max_sum self.maintain_fee = m.meta.get('maintain_fee', False) self.start()
def __init__(self): # init IHM self.ihm = IHM(hauteur=settings.FENETRE_LONGUEUR, largeur=settings.FENETRE_LARGEUR) donnees_joueur = self.ihm.menuDemarrage() self.ihm.log(['Données joueurs récupérées']) # on init. la map self.ihm.log(['Création de la Map']) self.map = Map(settings.LONGUEUR, settings.LARGEUR) # on init le joueur self.ihm.log(['Creation du joueur']) self.joueur = Joueur(nom = "Richard", carSec = donnees_joueur['secu'], carIhm = donnees_joueur['ihm'], carKernel = donnees_joueur['kernel'], carHard = donnees_joueur['hardware'] ) # init du jeu (IHM) self.ihm.log(['Initialiser jeu']) self.ihm.initialiserJeu(self.joueur, self.map) self.objets = {} # pas pour le prochain monstre self.ihm.log(['Tirage au sort du nombre de pas']) self.reinit_pas() self.ihm.log(['Création de la liste des monstres']) self.generer_liste_monstres()
def _create_game(self, num_of_players, clients): start_positions = {2: [], 3: [], 4: []} for key, arr in start_positions.items(): arr.extend([int(i * (MAP_W / key)) for i in range(key)]) game_map = Map(MAP_W, MAP_H, True) game = { 'clients': [], 'positions': start_positions[num_of_players], 'positions_y': [], 'mutex': Lock(), 'num_of_players': num_of_players, 'collision_map': game_map.collision_noise, 'health': [100 for x in range(num_of_players)], 'last_explode_time': 0.0, 'map': game_map, 'clock': 0.0, 'finished': False, 'turn': 0 } for client in clients: game['clients'].append(client) join_game_req = { 'action': REQUEST.JOIN_GAME, 'map': zlib.compress(bson.dumps({'data': game['collision_map']}), 7), 'tank_id': clients.index(client), 'start_x': start_positions[num_of_players] } client.send(bson.dumps(join_game_req)) game['map'].create_map(game['collision_map']) client_invalid_request = False for client in clients: data = client.recv() if data['action'] != REQUEST.JOIN_GAME: client_invalid_request = True for pos_x in game['positions']: game['positions_y'].append(game['map'].get_height(pos_x)) if client_invalid_request: for client in clients: self.clients_lock.acquire() self.clients.remove(client) self.clients_lock.release() client.close() return self.games.append(game) for x in range(num_of_players): self.game_players[clients[x]] = self.games[len(self.games) - 1] self._send_change_turn_req(game)
def parse_map(json_object: dict) -> Map: res = Map() m = json_object["map"] MapLoader.parse_nodes(res, m["nodes"]) MapLoader.parse_paths(res, m["paths"]) return res
def _deployVertical(self): min_y = 0 max_y = Map.getMap().height if self._clan_id == Clan.RED: min_x = 0 max_x = Map.getMap().width / 3 else: min_x = (Map.getMap().width / 3) * 2 max_x = Map.getMap().width pos_x = min_x + 1 pos_y = min_y + 1 for p in range(self._size): self._addElement(pos_x, pos_y) pos_y += 1 if pos_y == max_y - 1: pos_y = min_y + 1 pos_x += 1
def _deployLowerDiag(self): b = math.ceil(math.sqrt(2 * self._size)) xmax = int(Map.getMap().width / 3) m = 0 f = False for i in range(b): for j in range(b - i): if (self._clan_id == Clan.RED): self._addElement(j, Map.getMap().height - i - 1) else: self._addElement(Map.getMap().width - j - 1, i) m += 1 if (m == self._size): f = True break if (f): break
def _deployHorizontal(self): min_x = 50 max_x = Map.getMap().width if self._clan_id == Clan.RED: min_y = 0 max_y = Map.getMap().height / 3 else: min_y = (Map.getMap().height / 3) * 2 max_y = Map.getMap().height pos_x = min_x + 1 pos_y = min_y + 1 for p in range(self._size): self._addElement(pos_x, pos_y) pos_x += 1 if pos_x == max_x - 1: pos_x = min_x + 1 pos_y += 1
def move(self, move_vector: (float, float)) -> bool: """This function represents the interaction between my character and the environment. The speed and terrain part that follows could be simplified in our current case, since all the terrain is the same and the speed of our army elements is all equal. But in a more complex situation, where the terrain is heterogeneous and we have a mixed army, this code would be able to handle properly the movement in such cases Returns ------- """ factor = Map.getTerrainAt(int(self._x), int(self._y)).cross() * self._speed m_x = move_vector[0] * factor m_y = move_vector[1] * factor new_x = self._x + m_x new_y = self._y + m_y if Map.getMap().width >= new_x >= 0: self._x = new_x elif Map.getMap().width < new_x: self._x = Map.getMap().width else: self._x = 0 if Map.getMap().height >= new_y >= 0: self._y = new_y elif Map.getMap().height < new_y: self._y = Map.getMap().height else: self._y = 0 return True
def __init__(self,interface, socket_to_server): self.isharvest = False self.isfighting = False self.spells = Spells(interface) self.map = Map(interface) self.interface = interface self.socket_to_server = socket_to_server self.deplacement = Deplacement(self.socket_to_server) self.entity = None
def _deployerDownDiagonal(self): base = math.ceil(math.sqrt(2 * self._size)) xmax = int(Map.getMap().width / 3) count = 0 full = False for i in range(base): for j in range(base - i): if (self._clan_id == Clan.RED): self._addElement(j, Map.getMap().height - i - 1) else: self._addElement(Map.getMap().width - j - 1, i) count += 1 if (count == self._size): full = True break if (full): break
def _deployTriangle(self): n = math.ceil(math.sqrt(self._size)) base = int(Map.getMap().width / 3) mid = int(Map.getMap().height / 2) full = False count = 0 for i in range(n): for j in range(-i, i + 1, 1): if (self._clan_id == Clan.RED): self._addElement(base - i, mid + j) else: self._addElement(base * 2 + i, mid + j) count += 1 if (count == self._size): full = True break if (full): break
def _load_map(self, screen): """ Search for the map in the ./map/map_order.xml file and load it in the game. Then we send the map to the guide :param screen: .Screen object """ if not self.map_path: map_name = self.search_map() self.map_path = "../map/%s" % map_name self.client.send_new_map(self.map_path, self.get_map_timer()) # Load the map self.map = Map(self, screen, self.map_path, self.get_map_timer(), blind=True) self.map.draw_static_sprites() super(GameBlind, self)._load_map(screen)
def _deployRandom(self): min_x = 50 max_x = Map.getMap().width if self._clan_id == Clan.RED: min_y = 0 max_y = Map.getMap().height / 3 else: min_y = (Map.getMap().height / 3) * 2 max_y = Map.getMap().height pos_x = min_x + 1 pos_y = min_y + 1 for p in range(self._size): self._addElement(pos_x, pos_y) pos_x += 1 rand = random.randint(1, 5) randGrand = random.randint(25, 50) if pos_x > randGrand: pos_x = rand pos_y += rand
def __init__(self): SCREEN_WIDTH, SCREEN_HEIGHT = 96, 54 VIEW_WIDTH, VIEW_HEIGHT = 70, 36 self.gamestate = Gamestates.PLAYER_ROUND self.map = Map(96, 54) xo, yo = self.map.generate_map(6, 10, 30) # Systems self.input = InputHandler() self.camera = CameraSystem(xo, yo, VIEW_WIDTH, VIEW_HEIGHT, 2) self.window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, VIEW_WIDTH, VIEW_HEIGHT) self.render = RenderSystem(self.window.map_con) self.ai = RandomAI() self.fov = FOVSystem() self.movement = BasicMovementSystem() self.cmd = CommandHandler(self) self.update_observers() self.current_control_index = 0
def updateArmy(self) -> None: NewArmy = [] for x in range(len(self._army)): if (self._army[x].health > 0 and (self._army[x].x < Map.getMap().width or self._army[x].y < Map.getMap().height)): NewArmy.append(self._army[x]) self._army = NewArmy self._size = len(self._army) print("---------------------------------") print(self._clan_id) print(self._size)
def connect(self): # Try until the connection is up connected = False while not connected: try: requests.get(self._url) connected = True except: pass print(f'Connected to {self._url}') # Kick all other players #self.post('kick_all') response_json = self.post('add_player') # return {'rez': 'success', 'map_name': self._map.map_name, 'new_name': player_name} self._name = response_json['new_name'] self._map = Map(response_json['map_name']) print(f'Name is {self._name}') print(f'Playing on map {self._map.map_name}')
def __init__(self, enable_bean=True, enable_wall=True, enable_no_resp_die=True, map=None): self.enable_bean = enable_bean self.enable_wall = enable_wall self.enable_no_resp_die = enable_no_resp_die if not map: map = Map.loadfile(DEFAULT_MAP) self.set_map(map) self.start()
def handle(self, max_lat, max_lng, seed, points, hill_noise, heights_map_width, *args, **options): if seed is None: seed = int(random.random() * 10000) print('seed = %s' % seed) map_obj = Map(seed, [ generators.points.RelaxedPoints(points_number=points).generate, generators.graph.VoronoiGraph().generate, generators.graph.VoronoiGraph().imporove_corners, generators.land.SimplexIsland().generate, generators.elevation.FromCoast().generate, generators.rivers.RandomRiver().generate, generators.biomes.Moisture().generate, generators.regions.HexGrid().generate, exports.ModelExporter( Biome, River, Region, City, max_lat=max_lat, max_lng=max_lng).export, exports.GeoTiffExporter(max_lat, max_lng, heights_map_width, hill_noise).export, # renderers.RegionRenderer().render, ]) map_obj.generate()
def __init__(self): self.runDisplay = Display("mapaReducido.tmx") self.win = self.runDisplay.displayWindow self.map = Map(self.runDisplay.map.gameMap.tilewidth, self.runDisplay.map.gameMap.tileheight, self.runDisplay.map.walkableTiles, self.runDisplay.map.zones) self.peoples = [ Worker(5, 2, self.map), Worker(10, 4, self.map), Worker(6, 4, self.map), Worker(1, 4, self.map), Customer(36, 2, self.map), Customer(37, 2, self.map), Customer(36, 3, self.map) ] #self.peoples = [Worker(5,2,self.map)] self.tasks = deque([]) self.objects = deque([]) self.tasks_doing = deque([])
def handle(self, max_lat, max_lng, seed, points, hill_noise, heights_map_width, *args, **options): if seed is None: seed = int(random.random() * 10000) print("seed = %s" % seed) map_obj = Map( seed, [ generators.points.RelaxedPoints(points_number=points).generate, generators.graph.VoronoiGraph().generate, generators.graph.VoronoiGraph().imporove_corners, generators.land.SimplexIsland().generate, generators.elevation.FromCoast().generate, generators.rivers.RandomRiver().generate, generators.biomes.Moisture().generate, generators.regions.HexGrid().generate, exports.ModelExporter(Biome, River, Region, City, max_lat=max_lat, max_lng=max_lng).export, exports.GeoTiffExporter(max_lat, max_lng, heights_map_width, hill_noise).export, # renderers.RegionRenderer().render, ], ) map_obj.generate()
def main(): game_map = Map(15, 15) while True: game_map.draw() game_map.next_move() c = raw_input() if c == "x": break
def load_in_to_class(self): ''' DataFrame: ''' self.dataSource = {} connection = dataSource.Database().get_connection() cursor = connection.cursor(dictionary=True) try: cursor.execute('SELECT * FROM maps;') data = cursor.fetchall() for result in data: try: mapData = Map( result['id'], result['date'], result['width'], result['heigth'], result['key'], result['places'], result['mapData'], result['cells'], result['monsters'], result['mappos'], result['numgroup'], result['fixSize'], result['minSize'], result['maxSize'], result['cases'], result['forbidden'], ) self.dataSource[result['id']] = mapData except Exception as Error: self.log.warning( 'maps_data.py - maps:{} can\'t be loaded'.format( str(result['id']))) self.log.warning(Error) except Exception as Error: self.log.warning('map_data.py - Can\'t load table accounts') self.log.warning(str(Error)) finally: cursor.close() connection.close()
class MapLoaderHandler(osmium.SimpleHandler): excluded_ways = ('footway', 'corridor', 'sidewalks', 'steps', 'crossing') def __init__(self): super(MapLoaderHandler, self).__init__() self.map = Map() def node(self, n): position = GeoPosition(lon=n.location.lon, lat=n.location.lat) node = Node(position=position) self.map.add(node) def way(self, way): if not way.nodes or 'highway' not in way.tags or way.is_closed(): return if way.tags['highway'] in MapLoaderHandler.excluded_ways: return previous = way.nodes[0] # Ensure nodes are added to map in case they haven't been added before # We want nodes to be added before ways, not the other way around # Adding all necessary nodes here helps ensure that self.map.add(previous) for i in range(1, len(way.nodes)): current = way.nodes[i] self.map.add(current) begin = GeoPosition(lon=previous.lon, lat=previous.lat) end = GeoPosition(lon=current.lon, lat=current.lat) path = Path(begin=begin, end=end) self.map.add(path) previous = current def relation(self, way): """noop -> There's no need to handle relations, at least not now"""
def move( self, e_center: (float, float), vectorCenterToCenter: (float, float) ) -> bool: """This function represents the interaction between my character and the environment. The speed and terrain part that follows could be simplified in our current case, since all the terrain is the same and the speed of our army elements is all equal. But in a more complex situation, where the terrain is heterogeneous and we have a mixed army, this code would be able to handle properly the movement in such cases Returns ------- """ factor = Map.getTerrainAt(int(self._x), int( self._y)).cross() * self._speed Vg = (e_center[0] - self._x, e_center[1] - self._y) Mag = sqrt(pow(Vg[0], 2) + pow(Vg[1], 2)) Vg = (Vg[0] / Mag, Vg[1] / Mag) Vt = (Vg[0] + vectorCenterToCenter[0], Vg[1] + vectorCenterToCenter[1]) mag2 = sqrt(pow(Vt[0], 2) + pow(Vt[1], 2)) move_vector = (Vt[0] / mag2, Vt[1] / mag2) m_x = move_vector[0] * factor m_y = move_vector[1] * factor new_x = self._x + m_x new_y = self._y + m_y if Map.getMap().width > new_x >= 0: self._x = new_x elif Map.getMap().width <= new_x: self._x = Map.getMap().width - 1 else: self._x = 0 if Map.getMap().height > new_y >= 0: self._y = new_y elif Map.getMap().height <= new_y: self._y = Map.getMap().height - 1 else: self._y = 0 return True
def _deployDiagonal(self): min_x = 50 max_x = Map.getMap().width if self._clan_id == Clan.RED: min_y = 0 max_y = Map.getMap().height / 3 else: min_y = (Map.getMap().height / 3) * 2 max_y = Map.getMap().height pos_x = min_x + 1 pos_y = min_y + 1 for p in range(self._size): self._addElement(pos_x, pos_y) pos_x += 1 if pos_x > 1: pos_x += 1 pos_y += 1 if pos_y > Map.getMap().height or pos_y < 0: pos_y = min_y elif pos_x > Map.getMap().width or pos_x < 0: pos_x = min_x
def __init__(self): super(MapLoaderHandler, self).__init__() self.map = Map()
class Client: def __init__(self, ip: str, port: str, player_name: str): self._url = f'http://{ip}:{port}' self._name = player_name self._map = None self._font_size = 13 self._entities = {} self.connect() self._window = GraphWin('GAY', self._map.length, self._map.height) self._pressed = {} def post(self, request_type: str, request_body: Map = {}): request_body['player_name'] = self._name return requests.post(self._url, json={ 'request_type': request_type, 'request_body': request_body }).json() def connect(self): # Try until the connection is up connected = False while not connected: try: requests.get(self._url) connected = True except: pass print(f'Connected to {self._url}') # Kick all other players #self.post('kick_all') response_json = self.post('add_player') # return {'rez': 'success', 'map_name': self._map.map_name, 'new_name': player_name} self._name = response_json['new_name'] self._map = Map(response_json['map_name']) print(f'Name is {self._name}') print(f'Playing on map {self._map.map_name}') def draw(self): self._map.draw_stage(self._window) print('done drawing stage') while True: entity_info = None try: entity_info = requests.get(self._url).json() except: print('Problem with the server, shutting down') for player, player_info in entity_info.items(): x, y = player_info['x_coord'], player_info['y_coord'] height, width = player_info['height'], player_info['width'] color = player_info['color'] name_tag_x = x + width / 2 name_tag_y = y - height - self._font_size if f'{player}_name' in self._entities: item = self._entities[f'{player}_name'] item.move(name_tag_x - item.getAnchor().getX(), name_tag_y - item.getAnchor().getY()) else: text = Text(Point(name_tag_x, name_tag_y), player) text.setSize(self._font_size) text.draw(self._window) self._entities[f'{player}_name'] = text if player in self._entities: item = self._entities[player] item.move(x - item.getP1().getX(), y - item.getP1().getY()) else: rect = Rectangle(Point(x, y), Point(x + width, y - height)) rect.setFill(color) rect.draw(self._window) self._entities[player] = rect k = self._window.checkKey() if k == 'Left' or k == 'Right': self._pressed[k] = True elif k == '': self._pressed = {} if 'Left' in self._pressed: self.post('move_left') if 'Right' in self._pressed: self.post('move_right') self._window.getMouse() self._window.close()
class Jeu: """ Classe de jeu """ def __init__(self): # init IHM self.ihm = IHM(hauteur=settings.FENETRE_LONGUEUR, largeur=settings.FENETRE_LARGEUR) donnees_joueur = self.ihm.menuDemarrage() self.ihm.log(['Données joueurs récupérées']) # on init. la map self.ihm.log(['Création de la Map']) self.map = Map(settings.LONGUEUR, settings.LARGEUR) # on init le joueur self.ihm.log(['Creation du joueur']) self.joueur = Joueur(nom = "Richard", carSec = donnees_joueur['secu'], carIhm = donnees_joueur['ihm'], carKernel = donnees_joueur['kernel'], carHard = donnees_joueur['hardware'] ) # init du jeu (IHM) self.ihm.log(['Initialiser jeu']) self.ihm.initialiserJeu(self.joueur, self.map) self.objets = {} # pas pour le prochain monstre self.ihm.log(['Tirage au sort du nombre de pas']) self.reinit_pas() self.ihm.log(['Création de la liste des monstres']) self.generer_liste_monstres() def stop(self): exit(0) def start(self): """ fonction qui bosse (la seule qui bosse ici en fait....) """ self.ihm.log(['On attaque la boucle infinie']) while 1: # 1. afficher le jeu self.ihm.afficherJeu() if self.ihm.utilisateurQuitte(): self.stop() # 2. attendre un mouvement # 3. IHM nous file la direction mouv = self.ihm.mouvement() if self.ihm.utilisateurQuitte(): self.stop() # 4. on demande à la map si c'est OK # 5. on fait buoger le joueur si OK #juste pour faciliter l'accès x = self.joueur.x y = self.joueur.y if mouv == "haut": if self.map.case_libre(x, y-1): self.joueur.haut() else: continue elif mouv == "droite": if self.map.case_libre(x+1, y): self.joueur.droite() else: continue elif mouv == "bas": if self.map.case_libre(x, y+1): self.joueur.bas() else: continue elif mouv == "gauche": if self.map.case_libre(x-1, y): self.joueur.gauche() else: continue else: pass # quitter le jeu # on retire 1 au compteur de pas self.pas_pour_monstre -= 1 # 6.1. monstre ? if not self.pas_pour_monstre: self.ihm.log(["C'est l'heure du monstre"]) # 7.1. on l'instancie monstre = self.spawn_monstre() # 8.1. on génère un combat combat = Combat(self.joueur, monstre) # 9.1. on refourgue le combat à l'ihm qui affiche un dialog if self.ihm.utilisateurQuitte(): self.stop() choix_combat = self.ihm.dialogCombat(combat) if choix_combat == 'combattre': combat.combat() else: combat.fuite() self.ihm.finCombat(combat) if self.ihm.utilisateurQuitte(): self.stop() self.reinit_pas() # 6.2. objet ? # 7.2. on le récupère/on l'instancie # 8.2. on le refourgue à l'IHM qui affiche un dialog # 9.2. l'user répond et on prend en compte son choix self.ihm.log(["Checks pour les objets"]) if self.ihm.utilisateurQuitte(): self.stop() self.objet_trouve() def generer_liste_monstres(self): """ génère une liste de monstres à partir des fichiers dans RESSOURCES_PATH/monstres """ self.ihm.log(["Generation de la liste de monstres"]) # la première liste (celle à l'intérieure récupère la liste des fichiers via glob() et vire le path jusqu'au # fichier. La seconde enlève le .json à la fin self.liste_monstres = [__.split('.')[0] for __ in [_.split('/')[-1] for _ in glob('{0}/monstres/*.json'.format(settings.RESSOURCES_PATH))]] def objet_trouve(self): """ Demande à la map si un objet est là et instancie l'objet au besoin """ nom_objet = self.map.objet_present(self.joueur.x, self.joueur.y) if not nom_objet == "": # s'il y a un objet dans cette case if nom_objet in self.objets.keys(): objet = self.objets[nom_objet] else: # on instancie l'objet donnees_objet = load(open('{0}/objets/{1}.json'.format(settings.RESSOURCES_PATH, nom_objet))) objet = Objet( nom_objet, poids = donnees_objet['poids'], carSec = donnees_objet['carSec'], carIhm = donnees_objet['carIhm'], carKernel = donnees_objet['carKernel'], carHard = donnees_objet['carHard'] ) self.objets[nom_objet] = objet if self.joueur.peut_equiper(objet.poids): if self.ihm.dialogObjet(objet): # vrai si l'usr souhaite garder l'objet resultat_equipement = self.joueur.equiperObjet(objet) def spawn_monstre(self): """ choisit un monstre au hasard, l'instancie et le retourne """ nom_monstre = choice(self.liste_monstres) donnees_monstre = load(open('{0}/monstres/{1}.json'.format(settings.RESSOURCES_PATH, nom_monstre))) monstre = Ennemi( nom_monstre, cafe = donnees_monstre['cafe'], carSec = donnees_monstre['carSec'], carIhm = donnees_monstre['carIhm'], carKernel = donnees_monstre['carKernel'], carHard = donnees_monstre['carHard'] ) return monstre def reinit_pas(self): """ Réinitialise le nombre de pas pour le prochain monstre """ self.pas_pour_monstre = randrange( settings.PAS-settings.PAS/2, settings.PAS+settings.PAS/2 )
class Game: def __init__(self, screen): self.screen = screen self.map_screen = self.screen.subsurface(0, 0, MAP_WIDTH, MAP_HEIGHT) #pygame.display.set_icon(pygame.image.load(os.path.join("images", "ui","icon.png"))) self.loaded_maps = {} self.current_map = None pygame.mouse.set_visible(1); self.hasKey = False self.animalsFreed = False self.soundUtil = SoundUtil() self.soundUtil.sound_on = True self.pauseMenu = PauseScreen(self) self.cursor = Sprite() self.cursor.rect = Rect(0,0,1,1) self.hud = Hud(self) self.player_group = Group() self.player = Taz(image_util.load_image("tasmanian.png"), 1, 1, self) self.player.inUse = True self.player.current_image = self.player.image self.hud.set_player(self.player) self.last_rendered_achievement = 0 self.achievement_countdown = 0 self.clock = pygame.time.Clock() self.achievements_done = [] self.pressed = [] for key in pygame.key.get_pressed(): self.pressed.append( True ) self.loadLevel("jail.txt") self.isGameOver = False self.returnToMainMenu = False def reset(self): self.player_group.remove(self.player) self.current_map.game_objects.remove(self.player) self.player = self.player.newPlayer() self.player.inUse = True self.player.current_image = self.player.image self.pressed = [] for key in pygame.key.get_pressed(): self.pressed.append( False ) self.loadLevel("jail.txt") self.player.x = TILE_SIZE self.player.y = TILE_SIZE self.player.rect.left = self.player.x + self.player.left_offset self.player.rect.top = self.player.y + self.player.top_offset def loadLevel(self, file): self.pressed = [] for key in pygame.key.get_pressed(): self.pressed.append( False ) if file in self.loaded_maps: self.current_map = self.loaded_maps[file] self.current_map.reset() else: self.current_map = Map(file, self.screen, self) self.loaded_maps[file] = self.current_map self.current_map.intialize() def change_maps(self, dest, x, y): if self.player.isInCar: self.current_map.game_objects.remove(self.player.car) self.current_map.not_player.remove(self.player.car) self.loadLevel(dest) self.player.x = x * TILE_SIZE self.player.y = y * TILE_SIZE self.player.rect.left = self.player.x + self.player.left_offset self.player.rect.top = self.player.y + self.player.top_offset if self.player.isInCar: if isinstance(self.player.car, ImperviousCar): self.player.car = Car(None,0,0,self) self.player.car.driver = self.player self.player.car.driving = True self.player.car.x = x * TILE_SIZE self.player.car.y = y * TILE_SIZE self.player.car.rect.left = self.player.car.x self.player.car.rect.top = self.player.car.y self.player.car.avoidMapLinks() self.current_map.game_objects.add(self.player.car) elif self.player.isInTree: self.player.getOutOfTree() self.player.x = TILE_SIZE self.player.y = TILE_SIZE self.player.rect.left = self.player.x + self.player.left_offset self.player.rect.top = self.player.y + self.player.top_offset def change_player(self, newPlayer): self.player.inUse = False self.player.leave_car() self.current_map.game_objects.add(self.player) self.player = newPlayer; self.player.inUse = True self.player.current_image = self.player.image self.hud.set_player(self.player) def free_all_animals(self): self.free_animal("Koala") self.free_animal("Tasmanian Devil") self.free_animal("Kangaroo") self.free_animal("Brown Snake") self.free_animal("Dingo") def free_animal(self, animal_name): animals_freed[animal_name] = image_util.load_image(animal_info.info[animal_name][3]) self.hud.draw() if len(animals_freed) is 5 and self.animalsFreed is False: cutscene = Cutscene(self, "escape the zoo", \ [image_util.load_image(os.path.join("cutscenes","escape_the_zoo.png"))], \ image_util.load_sliced_sprites(210, 80, os.path.join("cutscenes","press_enter.png"))); cutscene.fire(self.player) self.animalsFreed = True def gameloop(self): self.returnToMainMenu = False self.hud.draw() while self.returnToMainMenu is False: self.clock.tick(60) self.get_input() self.update_state() self.draw() print "GAME ENDING!" def achievement(self): killed = self.hud.visitors_killed if killed >= 1000 and 1000 not in self.achievements_done:#not killed == self.last_rendered_achievement: #self.last_rendered_achievement = killed self.achievements_done.append(1000) self.achievement_image = image_util.load_image("achievement_1000.png") self.achievement_countdown = 200 elif killed >= 500 and 500 not in self.achievements_done:## and not killed == self.last_rendered_achievement: self.achievements_done.append(500) #self.last_rendered_achievement = killed self.achievement_image = image_util.load_image("achievement_500.png") self.achievement_countdown = 200 elif killed >= 100 and 100 not in self.achievements_done:## and not killed == self.last_rendered_achievement: self.achievements_done.append(100) #self.last_rendered_achievement = killed self.achievement_image = image_util.load_image("achievement_100.png") self.achievement_countdown = 200 elif killed >= 10 and 10 not in self.achievements_done:## and not killed == self.last_rendered_achievement: self.achievements_done.append(10) #self.last_rendered_achievement = killed self.achievement_image = image_util.load_image("achievement_10.png") self.achievement_countdown = 200 if self.achievement_countdown > 0: self.screen.blit(self.achievement_image, (250,100)) self.achievement_countdown -= 1 def get_input(self): self.getEvents() self.getButtonPresses() return def getEvents(self): for event in pygame.event.get(): if event.type == QUIT: sys.exit() def getButtonPresses(self): keys = pygame.key.get_pressed() # quit if(keys[K_ESCAPE]): if not self.pressed[K_ESCAPE]: self.pressed[K_ESCAPE] = True self.pauseMenu.loop() #figure out what we wanted to do if self.pauseMenu.index is CONTINUE: self.hud.draw() elif self.pauseMenu.index is MAIN_MENU: self.returnToMainMenu = True else: self.pressed[K_ESCAPE] = False # attack if(keys[K_SPACE]): if not self.pressed[K_SPACE]: self.pressed[K_SPACE] = True self.player.attack() else: self.pressed[K_SPACE] = False # use ability if(keys[K_RETURN]): if not self.pressed[K_RETURN]: self.pressed[K_RETURN] = True self.player.use_ability() else: self.pressed[K_RETURN] = False # use ability if(keys[K_F1]): if not self.pressed[K_F1]: self.pressed[K_F1] = True self.free_all_animals() else: self.pressed[K_F1] = False # get into and out of car if(keys[K_q]): if not self.pressed[K_q]: self.pressed[K_q] = True self.player.use_object() else: self.pressed[K_q] = False # move if(keys[K_w]): if not self.pressed[K_w]: self.player.move(0, -1) else: self.pressed[K_w] = False if(keys[K_s]): if not self.pressed[K_s]: self.player.move(0, 1) else: self.pressed[K_s] = False if(keys[K_a]): if not self.pressed[K_a]: self.player.move(-1, 0) else: self.pressed[K_a] = False if(keys[K_d]): if not self.pressed[K_d]: self.player.move(1, 0) else: self.pressed[K_d] = False if(keys[K_UP]): if not self.pressed[K_UP]: self.player.move(0, -1) else: self.pressed[K_UP] = False if(keys[K_DOWN]): if not self.pressed[K_DOWN]: self.player.move(0, 1) else: self.pressed[K_DOWN] = False if(keys[K_LEFT]): if not self.pressed[K_LEFT]: self.player.move(-1, 0) else: self.pressed[K_LEFT] = False if(keys[K_RIGHT]): if not self.pressed[K_RIGHT]: self.player.move(1, 0) else: self.pressed[K_RIGHT] = False if(keys[K_o]): if not self.pressed[K_o]: self.pressed[K_o] = True if self.soundUtil.sound_on: self.soundUtil.sound_on = False else: self.soundUtil.sound_on = True else: self.pressed[K_o] = False def update_state(self): if self.current_map is not None: self.current_map.update_objects() for p in self.player_group: p.update() def draw_without_flip(self): self.map_screen.fill((0,0,0)) if self.current_map is not None: self.current_map.draw_tiles() self.current_map.draw_objects() #for p in self.player_group: # p.draw() self.player.draw() self.achievement() def draw(self): self.draw_without_flip() for cutscene in self.current_map.start_cutscenes: self.current_map.start_cutscenes.remove(cutscene) cutscene.fire(self.player) pygame.display.flip()