Пример #1
0
	def show(self):
		if not self._check_connection():
			return

		self._gui = load_uh_widget('multiplayermenu.xml')
		self._gui.mapEvents({
			'cancel' : self._windows.close,
			'join'   : self._join_game,
			'create' : self._create_game,
			'refresh': Callback(self._refresh, play_sound=True)
		})

		self._gui.findChild(name='gamelist').capture(self._update_game_details)
		self._playerdata = PlayerDataSelection()
		self._gui.findChild(name="playerdataselectioncontainer").addChild(self._playerdata.get_widget())

		refresh_worked = self._refresh()
		if not refresh_worked:
			self._windows.close()
			return

		# FIXME workaround for multiple callback registrations
		# this happens because subscription is done when the window is showed, unsubscription
		# only when it is closed. if new windows appear and disappear, show is called multiple
		# times. the error handler is used throughout the entire mp menu, that's why we can't
		# unsubscribe in hide. need to find a better solution.
		NetworkInterface().discard("error", self._on_error)
		NetworkInterface().subscribe("error", self._on_error)

		self._gui.show()

		# TODO Remove once loading a game is implemented again
		self._gui.findChild(name='load').parent.hide()
Пример #2
0
	def _show_change_player_details_popup(self, game):
		"""Shows a dialog where the player can change its name and/or color"""

		assigned = [p["color"] for p in NetworkInterface().get_game().get_player_list()
		            if p["name"] != NetworkInterface().get_client_name()]
		unused_colors = set(Color) - set(assigned)

		playerdata = PlayerDataSelection(color_palette=unused_colors)
		playerdata.set_player_name(NetworkInterface().get_client_name())
		playerdata.set_color(NetworkInterface().get_client_color())

		dialog = load_uh_widget('set_player_details.xml')
		dialog.findChild(name="playerdataselectioncontainer").addChild(playerdata.get_widget())

		def _change_playerdata():
			NetworkInterface().change_name(playerdata.get_player_name())
			NetworkInterface().change_color(playerdata.get_player_color().id)
			dialog.hide()
			self._update_game_details()

		def _cancel():
			dialog.hide()

		dialog.mapEvents({
			OkButton.DEFAULT_NAME: _change_playerdata,
			CancelButton.DEFAULT_NAME: _cancel
		})

		dialog.show()
    def __init__(self, windows):
        super(SingleplayerMenu, self).__init__(windows)

        self._mode = None

        self._gui = load_uh_widget('singleplayermenu.xml')
        self._gui.mapEvents({
            'cancel':
            self._windows.close,
            'okay':
            self.act,
            'scenario':
            Callback(self._select_mode, 'scenario'),
            'random':
            Callback(self._select_mode, 'random'),
            'free_maps':
            Callback(self._select_mode, 'free_maps')
        })

        self._playerdata = PlayerDataSelection()
        self._aidata = AIDataSelection()
        self._gui.findChild(name="playerdataselectioncontainer").addChild(
            self._playerdata.get_widget())
        self._gui.findChild(name="aidataselectioncontainer").addChild(
            self._aidata.get_widget())
    def __init__(self, mainmenu, windows):
        super(MultiplayerMenu, self).__init__(windows)
        self._mainmenu = mainmenu
        self._gui = load_uh_widget('multiplayermenu.xml')
        self._gui.mapEvents({
            'cancel': self._windows.close,
            'join': self._join_game,
            'create': self._create_game,
            'refresh': Callback(self._refresh, play_sound=True)
        })

        self._gui.findChild(name='gamelist').capture(self._update_game_details)
        self._playerdata = PlayerDataSelection()
        self._gui.findChild(name="playerdataselectioncontainer").addChild(
            self._playerdata.get_widget())

        # to track if the menu window is opened or not.
        self._is_open = False
    def __show_change_player_details_popup(self):
        """Shows a dialog where the player can change its name and/or color"""
        def _get_unused_colors():
            """Returns unused colors list in a game """
            assigned = [
                p["color"]
                for p in NetworkInterface().get_game().get_player_list()
                if p["name"] != NetworkInterface().get_client_name()
            ]
            available = set(Color) - set(assigned)
            return available

        set_player_details_dialog = self.widgets['set_player_details']
        #remove all children of color and name pop-up and then show them
        set_player_details_dialog.findChild(
            name="playerdataselectioncontainer").removeAllChildren()
        #assign playerdata to self.current.playerdata to use self.__apply_new_color() and __apply_new_nickname()
        self.current.playerdata = PlayerDataSelection(
            set_player_details_dialog,
            self.widgets,
            color_palette=_get_unused_colors())
        self.current.playerdata.set_player_name(
            NetworkInterface().get_client_name())
        self.current.playerdata.set_color(
            NetworkInterface().get_client_color())

        def _change_playerdata():
            self.__apply_new_nickname()
            self.__apply_new_color()
            set_player_details_dialog.hide()
            self.__update_game_details()

        def _cancel():
            set_player_details_dialog.hide()

        events = {
            OkButton.DEFAULT_NAME: _change_playerdata,
            CancelButton.DEFAULT_NAME: _cancel
        }
        self.on_escape = _cancel

        set_player_details_dialog.mapEvents(events)
        set_player_details_dialog.show()
    def show_multi(self):
        """Shows main multiplayer menu"""
        if enet is None:
            headline = _(u"Unable to find pyenet")
            descr = _(
                u'The multiplayer feature requires the library "pyenet", '
                u"which could not be found on your system.")
            advice = _(
                u"Linux users: Try to install pyenet through your package manager."
            )
            self.show_error_popup(headline, descr, advice)
            return

        if NetworkInterface() is None:
            try:
                NetworkInterface.create_instance()
            except RuntimeError as e:
                headline = _(u"Failed to initialize networking.")
                descr = _(
                    "Network features could not be initialized with the current configuration."
                )
                advice = _(
                    "Check the settings you specified in the network section.")
                self.show_error_popup(headline, descr, advice, unicode(e))
                return

        if not NetworkInterface().isconnected():
            connected = self.__connect_to_server()
            if not connected:
                return

        if NetworkInterface().isjoined():
            if not NetworkInterface().leavegame():
                return

        event_map = {
            'cancel': self.__cancel,
            'join': self.__join_game,
            'create': self.__show_create_game,
            'load': self.__show_load_game,
            'refresh': Callback(self.__refresh, play_sound=True)
        }
        # store old name and color
        self.__apply_new_nickname()
        self.__apply_new_color()
        # reload because changing modes (not yet implemented) will need it
        self.widgets.reload('multiplayermenu')
        self._switch_current_widget('multiplayermenu',
                                    center=True,
                                    event_map=event_map,
                                    hide_old=True)

        refresh_worked = self.__refresh()
        if not refresh_worked:
            self.show_main()
            return
        self.current.findChild(name='gamelist').capture(
            self.__update_game_details)
        self.current.findChild(name='showonlyownversion').capture(
            self.__show_only_own_version_toggle)
        self.current.playerdata = PlayerDataSelection(self.current,
                                                      self.widgets)

        self.current.show()

        self.on_escape = event_map['cancel']
class SingleplayerMenu(object):
    def show_single(self, show='scenario'):  # tutorial
        """
		@param show: string, which type of games to show
		"""
        assert show in ('random', 'scenario', 'campaign', 'free_maps')
        self.hide()
        # reload since the gui is changed at runtime
        self.widgets.reload('singleplayermenu')
        self._switch_current_widget('singleplayermenu', center=True)
        eventMap = {
            'cancel': self.show_main,
            'okay': self.start_single,
            'showScenario': Callback(self.show_single, show='scenario'),
            'showCampaign': Callback(self.show_single, show='campaign'),
            'showRandom': Callback(self.show_single, show='random'),
            'showMaps': Callback(self.show_single, show='free_maps')
        }

        adjust_widget_black_background(self.widgets['singleplayermenu'])

        # init gui for subcategory
        if show == 'random':
            del eventMap['showRandom']
            self.current.findChild(name="showRandom").marked = True
            to_remove = self.current.findChild(name="map_list_area")
            to_remove.parent.removeChild(to_remove)
            to_remove = self.current.findChild(name="choose_map_lbl")
            to_remove.parent.removeChild(to_remove)
            # need to add some options here (generation algo, size, ... )
        else:
            if show == 'free_maps':
                del eventMap['showMaps']
                self.current.findChild(name="showMaps").marked = True
                self.current.files, maps_display = SavegameManager.get_maps()
            elif show == 'campaign':
                del eventMap['showCampaign']
                self.current.findChild(name="showCampaign").marked = True
                self.current.files, maps_display = SavegameManager.get_campaigns(
                )
            else:  # scenario
                del eventMap['showScenario']
                self.current.findChild(name="showScenario").marked = True
                choosable_locales = ['en', horizons.main.fife.get_locale()]
                self.current.files, maps_display = SavegameManager.get_available_scenarios(
                    locales=choosable_locales)

            # get the map files and their display names
            self.current.distributeInitialData({
                'maplist': maps_display,
            })
            if len(maps_display) > 0:
                # select first entry
                self.current.distributeData({
                    'maplist': 0,
                })

                if show == 'scenario':  # update infos for scenario
                    from horizons.scenario import ScenarioEventHandler, InvalidScenarioFileFormat

                    def _update_infos():
                        """Fill in infos of selected scenario to label"""
                        try:
                            difficulty = ScenarioEventHandler.get_difficulty_from_file(
                                self.__get_selected_map())
                            desc = ScenarioEventHandler.get_description_from_file(
                                self.__get_selected_map())
                            author = ScenarioEventHandler.get_author_from_file(
                                self.__get_selected_map())
                        except InvalidScenarioFileFormat, e:
                            self.__show_invalid_scenario_file_popup(e)
                            return
                        self.current.findChild(
                            name="map_difficulty"
                        ).text = _("Difficulty: ") + unicode(difficulty)
                        self.current.findChild(
                            name="map_author"
                        ).text = _("Author: ") + unicode(author)
                        self.current.findChild(
                            name="map_desc"
                        ).text = _("Description: ") + unicode(desc)
                        #self.current.findChild(name="map_desc").parent.adaptLayout()
                elif show == 'campaign':  # update infos for campaign

                    def _update_infos():
                        """Fill in infos of selected campaign to label"""
                        campaign_info = SavegameManager.get_campaign_info(
                            file=self.__get_selected_map())
                        if not campaign_info:
                            # TODO : an "invalid campaign popup"
                            self.__show_invalid_scenario_file_popup(e)
                            return
                        self.current.findChild(
                            name="map_difficulty"
                        ).text = _("Difficulty: ") + unicode(
                            campaign_info.get('difficulty', ''))
                        self.current.findChild(
                            name="map_author").text = _("Author: ") + unicode(
                                campaign_info.get('author', ''))
                        self.current.findChild(
                            name="map_desc"
                        ).text = _("Description: ") + unicode(
                            campaign_info.get('description', ''))

                if show in ('scenario', 'campaign'):
                    self.current.findChild(
                        name="maplist").capture(_update_infos)
                    _update_infos()

        self.current.mapEvents(eventMap)

        self.current.playerdata = PlayerDataSelection(self.current,
                                                      self.widgets)
        self.current.show()
        self.on_escape = self.show_main