Exemplo n.º 1
0
    def simulate_rest_of_player_turn(self, player) -> None:
        """
        Simulates rest of turn for given player

        :param player: Player to simulate rest of turn for
        """
        units = self.__player_units[player]

        for unit in units:
            if Connector().get_variable('game_over'):
                return
            self.execute_unit_turn(unit)

        income = self.__player_resources[player].income
        self.execute_action(EarnResourcesAction(self, player, income))

        income_increase = self.__player_resources[player].income_increase
        if income_increase > 0:
            self.execute_action(
                IncomeResourcesIncrease(self, player, income_increase))

        # Check base
        if player.role == GameRole.DEFENDER and self.__game_history.in_preset and not self.player_have_base(
                player):
            Connector().emit('game_over')
            return

        self.__game_history.end_turn()
Exemplo n.º 2
0
    def run_inference_slot(self) -> None:
        """ Run current player turn (act method)"""

        if self.__game_engine.get_game_history().on_first_player:
            self.__game_engine.get_game_history().active_player.act()

        Connector().emit('redraw_ui')
        Connector().emit('redraw_map')
Exemplo n.º 3
0
    def __init__(self, parent: QWidget = None, game_engine: GameEngine = None):
        super().__init__(parent)

        self.__game_engine = game_engine

        Connector().subscribe('redraw_ui', self.update_text)
        Connector().subscribe('game_thread_finished', self.update_text)

        self.init_ui()
Exemplo n.º 4
0
    def history_point_slot(self, item) -> None:
        """
        Move history to selected item

        :param item: selected item
        """
        self.__game_engine.get_game_history().to_history_point(*item[257])

        Connector().emit('redraw_map')
        Connector().emit('redraw_ui')
Exemplo n.º 5
0
    def __init__(self, parent: QWidget = None, game_engine: GameEngine = None):
        super().__init__(parent)
        self.__game_engine = game_engine

        self.borders = {}  # type: Dict[Position, Border]
        self.transformation = 0.4

        Connector().subscribe('redraw_map', self.redraw_map)
        Connector().subscribe('display_border', self.display_borders)
        Connector().subscribe('game_thread_finished', self.redraw_map)

        self.init_ui()
Exemplo n.º 6
0
    def __init__(self, game_engine: GameEngine):
        super().__init__()

        self.app = QtWidgets.QApplication([])
        self.window = QtWidgets.QMainWindow()
        self.game_engine = game_engine

        Connector().subscribe('status_message', self.status_info)
        Connector().subscribe('map_position_change', self.tile_selected)
        Connector().subscribe('map_position_clear', self.tile_unselected)
        Connector().subscribe('error_message', self.error_message_slot)

        self.init_ui()
Exemplo n.º 7
0
    def previous_turn_slot(self) -> None:
        """ Move history to previous turn"""
        self.__game_engine.get_game_history().move_turn_back()

        # Enable `Next turn` and `Last turn` buttons
        self.findChild(QPushButton, 'nextTurnButton').setDisabled(False)
        self.findChild(QPushButton, 'lastTurnButton').setDisabled(False)

        if self.__game_engine.get_game_history().at_start:
            self.findChild(QPushButton, 'previousTurnButton').setDisabled(True)

        Connector().emit('redraw_ui')
        Connector().emit('redraw_map')
Exemplo n.º 8
0
    def __init__(self, parent: QWidget = None, game_engine: GameEngine = None):
        super().__init__(parent)

        self.__game_engine = game_engine
        self.__selected_tile = None  # type: Optional[Position]

        Connector().subscribe('map_position_change', self.map_tile_select_slot)
        Connector().subscribe('redraw_ui', self.redraw_ui_slot)
        Connector().subscribe('game_thread_finished', self.redraw_ui_slot)
        Connector().subscribe('map_position_clear',
                              self.map_tile_unselected_slot)

        self.init_ui()
Exemplo n.º 9
0
    def last_turn_slot(self) -> None:
        """ Move history to present """
        self.__game_engine.get_game_history().move_to_present()

        # If game is in present, disable `Next turns and `Last turn` buttons
        if self.__game_engine.get_game_history().in_preset:
            self.findChild(QPushButton, 'nextTurnButton').setDisabled(True)
            self.findChild(QPushButton, 'lastTurnButton').setDisabled(True)

        # Enable `Previous turn` button
        self.findChild(QPushButton, 'previousTurnButton').setDisabled(False)

        Connector().emit('redraw_ui')
        Connector().emit('redraw_map')
Exemplo n.º 10
0
    def show_accessible_tiles_slot(self) -> None:
        """ Display accessible tiles of the unit on the selected position"""
        tiles = self.__game_engine.get_game_object(
            self.__selected_tile).accessible_tiles

        border_dict = BorderFactory.create(3, QColor(0, 0, 255), tiles)

        Connector().emit('display_border', border_dict, [QColor(0, 0, 255)])
Exemplo n.º 11
0
    def end_of_round_slot(self) -> None:
        """ Slot for button `End of round` """

        game_history = self.__game_engine.get_game_history()
        current_player = self.__game_engine.get_player(
            game_history.current_player)

        self.__game_engine.simulate_rest_of_player_turn(current_player)

        while not game_history.on_first_player and not Connector(
        ).get_variable('game_over'):
            game_history.active_player.act()
            self.__game_engine.simulate_rest_of_player_turn(
                game_history.active_player)

        Connector().emit('redraw_map')
        Connector().emit('redraw_ui')
Exemplo n.º 12
0
    def display_spawn_slot(self) -> None:
        """ Handle display spawn tiles on map"""

        border_dict = {}
        for position in self.uncertainty_spawn.positions:
            border_dict[position.position] = Border.full(3, QColor(255, 21, 221))

        Connector().emit('display_border', border_dict, [QColor(255, 21, 221)])
Exemplo n.º 13
0
    def __init__(self, parent: QWidget = None, game_engine: GameEngine = None):
        super().__init__(parent)

        self.__game_engine = game_engine

        Connector().subscribe('game_over', self.game_over_slot)

        self.init_ui()
Exemplo n.º 14
0
    def remove(self, game_object: GameObject) -> None:
        """
        Removes given game object from the game

        :param game_object: Game object to be removed
        """
        if game_object.object_type == GameObjectType.BASE:
            for player, _game_object in self.__defender_bases.items():
                if game_object == _game_object:
                    del self.__defender_bases[player]

                    if self.__game_history.in_preset and not Connector(
                    ).get_variable('game_over'):
                        Connector().set_variable('game_over', True)
                        Connector().emit('game_over')
                    break

        self.delete_game_object(game_object)
Exemplo n.º 15
0
    def game_over_slot(self) -> None:
        """ Raise game over on game over signal"""
        result = GameOverDialog.execute_()

        if result == GameOverStates.LET_HIM_DIE.value:
            exit(0)

        if result == GameOverStates.FIND_REASON.value:
            Connector().set_variable('find_reason', True)
Exemplo n.º 16
0
    def show_attack_range_slot(self) -> None:
        """ Display attack range of the unit on the selected position """
        attack_range = self.__game_engine.get_game_object(
            self.__selected_tile).get_attribute(AttributeType.ATTACK_RANGE)

        tiles = self.__game_engine.get_game_map().get_visible_tiles(
            self.__selected_tile, attack_range)

        border_dict = BorderFactory.create(3, QColor(0, 0, 255), tiles)

        Connector().emit('display_border', border_dict, [QColor(0, 0, 255)])
Exemplo n.º 17
0
    def run(self):
        """ Execute job in other thread """
        # Lock is necessary because we are working with same game engine instance
        self._lock.acquire()

        # Minimum sleep time is here for PyQt loop need time to redraw dialogs
        time.sleep(max(self.delay, 0.1))

        getattr(self.game_engine, self.function_name)(*self.args,
                                                      **self.kwargs)
        Connector().emit('game_thread_finished')

        self._lock.release()
Exemplo n.º 18
0
    def click_on_map(self, event: QGraphicsSceneMouseEvent,
                     transformation: float) -> None:
        """ Handle click on map - try to compute position and inform about selected tile """

        position = Position.from_pixel(event.scenePos(), transformation).offset

        if self.__game_engine.get_game_map().position_on_map(position):
            self.borders.clear()

            self.borders[position] = Border.full(3, QColor(255, 0, 0))
            Connector().emit('map_position_change', position)

        self.scene.update()
Exemplo n.º 19
0
    def run_game_rounds(self, rounds: int) -> None:
        """
        Simulate N number of rounds in game engine

        :param rounds: Number of rounds to be simulated
        """
        game_history = self.get_game_history()
        while rounds > 0 and not Connector().get_variable('game_over'):
            game_history.active_player.act()
            self.simulate_rest_of_player_turn(game_history.active_player)

            if game_history.on_first_player:
                rounds -= 1
Exemplo n.º 20
0
    def syntaxError(self, recognizer, offending_symbol, line: int, column: int,
                    msg: str, e: Exception):
        """ Syntax error in the rules """

        error_msg = 'Error: Problem with parsing rules: {} at line {} column {}. Rules not parsed!\n'.format(
            msg, line, column)

        sys.stderr.write(error_msg)

        ui_error = 'Problem with parsing rules:\n\n{} at line {} column {}.\n\nRules not parsed!\n'.format(
            msg, line, column)
        Connector().emit('error_message', 'Rule parser', ui_error)

        raise IllegalRulesFormat
Exemplo n.º 21
0
    def act(self) -> None:
        """
        Execute on user action round

        * Call create_knowledge_base from user knowledge base
        * Parse rules from rules file
        * Run user interference method with knowledge, parsed rules and action base
        """
        knowledge = self.knowledge_base.create_knowledge_base()
        rules = self.__parse_rules()

        if rules is None:
            sys.stderr.write('Rules file not found! Stopping interference!\n')
            Connector().emit('error_message', 'Interference error', 'Rules file not found! Stopping interference!')
            return
        self.interference.infere(knowledge, rules, self.action_base)
Exemplo n.º 22
0
    def redraw_ui(self) -> None:
        """ Redraw whole tab UI """

        game_history = self.__game_engine.get_game_history()
        if game_history:

            # Current round and player labels
            self.findChild(QLabel, 'currentRoundLabel').setText(
                str(game_history.current_turn))
            self.findChild(QLabel, 'currentPlayerLabel').setText(
                game_history.active_player.name)

            inference_button = typing.cast(
                QPushButton, self.findChild(QPushButton, 'runInferenceButton'))
            end_of_round_button = typing.cast(
                QPushButton, self.findChild(QPushButton, 'endOfRoundButton'))
            play_button = typing.cast(
                QPushButton, self.findChild(QPushButton, 'playButton'))

            # If not in present disable round control buttons
            if not game_history.in_preset:
                end_of_round_button.setDisabled(True)
                play_button.setDisabled(True)
            else:
                end_of_round_button.setDisabled(False)
                play_button.setDisabled(False)

            # If not in present disable inference button
            if game_history.on_first_player and game_history.in_preset:
                inference_button.setDisabled(False)
            else:
                inference_button.setDisabled(True)

            # If game is over, disable play buttons
            if Connector().get_variable('game_over'):
                play_button.setDisabled(True)
                end_of_round_button.setDisabled(True)
                inference_button.setDisabled(True)
Exemplo n.º 23
0
    def __init__(self):
        super().__init__()
        self.init_ui()

        Connector().subscribe('game_over', self.accept)
        Connector().subscribe('game_thread_finished', self.accept)
Exemplo n.º 24
0
    def __init__(self, game_engine: "GameEngine"):
        super().__init__()
        self.game_engine = game_engine

        Connector().subscribe('log_message', self.create_log_record_slot)
Exemplo n.º 25
0
    def log(text: str) -> None:
        """ Log message to the game history. Log message must be string """
        if type(text) != str:
            raise IllegalLogMessage('Log messages must be string type')

        Connector().emit('log_message', text)
Exemplo n.º 26
0
def main(gui, rounds, log_output, verbose):
    """ Welcome to Orodael Turrim game. You can start GUI application without parameters or set --nogui option for
    console interface only. Console is faster, but you will get only limited information. Also you cannot order your
    units from console. Everything will be handled by your lieutenant Expert System.
    """
    # Load map configuration from config or generate random map
    height = Config.MAP_HEIGHT
    width = Config.MAP_WIDTH

    if (height is None or width is None) and Config.GAME_MAP:
        height = len(Config.GAME_MAP)
        width = len(Config.GAME_MAP[0])

    if height is None or width is None:
        raise IllegalConfigState('You must specify MAP_WIDTH and MAP_HEIGHT or GAME_MAP parameter in config file!')

    game_map = MapGenerator(width, height).generate(Config.GAME_MAP)

    # Initialize game engine
    game_engine = GameEngine(game_map)

    map_proxy = MapProxy(game_engine)
    game_object_proxy = GameObjectProxy(game_engine)
    game_control_proxy = GameControlProxy(game_engine)
    game_uncertainty_proxy = GameUncertaintyProxy(game_engine)

    # Initialize Filter factory
    FilterFactory(map_proxy, game_object_proxy)

    # Initialize Logger
    _ = LogReceiver(game_engine)

    # Register defender
    defender = Player(map_proxy, game_object_proxy, game_control_proxy, game_uncertainty_proxy)
    game_engine.register_player(defender, PlayerResources(Config.DEFENDER_STARTING_MONEY, Config.DEFENDER_INCOME), [])

    # Register attacker
    player2 = AIPlayer(map_proxy, game_object_proxy, game_control_proxy, game_uncertainty_proxy)
    game_engine.register_player(player2, PlayerResources(Config.ATTACKER_STARTING_MONEY, Config.ATTACKER_INCOME,
                                                         Config.ATTACKER_INCOME_INCREASE), [])
    player2.initialize()

    game_engine.start(rounds)

    if gui:
        # Inicialize main widget
        main_window = MainWindow(game_engine)

        Connector().emit('redraw_ui')
        main_window.execute()

    else:
        current_round = 0
        game_history = game_engine.get_game_history()
        while rounds > current_round and not Connector().get_variable('game_over'):
            game_history.active_player.act()
            game_engine.simulate_rest_of_player_turn(game_history.active_player)

            if game_history.on_first_player:
                current_round += 1

        print('\nGAME OVER\n')
        print('User survive {} rounds'.format(current_round))
        if verbose:
            print('\nConfiguration:')
            print('  MAP_RANDOM_SEED: ', Config.MAP_RANDOM_SEED)
            print('  UNCERTAINTY_RANDOM_SEED: ', Config.UNCERTAINTY_RANDOM_SEED)
            print('  AI_RANDOM_SEED: ', Config.AI_RANDOM_SEED)

    if log_output:
        text = game_engine.get_game_history()
        with open(log_output, 'w') as f:
            f.write(str(text))
Exemplo n.º 27
0
 def clear_view_slot(self):
     """ Clear all borders on map and clear selected position"""
     Connector().emit('map_position_clear')
     self.borders.clear()
     self.redraw_map()
Exemplo n.º 28
0
 def redraw_map(self) -> None:
     """ Update scene based on redraw signal """
     if not Connector().get_variable('redraw_disable'):
         self.scene.update()