예제 #1
0
    def unpause(self):
        self.paused = False
        self.oath_sworn_to.character_members.add(self)
        self.world.get_barbaric_state().character_members.remove(self)
        self.save()

        CharacterEvent.objects.create(
            character=self,
            active=False,
            type=CharacterEvent.UNPAUSE,
            counter=0,
            hour_cost=None,
            start_turn=self.world.current_turn,
            end_turn=self.world.current_turn
        )

        message = shortcuts.create_message(
            'messaging/messages/character_unpaused.html',
            self.world,
            'OOC: {} has been unpaused'.format(self.name),
            {'character': self},
            link=self.get_absolute_url()
        )
        shortcuts.add_organization_recipient(
            message,
            self.get_violence_monopoly(),
            add_lead_organizations=True
        )
예제 #2
0
    def create_recipients_from_post_data(self, request, message):
        raw_recipients = request.POST.getlist('recipient')
        organization_count = 0
        character_count = 0

        for raw_recipient in raw_recipients:
            split = raw_recipient.split('_')

            if split[0] == 'settlement':
                for character in request.hero.location.character_set.all():
                    character_count += 1
                    add_character_recipient(message, character)
            elif split[0] == 'region':
                for character in Character.objects.filter(
                        location__tile=request.hero.location.tile):
                    character_count += 1
                    add_character_recipient(message, character)
            elif split[0] == 'organization':
                organization_count += 1
                organization = get_object_or_404(Organization, id=split[1])
                add_organization_recipient(message, organization)
            elif split[0] == 'character':
                character_count += 1
                character = get_object_or_404(Character, id=split[1])
                add_character_recipient(message, character)
            else:
                message.delete()
                raise ComposeView.RecipientBuildingException(
                    "Invalid recipient.")

        if organization_count > 4 or character_count > 40:
            message.delete()
            raise ComposeView.RecipientBuildingException(
                "Too many recipients.")
예제 #3
0
 def announce_proposal(self):
     message = shortcuts.create_message(
         "New {}".format(self),
         self.capability.organization.world,
         category="proposal",
         link=self.get_absolute_url(),
     )
     shortcuts.add_organization_recipient(message,
                                          self.capability.applying_to)
     shortcuts.add_organization_recipient(message,
                                          self.capability.organization)
예제 #4
0
 def announce_execution(self, text, category, link=None):
     message = shortcuts.create_message(
         ("{}'s proposal passed: {}" if self.democratic else
          "Action by {}: {}").format(self.proposing_character, text),
         self.capability.organization.world,
         category=category,
         link=(self.get_absolute_url()
               if link is None and self.democratic else link),
     )
     shortcuts.add_organization_recipient(message,
                                          self.capability.applying_to)
     shortcuts.add_organization_recipient(message,
                                          self.capability.organization)
     return message
    def announce_proposal(self, extra_context=None):
        context = {'proposal': self}
        if extra_context is not None:
            context = {**context, **extra_context}

        message = shortcuts.create_message(
            template='messaging/messages/proposal.html',
            world=self.capability.organization.world,
            title="New proposal",
            template_context=context,
            link=self.get_absolute_url(),
        )
        shortcuts.add_organization_recipient(message,
                                             self.capability.applying_to)
        shortcuts.add_organization_recipient(message,
                                             self.capability.organization)
def present_candidacy_capability_view(request, capability_id):
    capability = get_object_or_404(Capability,
                                   id=capability_id,
                                   type=Capability.CANDIDACY)

    election = capability.applying_to.current_election
    if not election:
        messages.error(request, "There is currently no election in progress!",
                       "danger")
        return redirect(capability.get_absolute_url())

    description = request.POST.get('description')
    retire = request.POST.get('retire')

    candidacy, new = PositionCandidacy.objects.get_or_create(
        election=election, candidate=request.hero)

    if retire:
        candidacy.retired = True
        messages.success(request, "Your candidacy has been retired.",
                         "success")
    else:
        candidacy.description = description
        if new:
            messages.success(request, "Your candidacy has been created.",
                             "success")
        else:
            messages.success(request, "Your candidacy has been updated.",
                             "success")
    candidacy.save()

    message = shortcuts.create_message(
        'messaging/messages/elections_candidacy.html',
        capability.applying_to.world,
        'New candidate to elections', {
            'candidacy': candidacy,
            'retire': retire,
            'new': new
        },
        link=election.get_absolute_url())
    shortcuts.add_organization_recipient(message,
                                         capability.applying_to,
                                         add_lead_organizations=True)

    return redirect(capability.get_absolute_url())
    def announce_execution(self, title, extra_context=None, link=None):
        context = {'proposal': self}
        if extra_context is not None:
            context = {**context, **extra_context}

        message = shortcuts.create_message(
            template='messaging/messages/proposal_execution/{}.html'.format(
                self.capability.type),
            world=self.capability.organization.world,
            title=title,
            template_context=context,
            link=(self.get_absolute_url()
                  if link is None and self.democratic else link),
        )
        shortcuts.add_organization_recipient(message,
                                             self.capability.applying_to)
        shortcuts.add_organization_recipient(message,
                                             self.capability.organization)
        return message
예제 #8
0
    def pause(self):
        self.oath_sworn_to = self.get_violence_monopoly()
        self.save()

        for unit in self.worldunit_set.all():
            unit.disband()

        while self.organization_set.exclude(
                id=self.world.get_barbaric_state().id
        ).exists():
            organization = self.organization_set.exclude(
                id=self.world.get_barbaric_state().id)[0]
            organization.remove_member(self)

            message = shortcuts.create_message(
                'messaging/messages/character_paused.html',
                self.world,
                'OOC: {} has been paused'.format(self.name),
                {'character': self},
                link=self.get_absolute_url()
            )
            shortcuts.add_organization_recipient(
                message,
                organization,
                add_lead_organizations=True
            )

            self.refresh_from_db()

        self.last_activation_time = timezone.now()
        self.paused = True
        self.save()

        CharacterEvent.objects.create(
            character=self,
            active=False,
            type=CharacterEvent.PAUSE,
            counter=0,
            hour_cost=None,
            start_turn=self.world.current_turn,
            end_turn=self.world.current_turn
        )
예제 #9
0
    def remove_member(self, member):
        if member not in self.character_members.all():
            raise Exception("{} is not a member of {}".format(member, self))
        self.character_members.remove(member)

        message_content = "{} left {}.".format(member, self)

        if self.leader and member in \
                self.leader.character_members.all():
            self.leader.remove_member(member)

        if member.get_violence_monopoly() is None:
            member.world.get_barbaric_state().character_members.add(member)

        if self.is_position:
            if (self.heir_first
                    and self.heir_first in self.get_heir_candidates()):
                self.character_members.add(self.heir_first)
                self.heir_first = self.heir_second = None
                self.save()
                message_content += " {} is the new {}.".format(
                    self.get_position_occupier(), self)
            elif (self.heir_second
                  and self.heir_second in self.get_heir_candidates()):
                self.character_members.add(self.heir_second)
                self.heir_first = self.heir_second = None
                self.save()
                message_content += " {} is the new {}.".format(
                    self.get_position_occupier(), self)
            elif self.position_type == self.ELECTED:
                self.convoke_elections()

        if self.leader and self.leader.character_is_member(member):
            self.leader.remove_member(member)

        message = shortcuts.create_message(message_content,
                                           self.world,
                                           'leaving',
                                           link=self.get_absolute_url())
        shortcuts.add_organization_recipient(message, self)
        for org in self.leaded_organizations.all():
            shortcuts.add_organization_recipient(message, org)
예제 #10
0
    def do_state_taxes(self, state: organization.models.Organization):
        if not state.character_members.exists():
            return

        settlement_input = []
        total_input = 0
        for tile in state.get_all_controlled_tiles():
            for settlement in tile.settlement_set.all():
                t = 0
                for guild in settlement.building_set.filter(
                        type=Building.GUILD):
                    cash_produced = guild.field_production_counter * 6
                    t += cash_produced
                    total_input += cash_produced
                    guild.field_production_counter = 0
                    guild.save()

                settlement_input.append((settlement, t))

        member_share = math.floor(total_input /
                                  state.character_members.count())
        for member in state.character_members.all():
            member.cash += member_share
            member.save()

        message_content = "<p>Tax collection in {}.</p><ul>".format(state)
        for settlement, cash in settlement_input:
            message_content += "<li>{} produced {} coins.</li>".format(
                settlement, cash)
        message_content += "</ul><p>Total: {} silver coins.</p>".format(
            total_input)
        message_content += "<p>Each member receives {} coins.</p>".format(
            member_share)

        message = shortcuts.create_message(
            message_content,
            self.world,
            'taxes',
            safe=True,
        )
        shortcuts.add_organization_recipient(message, state)
예제 #11
0
    def remove_member(self, member):
        if member not in self.character_members.all():
            raise Exception("{} is not a member of {}".format(member, self))
        self.character_members.remove(member)

        if self.leader and member in \
                self.leader.character_members.all():
            self.leader.remove_member(member)

        if member.get_violence_monopoly() is None:
            member.world.get_barbaric_state().character_members.add(member)

        if self.is_position:
            if (self.heir_first
                    and self.heir_first in self.get_heir_candidates()):
                self.character_members.add(self.heir_first)
                self.heir_first = self.heir_second = None
                self.save()
            elif (self.heir_second
                  and self.heir_second in self.get_heir_candidates()):
                self.character_members.add(self.heir_second)
                self.heir_first = self.heir_second = None
                self.save()
            elif self.position_type == self.ELECTED:
                self.convoke_elections()

        if self.leader and self.leader.character_is_member(member):
            self.leader.remove_member(member)

        message = shortcuts.create_message(
            'messaging/messages/member_left_organization.html',
            self.world,
            'Member leaves', {
                'organization': self,
                'member': member
            },
            link=self.get_absolute_url())
        shortcuts.add_organization_recipient(message,
                                             self,
                                             add_lead_organizations=True)
예제 #12
0
    def resolve(self):
        max_votes = 0
        winners = []
        for candidacy in self.open_candidacies().all():
            votes = candidacy.positionelectionvote_set.count()
            if votes > max_votes:
                max_votes = votes
                winners = []
            if votes == max_votes:
                winners.append(candidacy)

        if len(winners) != 1:
            self.position.convoke_elections()
            winning_candidate = None
        else:
            winning_candidacy = winners[0]
            winning_candidate = winning_candidacy.candidate
            self.winner = winning_candidacy
            self.position.character_members.remove(
                self.position.get_position_occupier())
            self.position.character_members.add(winning_candidate)

        message = shortcuts.create_message(
            'messaging/messages/elections_resolved.html',
            self.position.world,
            'Election results', {
                'election': self,
                'winner_count': len(winners),
                'winner': winning_candidate
            },
            link=self.get_absolute_url())
        shortcuts.add_organization_recipient(message,
                                             self.position,
                                             add_lead_organizations=True)

        self.position.last_election = self
        self.position.current_election = None
        self.position.save()
        self.closed = True
        self.save()
예제 #13
0
    def convoke_elections(self, months_to_election=6):
        if not self.is_position:
            raise Exception("Elections only work for positions")
        new_election = election.PositionElection.objects.create(
            position=self, turn=self.world.current_turn + months_to_election)
        self.current_election = new_election
        self.save()
        if self.get_position_occupier() is not None:
            election.PositionCandidacy.objects.create(
                election=new_election,
                candidate=self.get_position_occupier(),
                description="Automatic candidacy for incumbent character.")

        message = shortcuts.create_message(
            'messaging/messages/elections_convoked.html',
            self.world,
            'Elections convoked', {'organization': self},
            link=new_election.get_absolute_url())
        shortcuts.add_organization_recipient(message,
                                             self,
                                             add_lead_organizations=True)
        return self.current_election
예제 #14
0
    def convoke_elections(self, months_to_election=6):
        if not self.is_position:
            raise Exception("Elections only work for positions")
        election = PositionElection.objects.create(
            position=self, turn=self.world.current_turn + months_to_election)
        self.current_election = election
        self.save()
        if self.get_position_occupier() is not None:
            PositionCandidacy.objects.create(
                election=election,
                candidate=self.get_position_occupier(),
                description="Auto-generated candidacy for incumbent character."
            )

        message = shortcuts.create_message(
            "Elections have been convoked for the position {}. "
            "They will take place in {} months.".format(
                self, months_to_election),
            self.world,
            'elections',
            link=election.get_absolute_url())
        shortcuts.add_organization_recipient(message, self)
        for org in self.leaded_organizations.all():
            shortcuts.add_organization_recipient(message, org)
    def execute(self):
        proposal = self.get_proposal_json_content()
        applying_to = self.capability.applying_to
        if self.capability.type == Capability.POLICY_DOCUMENT:
            try:
                if proposal['new']:
                    document = organization.models.document.PolicyDocument(
                        organization=applying_to)
                else:
                    document = organization.models.document.PolicyDocument.objects.get(
                        id=proposal['document_id'])

                if proposal['delete']:
                    self.announce_execution("Document voided",
                                            extra_context={
                                                'deleted': True,
                                                'document': document
                                            })
                    document.delete()
                else:
                    document.title = proposal.get('title')
                    document.body = proposal.get('body')
                    document.public = proposal.get('public') is not None
                    document.last_modified_turn = self.capability. \
                        organization.world.current_turn
                    document.save()

                    self.announce_execution("Policy and law",
                                            extra_context={
                                                'new': proposal['new'],
                                                'document': document
                                            },
                                            link=document.get_absolute_url())

            except organization.models.document.PolicyDocument.DoesNotExist:
                pass

        elif self.capability.type == Capability.BAN:
            try:
                character_to_ban = character.models.Character.objects.get(
                    id=proposal['character_id'])
                applying_to.remove_member(character_to_ban)
                self.announce_execution('Banned from {}!'.format(applying_to),
                                        {'banned_character': character_to_ban})
            except character.models.Character.DoesNotExist:
                pass

        elif self.capability.type == Capability.ARREST_WARRANT:
            if proposal['action'] == 'issue':
                try:
                    character_to_imprison = character.models.Character.objects.get(
                        id=proposal['character_id'])
                    character.models.CharacterEvent.objects.create(
                        character=character_to_imprison,
                        start_turn=applying_to.world.current_turn,
                        active=True,
                        type=character.models.CharacterEvent.ARREST_WARRANT,
                        organization=applying_to,
                    )
                    character_to_imprison.add_notification(
                        'messaging/messages/arrest_warrant.html',
                        'Arrest warrant against you',
                        {'warrantor': applying_to})
                    self.announce_execution(
                        '{} issues arrest warrant'.format(applying_to.name), {
                            'action': 'issue',
                            'character_to_imprison': character_to_imprison
                        })
                except character.models.Character.DoesNotExist:
                    pass
            elif proposal['action'] == 'revoke':
                try:
                    warrant = character.models.CharacterEvent.objects.get(
                        id=proposal['warrant_id'],
                        active=True,
                        organization=applying_to,
                        type=character.models.CharacterEvent.ARREST_WARRANT)
                    warrant.active = False
                    warrant.save()
                    warrant.character.add_notification(
                        'messaging/messages/arrest_warrant_revoked.html',
                        'Arrest warrant against you revoked',
                        {'warrantor': applying_to})
                    self.announce_execution(
                        '{} revokes arrest warrant'.format(applying_to.name), {
                            'action': 'revoke',
                            'warrant': warrant
                        })
                except character.models.CharacterEvent.DoesNotExist:
                    pass

        elif self.capability.type == Capability.CONVOKE_ELECTIONS:
            if applying_to.current_election is None:
                months_to_election = proposal['months_to_election']
                election = applying_to.convoke_elections(months_to_election)
                self.announce_execution('Elections convoked',
                                        {'election': election})

        elif self.capability.type == Capability.DIPLOMACY:
            try:
                target_organization = organization.models.organization.Organization.objects.get(
                    id=proposal['target_organization_id'])
                target_relationship = proposal['target_relationship']
                changing_relationship = applying_to. \
                    get_relationship_to(target_organization)
                reverse_relationship = changing_relationship.reverse_relation()
                action_type = proposal['type']

                if self.democratic:
                    self.announce_execution(
                        'Diplomacy', {
                            'action_type':
                            action_type,
                            'target_organization':
                            target_organization,
                            'target_relationship':
                            target_relationship,
                            'changing_relationship':
                            changing_relationship,
                            'reverse_relationship':
                            reverse_relationship,
                            'has_to_be_agreed':
                            changing_relationship.target_has_to_be_agreed_upon(
                                target_relationship)
                        })

                if action_type == 'propose':
                    changing_relationship.desire(target_relationship)
                elif action_type == 'accept':
                    if reverse_relationship.desired_relationship == \
                            target_relationship:
                        changing_relationship.set_relationship(
                            target_relationship)
                elif action_type == 'take back':
                    if changing_relationship.desired_relationship == \
                            target_relationship:
                        changing_relationship.desired_relationship = None
                        changing_relationship.save()
                elif action_type == 'refuse':
                    if reverse_relationship.desired_relationship == \
                            target_relationship:
                        reverse_relationship.desired_relationship = None
                        reverse_relationship.save()

            except organization.models.organization.Organization.DoesNotExist:
                pass

        elif self.capability.type == Capability.MILITARY_STANCE:
            try:
                target_organization = organization.models.organization.Organization.objects.get(
                    id=proposal['target_organization_id'])
                if 'region_id' in proposal.keys():
                    region = world.models.geography.Tile.objects.get(
                        id=proposal['region_id'])
                    target_stance = applying_to. \
                        get_region_stance_to(target_organization, region)
                else:
                    target_stance = applying_to. \
                        get_default_stance_to(target_organization)
                target_stance.stance_type = proposal.get('target_stance')
                target_stance.save()

                self.announce_execution(
                    'New military stance',
                    extra_context={'stance': target_stance})

            except (world.models.geography.Tile.DoesNotExist,
                    organization.models.organization.Organization.DoesNotExist
                    ):
                pass

        elif self.capability.type == Capability.BATTLE_FORMATION:
            try:
                formation = battle.models.BattleFormation.objects.get(
                    organization=applying_to, battle=None)
            except battle.models.BattleFormation.DoesNotExist:
                formation = battle.models.BattleFormation(
                    organization=applying_to, battle=None)
            formation.formation = proposal['formation']
            formation.spacing = proposal['spacing']
            formation.element_size = proposal['element_size']
            formation.save()

            self.announce_execution('New battle formation',
                                    {'formation': formation})

        elif self.capability.type == Capability.CONQUEST:
            try:
                tile = world.models.geography.Tile.objects.get(
                    id=proposal['tile_id'])
                if proposal['stop']:
                    tile_event = world.models.events.TileEvent.objects.get(
                        tile=tile,
                        organization=applying_to,
                        active=True,
                        type=world.models.events.TileEvent.CONQUEST,
                    )
                    tile_event.end_turn = applying_to. \
                        world.current_turn
                    tile_event.active = False
                    tile_event.save()
                    self.announce_execution('Occupation halted', {
                        'tile_event': tile_event,
                        'action': 'stop'
                    })
                else:
                    if tile in applying_to.conquestable_tiles():
                        tile_event = world.models.events.TileEvent.objects. \
                            create(
                            tile=tile,
                            type=world.models.events.TileEvent.CONQUEST,
                            organization=applying_to,
                            counter=0,
                            start_turn=applying_to.world.current_turn,
                            active=True
                        )
                        self.announce_execution('Occupation starts!', {
                            'tile_event': tile_event,
                            'action': 'start'
                        })

                        tile.world.broadcast(
                            'messaging/messages/conquest_start.html',
                            'Occupation', {'tile_event': tile_event},
                            tile.get_absolute_url())

            except (world.models.geography.Tile.DoesNotExist,
                    world.models.events.TileEvent.DoesNotExist):
                pass

        elif self.capability.type == Capability.GUILDS:
            try:
                settlement = world.models.geography.Settlement.objects.get(
                    id=proposal['settlement_id'])
                if ((settlement.tile in applying_to.get_all_controlled_tiles())
                        and (proposal['option'] in [
                            choice[0] for choice in
                            world.models.geography.Settlement.GUILDS_CHOICES
                        ])):
                    settlement.guilds_setting = proposal['option']
                    settlement.save()
                    self.announce_execution('Guilds change',
                                            {'settlement': settlement})
            except world.models.geography.Settlement.DoesNotExist:
                pass

        elif self.capability.type == Capability.HEIR:
            try:
                first_heir = character.models.Character.objects.get(
                    id=proposal['first_heir'])
                if (first_heir in applying_to.get_heir_candidates()
                        and first_heir != applying_to.get_position_occupier()):
                    applying_to.heir_first = first_heir
                    applying_to.save()

                    second_heir = None if proposal['second_heir'] == 0 else \
                        character.models.Character.objects.get(
                            id=proposal['second_heir']
                        )
                    if second_heir is None or (
                            second_heir in applying_to.get_heir_candidates()
                            and second_heir !=
                            applying_to.get_position_occupier()):
                        applying_to.heir_second = second_heir
                        applying_to.save()

                    message = self.announce_execution('New heir')
                    shortcuts.add_organization_recipient(
                        message, applying_to.get_violence_monopoly())

            except character.models.Character.DoesNotExist:
                pass

        else:
            raise Exception(
                "Executing unknown capability action_type '{}'".format(
                    self.capability.type))

        self.executed = True
        self.closed = True
        self.save()
예제 #16
0
    def post(self, request, *args, **kwargs):
        if not can_create_character(request.user):
            raise Http404()

        try:
            world_id = kwargs['world_id']
            world = World.objects.get(id=world_id)
        except World.DoesNotExist:
            messages.add_message(request, request.ERROR, "Invalid World")
            return redirect('world:create_character')

        try:
            state_id = request.POST.get('state_id')
            state = Organization.objects.get(id=state_id)
        except Organization.DoesNotExist:
            return self.fail_post_with_error(request, world_id,
                                             "Select a valid Realm")

        name = request.POST.get('name')
        surname = request.POST.get('surname')

        if name not in get_names() or surname not in get_surnames():
            return self.fail_post_with_error(request, world_id,
                                             "Select a valid name/surname")

        profile = request.POST.get('profile')
        if profile not in (choice[0] for choice in Character.PROFILE_CHOICES):
            return self.fail_post_with_error(request, world_id,
                                             "Select a valid profile")

        character = Character.objects.create(
            name=name + ' ' + surname,
            world=world,
            location=random.choice(
                Settlement.objects.filter(
                    tile__in=state.get_all_controlled_tiles())),
            oath_sworn_to=state if state.leader is None else state.leader,
            owner_user=request.user,
            cash=100,
            profile=profile)

        if character.profile == Character.TRADER:
            InventoryItem.objects.create(
                type=InventoryItem.CART,
                quantity=5,
                owner_character=character,
            )

        character.add_notification(
            'welcome',
            '<h4>Welcome, {char_name}!</h4>'
            '<p>'
            'You are starting as a member of {state_link}, a realm in '
            '<a href="{world_url}">{world_name}</a>.'
            '</p>'
            '<p>'
            'A good way to start your journey is to write a message '
            'to the other members of {state_link} asking for orders '
            'or guidance on how you can be useful.'
            '</p>'
            '<p>'
            'It is encouraged that you role play your character. This '
            'means that you should try to write in the voice of your '
            'character, {char_name}, an inhabitant of {world_name}, instead '
            'of your own, a person playing a computer game. You may want to '
            'come up with a simple past history of your '
            'character and presenting yourself to your realm. '
            'If you need to say something that your character would not say, '
            'you should prepend the letters OOC, meaning "out of character".'
            '</p>'
            ''.format(char_name=character.name,
                      state_link=state.get_html_link(),
                      world_url=world.get_absolute_url(),
                      world_name=world.name),
            safe=True)

        message = shortcuts.create_message(
            "{} just joined {}. Let's give a warm welcome!".format(
                character, state),
            world,
            "newcomer",
            link=character.get_absolute_url())
        shortcuts.add_organization_recipient(message, state)

        state.character_members.add(character)

        return redirect(character.activation_url)
예제 #17
0
    def execute(self):
        proposal = self.get_proposal_json_content()
        applying_to = self.capability.applying_to
        if self.capability.type == Capability.POLICY_DOCUMENT:
            try:
                if proposal['new']:
                    document = PolicyDocument(organization=applying_to)
                else:
                    document = PolicyDocument.objects.get(
                        id=proposal['document_id'])

                if proposal['delete']:
                    self.announce_execution(
                        "The document {} has been deleted".format(document),
                        "policy")
                    document.delete()
                else:
                    document.title = proposal.get('title')
                    document.body = proposal.get('body')
                    document.public = proposal.get('public') is not None
                    document.last_modified_turn = self.capability.\
                        organization.world.current_turn
                    document.save()

                    self.announce_execution(
                        ("A new document titled {} has been created"
                         if proposal['new'] else
                         "The document {} has been edited").format(document),
                        "policy",
                        link=document.get_absolute_url())

            except PolicyDocument.DoesNotExist:
                pass

        elif self.capability.type == Capability.BAN:
            try:
                character_to_ban = world.models.Character.objects.get(
                    id=proposal['character_id'])
                applying_to.remove_member(character_to_ban)
            except world.models.Character.DoesNotExist:
                pass

            self.announce_execution(
                "{} has been banned from {}".format(character_to_ban,
                                                    applying_to), 'ban')

        elif self.capability.type == Capability.CONVOKE_ELECTIONS:
            if applying_to.current_election is None:
                months_to_election = proposal['months_to_election']
                election = applying_to.convoke_elections(months_to_election)

        elif self.capability.type == Capability.DIPLOMACY:
            try:
                target_organization = Organization.objects.get(
                    id=proposal['target_organization_id'])
                target_relationship = proposal['target_relationship']
                changing_relationship = applying_to.\
                    get_relationship_to(target_organization)
                reverse_relationship = changing_relationship.reverse_relation()
                action_type = proposal['type']
                if action_type == 'propose':
                    changing_relationship.desire(target_relationship)
                elif action_type == 'accept':
                    if reverse_relationship.desired_relationship == \
                            target_relationship:
                        changing_relationship.set_relationship(
                            target_relationship)
                elif action_type == 'take back':
                    if changing_relationship.desired_relationship == \
                            target_relationship:
                        changing_relationship.desired_relationship = None
                        changing_relationship.save()
                elif action_type == 'refuse':
                    if reverse_relationship.desired_relationship == \
                            target_relationship:
                        reverse_relationship.desired_relationship = None
                        reverse_relationship.save()

            except Organization.DoesNotExist:
                pass

        elif self.capability.type == Capability.MILITARY_STANCE:
            try:
                target_organization = Organization.objects.get(
                    id=proposal['target_organization_id'])
                if 'region_id' in proposal.keys():
                    region = world.models.Tile.objects.get(
                        id=proposal['region_id'])
                    target_stance = applying_to.\
                        get_region_stance_to(target_organization, region)
                else:
                    target_stance = applying_to.\
                        get_default_stance_to(target_organization)
                target_stance.stance_type = proposal.get('target_stance')
                target_stance.save()

                self.announce_execution(
                    ("The general military stance of {from_} towards {to} "
                     "is now {stance}" if target_stance.region is None else
                     "The military stance of {from_} towards {to} "
                     "in {region} is now {stance}").format(
                         from_=target_stance.from_organization,
                         to=target_stance.to_organization,
                         stance=target_stance.get_stance_type_display(),
                         region=target_stance.region,
                     ), 'military stance')

            except (world.models.Tile.DoesNotExist, Organization.DoesNotExist):
                pass

        elif self.capability.type == Capability.BATTLE_FORMATION:
            try:
                formation = BattleFormation.objects.get(
                    organization=applying_to, battle=None)
            except BattleFormation.DoesNotExist:
                formation = BattleFormation(organization=applying_to,
                                            battle=None)
            formation.formation = proposal['formation']
            formation.spacing = proposal['spacing']
            formation.element_size = proposal['element_size']
            formation.save()

            self.announce_execution(
                "The battle formation of {} has been changed ({})".format(
                    applying_to, formation.formation), 'battle formation')

        elif self.capability.type == Capability.CONQUEST:
            try:
                tile = world.models.Tile.objects.get(id=proposal['tile_id'])
                if proposal['stop']:
                    tile_event = world.models.TileEvent.objects.get(
                        tile=tile,
                        organization=applying_to,
                        end_turn__isnull=True)
                    tile_event.end_turn = applying_to.\
                        world.current_turn
                    tile_event.save()
                else:
                    if tile in \
                            applying_to.conquestable_tiles():
                        world.models.TileEvent.objects.create(
                            tile=tile,
                            type=world.models.TileEvent.CONQUEST,
                            organization=applying_to,
                            counter=0,
                            start_turn=applying_to.world.current_turn)
                        tile.world.broadcast(
                            "{} has started conquering {}!".format(
                                applying_to, tile), 'conquest',
                            tile.get_absolute_url())
            except (world.models.Tile.DoesNotExist,
                    world.models.TileEvent.DoesNotExist):
                pass

        elif self.capability.type == Capability.GUILDS:
            try:
                settlement = world.models.Settlement.objects.get(
                    id=proposal['settlement_id'])
                if ((settlement.tile in applying_to.get_all_controlled_tiles())
                        and
                    (proposal['option'] in [
                        choice[0]
                        for choice in world.models.Settlement.GUILDS_CHOICES
                    ])):
                    settlement.guilds_setting = proposal['option']
                    settlement.save()
                    self.announce_execution(
                        "{} in {}".format(
                            settlement.get_guilds_setting_display(),
                            settlement), 'guilds',
                        settlement.tile.get_absolute_url())
            except world.models.Settlement.DoesNotExist:
                pass

        elif self.capability.type == Capability.HEIR:
            try:
                first_heir = world.models.Character.objects.get(
                    id=proposal['first_heir'])
                if (first_heir in applying_to.get_heir_candidates()
                        and first_heir != applying_to.get_position_occupier()):
                    applying_to.heir_first = first_heir
                    applying_to.save()

                    second_heir = None if proposal['second_heir'] == 0 else \
                        world.models.Character.objects.get(
                            id=proposal['second_heir']
                        )
                    if second_heir is None or (
                            second_heir in applying_to.get_heir_candidates()
                            and second_heir !=
                            applying_to.get_position_occupier()):
                        applying_to.heir_second = second_heir
                        applying_to.save()

                    message_content = "{} is now the heir of {}.".format(
                        applying_to.heir_first, applying_to)
                    if applying_to.heir_second:
                        message_content += " {} is the second in the line of" \
                                           "succession".format(
                                                applying_to.heir_second
                                            )
                    message = shortcuts.create_message(
                        message_content,
                        applying_to.world,
                        'heir',
                        link=applying_to.get_absolute_url())
                    shortcuts.add_organization_recipient(
                        message, applying_to.get_violence_monopoly())

            except world.models.Character.DoesNotExist:
                pass

        else:
            raise Exception(
                "Executing unknown capability action_type '{}'".format(
                    self.capability.type))

        self.executed = True
        self.closed = True
        self.save()
예제 #18
0
    def post(self, request, *args, **kwargs):
        if not can_create_character(request.user):
            raise Http404()

        try:
            world_id = kwargs['world_id']
            world = World.objects.get(id=world_id)
        except World.DoesNotExist:
            messages.add_message(request, request.ERROR, "Invalid World")
            return redirect('character:create')

        try:
            state_id = request.POST.get('state_id')
            state = Organization.objects.get(id=state_id)
        except Organization.DoesNotExist:
            return self.fail_post_with_error(request, world_id,
                                             "Select a valid Realm")

        name = request.POST.get('name')
        surname = request.POST.get('surname')

        if name not in get_names() or surname not in get_surnames():
            return self.fail_post_with_error(request, world_id,
                                             "Select a valid name/surname")

        profile = request.POST.get('profile')
        if profile not in (choice[0] for choice in Character.PROFILE_CHOICES):
            return self.fail_post_with_error(request, world_id,
                                             "Select a valid profile")

        character = Character.objects.create(
            name=name + ' ' + surname,
            world=world,
            location=random.choice(
                Settlement.objects.filter(
                    tile__in=state.get_all_controlled_tiles())),
            oath_sworn_to=state if state.leader is None else state.leader,
            owner_user=request.user,
            cash=100,
            profile=profile)

        if character.profile == Character.TRADER:
            InventoryItem.objects.create(
                type=InventoryItem.CART,
                quantity=5,
                owner_character=character,
            )

        character.add_notification('messaging/messages/welcome.html',
                                   'Welcome, {}'.format(character), {
                                       'state': state,
                                       'character': character
                                   })

        if not state.barbaric:
            message = shortcuts.create_message(
                'messaging/messages/new_character.html',
                world,
                "New member", {
                    'character': character,
                    'organization': state
                },
                link=character.get_absolute_url())
            shortcuts.add_organization_recipient(message, state)

        state.character_members.add(character)

        return redirect(character.activation_url)