def __init__(self): """ Инициализация новой игровой сессии """ self.players: Player = [] self.players_count = 0 self.map = Map(20, 20)
def game(): pygame.init() clock = pygame.time.Clock() canvas = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Traffic Simulation') FONT = pygame.font.SysFont("Bizarre-Ass Font Sans Serif", 20) renderEngine = RenderEngine(canvas, pygame, BLOCK_SIZE, WIDTH, HEIGHT, FONT) game_map = Map(renderEngine, ROAD_MAP, BLOCK_SIZE, DEBUG) while True: for ev in pygame.event.get(): if ev.type == pygame.QUIT: pygame.quit() if not config['USE_TEXTURES']: canvas.fill(BACKGROUND_COLOR) Veichle.dt = clock.get_time() / 1000 game_map.update() message = 'Time: ' + str(int(pygame.time.get_ticks() / 1000)) renderEngine.drawText(message, 20, 20) renderEngine.drawText('Fps: ' + str(int(clock.get_fps())), 20, 40) pygame.display.update() pygame.display.flip() clock.tick(180)
def create_new_world(game_state): map_1 = Map("Swindon", (60, 50), (game_state.screen_width, game_state.screen_height)) map_1.map_generation() Avatar(5, 5, map_1) game_state.maps[map_1.name] = map_1 game_state.active_map = game_state.maps["Swindon"] game_state.player = game_state.active_map.entity_group["Avatar"][0] game_state.player.fight_frame = 0 debug_stats = debug.DebugStatus(game_state.active_map, game_state) debug_stats.tile_selector_graphic = ui.TileSelectorGraphic(0, 0, game_state.active_map) game_state.debug_status = debug_stats # Sets player's inventory at start to basic starting equipment initial_equipment = [weapon.weapon_functions[0](1, game_state.player.level, "Iron "), armor.armor_functions[3](1, game_state.player.level, "Iron "), armor.clothing_functions[0](1, game_state.player.level), armor.clothing_functions[1](1, game_state.player.level), armor.clothing_functions[3](1, game_state.player.level)] for each in initial_equipment: game_state.player.inventory.add_item(each) for category in game_state.player.inventory.items: for each in game_state.player.inventory.items[category]: game_state.player.equip(each) map_1.update_object_layer()
def __init__(self, canvas): self.canvas = canvas self.game_map = Map() self.hero = Hero(0, 1) self.boss = Boss(0, 5) self.skeleton = Skeleton(6, 8) self.skeleton2 = Skeleton(0, 7) self.skeleton3 = Skeleton(4, 5) self.stat = Stat(self.hero, self.boss) self.monster_position()
def __init__(self): """ Initializes player, game map. """ mapSquareSize = random.randint(10, 20) mapSize = Position(mapSquareSize, mapSquareSize) startPos = \ Position(random.randint(0, mapSquareSize - 1), random.randint(0, mapSquareSize - 1)) self.player = Player(position=startPos, hp=3, bag_counter=0) self.enemy = Enemy(3, 1, Position(1, 1), Position(0, 0), Position(mapSize.x, mapSize.y)) self.level = Map(size=mapSize, treasures=6, traps=6) self.actions = { "Up": "w", "Down": "s", "Left": "a", "Right": "d", "Save": "save", "Load": "load", "Help": "help", "Exit": "exit" } self.game_status = GameState.INGAME self.__ready_to_end = False self.mrlock = threading.RLock() def enemy_update(enemy, player): while not self.ready_to_end: time.sleep(3) enemy.update(player) self.enemyThread = threading.Thread(target=enemy_update, args=(self.enemy, self.player)) self.enemyThread.start()
def main(): map1 = Map(x_size=10, y_size=10) map1.generate_map() # x_min = map1.map_start_coordinates[0] - 2 # y_min = map1.map_start_coordinates[1] - 2 # x_max = map1.map_start_coordinates[0] + 2 # y_max = map1.map_start_coordinates[1] + 2 x_min = 0 y_min = 0 x_max = map1.x_size - 1 y_max = map1.y_size - 1 map1.print_map(x_min, y_min, x_max, y_max) player = Player(name='Brian', coordinates=map1.map_start_coordinates) # game loop while True: current_room = map1.rooms[player.coordinates] print(f'player.coordinates = {player.coordinates}') print(f'room.description = "{current_room.description}"') print(f'room.doors = "{current_room.doors}"') command = input('> ').upper() print(f"'{command}'") break
def init(): window = pyglet.window.Window(width=800,height=600, resizable=True, visible=False) window.clear() window.resize = resize window.set_visible(True) window.resize(window.width, window.height) current_dir = os.path.abspath(os.path.dirname(__file__)) load_files_from_dir = 'data' data_dir = os.path.normpath(os.path.join(current_dir, '..', load_files_from_dir)) game_data = {} scanDirectory(data_dir, game_data) loadImages(game_data['data']['agents']['Monster01']['animations']) loadImages(game_data['data']['map']['elements']['House01']) game_data["window"] = window state = GameState(game_data) game_data["game"] = state map = Map(32, 32, game_data, 32) spawner = Spawn(game_data) map.populate() render = Render(game_data) print game_data
def test_init(self): size = 100 treasures = 10 traps = 11 mgame_map = Map(Position(size, size), treasures, traps) mmap = mgame_map.game_map treasuresCount = 0 trapsCount = 0 for line in mmap: treasuresCount += line.count("!") trapsCount += line.count("x") self.assertEqual(treasuresCount, treasures) self.assertEqual(traps, trapsCount)
def moveGoodForPlayer(self, player_id, move): if not self.moveValidForPlayer(player_id, move): return False player = self.players[player_id] playerGrid = list(util.coordToGrid(player.x, player.y)) distance = Direction.distances[move] playerGrid[0] += distance[0] playerGrid[1] += distance[1] if not Map.gridInMap(*playerGrid): return False grid = self.game_map.grids[util.gridToPos(*playerGrid)] return grid.canPass()
def find_successors(game_map, gridX, gridY): successors = [] for direction in Direction.ALL: if direction == Direction.STOP: continue distance = Direction.distances[direction] newX = gridX + distance[0] newY = gridY + distance[1] if not Map.gridInMap(newX, newY): continue newPos = util.gridToPos(newX, newY) if game_map.grids[newPos].isWall(): continue successors.append((direction, newPos)) return successors
def start_game(config): # Loads game data, setups first map of the game then runs the main game loop. # Load all game data. tiles_data, generation_data, actor_data, item_data, animation_data = load_data( ) # Initialize map then generate a new map. current_map = Map(100, 100) start_x, start_y = generate_cave_map(current_map, generation_data, tiles_data, actor_data, item_data) # Initialize camera. camera = Camera(0, 0, config['camera_width'], config['camera_height'], 0, 0) # Spawn player. player_stats = { "hp": 100, "mp": 100, "starting_ap": 2, "max_ap": 10, "ap_recovery": 2, "base_damage": "1d4", "ac": 10, "hit": 4 } player = Actor(start_x, start_y, 'Player', '@', [255, 255, 255, 255]) player_inventory = Inventory(player) player.alive = Alive(player, player_stats, inventory=player_inventory) # Initialize FOV. fov = FOV(player, 5, current_map) under_mouse = None debug = False game_state = GameState.players_turn previous_state = None # Setup presets/containers for the game loop. actor_queue = PriorityQueue() actor_turns_left = False animations = [] no_block_animations = [] widgets = [] targeting_action = None terminal.refresh() while True: terminal.clear() if not debug: if current_map.tiles[player.x][player.y].is_stairs: player.x, player.y = generate_cave_map(current_map, generation_data, tiles_data, actor_data, item_data) current_map.depth += 1 render_all(player, current_map, fov, camera, under_mouse, animations, no_block_animations, widgets, targeting_action, game_state, config, animation_data) # Parse player input. action = handle_input(player, current_map, camera, fov, under_mouse, widgets, targeting_action, animations, no_block_animations, animation_data, game_state) under_mouse = get_under_mouse(player, current_map.tiles, current_map.actors, current_map.items, widgets, camera, game_state) # If an action was returned, complete that action. if isinstance(action, str): if action == 'restart': start_game(config) elif action == 'end-turn': if player.alive.check_in_combat(current_map.actors, fov): game_state = GameState.actors_turn elif action == 'toggle-inventory': if game_state == GameState.show_inventory: game_state = previous_state widgets = [] else: previous_state = game_state game_state = GameState.show_inventory fill_widgets(player, widgets, config, game_state) elif action == 'toggle-targeting': game_state = previous_state targeting_action = None elif action == 'toggle-map': if game_state == GameState.show_full_map: game_state = previous_state else: previous_state = game_state game_state = GameState.show_full_map elif action: if len(animations) == 0: if game_state == GameState.show_inventory: game_state = previous_state widgets = [] if action.item.targeting: previous_state = game_state game_state = GameState.targeting targeting_action = action elif game_state == GameState.targeting: game_state = previous_state targeting_action = None if game_state == GameState.players_turn: action.perform(animations, no_block_animations, animation_data) # Check if camera was moved, if it was, recalculate FOV. camera_moved = camera.move_camera(player.x, player.y, current_map) if camera_moved: fov.fov_recompute() # If player is in combat and out of ap, end the players turn. if player.alive.check_in_combat(current_map.actors, fov): if player.alive.get_ap(False) <= 0: game_state = GameState.actors_turn # Only continue if all animations have finished. if len(animations) == 0: # Go through all actors and let them take turns until # they are out of ap or decide not to take any actions. if game_state == GameState.actors_turn: # Fill the queue with actors that still need to take turns. if actor_queue.empty(): for actor in current_map.actors: if actor.alive and not actor.alive.turn_over and fov.in_fov( actor): actor_queue.put(actor, actor.alive.get_ap(False)) else: actor = actor_queue.get() if actor.alive: action = actor.alive.get_action( player, current_map, fov) if action: action.perform(animations, no_block_animations, animation_data) actor_turns_left = True else: actor.alive.turn_over = True # Player recovers ap at the end of the actors turn. if actor_queue.empty(): if not actor_turns_left: player.alive.recover_ap() game_state = GameState.players_turn for actor in current_map.actors: if actor.alive: actor.alive.turn_over = False actor_turns_left = False else: debug_render(player, current_map) # Parse player input. action = handle_input(player, current_map, camera) if action == 'restart': start_game(config) if action == 'debug': debug = not debug terminal.set("window: size='40x20', cellsize='24x24'") terminal.refresh()
class Game(): def __init__(self, canvas): self.canvas = canvas self.game_map = Map() self.hero = Hero(0, 1) self.boss = Boss(0, 5) self.skeleton = Skeleton(6, 8) self.skeleton2 = Skeleton(0, 7) self.skeleton3 = Skeleton(4, 5) self.stat = Stat(self.hero, self.boss) self.monster_position() def monster_position(self): self.monster_position = [(self.boss.x, self.boss.y), (self.skeleton.x, self.skeleton.y), (self.skeleton2.x, self.skeleton2.y), (self.skeleton3.x, self.skeleton3.y)] def keyPressed(self, event): if event.keysym == 'Down': if self.game_map.can_move(self.hero.x, self.hero.y + 1, self.hero.x, self.hero.y, self.monster_position): # if self.game_map.check_edge(self.hero.x, self.hero.y+1) and self.game_map.check_tile(self.hero.x, self.hero.y+1): self.hero.move_down() else: self.hero.turn_down() self.hero.draw_char(self.canvas) if event.keysym == 'Right': if self.game_map.check_edge( self.hero.x + 1, self.hero.y) and self.game_map.check_tile( self.hero.x + 1, self.hero.y): self.hero.move_right() else: self.hero.turn_right() self.hero.draw_char(self.canvas) if event.keysym == 'Left': if self.game_map.check_edge( self.hero.x - 1, self.hero.y) and self.game_map.check_tile( self.hero.x - 1, self.hero.y): self.hero.move_left() else: self.hero.turn_left() self.hero.draw_char(self.canvas) if event.keysym == 'Up': if self.game_map.check_edge( self.hero.x, self.hero.y - 1) and self.game_map.check_tile( self.hero.x, self.hero.y - 1): self.hero.move_up() else: self.hero.turn_up() self.hero.draw_char(self.canvas) if event.keysym == 'Space': self.battle() # # def start_the_battle(self): # if self.game_map.is_this_tile_occupied(self.hero.x, self.hero.y, self.monster_position): # self.strike(self.game_map.get_the_enemy(self.hero.x, self.hero.y, self.monster_position)) # # def strike(self,attacker): # if attacker == 'self.boss': # # self.stat.draw_skeleton_boss # self.strike_1 = self.hero.sp + self.d6 + self.d6 # self.strike_2 = self.boss.sp + self.d6 + self.d6 # if self.strike_1 > self.boss.dp: # self.boss.damage(self.strike_1) # if self.strike_2 + self.d6 + self.d6 > self.hero.dp: # self.hero.damage(self.strike_2) # # # elif attacker == 'self.skeleton': # # self.stat.draw_skeleton_stat_1() # self.strike_1 = self.hero.sp + self.d6 + self.d6 # self.strike_2 = self.skeleton.sp + self.dice + self.d6 # if self.strike_1 > self.skeleton.dp: # self.skeleton.damage(self.strike_1) # if self.strike_2 + self.d6+self.d6 > self.hero.dp: # self.hero.damage(self.strike_2) # # # elif attacker == 'self.skeleton2': # # self.stat.draw_skeleton_stat_2() # self.strike_1 = self.hero.sp+self.d6 + self.d6 # self.strike_2 = self.skeleton2.sp + self.dice + self.dice # if self.strike_1 > self.skeleton2.self.dp: # self.skeleton2.damage(self.strike_1) # if self.strike_2 + self.d6 + self.d6 > self.hero.dp: # self.hero.damage(self.strike_2) # # elif attacker == 'self.skeleton3': # # self.stat.draw_skeleton_stat_3() # self.strike_1 = self.hero.sp + self.d6 + self.d6 # self.strike_2 = self.skeleton_3.sp + self.dice + self.d6 # if self.strike_1 > self.skeleton3.dp: # self.skeleton3.damage(self.strike_1) # if self.strike_2 + self.d6 + self.d6 > self.hero.dp: # self.hero.damage(self.strike_2) def draw_all(self): self.game_map.draw_tile(self.canvas) self.hero.draw_char(self.canvas) self.boss.draw_char(self.canvas) self.skeleton.draw_char(self.canvas) self.skeleton2.draw_char(self.canvas) self.skeleton3.draw_char(self.canvas) self.stat.draw_hero_text(self.canvas) self.stat.draw_boss_text(self.canvas)
def __init__(self): self.game_started = False self.game_map = Map() self.players = {}
class Room: def __init__(self): """ Инициализация новой игровой сессии """ self.players: Player = [] self.players_count = 0 self.map = Map(20, 20) def search_free_spawn(self): """ Метод выполняет поиск свободного пространства для спавна игрока. """ return [Coord(18, 18)] def del_player(self, event): """ Удаление игрока """ print('Удаление игрока') del_player = event.get('player') if not del_player: return self.players.remove(del_player) def add_player(self, event): """ Добавление нового игрока в комнату """ print('Игрока добавили') self.players_count += 1 # Имя игрока name = f'Player{self.players_count}' new_player = Player(name, self.search_free_spawn()) source = event.get('source') # Подписываем игрока на событие нажатия клавиши source.on('KEY_PRESSED', Handler(new_player.key_pressed)) # Подписываем игрока на событие отключения source.on_close(Handler(self.del_player, player=new_player)) self.players.append(new_player) def send_positions(self, event): """ Итерация ходов. """ source = event.get('source') for player in self.players: if player.dead: continue head = player.get_step() print('Head: ', head) ceil = self.map.ceil(head) if ceil in (Ceil.WALL, Ceil.PLAYER): print('Игрок умер') player.dead = True elif ceil == Ceil.EMPTY: tail = player.snake.move_tail() self.map.map[tail.y][tail.x] = Ceil.EMPTY self.map.map[head.y][head.x] = Ceil.PLAYER
from itertools import cycle map_data = None def is_valid_pos(cur_pos): x, y = cur_pos.x, cur_pos.y return 0 <= x < 100 and 0 <= y < 100 and map_data[y][x] if __name__ == "__main__": map_data = map_generator.generate_map(100, 100, seed=25, obstacle_density=0.35) game_map = Map(map_data) start = Point(2, 2) end = Point(25, 65) rel_pos = [ Point(-1, 1), Point(1, 1), Point(0, 0), Point(-1, -1), Point(1, -1), ] units_pos = [start + pos for pos in rel_pos] units = [] for i, unit_pos in enumerate(units_pos): unit = FORMATION.copy(start + rel_pos[i]) unit.add_to_formation(
class Game(object): nonword_characters = re.compile('[\W_]+') def __init__(self, name, gender): self.player = Player(name, gender) self.map = Map('farm_map.txt', 'farm_descriptions.txt', 'farm_items.txt', 'farm_items_map.txt') self.item_fns = ItemFns(self.map, self.player) def move_to(self, location): if not location: return False self.player.location = location print(self.map.get_atmosphere(self.player.location)) return True def describe(self, target): if not target: # Describe the current location. print(self.map.get_atmosphere(self.player.location)) return True print(self.get_description(target)) return True def take(self, key): print("Items: {0}".format(self.map.get_items(self.player.location))) if not key in [ item.key for item in self.map.get_items(self.player.location) ]: return False item = self.map.get_item(key) print("You pick up the {0}.".format(item.name)) self.player.inventory[key] = item return True known_actions = { 'move': move_to, 'go': move_to, 'approach': move_to, 'look': describe, 'investigate': describe, 'describe': describe, 'pick up': take, 'grab': take, 'take': take, } def print_intro(self): text = """A long time ago, a $MAN named {0} lived in the wilderness with $HIS aging parents. $HE lived a poor life, farming just enough for them to get by, eking out a living in the rocky soil. Eventually, $HIS mother died, and $HIS father did not survive long after that. Now all alone, the $MAN must decide what to do with $HIS life."""\ .format(self.player.name) text = self.process_text(text) print(text) self.prompt() def process_input(self, text): words = text.split() words = map(lambda w: self.nonword_characters.sub('', w), words) seen_locations = self.get_visible_locations() seen_items = self.get_visible_items() permanent_actions = list(self.known_actions.keys()) item_actions = self.item_fns.available(self.player) targets = seen_locations + seen_items actions = permanent_actions + item_actions # print(seen_locations) # print(seen_items) action = next((action for action in actions if action in text), None) target = next((target for target in targets if target.name in text), None) if target: target = target.key print("Action: {0}\nTarget: {1}".format(action, target)) succeeded = False if action in self.known_actions: succeeded = self.known_actions[action](self, target) elif action: succeeded = self.item_fns.process_input(action, target) if not succeeded: print( "I'm sorry, I didn't understand. Try again, or /help for help." ) self.prompt() def prompt(self): setting = "You are standing by {0}. You can see "\ .format(self.map.get_printable_name(self.player.location)) for i, loc in enumerate(self.get_visible_locations_names()): if i < len(self.get_visible_locations_names()) - 1: setting += "{0}, ".format(loc) else: setting += "and {0}".format(loc) if len(self.get_visible_locations_names()) == 0: setting += "nothing" setting += " nearby." print(setting) print("What do you do?") # Fixes pronouns and extra spaces. def process_text(self, text): text = text.replace("$HE", "he" if self.is_male() else "she") text = text.replace("$HIS", "his" if self.is_male() else "her") text = text.replace("$MAN", "man" if self.is_male() else "woman") return ' '.join(text.split()) def is_male(self): return self.player.gender == 'm' def is_female(self): return not is_male() def get_visible_locations(self): return self.map.get_visible(self.player.location) def get_visible_items(self): return self.map.get_items(self.player.location) def get_visible_locations_names(self): return [loc.printable_name for loc in self.get_visible_locations()] def get_description(self, target): if target in [ location.key for location in self.get_visible_locations() ]: return self.map.describe(target) elif target in [item.key for item in self.get_visible_items()]: return self.map.get_item(target).description
def __init__(self, name, gender): self.player = Player(name, gender) self.map = Map('farm_map.txt', 'farm_descriptions.txt', 'farm_items.txt', 'farm_items_map.txt') self.item_fns = ItemFns(self.map, self.player)
class GameWorld: """ Game world. """ def __init__(self): """ Initializes player, game map. """ mapSquareSize = random.randint(10, 20) mapSize = Position(mapSquareSize, mapSquareSize) startPos = \ Position(random.randint(0, mapSquareSize - 1), random.randint(0, mapSquareSize - 1)) self.player = Player(position=startPos, hp=3, bag_counter=0) self.enemy = Enemy(3, 1, Position(1, 1), Position(0, 0), Position(mapSize.x, mapSize.y)) self.level = Map(size=mapSize, treasures=6, traps=6) self.actions = { "Up": "w", "Down": "s", "Left": "a", "Right": "d", "Save": "save", "Load": "load", "Help": "help", "Exit": "exit" } self.game_status = GameState.INGAME self.__ready_to_end = False self.mrlock = threading.RLock() def enemy_update(enemy, player): while not self.ready_to_end: time.sleep(3) enemy.update(player) self.enemyThread = threading.Thread(target=enemy_update, args=(self.enemy, self.player)) self.enemyThread.start() # threading._start_new_thread(Enemy.update, (self.enemy, self.player) @property def ready_to_end(self): self.mrlock.acquire() res = self.__ready_to_end self.mrlock.release() return res @ready_to_end.setter def ready_to_end(self, value): self.mrlock.acquire() self.__ready_to_end = value self.mrlock.release() @logging_debug_decorator @logging_info_decorator def save(self): """ Wrapper for savegame_utility save call. """ savegame_utility.save(self.level.game_map, self.player.position) @logging_debug_decorator @logging_info_decorator def load(self): """ Wrapper for savegame_utility load call. """ mmap, player_pos = None, None try: mmap, player_pos = savegame_utility.load() except FileNotFoundError: return self.level.game_map, self.player.position = mmap, player_pos try: self.level.check() except Exception as identifier: print(identifier.__str__) raise self.player.bag_counter = 0 self.player.hp = 3 @logging_debug_decorator @logging_info_decorator def update_actions(self): """ Returns: [str...] - actions performed. """ input_str = input("Your turn\n") input_list = input_str.split(" ") actions = [] for mstr in input_list: for name, key in self.actions.items(): if key.casefold() == mstr.casefold(): actions.append(name) return actions @logging_debug_decorator @logging_info_decorator def print_hint(self): """ If there is at least 1 treasure || trap in player's view - prints hint. """ positions = [ Position(self.player.position.x + self.level.view.x, self.player.position.y), Position(self.player.position.x - self.level.view.x, self.player.position.y), Position(self.player.position.x, self.player.position.y + self.level.view.y), Position(self.player.position.x, self.player.position.y - self.level.view.y) ] for position in positions: # check position position.clamp(min=Position(0, 0), max=self.level.size) # check cell if self.level.map_wrapper(position) == \ self.level.reprs["treasure"]: print("There is a treasure near you.") if self.level.map_wrapper(position) == \ self.level.reprs["trap"]: print("Careful! Trap is near you.") @logging_debug_decorator @logging_info_decorator def on_move_action(self, action): """ Args: action (str): Up/Down/Left/Right move action. """ if action != "Up" and \ action != "Down" and \ action != "Left" and \ action != "Right": raise ActionError(f'{action} unsupported in this context', ["Up", "Down", "Left", "Right"]) self.player.move_with_restr(action, self.level.size) # on treasure || trap if self.level.map_wrapper(self.player.position) == \ self.level.reprs["treasure"]: self.player.bag_counter += 1 position = self.player.position self.level.game_map[position.y][position.x] = \ self.level.reprs["nothing"] print("Good job, you found a treasure!") elif self.level.map_wrapper(self.player.position) == \ self.level.reprs["trap"]: self.player.hp -= 1 position = self.player.position self.level.game_map[position.y][position.x] = \ self.level.reprs["nothing"] if self.player.hp > 0: print(f'Careful, you\'ve got {self.player.hp} hp left') # perform win/loss check if self.player.hp <= 0: print("You lost, try again.") self.game_status = GameState.ENDING elif self.player.bag_counter >= 3: print("Congrats, winner!") self.game_status = GameState.ENDING @logging_debug_decorator @logging_info_decorator def on_action(self, action): """ Changes game state on action. Args: action (str): name of the action from self.actions. """ if action == "Up" or \ action == "Down" or \ action == "Left" or \ action == "Right": self.on_move_action(action) print(f'{self.player.position.x} {self.player.position.y}') elif action == "Save": self.save() print("GAME SAVED") elif action == "Load": self.load() print("GAME LOADED") elif action == "Help": print(self.actions) elif action == "Exit": self.game_status = GameState.ENDING else: raise ActionError(f'{action} is not supported in this context.', self.actions) @logging_debug_decorator @logging_info_decorator def on_ingame(self): """ Performs ingame step: 1) Show lvl. 2) Print hints if any. 3) Get Actions input. 4) Change state depending on actions. """ self.level.show(player_pos=Position(self.player.position.x, self.player.position.y), enemies_pos=[ Position(self.enemy.position.x, self.enemy.position.y) ]) self.print_hint() actions_performed = self.update_actions() for action in actions_performed: try: self.on_action(action) except ActionError as identifier: print(identifier.__str__) @logging_debug_decorator @logging_info_decorator def on_ending(self): print("This world will miss you, goodbye!") self.ready_to_end = True @logging_debug_decorator @logging_info_decorator def update(self): """ Game step. """ # update actions if (self.game_status == GameState.INGAME): self.on_ingame() elif (self.game_status == GameState.ENDING): self.on_ending() else: raise ValueError(f'{self.game_status} is unsupported!') @logging_debug_decorator @logging_info_decorator def update_loop(self): """ Wrapper around update. Exits when self.game_status == GameState.ENDING. """ while not self.ready_to_end: try: self.update() except ValueError as identifier: print(identifier.__str__) self.ready_to_end = True
class GameState(object): # Static current = None def __init__(self): self.game_started = False self.game_map = Map() self.players = {} def start_game(self, already_started): def __internal_preparing(state): print('Game started') state.game_started = True for player_id, player in self.players.items(): player.setPreparing() if already_started: print('Game started immediately') __internal_preparing(self) else: print('Game will start in 3 seconds') util.loop.add_timed_task(3, __internal_preparing, self) def set_players(self, player_list): print('Receive players') for playerObj in player_list: player_id = playerObj['playerid'] # Create the player if not exist if player_id not in self.players: self.add_player(player_id, playerObj['name']) # Update info player = self.players[player_id] player.setCoord(playerObj['x'], playerObj['y']) player.updateStatus(playerObj['dead'], playerObj['disconnected']) self.dump_players() def dump_players(self): for player_id, player in self.players.items(): print(player) def add_player(self, player_id, name): self.players[player_id] = Player(player_id, name) def me(self): return self.players[Player.thisPlayer_id] def checkLeave(self, pos): # Only myself requires checking. Each client handles himself/herself player = self.me() if self.game_map.grids[pos].grid_type != Grid.BOMB: # XXX I don't know why bombs vanished print('Bomb at %s vanished' % util.gridStr(pos)) return if self.game_map.nearPos(player.x, player.y, pos): print("I am on a bomb") print((player.x, player.y)) print(util.posToGrid(pos)) player.onBomb = True util.loop.add_timed_task(util.BASE_INTERVAL, self.checkLeave, pos) else: print("I exit a bomb") player.onBomb = False def checkLeaveWall(self): player = self.me() if self.game_map.near(player.x, player.y, passBomb=player.onBomb): print("Still in some wall") util.loop.add_timed_task(util.BASE_INTERVAL, self.checkLeaveWall) else: print("Dropping UFO") player.penetrate = False util.packet_queue.put({ 'event': 'ufo_removal', 'playerid': Player.thisPlayer_id }) def moveValidForPlayer(self, player_id, move): p = self.players[player_id] move_distance = Direction.distances[move] newX = p.x + move_distance[0] * p.speed newY = p.y + move_distance[1] * p.speed return not self.game_map.near(newX, newY, p.onBomb, p.penetrate) def moveValidForMe(self, move): return self.moveValidForPlayer(Player.thisPlayer_id, move) def validMovesForPlayer(self, player_id): ret = [] for move in Direction.ALL: if self.moveValidForPlayer(player_id, move): ret.append(move) return ret def validMovesForMe(self): return self.validMovesForPlayer(Player.thisPlayer_id) def moveGoodForPlayer(self, player_id, move): if not self.moveValidForPlayer(player_id, move): return False player = self.players[player_id] playerGrid = list(util.coordToGrid(player.x, player.y)) distance = Direction.distances[move] playerGrid[0] += distance[0] playerGrid[1] += distance[1] if not Map.gridInMap(*playerGrid): return False grid = self.game_map.grids[util.gridToPos(*playerGrid)] return grid.canPass() def moveGoodForMe(self, move): return self.moveGoodForPlayer(Player.thisPlayer_id, move) def goodMovesForPlayer(self, player_id): ret = [] for move in Direction.ALL: if self.moveGoodForPlayer(player_id, move): ret.append(move) return ret def goodMovesForMe(self): return self.goodMovesForPlayer(Player.thisPlayer_id)
room["outside"].add_item(Lightsource("torch", "Should be enough to see...")) room["foyer"].add_item( Item("sword", "Not the sharpest..."), Treasure("spoon", "I think it's worth something.", 10, False)) room["overlook"].add_item(Treasure("ruby", "Shines bright...", 20, False)) room["treasure"].add_item( Treasure("coin", "At least it's something.", 15, False)) # Nothin in narrow and treasure # # Main # # Make a new player object that is currently in the 'outside' room. player = Player(room["outside"]) map = Map() print(player.current_room.items[0].name) print( f"\n\nWelcome adventurer, you are currently in {player.current_room.name}. {player.current_room.descr}\n" ) print(""" XXXXXXXX XXX XXXXX XXXX XX XXXXXXXX XX XXXXXX XXXX XXXXXXXXXX XXXX XXXX XX XXXXX X +----------------+ | Overlook | +------+ +-------+ | | | | +------------+ | | | Treasure |