def initialization(): """инициализация нужных файлов игры""" pygame.init() Viewer.init() Display.init(width=settings.WINDOW_WIDTH, height=settings.WINDOW_HEIGHT, framerate=settings.FRAMERATE) Menu.init() Skins.init() Map.init(width=settings.MAP_WIDTH, height=settings.MAP_HEIGHT)
def start(self, rows: int, columns: int, mines: int): assert columns > 0 and rows > 0 and 0 < mines < rows * columns # Initialize game data self.rows, self.cols, self.mines = rows, columns, mines self.remain = rows * columns self.marked, self.moves, self.status = 0, 0, STATUS.RUNNING self.start_time, self.__duration = time.time(), 0. self.__map = Map(rows, columns, self.mines) self.__mask = [[MASK.UNKNOWN for _ in range(columns)] for _ in range(rows)]
def handleKeys(cls): """Функция, проверяющая нажатие кнопок клавиатуры""" keys = pygame.key.get_pressed() if keys[pygame.K_ESCAPE]: cls.finished = True # выход из игры for event in pygame.event.get(): if event.type == pygame.VIDEORESIZE: Display.resize(event.w, event.h) # изменение размера экрана if event.type == pygame.QUIT: cls.finished = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_F12: Display.full_screen() # полноэкранный размер if event.key == pygame.K_SPACE: # разбиение нашего шарика if Map.is_player_alive(): Map.split_player()
def handleKeys(cls) -> None: """Méthode permettant de traiter les entrées clavier""" keys = pygame.key.get_pressed() if keys[pygame.K_RETURN]: for k in Map.creatures.keys(): if k == Map.player_id: for creature in Map.creatures[k]: creature.score += 100 #! à retirer if keys[pygame.K_ESCAPE]: # Si la touche ESC est pressée if cls.keytime.get(pygame.K_ESCAPE, 0) > cls.ESC_MAX_FRAMECOUNT: # Si l'on est au dessus de la valeur maximale pour quitter cls.finished = True else: cls.keytime[pygame.K_ESCAPE] = cls.keytime.get( pygame.K_ESCAPE, 0) + 1 # Sinon on incrémente le nombre d'images écoulées else: cls.keytime[pygame.K_ESCAPE] = 0 # Si elle est relachée on remet le compteur à 0 for event in pygame.event.get(): if event.type == pygame.VIDEORESIZE: # Quand la fenêtre est redimensionnée Display.resize(event.w, event.h) if event.type == pygame.QUIT: # Détection de la fermeture de la fenêtre cls.finished = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_F11: # Quand F11 on se met en plein écran Display.toggleFullscreen() if event.key == pygame.K_SPACE: if Map.isPlayerAlive(): Map.splitPlayer()
def main(filename): """Parse the input file and output the results.""" with open(filename) as f: map_ = [list(l) for l in f.read().splitlines()] map_ = Map(map_) map_.init() print("Initial") show_map(map_) round_ = 0 while True: round_ += 1 if not start_round(map_): break print(f"Finished Round {round_}") show_map(map_) show_map(map_) total_hp = sum([u.hp for u in map_.units.values() if not u.is_dead]) round_ -= 1 print( f"Rounds {round_}, Total HP: {total_hp}, Outcome: {round * total_hp}")
class Game: characters = [] character_to_team = {} str_to_print = [] def __init__(self, teams=2): self.map = Map(self) self.team_to_character = [Team() for _ in range(teams)] def add_character(self, character: Character, team: int = 0): self.characters.append(character) self.team_to_character[team].add_character(character) self.character_to_team[character] = team def remove_character(self, character: Character): self.characters.remove(character) team = self.character_to_team[character] self.team_to_character[team].remove_character(character) self.character_to_team.pop(character) def register_print(self, str_to_print): self.str_to_print.append(str_to_print) def execute_one_round(self): self.characters.sort(key=lambda character: character.agi, reverse=True) for character in self.character_to_team: character.handle_event(my_new_round_event) movement_hit_event = self.map.move(character) if movement_hit_event: character.handle_event(movement_hit_event) movement_hit_event.target.handle_event(movement_hit_event) character.handle_event(my_movement_finish_event) for character in self.characters: target: Character = self.map.find_nearest_enemy(character) target.handle_event(SkillHit(character.skill_instruction, target)) character.handle_event(my_round_finish_event) for character in self.characters: character.handle_event(game_round_finish_event)
from game.character import Character from game.map import Map def parse_commandline(): parser = argparse.ArgumentParser(description="Play Hunt the Wumpus.") parser.add_argument('--width', type=int, default=10, help="Width to use for map") parser.add_argument('--height', type=int, default=10, help="Height to use for map") parser.add_argument('--seed', type=int, default=random.random() * 1000, help="Seed random generator with given value") parser.add_argument('--ui', type=str, default="text", help="UI to load (curses, gtk, text)") return parser.parse_args() if __name__ == "__main__": args = parse_commandline() print("Building {0}x{1} map".format(args.width, args.height)) map = Map(height=args.height, width=args.width, seed=args.seed) map.generate() player = Character(name="Player") wumpus = Character(name="Wumpus") map.place_character(player) map.place_character(wumpus) print(map)
def __init__(self): self.room_map = Map(a_scale=1, backgroundX=0, backgroundY=0) self.players = [] pyglet.clock.schedule_interval(self.update, 1/60.0) pyglet.clock.schedule_interval(self.check_ground, 1/60.0)
class Game(): def __init__(self): self.room_map = Map(a_scale=1, backgroundX=0, backgroundY=0) self.players = [] pyglet.clock.schedule_interval(self.update, 1/60.0) pyglet.clock.schedule_interval(self.check_ground, 1/60.0) def update(self, dt): for player in self.players: current_room = self.room_map.change_to_room(player.room_number, player.level) if (player.is_moving): if (player.facing == Direction.NORTH or player.facing == Direction.SOUTH): total_damage = current_room.update(dt, playerX=player.x, playerY=player.nextBoxCoord) if (total_damage > 0): is_dead = player.change_life(-1 * total_damage) if (is_dead): self.player_died(player) else: total_damage = current_room.update(dt, playerX=player.nextBoxCoord, playerY=player.y) if (total_damage > 0): is_dead = player.change_life(-1 * total_damage) if (is_dead): self.player_died(player) else: total_damage = current_room.update(dt, playerX=player.x, playerY=player.y) if (total_damage > 0): is_dead = player.change_life(-1 * total_damage) if (is_dead): self.player_died(player) def check_ground(self, dt): for player in self.players: current_room = self.room_map.change_to_room(player.room_number, player.level) result = current_room.intersecting_item(playerX=player.x, playerY=player.y) player.visibility.update_coords(aX=(player.x + (40 / 2)), aY=(player.y + (40 / 2))) if (not result is None): ground_type = result.item_enum add_result = player.add_to_inventory(to_add=ground_type) if (add_result): result.remove_self() def player_died(self, player): player.stop_moving() player.fade() def start_moving_player(self, dt, p): self.players[p].scheduled_moving = False self.set_next_box_coords(p) valid = self.check_player_legal_movement(p) if (valid): self.players[p].start_moving() pyglet.clock.schedule_interval(self.moving_bounds_check, 1/100.0, p) def set_next_box_coords(self, p): if (self.players[p].facing == Direction.WEST): self.players[p].nextBoxCoord = self.players[p].x - ((self.players[p].x - 0) % 40) elif (self.players[p].facing == Direction.EAST): self.players[p].nextBoxCoord = self.players[p].x + (40 - ((self.players[p].x - 0) % 40)) elif (self.players[p].facing == Direction.NORTH): self.players[p].nextBoxCoord = self.players[p].y + (40 - ((self.players[p].y - 0) % 40)) else: self.players[p].nextBoxCoord = self.players[p].y - ((self.players[p].y - 0) % 40) def check_player_legal_movement(self, p) -> bool: curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) if (self.players[p].facing == Direction.WEST): result = self.players[p].x > 0 check_x = self.players[p].nextBoxCoord if (check_x == self.players[p].x): check_x = check_x - 40 is_monster = curr_room.is_monster(aX=(check_x), aY=(self.players[p].y)) if (not result): door = curr_room.intersecting_door(playerX=self.players[p].x, playerY=self.players[p].y) if (not door is None): is_golden = door.is_level_up() if (not is_golden): self.change_player_room(p) else: self.change_player_level(p) return result and (not is_monster) elif (self.players[p].facing == Direction.EAST): result = self.players[p].x < 0 + 1000 - 40 check_x = self.players[p].nextBoxCoord if (check_x == self.players[p].x): check_x = check_x + 40 is_monster = curr_room.is_monster(aX=(check_x), aY=(self.players[p].y)) if (not result): door = curr_room.intersecting_door(playerX=self.players[p].x, playerY=self.players[p].y) if (not door is None): is_golden = door.is_level_up() if (not is_golden): self.change_player_room(p) else: self.change_player_level(p) return result and (not is_monster) elif (self.players[p].facing == Direction.NORTH): result = self.players[p].y < 0 + 1000 - 40 check_y = self.players[p].nextBoxCoord if (check_y == self.players[p].y): check_y = check_y + 40 is_monster = curr_room.is_monster(aX=(self.players[p].x), aY=(check_y)) if (not result): door = curr_room.intersecting_door(playerX=self.players[p].x, playerY=self.players[p].y) if (not door is None): is_golden = door.is_level_up() if (not is_golden): self.change_player_room(p) else: self.change_player_level(p) return result and (not is_monster) else: result = self.players[p].y > 0 check_y = self.players[p].nextBoxCoord if (check_y == self.players[p].y): check_y = check_y - 40 is_monster = curr_room.is_monster(aX=(self.players[p].x), aY=(check_y)) if (not result): door = curr_room.intersecting_door(playerX=self.players[p].x, playerY=self.players[p].y) if (not door is None): is_golden = door.is_level_up() if (not is_golden): self.change_player_room(p) else: self.change_player_level(p) return result and (not is_monster) def change_player_room(self, p): curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) room_location = curr_room.location player_facing = self.players[p].facing if (room_location == Direction.NW): if (player_facing == Direction.EAST): self.players[p].room_number = self.players[p].room_number + 1 self.players[p].x = self.players[p].x - (1000 - 40) elif (player_facing == Direction.SOUTH): num_rooms_per_side = (self.players[p].level * 2) + 1 self.players[p].room_number = (num_rooms_per_side**2) - 1 self.players[p].y = self.players[p].y + (1000 - 40) elif (room_location == Direction.NE): if (player_facing == Direction.WEST): self.players[p].room_number = self.players[p].room_number - 1 self.players[p].x = self.players[p].x + (1000 - 40) elif (player_facing == Direction.SOUTH): self.players[p].room_number = self.players[p].room_number + 1 self.players[p].y = self.players[p].y + (1000 - 40) elif (room_location == Direction.SE): if (player_facing == Direction.NORTH): self.players[p].room_number = self.players[p].room_number - 1 self.players[p].y = self.players[p].y - (1000 - 40) elif (player_facing == Direction.WEST): self.players[p].room_number = self.players[p].room_number + 1 self.players[p].x = self.players[p].x + (1000 - 40) elif (room_location == Direction.SW): if (player_facing == Direction.EAST): self.players[p].room_number = self.players[p].room_number - 1 self.players[p].x = self.players[p].x - (1000 - 40) elif (player_facing == Direction.NORTH): self.players[p].room_number = self.players[p].room_number + 1 self.players[p].y = self.players[p].y - (1000 - 40) elif (room_location == Direction.NORTH): if (player_facing == Direction.EAST): self.players[p].room_number = self.players[p].room_number + 1 self.players[p].x = self.players[p].x - (1000 - 40) elif (player_facing == Direction.WEST): self.players[p].room_number = self.players[p].room_number - 1 self.players[p].x = self.players[p].x + (1000 - 40) elif (room_location == Direction.EAST): if (player_facing == Direction.NORTH): self.players[p].room_number = self.players[p].room_number - 1 self.players[p].y = self.players[p].y - (1000 - 40) elif (player_facing == Direction.SOUTH): self.players[p].room_number = self.players[p].room_number + 1 self.players[p].y = self.players[p].y + (1000 - 40) elif (room_location == Direction.SOUTH): if (player_facing == Direction.EAST): self.players[p].room_number = self.players[p].room_number - 1 self.players[p].x = self.players[p].x - (1000 - 40) elif (player_facing == Direction.WEST): self.players[p].room_number = self.players[p].room_number + 1 self.players[p].x = self.players[p].x + (1000 - 40) else: if (player_facing == Direction.NORTH): num_rooms_per_side = (self.players[p].level * 2) + 1 if (self.players[p].room_number == ((num_rooms_per_side**2) - 1)): self.players[p].room_number = (((self.players[p].level - 1) * 2) + 1)**2 else: self.players[p].room_number = self.players[p].room_number + 1 self.players[p].y = self.players[p].y - (1000 - 40) elif (player_facing == Direction.SOUTH): self.players[p].room_number = self.players[p].room_number - 1 self.players[p].y = self.players[p].y + (1000 - 40) def change_player_level(self, p): curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) room_location = curr_room.location player_facing = self.players[p].facing if ((room_location == Direction.NW or room_location == Direction.NORTH or room_location == Direction.NE) and (player_facing == Direction.NORTH)): result = self.room_map.level_prepared(level=(self.players[p].level + 1)) door = None if (not result): self.players[p].add_experience(exp=(5 * (self.players[p].level + 1))) self.room_map.prepare_level(level_num=(self.players[p].level + 1)) door = Door(game_scale=1, direct=Direction.SOUTH, backgroundX=0, backgroundY=0) door.make_golden() self.players[p].room_number = self.players[p].room_number + (8 * self.players[p].level) + 1 self.players[p].level = self.players[p].level + 1 curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].y = self.players[p].y - (1000 - 40) if (not door is None): curr_room.entities.append(door) elif ((room_location == Direction.NW or room_location == Direction.WEST or room_location == Direction.SW) and (player_facing == Direction.WEST)): result = self.room_map.level_prepared(level=(self.players[p].level + 1)) door = None if (not result): self.players[p].add_experience(exp=(5 * (self.players[p].level + 1))) self.room_map.prepare_level(level_num=(self.players[p].level + 1)) door = Door(game_scale=1, direct=Direction.EAST, backgroundX=0, backgroundY=0) door.make_golden() self.players[p].room_number = self.players[p].room_number + (8 * self.players[p].level) + 7 self.players[p].level = self.players[p].level + 1 curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].x = self.players[p].x + (1000 - 40) if (not door is None): curr_room.entities.append(door) elif ((room_location == Direction.SW or room_location == Direction.SOUTH or room_location == Direction.SE) and (player_facing == Direction.SOUTH)): result = self.room_map.level_prepared(level=(self.players[p].level + 1)) door = None if (not result): self.players[p].add_experience(exp=(5 * (self.players[p].level + 1))) self.room_map.prepare_level(level_num=(self.players[p].level + 1)) door = Door(game_scale=1, direct=Direction.NORTH, backgroundX=0, backgroundY=0) door.make_golden() self.players[p].room_number = self.players[p].room_number + (8 * self.players[p].level) + 5 self.players[p].level = self.players[p].level + 1 curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].y = self.players[p].y + (1000 - 40) if (not door is None): curr_room.entities.append(door) elif ((room_location == Direction.NE or room_location == Direction.EAST or room_location == Direction.SE) and (player_facing == Direction.EAST)): result = self.room_map.level_prepared(level=(self.players[p].level + 1)) door = None if (not result): self.players[p].add_experience(exp=(5 * (self.players[p].level + 1))) self.room_map.prepare_level(level_num=(self.players[p].level + 1)) door = Door(game_scale=1, direct=Direction.WEST, backgroundX=0, backgroundY=0) door.make_golden() self.players[p].room_number = self.players[p].room_number + (8 * self.players[p].level) + 3 self.players[p].level = self.players[p].level + 1 curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].x = self.players[p].x - (1000 - 40) if (not door is None): curr_room.entities.append(door) elif ((room_location == Direction.NORTH) and (player_facing == Direction.SOUTH)): self.players[p].level = self.players[p].level - 1 self.players[p].room_number = self.players[p].room_number - ((8 * self.players[p].level) + 1) if (self.players[p].level == 0): self.players[p].room_number = 0 curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].y = self.players[p].y + (1000 - 40) elif ((room_location == Direction.EAST) and (player_facing == Direction.WEST)): self.players[p].level = self.players[p].level - 1 self.players[p].room_number = self.players[p].room_number - ((8 * self.players[p].level) + 3) if (self.players[p].level == 0): self.players[p].room_number = 0 curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].x = self.players[p].x + (1000 - 40) elif ((room_location == Direction.SOUTH) and (player_facing == Direction.NORTH)): self.players[p].level = self.players[p].level - 1 self.players[p].room_number = self.players[p].room_number - ((8 * self.players[p].level) + 5) if (self.players[p].level == 0): self.players[p].room_number = 0 curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].y = self.players[p].y - (1000 - 40) elif ((room_location == Direction.WEST) and (player_facing == Direction.EAST)): self.players[p].level = self.players[p].level - 1 self.players[p].room_number = self.players[p].room_number - ((8 * self.players[p].level) + 7) if (self.players[p].level == 0): self.players[p].room_number = 0 curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].x = self.players[p].x - (1000 - 40) else: if (player_facing == Direction.NORTH): result = self.room_map.level_prepared(level=(self.players[p].level + 1)) door = None if (not result): self.players[p].add_experience(exp=(5 * (self.players[p].level + 1))) self.room_map.prepare_level(level_num=(self.players[p].level + 1)) door = Door(game_scale=1, direct=Direction.SOUTH, backgroundX=0, backgroundY=0) door.make_golden() self.players[p].room_number = self.players[p].room_number + 2 self.players[p].level = self.players[p].level + 1 curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].y = self.players[p].y - (1000 - 40) if (not door is None): curr_room.entities.append(door) elif (player_facing == Direction.EAST): result = self.room_map.level_prepared(level=(self.players[p].level + 1)) door = None if (not result): self.players[p].add_experience(exp=(5 * (self.players[p].level + 1))) self.room_map.prepare_level(level_num=(self.players[p].level + 1)) door = Door(game_scale=1, direct=Direction.WEST, backgroundX=0, backgroundY=0) door.make_golden() self.players[p].room_number = self.players[p].room_number + 4 self.players[p].level = self.players[p].level + 1 curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].x = self.players[p].x - (1000 - 40) if (not door is None): curr_room.entities.append(door) elif (player_facing == Direction.SOUTH): result = self.room_map.level_prepared(level=(self.players[p].level + 1)) door = None if (not result): self.players[p].add_experience(exp=(5 * (self.players[p].level + 1))) self.room_map.prepare_level(level_num=(self.players[p].level + 1)) door = Door(game_scale=1, direct=Direction.NORTH, backgroundX=0, backgroundY=0) door.make_golden() self.players[p].room_number = self.players[p].room_number + 6 self.players[p].level = self.players[p].level + 1 curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].y = self.players[p].y + (1000 - 40) if (not door is None): curr_room.entities.append(door) else: result = self.room_map.level_prepared(level=(self.players[p].level + 1)) door = None if (not result): self.players[p].add_experience(exp=(5 * (self.players[p].level + 1))) self.room_map.prepare_level(level_num=(self.players[p].level + 1)) door = Door(game_scale=1, direct=Direction.EAST, backgroundX=0, backgroundY=0) door.make_golden() self.players[p].room_number = self.players[p].room_number + 8 self.players[p].level = self.players[p].level + 1 curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].x = self.players[p].x + (1000 - 40) if (not door is None): curr_room.entities.append(door) def moving_bounds_check(self, dt, p): self.set_next_box_coords() valid = self.check_player_legal_movement() if (not valid): self.players[p].stop_moving() self.set_player_last_valid(p) pyglet.clock.unschedule(self.moving_bounds_check) def set_player_last_valid(self, p): if (self.players[p].facing == Direction.WEST): if (self.players[p].x <= 0): self.players[p].x = 0 else: if (self.players[p].x != self.players[p].nextBoxCoord): self.players[p].x = self.players[p].nextBoxCoord + 40 elif (self.players[p].facing == Direction.EAST): if (self.players[p].x >= 0 + 1000 - 40): self.players[p].x = 0 + 1000 - 40 else: if (self.players[p].x != self.players[p].nextBoxCoord): self.players[p].x = self.players[p].nextBoxCoord - 40 elif (self.players[p].facing == Direction.NORTH): if (self.players[p].y >= 0 + 1000 - 40): self.players[p].y = 0 + 1000 - 40 else: if (self.players[p].y != self.players[p].nextBoxCoord): self.players[p].y = self.players[p].nextBoxCoord - 40 else: if (self.players[p].y <= 0): self.players[p].y = 0 else: if (self.players[p].y != self.players[p].nextBoxCoord): self.players[p].y = self.players[p].nextBoxCoord + 40 def player_attack(self, p): if self.players[p].attack > 0 and not self.players[p].is_attacking: curr_room = self.room_map.change_to_room(number=self.players[p].room_number, level=self.players[p].level) self.players[p].is_attacking = True pyglet.clock.schedule_once(self.players[p].stop_attack, 0.75) self.players[p].attack_sprite.reset_animation() if self.players[p].facing == Direction.NORTH: check_y = self.players[p].nextBoxCoord if (check_y == self.players[p].y): check_y = check_y + 40 total_exp = curr_room.player_attack(damage=self.players[p].attack, playerX=self.players[p].x, playerY=check_y) result = self.players[p].selected_weapon.take_damage(damage=5) self.players[p].add_experience(exp=total_exp) if (result): self.players[p].selected_weapon = None elif self.players[p].facing == Direction.EAST: check_x = self.players[p].nextBoxCoord if (check_x == self.players[p].x): check_x = check_x + 40 total_exp = curr_room.player_attack(damage=self.players[p].attack, playerX=check_x, playerY=self.players[p].y) result = self.players[p].selected_weapon.take_damage(damage=5) self.players[p].add_experience(exp=total_exp) if (result): self.players[p].selected_weapon = None elif self.players[p].facing == Direction.SOUTH: check_y = self.players[p].nextBoxCoord if (check_y == self.players[p].y): check_y = check_y - 40 total_exp = curr_room.player_attack(damage=self.players[p].attack, playerX=self.players[p].x, playerY=check_y) result = self.players[p].selected_weapon.take_damage(damage=5) self.players[p].add_experience(exp=total_exp) if (result): self.players[p].selected_weapon = None else: check_x = self.players[p].nextBoxCoord if (check_x == self.players[p].x): check_x = check_x - 40 total_exp = curr_room.player_attack(damage=self.players[p].attack, playerX=check_x, playerY=self.players[p].y) result = self.players[p].selected_weapon.take_damage(damage=5) self.players[p].add_experience(exp=total_exp) if (result): self.players[p].selected_weapon = None
def run(self, config=None, first_run=False): # setup and check if village still exists / is accessible self.config = config self.wrapper.delay = self.get_config(section="bot", parameter="delay_factor", default=1.0) if not self.village_id: data = self.wrapper.get_url("game.php?screen=overview&intro") if data: self.game_data = Extractor.game_state(data) if self.game_data: self.village_id = str(self.game_data['village']['id']) self.logger = logging.getLogger( "Village %s" % self.game_data['village']['name']) self.logger.info("Read game state for village") else: data = self.wrapper.get_url("game.php?village=%s&screen=overview" % self.village_id) if data: self.game_data = Extractor.game_state(data) self.logger = logging.getLogger( "Village %s" % self.game_data['village']['name']) self.logger.info("Read game state for village") self.wrapper.reporter.report( self.village_id, "TWB_START", "Starting run for village: %s" % self.game_data['village']['name']) if not self.game_data: self.logger.error("Error reading game data for village %s" % self.village_id) return None if self.village_set_name and self.game_data['village'][ 'name'] != self.village_set_name: self.logger.name = "Village %s" % self.village_set_name if not self.get_config(section="villages", parameter=self.village_id): return None if self.get_config(section="server", parameter="server_on_twplus", default=False): self.twp.run( world=self.get_config(section="server", parameter="world")) vdata = self.get_config(section="villages", parameter=self.village_id) if not self.get_village_config( self.village_id, parameter="managed", default=False): return False if not self.game_data: return False if not self.resman: self.resman = ResourceManager(wrapper=self.wrapper, village_id=self.village_id) self.resman.update(self.game_data) self.wrapper.reporter.report(self.village_id, "TWB_PRE_RESOURCE", str(self.resman.actual)) if not self.rep_man: self.rep_man = ReportManager(wrapper=self.wrapper, village_id=self.village_id) self.rep_man.read(full_run=False) if not self.def_man: self.def_man = DefenceManager(wrapper=self.wrapper, village_id=self.village_id) self.def_man.map = self.area if not self.def_man.units: self.def_man.units = self.units last_attack = self.def_man.under_attack self.def_man.manage_flags_enabled = self.get_config( section="world", parameter="flags_enabled", default=False) self.def_man.support_factor = self.get_village_config( self.village_id, "support_others_factor", default=0.25) self.def_man.allow_support_send = self.get_village_config( self.village_id, parameter="support_others", default=False) self.def_man.allow_support_recv = self.get_village_config( self.village_id, parameter="request_support_on_attack", default=False) self.def_man.auto_evacuate = self.get_village_config( self.village_id, parameter="evacuate_fragile_units_on_attack", default=False) self.def_man.update(data.text, with_defence=self.get_config( section="units", parameter="manage_defence", default=False)) disabled_units = [] if not self.get_config( section="world", parameter="archers_enabled", default=True): disabled_units.extend(["archer", "marcher"]) if not self.get_config(section="world", parameter="building_destruction_enabled", default=True): disabled_units.extend(["ram", "catapult"]) if self.def_man.under_attack and not last_attack: self.logger.warning("Village under attack!") self.wrapper.reporter.report( self.village_id, "TWB_ATTACK", "Village: %s under attack" % self.game_data['village']['name']) # setup and check if village still exists / is accessible if self.get_config(section="world", parameter="quests_enabled", default=False): if self.get_quests(): self.logger.info( "There where completed quests, re-running function") self.wrapper.reporter.report(self.village_id, "TWB_QUEST", "Completed quest") return self.run(config=config) if not self.builder: self.builder = BuildingManager(wrapper=self.wrapper, village_id=self.village_id) self.builder.resman = self.resman # manage buildings (has to always run because recruit check depends on building levels) build_config = self.get_village_config(self.village_id, parameter="building", default=None) if not build_config: self.logger.warning( "Village %d does not have 'building' config override!" % self.village_id) build_config = self.get_config(section="building", parameter="default", default="purple_predator") new_queue = TemplateManager.get_template(category="builder", template=build_config) if not self.builder.raw_template or self.builder.raw_template != new_queue: self.builder.queue = new_queue self.builder.raw_template = new_queue if not self.get_config(section="world", parameter="knight_enabled", default=False): self.builder.queue = [ x for x in self.builder.queue if "statue" not in x ] self.builder.max_lookahead = self.get_config(section="building", parameter="max_lookahead", default=2) self.builder.max_queue_len = self.get_config( section="building", parameter="max_queued_items", default=2) self.builder.start_update(build=self.get_config( section="building", parameter="manage_buildings", default=True), set_village_name=self.village_set_name) if not self.units: self.units = TroopManager(wrapper=self.wrapper, village_id=self.village_id) self.units.resman = self.resman self.units.max_batch_size = self.get_config(section="units", parameter="batch_size", default=25) # set village templates unit_config = self.get_village_config(self.village_id, parameter="units", default=None) if not unit_config: self.logger.warning( "Village %d does not have 'building' config override!" % self.village_id) unit_config = self.get_config(section="units", parameter="default", default="basic") self.units.template = TemplateManager.get_template( category="troops", template=unit_config, output_json=True) entry = self.units.get_template_action(self.builder.levels) if entry and self.units.wanted != entry["build"]: # update wanted units if template has changed self.logger.info("%s as wanted units for current village" % (str(entry["build"]))) self.units.wanted = entry["build"] if self.units.wanted_levels != {}: self.logger.info("%s as wanted upgrades for current village" % (str(self.units.wanted_levels))) # get total amount of troops in village self.units.update_totals() if self.get_config(section="units", parameter="upgrade", default=False) and self.units.wanted_levels != {}: self.units.attempt_upgrade() if self.get_village_config( self.village_id, parameter="snobs", default=None) and self.builder.levels['snob'] > 0: if not self.snobman: self.snobman = SnobManager(wrapper=self.wrapper, village_id=self.village_id) self.snobman.troop_manager = self.units self.snobman.resman = self.resman self.snobman.wanted = self.get_village_config(self.village_id, parameter="snobs", default=0) self.snobman.building_level = self.builder.get_level("snob") self.snobman.run() # recruitment management if self.get_config(section="units", parameter="recruit", default=False): self.units.can_fix_queue = self.get_config( section="units", parameter="remove_manual_queued", default=False) self.units.randomize_unit_queue = self.get_config( section="units", parameter="randomize_unit_queue", default=True) # prioritize_building: will only recruit when builder has sufficient funds for queue items if self.get_village_config( self.village_id, parameter="prioritize_building", default=False) and not self.resman.can_recruit(): self.logger.info( "Not recruiting because builder has insufficient funds") elif self.get_village_config( self.village_id, parameter="prioritize_snob", default=False ) and self.snobman and self.snobman.can_snob and self.snobman.is_incomplete: self.logger.info( "Not recruiting because snob has insufficient funds") else: # do a build run for every for building in self.units.wanted: if not self.builder.get_level(building): self.logger.debug( "Recruit of %s will be ignored because building is not (yet) available" % building) continue self.units.start_update(building) self.logger.debug("Current resources: %s" % str(self.resman.actual)) self.logger.debug("Requested resources: %s" % str(self.resman.requested)) # attack management if self.units.can_attack: if not self.area: self.area = Map(wrapper=self.wrapper, village_id=self.village_id) self.area.get_map() if self.area.villages: self.units.can_scout = self.get_config( section="farms", parameter="force_scout_if_available", default=True) self.logger.info( "%d villages from map cache, (your location: %s)" % (len(self.area.villages), ':'.join( [str(x) for x in self.area.my_location]))) if not self.attack: self.attack = AttackManager(wrapper=self.wrapper, village_id=self.village_id, troopmanager=self.units, map=self.area) self.attack.repman = self.rep_man self.attack.target_high_points = self.get_config( section="farms", parameter="attack_higher_points", default=False) self.attack.farm_minpoints = self.get_config( section="farms", parameter="min_points", default=24) self.attack.farm_maxpoints = self.get_config( section="farms", parameter="max_points", default=1080) self.attack.farm_default_wait = self.get_config( section="farms", parameter="default_away_time", default=1200) self.attack.farm_high_prio_wait = self.get_config( section="farms", parameter="full_loot_away_time", default=1800) self.attack.farm_low_prio_wait = self.get_config( section="farms", parameter="low_loot_away_time", default=7200) if entry: self.attack.template = entry['farm'] if self.get_config( section="farms", parameter="farm", default=False) and not self.def_man.under_attack: self.attack.extra_farm = self.get_village_config( self.village_id, parameter="additional_farms", default=[]) self.attack.max_farms = self.get_config( section="farms", parameter="max_farms", default=25) self.attack.run() self.units.can_gather = self.get_village_config( self.village_id, parameter="gather_enabled", default=False) if not self.def_man or not self.def_man.under_attack: self.units.gather(selection=self.get_village_config( self.village_id, parameter="gather_selection", default=1), disabled_units=disabled_units) # market management if self.get_config(section="market", parameter="auto_trade", default=False) and self.builder.get_level("market"): self.logger.info("Managing market") self.resman.trade_max_per_hour = self.get_config( section="market", parameter="trade_max_per_hour", default=1) self.resman.trade_max_duration = self.get_config( section="market", parameter="max_trade_duration", default=1) if self.get_config(section="market", parameter="trade_multiplier", default=False): self.resman.trade_bias = self.get_config( section="market", parameter="trade_multiplier_value", default=1.0) self.resman.manage_market(drop_existing=self.get_config( section="market", parameter="auto_remove", default=True)) res = self.wrapper.get_action(village_id=self.village_id, action="overview") self.game_data = Extractor.game_state(res) self.resman.update(self.game_data) if self.get_config(section="world", parameter="trade_for_premium", default=False) and self.get_village_config( self.village_id, parameter="trade_for_premium", default=False): self.resman.do_premium_stuff() self.set_cache_vars() self.logger.info("Village cycle done, returning to overview") self.wrapper.reporter.report(self.village_id, "TWB_POST_RESOURCE", str(self.resman.actual)) self.wrapper.reporter.add_data(self.village_id, data_type="village.resources", data=json.dumps(self.resman.actual)) self.wrapper.reporter.add_data(self.village_id, data_type="village.buildings", data=json.dumps(self.builder.levels)) self.wrapper.reporter.add_data(self.village_id, data_type="village.troops", data=json.dumps( self.units.total_troops)) self.wrapper.reporter.add_data(self.village_id, data_type="village.config", data=json.dumps(vdata))
parser.add_argument('--height', type=int, default=10, help="Height to use for map") parser.add_argument('--seed', type=int, default=random.random() * 1000, help="Seed random generator with given value") parser.add_argument('--ui', type=str, default="text", help="UI to load (curses, gtk, text)") return parser.parse_args() if __name__ == "__main__": args = parse_commandline() print("Building {0}x{1} map".format(args.width, args.height)) map = Map(height=args.height, width=args.width, seed=args.seed) map.generate() player = Character(name="Player") wumpus = Character(name="Wumpus") map.place_character(player) map.place_character(wumpus) print(map)
def __init__(self, teams=2): self.map = Map(self) self.team_to_character = [Team() for _ in range(teams)]
def run(cls): """Запуск игры""" while not cls.finished: cls.handleKeys() mx, my = pygame.mouse.get_pos() mouse_pos = vector(mx, my) mouse_pressed = pygame.mouse.get_pressed()[0] Menu.state = GameState.MENU if cls.state == GameState.MENU: Display.draw_start_img( pygame.image.load("data/game_images/start1.png"), vector(0, 0)) Display.draw_start_img( pygame.image.load("data/game_images/f12.png"), vector(50, 0)) Display.draw_start_img( pygame.image.load("data/game_images/esc.png"), vector(0, 50)) Display.draw_start_img( pygame.image.load("data/game_images/space.png"), vector(50, 50)) Menu.update(mouse_pos, mouse_pressed) if Menu.can_play: cls.state = GameState.GAME if Menu.can_quit: cls.finished = True Menu.display() if Menu.can_play: Display.set_cursor() elif cls.state == GameState.END: Menu.update(mouse_pos, mouse_pressed) if not Map.end: Map.update() if Menu.can_play: cls.state = GameState.GAME Display.end = False Map.end = False if Menu.can_quit: cls.finished = True Map.display() Menu.display() if Menu.can_play: Display.set_cursor() elif cls.state == GameState.WIN: Menu.update(mouse_pos, mouse_pressed) if Menu.can_play: cls.state = GameState.GAME Display.end = False Map.end = False if Menu.can_quit: cls.finished = True Menu.display() if Menu.can_play: Display.set_cursor() elif cls.state == GameState.GAME: Map.set_mouse(mouse_pos / Display.zoom_factor) Map.update() Map.display() if Map.is_player_alive(): if Map.end: cls.state = GameState.WIN Menu.apply_state(GameState.WIN) else: cls.state = GameState.END Menu.apply_state(GameState.END) Display.update_frame()
def run(cls) -> None: """Méthode principale permettant de faire tourner le jeu""" cls.finished = False cls.keytime = {} cls.state = GameState.MENU while not cls.finished: cls.ESC_MAX_FRAMECOUNT = Display.real_framerate * 0.25 # On veut quitter après 0.25 secondes cls.handleKeys() mx, my = pygame.mouse.get_pos() mouse_pos = Vect2d(mx, my) # Position de la souris mouse_pressed = pygame.mouse.get_pressed()[0] # Clic ou non Menu.state = GameState.MENU if cls.state == GameState.MENU: # Affichage du menu Menu.update(mouse_pos, mouse_pressed) if Menu.can_play: # Si l'on veut rejouer cls.state = GameState.GAME if Menu.can_quit: # Si l'on veut quitter cls.finished = True Menu.display() if Menu.can_play: # Si l'on veut rejouer on remet le curseur normal Display.setCursorArrow() elif cls.state == GameState.END: # Partie perdue Menu.update(mouse_pos, mouse_pressed) if not Map.game_finished: # On update la map tant que la partie n'est pas terminée pour de bon # afin de faire jouer les IA Map.update() if Menu.can_play: cls.state = GameState.GAME if Menu.can_quit: cls.finished = True Map.display() Menu.display() # Affichage du menu et de l'effet de transparence au dessus de la map if Menu.can_play: Display.setCursorArrow() elif cls.state == GameState.WIN: # Victoire Menu.update(mouse_pos, mouse_pressed) if Menu.can_play: cls.state = GameState.GAME if Menu.can_quit: cls.finished = True Menu.display() if Menu.can_play: Display.setCursorArrow() elif cls.state == GameState.GAME: # Jeu en cours Map.setMousePos(mouse_pos / Display.zoom_factor) # On envoie la position de la souris à la map Map.update() Map.display() if Map.isPlayerAlive(): if Map.game_finished: cls.state = GameState.WIN Menu.applyState(GameState.WIN) else: cls.state = GameState.END Menu.applyState(GameState.END) else: raise ValueError("État inconnu") alpha = cls.keytime.get(pygame.K_ESCAPE, 0) / cls.ESC_MAX_FRAMECOUNT * 255 Display.drawText("Quitter...", Vect2d(50, 25), color=(255, 0, 0, alpha), size=16, base_pos=Vect2d(0, 0)) # Affichage du "Quitter" rouge en haut à gauche proportionnellement au temps d'appui de la touche ESC Display.updateFrame()
def play(cls) -> None: """Lorsqu'un bouton pour rejouer est cliqué""" Display.setCursorArrow() Map.reset() cls.can_play = True
def run(self, config=None): # setup and check if village still exists / is accessible self.config = config if not self.village_id: data = self.wrapper.get_url("game.php?screen=overview&intro") if data: self.game_data = Extractor.game_state(data) if self.game_data: self.village_id = str(self.game_data['village']['id']) self.logger = logging.getLogger("Village %s" % self.game_data['village']['name']) self.logger.info("Read game state for village") else: data = self.wrapper.get_url("game.php?village=%s&screen=overview" % self.village_id) if data: self.game_data = Extractor.game_state(data) self.logger = logging.getLogger("Village %s" % self.game_data['village']['name']) self.logger.info("Read game state for village") if str(self.village_id) not in self.config['villages']: return False self.twp.run(world=self.config['server']['world']) vdata = self.config['villages'][str(self.village_id)] if not vdata['managed']: return False if not self.game_data: return False # setup modules if not self.resman: self.resman = ResourceManager(wrapper=self.wrapper, village_id=self.village_id) self.resman.update(self.game_data) if not self.rep_man: self.rep_man = ReportManager(wrapper=self.wrapper, village_id=self.village_id) self.rep_man.read(full_run=False) if not self.def_man: self.def_man = DefenceManager(wrapper=self.wrapper, village_id=self.village_id) self.def_man.update(data.text) if self.def_man.under_attack: self.logger.warning("Village under attack!") # setup and check if village still exists / is accessible if self.config['world']['quests_enabled']: if self.get_quests(): self.logger.info("There where completed quests, re-running function") return self.run() if not self.builder: self.builder = BuildingManager(wrapper=self.wrapper, village_id=self.village_id) self.builder.resman = self.resman # manage buildings (has to always run because recruit check depends on building levels) build_config = vdata['building'] if vdata['building'] else self.config['building']['default'] self.builder.queue = TemplateManager.get_template(category="builder", template=build_config) self.builder.max_lookahead = self.config['building']['max_lookahead'] self.builder.max_queue_len = self.config['building']['max_queued_items'] self.builder.start_update(build=self.config['building']['manage_buildings']) if not self.units: self.units = TroopManager(wrapper=self.wrapper, village_id=self.village_id) self.units.max_batch_size = self.config['units']['batch_size'] self.units.resman = self.resman # set village templates unit_config = vdata['units'] if vdata['units'] else self.config['units']['default'] self.units.template = TemplateManager.get_template(category="troops", template=unit_config, output_json=True) entry = self.units.get_template_action(self.builder.levels) if entry and self.units.wanted != entry["build"]: # update wanted units if template has changed self.logger.info("%s as wanted units for current village" % (str(entry["build"]))) self.units.wanted = entry["build"] if entry and 'upgrades' in entry and self.units.wanted_levels != entry['upgrades']: self.logger.info("%s as wanted upgrades for current village" % (str(entry["upgrades"]))) self.units.wanted_levels = entry['upgrades'] # get total amount of troops in village self.units.update_totals() if self.config['units']['upgrade'] and self.units.wanted_levels != {}: self.units.attempt_upgrade(self.units.wanted_levels) if 'snobs' in vdata and self.builder.levels['snob'] > 0: if not self.snobman: self.snobman = SnobManager(wrapper=self.wrapper, village_id=self.village_id) self.snobman.troop_manager = self.units self.snobman.resman = self.resman self.snobman.wanted = vdata['snobs'] self.snobman.building_level = self.builder.levels['snob'] self.snobman.run() if self.config['units']['recruit']: # prioritize_building: will only recruit when builder has sufficient funds for queue items if vdata['prioritize_building'] and not self.resman.can_recruit(): self.logger.info("Not recruiting because builder has insufficient funds") elif vdata['prioritize_snob'] and self.snobman and self.snobman.can_snob and self.snobman.is_incomplete: self.logger.info("Not recruiting because snob has insufficient funds") else: # do a build run for every for building in self.units.wanted: if building not in self.builder.levels or self.builder.levels[building] == 0: self.logger.debug("Recruit of %s will be ignored because building is not available" % building) continue self.units.start_update(building) self.logger.debug("Current resources: %s" % str(self.resman.actual)) self.logger.debug("Requested resources: %s" % str(self.resman.requested)) if self.units.can_attack: if not self.area: self.area = Map(wrapper=self.wrapper, village_id=self.village_id) self.area.get_map() if self.area.villages: self.logger.info("%d villages from map cache, (your location: %s)" % ( len(self.area.villages), ':'.join([str(x) for x in self.area.my_location]))) if not self.attack: self.attack = AttackManager(wrapper=self.wrapper, village_id=self.village_id, troopmanager=self.units, map=self.area) self.attack.repman = self.rep_man if entry: self.attack.template = entry['farm'] if self.config['farms']['farm']: self.attack.extra_farm = vdata['additional_farms'] self.attack.max_farms = self.config['farms']['max_farms'] self.attack.run() if not self.def_man.under_attack: self.units.gather() if self.config['market']['auto_trade'] and "market" in self.builder.levels and self.builder.levels["market"] > 0: self.logger.info("Managing market") self.resman.trade_max_per_hour = self.config['market']['trade_max_per_hour'] self.resman.trade_max_duration = self.config['market']['max_trade_duration'] if self.config['market']['trade_multiplier']: self.resman.trade_bias = self.config['market']['trade_multiplier_value'] self.resman.manage_market(drop_existing=self.config['market']['auto_remove']) self.logger.info("Village cycle done, returning to overview") res = self.wrapper.get_action(village_id=self.village_id, action="overview") self.game_data = Extractor.game_state(res) self.resman.update(self.game_data)
class TestMap(unittest.TestCase): def setUp(self): self.map = Map() def test_generate(self): self.map.generate()
# Caméra from view.skins import Skins # Skins pygame.init() # Initialisation de pygame Camera.init() # Initialisation de la caméra Display.init(width=config.WINDOW_WIDTH, height=config.WINDOW_HEIGHT, framerate=config.FRAMERATE) # Initialisation de la fenêtre Menu.init() # Initialisation du menu Skins.init() # Initialisation et chargement des skins Map.init(width=config.MAP_WIDTH, height=config.MAP_HEIGHT) # Initialisation du terrain de jeu Game.run() # Lancement du jeu pygame.quit() # Fermeture de pygame
def setUp(self): self.map = Map()
def play(cls): """Для переигры""" Display.set_cursor() Map.reset() cls.can_play = True
class MineGame(object): """Mine sweeper game object.""" rows, cols, mines, marked, remain, moves = 0, 0, 0, 0, 0, 0 status = STATUS.WIN start_time, __duration = 0., 0. __map, __mask = None, None def start(self, rows: int, columns: int, mines: int): assert columns > 0 and rows > 0 and 0 < mines < rows * columns # Initialize game data self.rows, self.cols, self.mines = rows, columns, mines self.remain = rows * columns self.marked, self.moves, self.status = 0, 0, STATUS.RUNNING self.start_time, self.__duration = time.time(), 0. self.__map = Map(rows, columns, self.mines) self.__mask = [[MASK.UNKNOWN for _ in range(columns)] for _ in range(rows)] def view(self, row: int, col: int) -> int: # See the cell at [row, col] assert 0 <= col < self.cols and 0 <= row < self.rows if self.__mask[row][col] == MASK.KNOWN: value = self.__map[row][col] else: value = self.__mask[row][col].value return value def move(self, operation: OPERATION, row: int, col: int): assert self.status == STATUS.RUNNING assert 0 <= col < self.cols and 0 <= row < self.rows self.moves += 1 # Operations: uncover and mark / unmark do = { OPERATION.UNCOVER: self.__uncover, OPERATION.MARK: self.__mark }[operation] # Perform operation if self.__mask[row][col] != MASK.KNOWN: value = do(row, col) else: value = self.__map[row][col] if self.status != STATUS.RUNNING: self.__end_game() return value def __uncover(self, row: int, col: int) -> int: # Uncover grid direct = [[1, 0], [-1, 0], [0, 1], [0, -1], [-1, -1], [1, 1], [-1, 1], [1, -1]] value = self.__map.uncover(row, col) if self.__mask[row][col] == MASK.UNKNOWN: # New grid self.__mask[row][col] = MASK.KNOWN self.remain -= 1 if value == -1: self.status = STATUS.LOSE elif self.remain == self.mines: self.status = STATUS.WIN elif value == 0: # Recursively uncover neighborhood grids for dr, dc in direct: new_r = row + dr new_c = col + dc if 0 <= new_c < self.cols: if 0 <= new_r < self.rows: if self.__mask[new_r][new_c] == MASK.UNKNOWN: self.__uncover(new_r, new_c) return value def __mark(self, row: int, col: int) -> int: # Mark grid if self.__mask[row][col] == MASK.UNKNOWN: self.__mask[row][col] = MASK.MARKED self.marked += 1 elif self.__mask[row][col] == MASK.MARKED: # Unmark self.__mask[row][col] = MASK.UNKNOWN self.marked -= 1 return 0 def __end_game(self): # Freeze time when game is over self.__duration = time.time() - self.start_time @property def duration(self) -> float: if self.status == STATUS.RUNNING: return time.time() - self.start_time else: return self.__duration def show(self): signs = {MASK.UNKNOWN: '█', MASK.MARKED: colored('ⓜ', 'yellow')} if self.__map is None: print( colored(' * * * No game to show, please start game:( * * *', 'red')) return elif self.status == STATUS.RUNNING: print(' * * * Game is running... * * *') elif self.status == STATUS.WIN: print(colored(' * * * Congratulations! You win:) * * *', 'yellow')) else: print(colored(' * * * Oops, you lose:( * * *', 'red')) print( colored( ' ♣ Time: {:.2f}s\n' ' ♣ Mines: {}\n' ' ♣ Remain: {}\n' ' ♣ Marked: {}\n' ' ♣ Moves: {}'.format(self.duration, self.mines, self.remain, self.marked, self.moves), 'yellow')) # Show grid line index_row = ' ' for col in range(self.cols): index_row += str(col % 10) + ' ' sep_row = ' ╔' + '═' * (len(index_row) - 3) + '╗' print(index_row + '\n' + sep_row, end='') print('\n', end='') for row in range(self.rows): print('{:2d}║ '.format(row), end='') for col in range(self.cols): state = self.__mask[row][col] value = self.__map[row][col] if state in signs: c = signs[state] elif value == -1: c = colored('*', 'red') elif value == 0: c = ' ' else: c = str(value) print(c, end=' ') print('║\n', end='') sep_row = ' ╚' + '═' * (len(index_row) - 3) + '╝' print(sep_row)