def _add_player_line(player):
            name = player['name']
            pname = Label(name="pname_%s" % name)
            pname.helptext = _("Click here to change your name and/or color")
            pname.text = name
            pname.min_size = pname.max_size = (130, 15)

            if name == NetworkInterface().get_client_name():
                pname.capture(
                    Callback(self._show_change_player_details_popup, game))

            pcolor = Label(name="pcolor_%s" % name, text=u"   ")
            pcolor.helptext = _("Click here to change your name and/or color")
            pcolor.background_color = player['color']
            pcolor.min_size = pcolor.max_size = (15, 15)

            if name == NetworkInterface().get_client_name():
                pcolor.capture(
                    Callback(self._show_change_player_details_popup, game))

            pstatus = Label(name="pstatus_%s" % name)
            pstatus.text = "\t\t\t" + player['status']
            pstatus.min_size = pstatus.max_size = (120, 15)

            picon = HRule(name="picon_%s" % name)

            hbox = HBox()
            hbox.addChildren(pname, pcolor, pstatus)

            if NetworkInterface().get_client_name(
            ) == game.creator and name != game.creator:
                pkick = CancelButton(name="pkick_%s" % name)
                pkick.helptext = _("Kick {player}").format(player=name)
                pkick.capture(Callback(NetworkInterface().kick, player['sid']))
                pkick.path = "images/buttons/delete_small"
                pkick.min_size = pkick.max_size = (20, 15)
                hbox.addChild(pkick)

            players_vbox.addChildren(hbox, picon)
Beispiel #2
0
    def __init__(self, selected_instances=None):
        self.selected_instances = selected_instances or []

        # keep track of units that have stance
        self.stance_unit_number = 0
        # keep local track of selected instances
        self.instances = []
        # keep track of number of instances per type
        self.type_number = defaultdict(int)

        for i in self.selected_instances:
            if hasattr(i, 'stance'):
                self.stance_unit_number += 1
            self.instances.append(i)
            if not i.has_remove_listener(Callback(self.on_instance_removed,
                                                  i)):
                i.add_remove_listener(Callback(self.on_instance_removed, i))
            self.type_number[i.id] += 1

        self._scheduled_refresh = False

        super(SelectMultiTab, self).__init__()
Beispiel #3
0
    def __init__(self, session, id, name, color, **kwargs):
        super(Pirate, self).__init__(session, id, name, color, **kwargs)

        # choose a random water tile on the coast and call it home
        self.home_point = self.session.world.get_random_possible_coastal_ship_position(
        )
        # random sea tile if costal tile not found. Empty map?
        if not self.home_point:
            self.home_point = self.session.world.get_random_possible_ship_position(
            )
        self.log.debug("Pirate: home at (%d, %d), radius %d",
                       self.home_point.x, self.home_point.y, self.home_radius)
        self.__init()

        # create a ship and place it randomly (temporary hack)
        for i in range(self.ship_count):
            self.create_ship_at_random_position()

        Scheduler().add_new_object(Callback(self.tick), self, 1, -1,
                                   self.tick_interval)
        Scheduler().add_new_object(Callback(self.tick_long), self, 1, -1,
                                   self.tick_long_interval)
 def wreak_havoc(self, building):
     """Some inhabitants have to die."""
     super(BlackDeathDisaster, self)
     if building.inhabitants > 1:
         inhabitants_that_will_die = self._manager.session.random.randint(
             1, building.inhabitants)
         building.inhabitants -= inhabitants_that_will_die
         self.log.debug("%s inhabitants dying", inhabitants_that_will_die)
         Scheduler().add_new_object(Callback(self.wreak_havoc, building),
                                    self,
                                    run_in=self.TIME_BEFORE_HAVOC)
     else:
         self.recover(building)
	def __init__(self, instance):
		"""
		@param instance: ship instance used for trading
		"""
		super(TradeTab, self).__init__(widget='tradetab.xml',
		                               icon_path='icons/tabwidget/warehouse/buysell')
		events = {}
		for k, v in self.exchange_size_buttons.iteritems():
			events[v] = Callback(self.set_exchange, k)
		self.widget.mapEvents(events)
		self.instance = instance
		self.partner = None
		self.set_exchange(50, initial=True)
	def update_buttons(self, container_active, cancel_container):
		"""Show the correct active and inactive buttons, update cancel button"""
		button_active = container_active.findChild(name="toggle_active_active")
		button_inactive = container_active.findChild(name="toggle_active_inactive")
		to_active = not self.producer.is_active()

		if not to_active: # swap what we want to show and hide
			button_active, button_inactive = button_inactive, button_active
		if (Fife.getVersion() >= (0, 4, 0)):
			button_active.parent.hideChild(button_active)
		else:
			if button_active not in button_active.parent.hidden_children:
				button_active.parent.hideChild(button_active)
		button_inactive.parent.showChild(button_inactive)

		set_active_cb = Callback(self.producer.set_active, active=to_active)
		button_inactive.capture(set_active_cb, event_name="mouseClicked")

		cancel_container.parent.showChild(cancel_container)
		cancel_button = self.widget.findChild(name="UB_cancel_button")
		cancel_cb = Callback(CancelCurrentProduction(self.producer).execute, self.instance.session)
		cancel_button.capture(cancel_cb, event_name="mouseClicked")
	def _load(self, db, owner):
		self.__init(owner)

		db_result = db("SELECT ship_id, state_id FROM ai_combat_ship WHERE owner_id = ?", self.owner.worldid)
		for (ship_id, state_id,) in db_result:
			ship = WorldObject.get_object_by_id(ship_id)
			state = self.shipStates[state_id]

			# add move callbacks corresponding to given state
			if state == self.shipStates.moving:
				ship.add_move_callback(Callback(BehaviorMoveCallback._arrived, ship))

			self.add_new_unit(ship, state)
    def remove_weapon_from_storage(self, weapon_id):
        """
		removes weapon to storage
		@param weapon_id : id of the weapon to be removed
		"""
        self.log.debug("%s remove weapon %s", self, weapon_id)
        weapons = [w for w in self._weapon_storage if w.weapon_id == weapon_id]
        if not weapons:
            self.log.debug("%s can't remove, no weapons there", self)
            return False
        # Remove the weapon last added.
        weapon = weapons[-1]
        #
        remove_from_storage = False
        # If the weapon to be removed was stackable, try to decrease number.
        if self.session.db.get_weapon_stackable(weapon_id):
            try:
                weapon.decrease_number_of_weapons(1)
            except SetStackableWeaponNumberError:
                remove_from_storage = True
        else:
            remove_from_storage = True

        if remove_from_storage:
            self._weapon_storage.remove(weapon)
            weapon.remove_weapon_fired_listener(
                Callback(self._remove_from_fireable, weapon))
            weapon.remove_attack_ready_listener(
                Callback(self._add_to_fireable, weapon))
            weapon.remove_weapon_fired_listener(
                self._increase_fired_weapons_number)
            try:
                self._fireable.remove(weapon)
            except ValueError:
                pass

        self.on_storage_modified()
        self.equipped_weapon_number -= 1
        return True
Beispiel #9
0
	def _sail_random(self, pirate_ship):

		owner = pirate_ship.owner
		session = owner.session
		point = session.world.get_random_possible_ship_position()
		try:
			pirate_ship.move(point, Callback(self._arrived, pirate_ship))
			owner.ships[pirate_ship] = owner.shipStates.moving_random
			self.log.debug('Pirate %s: Ship %s(%s): moving random at %s' % (owner.worldid, pirate_ship.get_component(NamedComponent).name,
				owner.ships[pirate_ship], point))
		except MoveNotPossible:
			owner.ships[pirate_ship] = owner.shipStates.idle
			self.log.debug('Pirate %s: Ship %s: unable to move random at %s' % (owner.worldid, pirate_ship.get_component(NamedComponent).name, point))
Beispiel #10
0
    def _refresh_found_settlement_button(self, events):
        island_without_player_settlement_found = False
        helptext = T(
            "The ship needs to be close to an island to found a settlement.")
        for island in self.instance.session.world.get_islands_in_radius(
                self.instance.position, self.instance.radius):
            if not any(settlement.owner.is_local_player
                       for settlement in island.settlements):
                island_without_player_settlement_found = True
            else:
                helptext = T("You already have a settlement on this island.")

        if island_without_player_settlement_found:
            events['found_settlement'] = Callback(
                self.instance.session.ingame_gui._build, BUILDINGS.WAREHOUSE,
                weakref.ref(self.instance))
            self.widget.child_finder('found_settlement_bg').set_active()
            self.widget.child_finder('found_settlement').set_active()
            self.widget.child_finder('found_settlement').helptext = T(
                "Build settlement")
        else:
            events['found_settlement'] = None
            self.widget.child_finder('found_settlement_bg').set_inactive()
            self.widget.child_finder('found_settlement').set_inactive()
            self.widget.child_finder('found_settlement').helptext = helptext

        cb = Callback(
            self.instance.session.ingame_gui.resource_overview.
            set_construction_mode, self.instance,
            Entities.buildings[BUILDINGS.WAREHOUSE].costs)
        events['found_settlement/mouseEntered'] = cb

        cb1 = Callback(self.instance.session.ingame_gui.resource_overview.
                       close_construction_mode)
        cb2 = Callback(
            self.widget.child_finder('found_settlement').hide_tooltip)
        #TODO the tooltip should actually hide on its own. Ticket #1096
        cb = Callback.ChainedCallbacks(cb1, cb2)
        events['found_settlement/mouseExited'] = cb
Beispiel #11
0
    def _load(self, db, worldid):
        super(Pirate, self)._load(db, worldid)
        self.__init()

        remaining_ticks, = db(
            "SELECT remaining_ticks FROM ai_pirate WHERE rowid = ?",
            worldid)[0]
        Scheduler().add_new_object(Callback(self.tick), self, remaining_ticks,
                                   -1, self.tick_interval)

        remaining_ticks_long, = db(
            "SELECT remaining_ticks_long FROM ai_pirate WHERE rowid = ?",
            worldid)[0]
        Scheduler().add_new_object(Callback(self.tick_long), self,
                                   remaining_ticks_long, -1,
                                   self.tick_interval)

        home = db("SELECT x, y FROM pirate_home_point")[0]
        self.home_point = Point(home[0], home[1])

        self.log.debug("Pirate: home at (%d, %d), radius %d",
                       self.home_point.x, self.home_point.y, self.home_radius)
Beispiel #12
0
    def reached_warehouse(self, ship):
        """Actions that need to be taken when reaching a warehouse:
		Sell demanded res, buy offered res, simulate load/unload, continue route.
		@param ship: ship instance"""
        self.log.debug("Trader %s ship %s: reached warehouse", self.worldid,
                       ship.worldid)
        settlement = self.warehouse[ship.worldid].settlement
        # NOTE: must be sorted for mp games (same order everywhere)
        trade_comp = settlement.get_component(TradePostComponent)
        for res in sorted(trade_comp.buy_list.keys(
        )):  # check for resources that the settlement wants to buy
            # select a random amount to sell
            amount = self.session.random.randint(TRADER.SELL_AMOUNT_MIN,
                                                 TRADER.SELL_AMOUNT_MAX)
            # try to sell all, else try smaller pieces
            for try_amount in range(amount, 0, -1):
                price = int(
                    self.session.db.get_res_value(res) *
                    TRADER.PRICE_MODIFIER_SELL * try_amount)
                trade_successful = trade_comp.buy(res, try_amount, price,
                                                  self.worldid)
                self.log.debug(
                    "Trader %s: offered sell %s tons of res %s, success: %s",
                    self.worldid, try_amount, res, trade_successful)
                if trade_successful:
                    break

        # NOTE: must be sorted for mp games (same order everywhere)
        for res in sorted(trade_comp.sell_list.keys()):
            # select a random amount to buy from the settlement
            amount = self.session.random.randint(TRADER.BUY_AMOUNT_MIN,
                                                 TRADER.BUY_AMOUNT_MAX)
            # try to buy all, else try smaller pieces
            for try_amount in range(amount, 0, -1):
                price = int(
                    self.session.db.get_res_value(res) *
                    TRADER.PRICE_MODIFIER_BUY * try_amount)
                trade_successful = trade_comp.sell(res, try_amount, price,
                                                   self.worldid)
                self.log.debug(
                    "Trader %s: offered buy %s tons of res %s, success: %s",
                    self.worldid, try_amount, res, trade_successful)
                if trade_successful:
                    break

        del self.warehouse[ship.worldid]
        # wait a few seconds before going on to simulate loading/unloading process
        Scheduler().add_new_object(
            Callback(self.ship_idle, ship), self,
            Scheduler().get_ticks(TRADER.TRADING_DURATION))
        self.ships[ship] = self.shipStates.reached_warehouse
Beispiel #13
0
    def _init_tabs(self):
        """Add enough tabbuttons for all widgets."""
        def on_tab_removal(tabwidget):
            # called when a tab is being removed (via weakref since tabs shouldn't have references to the parent tabwidget)
            # If one tab is removed, the whole tabwidget will die..
            # This is easy usually the desired behaviour.
            if tabwidget():
                tabwidget().on_remove()

        # Load buttons
        for index, tab in enumerate(self._tabs):
            # don't add a reference to the
            tab.add_remove_listener(Callback(on_tab_removal,
                                             weakref.ref(self)))
            container = Container(name="container_%s" % index)
            background = Icon(name="bg_%s" % index)
            button = ImageButton(name=str(index))
            if self.current_tab is tab:
                background.image = tab.button_background_image_active
                button.up_image = tab.button_active_image
            else:
                background.image = tab.button_background_image
                button.up_image = tab.button_up_image
            button.down_image = tab.button_down_image
            button.hover_image = tab.button_hover_image
            button.is_focusable = False
            button.size = (50, 50)
            button.capture(Callback(self._show_tab, index))
            if hasattr(tab, 'helptext') and tab.helptext is not None:
                button.helptext = tab.helptext
            container.size = background.size
            container.addChild(background)
            container.addChild(button)
            self.content.addChild(container)
        self.widget.size = (50, 55 * len(self._tabs))
        self.widget.adaptLayout()

        self._apply_layout_hack()
Beispiel #14
0
    def save(self, db):
        super(Pirate, self).save(db)
        db("UPDATE player SET is_pirate = 1 WHERE rowid = ?", self.worldid)
        db("INSERT INTO pirate_home_point(x, y) VALUES(?, ?)",
           self.home_point.x, self.home_point.y)

        current_callback = Callback(self.tick)
        calls = Scheduler().get_classinst_calls(self, current_callback)
        assert len(calls) == 1, "got %s calls for saving %s: %s" % (
            len(calls), current_callback, calls)
        remaining_ticks = max(list(calls.values())[0], 1)

        current_callback_long = Callback(self.tick_long)
        calls = Scheduler().get_classinst_calls(self, current_callback_long)
        assert len(calls) == 1, "got %s calls for saving %s: %s" % (
            len(calls), current_callback_long, calls)
        remaining_ticks_long = max(list(calls.values())[0], 1)

        db(
            "INSERT INTO ai_pirate(rowid, remaining_ticks, remaining_ticks_long) VALUES(?, ?, ?)",
            self.worldid, remaining_ticks, remaining_ticks_long)

        for ship in self.ships:
            ship_state = self.ships[ship]
            db("INSERT INTO pirate_ships(rowid, state) VALUES(?, ?)",
               ship.worldid, ship_state.index)

        # save unit manager
        self.unit_manager.save(db)

        # save combat manager
        self.combat_manager.save(db)

        # save strategy manager
        self.strategy_manager.save(db)

        # save behavior manager
        self.behavior_manager.save(db)
	def infect(self, building, load=None):
		"""Infect a building with fire.
		@load: (db, disaster_worldid), set on restoring infected state of savegame"""
		super(FireDisaster, self).infect(building, load=load)
		# keep in sync with load()
		AddStatusIcon.broadcast(building, FireStatusIcon(building))
		NewDisaster.broadcast(building.owner, building, FireDisaster)
		self._affected_buildings.append(building)
		havoc_time = self.TIME_BEFORE_HAVOC
		if load:
			db, worldid = load
			havoc_time = db("SELECT remaining_ticks_havoc FROM fire_disaster WHERE disaster = ? AND building = ?", worldid, building.worldid)[0][0]

		Scheduler().add_new_object(Callback(self.wreak_havoc, building), self, run_in=havoc_time)
Beispiel #16
0
 def show_save_map_dialog(self):
     """Shows a dialog where the user can set the name of the saved map."""
     events = {
         OkButton.DEFAULT_NAME: self.save_map,
         CancelButton.DEFAULT_NAME: self._hide_save_map_dialog
     }
     self.main_gui.on_escape = self._hide_save_map_dialog
     dialog = self.widgets['save_map']
     name = dialog.findChild(name='map_name')
     name.text = u''
     dialog.mapEvents(events)
     name.capture(Callback(self.save_map))
     dialog.show()
     name.requestFocus()
Beispiel #17
0
    def make_ruin(self):
        """ Replaces itself with a ruin.
		"""
        command = Build(BUILDINGS.SETTLER_RUIN,
                        self.position.origin.x,
                        self.position.origin.y,
                        island=self.island,
                        settlement=self.settlement)

        # Remove the building and then place the Ruin
        Scheduler().add_new_object(Callback.ChainedCallbacks(
            self.remove, Callback(command, self.owner)),
                                   self,
                                   run_in=0)
Beispiel #18
0
def do_win(session):
	"""The player wins the current scenario."""
	PauseCommand().execute(session)
	show_db_message(session, 'YOU_HAVE_WON')
	horizons.globals.fife.play_sound('effects', "content/audio/sounds/events/scenario/win.ogg")

	continue_playing = session.gui.show_popup(_("You have won!"),
	                                          _("You have completed this scenario.") + u" " +
	                                          _("Do you want to continue playing?"),
	                                          show_cancel_button=True)
	if not continue_playing:
		Scheduler().add_new_object(Callback(session.gui.quit_session, force=True), session, run_in=0)
	else:
		UnPauseCommand().execute(session)
	def load(self, db, worldid):
		super().load(db, worldid)
		runtime, action_set_id = db.get_concrete_object_data(worldid)
		# action_set_id should never be None in regular games,
		# but this information was lacking in savegames before rev 59.
		if action_set_id is None:
			action_set_id = self.__class__.get_random_action_set(level=self.level if hasattr(self, "level") else 0)
		self.__init(action_set_id)

		# delay setting of runtime until load of sub/super-class has set the action
		def set_action_runtime(self, runtime):
			# workaround to delay resolution of self._instance, which doesn't exist yet
			self._instance.setActionRuntime(runtime)
		Scheduler().add_new_object(Callback(set_action_runtime, self, runtime), self, run_in=0)
	def remove_building(self, building):
		"""Called when a building is removed from the area (the building still exists during the call)."""
		if building.id in self.field_building_classes:
			# this can't be handled right now because the building still exists
			Scheduler().add_new_object(Callback(self._refresh_unused_fields), self, run_in=0)
			Scheduler().add_new_object(Callback(partial(super(ProductionBuilder, self).remove_building, building)), self, run_in=0)
		elif building.buildable_upon or building.id == BUILDINGS.TRAIL:
			pass # don't react to road, trees and ruined tents being destroyed
		else:
			self.register_change_list(list(building.position.tuple_iter()), BUILDING_PURPOSE.NONE, None)

			if building.id in self.collector_building_classes:
				self.collector_buildings.remove(building)
				self.simple_collector_area_cache.remove_building(building)
			elif building.id in self.production_building_classes:
				self.production_buildings.remove(building)

			if building.id == BUILDINGS.LUMBERJACK:
				self._handle_lumberjack_removal(building)
			elif building.id == BUILDINGS.FARM:
				self._handle_farm_removal(building)

			super(ProductionBuilder, self).remove_building(building)
Beispiel #21
0
    def __init__(self, world_editor, ingame_gui):
        super().__init__(widget=self.widget)

        self._world_editor = world_editor
        self._current_tile = 'sand'
        self._ingame_gui = ingame_gui
        self._tile_selected = 0

        # Brush size
        for i in range(EDITOR.MIN_BRUSH_SIZE, EDITOR.MAX_BRUSH_SIZE + 1):
            b = self.widget.findChild(name='size_{:d}'.format(i))
            b.capture(Callback(self._change_brush_size, i))

        # Activate radio button for default brush size
        self._change_brush_size(self._world_editor.brush_size)

        # Tile selection
        for tile_type in ('default_land', 'sand', 'shallow_water', 'water'):
            image = self.widget.findChild(name=tile_type)
            tile = getattr(GROUND, tile_type.upper())
            image.up_image = self._get_tile_image(tile)
            image.size = image.min_size = image.max_size = (64, 32)
            image.capture(Callback(self._set_cursor_tile, tile))

        self.widget.mapEvents({
            self.widget.name + '/mouseEntered/cursor':
            self._cursor_inside,
            self.widget.name + '/mouseExited/cursor':
            self._cursor_outside,
        })

        self._ingame_gui.mainhud.mapEvents({
            self._ingame_gui.mainhud.name + '/mouseEntered/cursor':
            self._cursor_inside,
            self._ingame_gui.mainhud.name + '/mouseExited/cursor':
            self._cursor_outside,
        })
Beispiel #22
0
    def show_change_name_dialog(self, instance):
        """Shows a dialog where the user can change the name of a NamedComponant.
		The game gets paused while the dialog is executed."""
        events = {
            OkButton.DEFAULT_NAME: Callback(self.change_name, instance),
            CancelButton.DEFAULT_NAME: self._hide_change_name_dialog
        }
        self.main_gui.on_escape = self._hide_change_name_dialog
        changename = self.widgets['change_name']
        oldname = changename.findChild(name='old_name')
        oldname.text = instance.get_component(SettlementNameComponent).name
        newname = changename.findChild(name='new_name')
        changename.mapEvents(events)
        newname.capture(Callback(self.change_name, instance))

        def forward_escape(event):
            # the textfield will eat everything, even control events
            if event.getKey().getValue() == fife.Key.ESCAPE:
                self.main_gui.on_escape()

        newname.capture(forward_escape, "keyPressed")

        changename.show()
        newname.requestFocus()
Beispiel #23
0
    def add_gui_entry(self, warehouse, resource_list=None):
        vbox = self._gui.findChild(name="left_vbox")
        entry = load_uh_widget("route_entry.xml")
        entry.name = 'container_%s' % len(self.widgets)
        entry.settlement = weakref.ref(warehouse.settlement)
        self.widgets.append(entry)

        settlement_name_label = entry.findChild(name="warehouse_name")
        settlement_name_label.text = warehouse.settlement.get_component(
            NamedComponent).name
        player_name_label = entry.findChild(name="player_name")
        player_name_label.text = warehouse.owner.name

        self.add_trade_slots(entry)

        index = 1
        resource_list = resource_list or {}
        for res_id in resource_list:
            if index > self.SLOTS_PER_ENTRY:
                break
            self.add_resource(slot=self.slots[entry][index - 1],
                              res_id=res_id,
                              entry=entry,
                              has_value=True,
                              value=resource_list[res_id])
            index += 1

        entry.mapEvents({
            'delete_warehouse/mouseClicked':
            Callback(self.remove_entry, entry),
            'move_up/mouseClicked':
            Callback(self.move_entry, entry, 'up'),
            'move_down/mouseClicked':
            Callback(self.move_entry, entry, 'down')
        })
        vbox.addChild(entry)
Beispiel #24
0
	def initialize(self):
		self.__init()
		# add production lines as specified in db.
		if self.__auto_init:
			for prod_line, attributes in self.production_lines.iteritems():
				if 'enabled_by_default' in attributes and not attributes['enabled_by_default']:
					continue  # It's set to False, don't add
				prod = self.create_production(prod_line)
				self.add_production(prod)
		# For newly built producers we set the utilization to full for the first
		# few seconds, this avoids the low productivity icon being shown every
		# time a new producer is built
		temp_util = self.__utilization
		self.__utilization = FullUtilization()
		Scheduler().add_new_object(Callback(self.__set_utilization, temp_util), self, Scheduler().get_ticks(15))
Beispiel #25
0
	def add_weapon_to_storage(self, weapon_id):
		"""
		adds weapon to storage
		@param weapon_id : id of the weapon to be added
		"""
		self.log.debug("%s add weapon %s", self, weapon_id)
		# If weapon is stackable, try to stack.
		weapon = None
		if self.equipped_weapon_number == self.total_number_of_weapons:
			self.log.debug("%s weapon storage full", self)
			return False
		if self.session.db.get_weapon_stackable(weapon_id):
			stackable = [w for w in self._weapon_storage if weapon_id == w.weapon_id]
			# Try to increase the number of weapons for one stackable weapon.
			increased = False
			for weapon in stackable:
				try:
					weapon.increase_number_of_weapons(1)
					increased = True
					break
				except SetStackableWeaponNumberError:
					continue

			if not increased:
				weapon = StackableWeapon(self.session, weapon_id)
		else:
			weapon = Weapon(self.session, weapon_id)
		if weapon:
			self._weapon_storage.append(weapon)
			weapon.add_weapon_fired_listener(Callback(self._remove_from_fireable, weapon))
			weapon.add_attack_ready_listener(Callback(self._add_to_fireable, weapon))
			weapon.add_weapon_fired_listener(self._increase_fired_weapons_number)
			self._fireable.append(weapon)
			self.equipped_weapon_number += 1
		self.on_storage_modified()  # This will update the range.
		return True
Beispiel #26
0
    def _load(self, db, worldid, success_callback, failure_callback):
        db_result = db(
            "SELECT source_settlement_manager, destination_settlement_manager, ship, state FROM ai_mission_special_domestic_trade WHERE rowid = ?",
            worldid)[0]
        self.source_settlement_manager = WorldObject.get_object_by_id(
            db_result[0])
        self.destination_settlement_manager = WorldObject.get_object_by_id(
            db_result[1])
        self.state = self.missionStates[db_result[3]]
        super().load(db, worldid, success_callback, failure_callback,
                     WorldObject.get_object_by_id(db_result[2]))

        if self.state is self.missionStates.moving_to_source_settlement:
            self.ship.add_move_callback(
                Callback(self._reached_source_settlement))
            self.ship.add_blocked_callback(
                Callback(self._move_to_source_settlement))
        elif self.state is self.missionStates.moving_to_destination_settlement:
            self.ship.add_move_callback(
                Callback(self._reached_destination_settlement))
            self.ship.add_blocked_callback(
                Callback(self._move_to_destination_settlement))
        else:
            assert False, 'invalid state'
Beispiel #27
0
    def refresh(self):
        super(PlayersSettlements, self).refresh()
        self._gui.findChild(
            name='headline').text = T("Settlements of {player}").format(
                player=self.session.world.player.name)

        sequence_number = 0
        events = {}
        for settlement in sorted(self.session.world.settlements,
                                 key=lambda settlement:
                                 (settlement.get_component(NamedComponent).
                                  name, settlement.worldid)):
            if settlement.owner is self.session.world.player:
                sequence_number += 1
                name_label, rename_icon = self._add_line_to_gui(
                    settlement, sequence_number)
                events['%s/mouseClicked' % name_label.name] = Callback(
                    self._go_to_settlement, settlement)
                cb = Callback(self.session.ingame_gui.show_change_name_dialog,
                              settlement)
                events['%s/mouseClicked' % rename_icon.name] = cb
        self._gui.mapEvents(events)
        self._add_summary_line_to_gui()
        self._content_vbox.adaptLayout()
Beispiel #28
0
    def add_resource(self,
                     res_id,
                     slot=None,
                     entry=None,
                     has_value=False,
                     value=0):
        button = slot.findChild(name="button")
        position = self.widgets.index(entry)
        # Remove old resource from waypoints.
        res = self.resource_for_icon[button.up_image.source]
        if res != 0:
            self._route_cmd("remove_from_resource_list", position, res)

        icon = self.icon_for_resource[res_id]
        button.up_image, button.down_image, button.hover_image = icon, icon, icon
        button.max_size = button.min_size = button.size = (32, 32)

        # Hide the resource menu.
        self.hide_resource_menu()

        # Show widget elements for new resource.
        slider = slot.findChild(name="slider")

        if not has_value:
            value = int(slider.value)
            if slot.action == "unload":
                value = -value

        if value < 0:
            self.show_unload_icon(slot)
            slider.value = float(-value)
            amount = -value
        elif value > 0:
            self.show_load_icon(slot)
            slider.value = float(value)
            amount = value
        else:
            # Keep the load/unload persistent if the slider value is 0.
            slider.value = 0.
            amount = value

        if res_id != 0:
            slot.findChild(name="amount").text = str(amount) + "t"
            slot.adaptLayout()
            self._route_cmd("add_to_resource_list", position, res_id, value)
            slider.capture(Callback(self.slider_adjust, slot, res_id, entry))
        else:
            slot.findChild(name="amount").text = ""
 def _sail_home(self, pirate_ship):
     owner = pirate_ship.owner
     try:
         pirate_ship.move(Circle(owner.home_point, self.pirate_home_radius),
                          Callback(self._arrived, pirate_ship))
         owner.ships[pirate_ship] = owner.shipStates.going_home
         self.log.debug(
             'Pirate %s: Ship %s(%s): sailing home at %s' %
             (owner.worldid, pirate_ship.get_component(NamedComponent).name,
              owner.ships[pirate_ship], owner.home_point))
     except MoveNotPossible:
         owner.ships[pirate_ship] = owner.shipStates.idle
         self.log.debug(
             'Pirate %s: Ship %s: unable to move home at %s' %
             (owner.worldid, pirate_ship.get_component(NamedComponent).name,
              owner.home_point))
Beispiel #30
0
	def _on_damage(self, caller=None):
		"""Called when health has changed"""
		if not self._instance: # dead
			# it is sometimes hard to avoid this being called after the unit has died,
			# e.g. when it's part of a list of changelisteners, and one of the listeners executed before kills the unit
			return
		health_was_displayed_before = self._health_displayed
		# always update
		self.draw_health()
		if health_was_displayed_before:
			return # don't schedule removal
		# remember that it has been drawn automatically
		self._last_draw_health_call_on_damage = True
		# remove later (but only in case there's no manual interference)
		ExtScheduler().add_new_object(Callback(self.draw_health, auto_remove=True),
		                              self, self.__class__.AUTOMATIC_HEALTH_DISPLAY_TIMEOUT)