Beispiel #1
0
def hvisit(var, wrapper, message):
    """Entrance a player, converting them to your team."""
    if VISITED.get(wrapper.source):
        wrapper.send(messages["succubus_already_visited"].format(VISITED[wrapper.source]))
        return

    target = get_target(var, wrapper, re.split(" +", message)[0], not_self_message="succubus_not_self")
    if not target:
        return

    target = try_misdirection(var, wrapper.source, target)
    if try_exchange(var, wrapper.source, target):
        return

    VISITED[wrapper.source] = target
    PASSED.discard(wrapper.source)

    if target not in get_all_players(("succubus",)):
        ENTRANCED.add(target)
        wrapper.send(messages["succubus_target_success"].format(target))
    else:
        wrapper.send(messages["harlot_success"].format(target))

    if wrapper.source is not target:
        if target not in get_all_players(("succubus",)):
            target.send(messages["notify_succubus_target"].format(wrapper.source))
        else:
            target.send(messages["harlot_success"].format(wrapper.source))

        revt = Event("succubus_visit", {})
        revt.dispatch(var, wrapper.source, target)

    debuglog("{0} (succubus) VISIT: {1} ({2})".format(wrapper.source, target, get_main_role(target)))
Beispiel #2
0
def on_update_stats3(evt, var, player, mainrole, revealrole, allroles):
    # if this is a night death and we know for sure that wolves (and only wolves)
    # killed, then that kill cannot be traitor as long as they're in wolfchat.
    # check if the reason == "night_death", otherwise it's probably a chained death which
    # can be traitor even if only wolves killed, so we short-circuit there as well
    # TODO: luck/misdirection totem can leak info due to our short-circuit below this comment.
    # If traitor dies due to one of these totems, both traitor count and villager count is reduced by
    # 1. If traitor does not die, and no other roles can kill (no death totems), then traitor count is unchanged
    # and villager count is reduced by 1. We should make it so that both counts are reduced when
    # luck/misdirection are potentially in play.
    # FIXME: this doesn't check RESTRICT_WOLFCHAT to see if traitor was removed from wolfchat. If
    # they've been removed, they can be killed like normal so all this logic is meaningless.
    if "traitor" not in evt.data["possible"] or evt.params.reason != "night_death" or mainrole == "traitor":
        return
    if var.PHASE == "day" and var.GAMEPHASE == "night":
        mevt = Event("get_role_metadata", {})
        mevt.dispatch(var, "night_kills")
        nonwolf = 0
        total = 0
        for role, num in mevt.data.items():
            if role != "wolf":
                nonwolf += num
            total += num
        if nonwolf == 0:
            evt.data["possible"].discard("traitor")
            return
Beispiel #3
0
def hvisit(var, wrapper, message):
    """Visit a player. You will die if you visit a wolf or a target of the wolves."""

    if VISITED.get(wrapper.source):
        wrapper.pm(messages["harlot_already_visited"].format(VISITED[wrapper.source]))
        return
    target = get_target(var, wrapper, re.split(" +", message)[0], not_self_message="harlot_not_self")
    if not target:
        return

    target = try_misdirection(var, wrapper.source, target)
    if try_exchange(var, wrapper.source, target):
        return

    vrole = get_main_role(target)

    VISITED[wrapper.source] = target
    PASSED.discard(wrapper.source)

    wrapper.pm(messages["harlot_success"].format(target))
    if target is not wrapper.source:
        target.send(messages["harlot_success"].format(wrapper.source))
        revt = Event("harlot_visit", {})
        revt.dispatch(var, wrapper.source, target)

    debuglog("{0} (harlot) VISIT: {1} ({2})".format(wrapper.source, target, vrole))
Beispiel #4
0
def main():
    evt = Event("init", {})
    evt.dispatch()
    src.plog("Connecting to {0}:{1}{2}".format(botconfig.HOST, "+" if botconfig.USE_SSL else "", botconfig.PORT))
    cli = IRCClient(
                      {"privmsg": lambda *s: None,
                       "notice": lambda *s: None,
                       "": handler.unhandled},
                     host=botconfig.HOST,
                     port=botconfig.PORT,
                     authname=botconfig.USERNAME,
                     password=botconfig.PASS,
                     nickname=botconfig.NICK,
                     ident=botconfig.IDENT,
                     real_name=botconfig.REALNAME,
                     sasl_auth=botconfig.SASL_AUTHENTICATION,
                     server_pass=botconfig.SERVER_PASS,
                     use_ssl=botconfig.USE_SSL,
                     cert_verify=var.SSL_VERIFY,
                     cert_fp=var.SSL_CERTFP,
                     client_certfile=var.SSL_CERTFILE,
                     client_keyfile=var.SSL_KEYFILE,
                     cipher_list=var.SSL_CIPHERS,
                     tokenbucket=TokenBucket(var.IRC_TB_BURST, var.IRC_TB_DELAY, init=var.IRC_TB_INIT),
                     connect_cb=handler.connect_callback,
                     stream_handler=src.stream,
    )
    cli.mainLoop()
Beispiel #5
0
def immunize(var, wrapper, message):
    """Immunize a player, preventing them from turning into a wolf."""
    if not DOCTORS[wrapper.source]:
        wrapper.pm(messages["doctor_fail"])
        return

    target = get_target(var, wrapper, re.split(" +", message)[0], allow_self=True)
    if not target:
        return

    target = try_misdirection(var, wrapper.source, target)
    if try_exchange(var, wrapper.source, target):
        return

    doctor_evt = Event("doctor_immunize", {"message": "villager_immunized"})
    doctor_evt.dispatch(var, wrapper.source, target)

    wrapper.pm(messages["doctor_success"].format(target))

    target.send(messages["immunization_success"].format(messages[doctor_evt.data["message"]]))

    IMMUNIZED.add(target)
    DOCTORS[wrapper.source] -= 1
    remove_lycanthropy(var, target)
    remove_disease(var, target)

    debuglog("{0} (doctor) IMMUNIZE: {1} ({2})".format(wrapper.source, target, get_main_role(target)))
Beispiel #6
0
def vigilante_kill(cli, nick, chan, rest):
    """Kill someone at night, but you die too if they aren't a wolf or win stealer!"""
    victim = get_victim(cli, nick, re.split(" +",rest)[0], False)
    if not victim:
        return

    if victim == nick:
        pm(cli, nick, messages["no_suicide"])
        return

    orig = victim
    evt = Event("targeted_command", {"target": victim, "misdirection": True, "exchange": True})
    evt.dispatch(cli, var, "kill", nick, victim, frozenset({"detrimental"}))
    if evt.prevent_default:
        return
    victim = evt.data["target"]

    KILLS[nick] = victim
    PASSED.discard(nick)

    msg = messages["wolf_target"].format(orig)
    pm(cli, nick, messages["player"].format(msg))

    debuglog("{0} ({1}) KILL: {2} ({3})".format(nick, get_role(nick), victim, get_role(victim)))

    chk_nightdone(cli)
Beispiel #7
0
def on_transition_day_resolve_end(evt, var, victims):
    evt2 = Event("get_role_metadata", {})
    evt2.dispatch(var, "lycanthropy_role")
    for victim in victims:
        if victim in LYCANTHROPES and evt.data["killers"][victim] == ["@wolves"] and victim in evt.data["dead"]:
            vrole = get_main_role(victim)
            if vrole not in Wolf:
                new_role = "wolf"
                prefix = LYCANTHROPES[victim]
                if vrole in evt2.data:
                    if "role" in evt2.data[vrole]:
                        new_role = evt2.data[vrole]["role"]
                    if "prefix" in evt2.data[vrole]:
                        prefix = evt2.data[vrole]["prefix"]
                    for sec_role in evt2.data[vrole].get("secondary_roles", ()):
                        var.ROLES[sec_role].add(victim)
                        to_send = "{0}_{1}".format(sec_role.replace(" ", "_"), "simple" if victim.prefers_simple() else "notify")
                        victim.send(messages[to_send])
                        # FIXME: Not every role has proper message keys, such as shamans

                change_role(var, victim, vrole, new_role, message=prefix + "_turn")
                evt.data["howl"] += 1
                evt.data["novictmsg"] = False
                evt.data["dead"].remove(victim)
                evt.data["killers"][victim].remove("@wolves")
                del evt.data["message"][victim]

                debuglog("{0} ({1}) TURN {2}".format(victim, vrole, new_role))
Beispiel #8
0
def mode_change(cli, rawnick, chan, mode, *targets):
    """Update the channel and user modes whenever a mode change occurs.

    Ordering and meaning of arguments for a MODE change:

    0 - The IRCClient instance (like everywhere else)
    1 - The raw nick of the mode setter/actor
    2 - The channel (target) of the mode change
    3 - The mode changes
    * - The targets of the modes (if any)

    This takes care of properly updating all relevant users and the
    channel modes to make sure we remain internally consistent.

    """

    if chan == users.Bot.nick: # we only see user modes set to ourselves
        users.Bot.modes.update(mode)
        return

    if "!" not in rawnick:
        # Only sync modes if a server changed modes because
        # 1) human ops probably know better
        # 2) other bots might start a fight over modes
        # 3) recursion; we see our own mode changes.
        evt = Event("sync_modes", {})
        evt.dispatch(var)
        return

    actor = users._get(rawnick, allow_none=True) # FIXME
    target = channels.add(chan, cli)
    target.queue("mode_change", {"mode": mode, "targets": targets}, (var, actor, target))
Beispiel #9
0
def hunter_kill(cli, nick, chan, rest):
    """Kill someone once per game."""
    if nick in HUNTERS and nick not in KILLS:
        pm(cli, nick, messages["hunter_already_killed"])
        return
    victim = get_victim(cli, nick, re.split(" +",rest)[0], False)
    if not victim:
        return

    if victim == nick:
        pm(cli, nick, messages["no_suicide"])
        return

    orig = victim
    evt = Event("targeted_command", {"target": victim, "misdirection": True, "exchange": True})
    evt.dispatch(cli, var, "kill", nick, victim, frozenset({"detrimental"}))
    if evt.prevent_default:
        return
    victim = evt.data["target"]

    KILLS[nick] = victim
    HUNTERS.add(nick)
    PASSED.discard(nick)

    msg = messages["wolf_target"].format(orig)
    pm(cli, nick, messages["player"].format(msg))

    debuglog("{0} ({1}) KILL: {2} ({3})".format(nick, get_role(nick), victim, get_role(victim)))
    chk_nightdone(cli)
Beispiel #10
0
def dullahan_kill(cli, nick, chan, rest):
    """Kill someone at night as a dullahan until everyone on your list is dead."""
    if not TARGETS[nick] & set(list_players()):
        pm(cli, nick, messages["dullahan_targets_dead"])
        return

    victim = get_victim(cli, nick, re.split(" +",rest)[0], False)
    if not victim:
        return

    if victim == nick:
        pm(cli, nick, messages["no_suicide"])
        return

    orig = victim
    evt = Event("targeted_command", {"target": victim, "misdirection": True, "exchange": True})
    evt.dispatch(cli, var, "kill", nick, victim, frozenset({"detrimental"}))
    if evt.prevent_default:
        return
    victim = evt.data["target"]

    KILLS[nick] = victim

    msg = messages["wolf_target"].format(orig)
    pm(cli, nick, messages["player"].format(msg))

    debuglog("{0} ({1}) KILL: {2} ({3})".format(nick, get_role(nick), victim, get_role(victim)))

    chk_nightdone(cli)
Beispiel #11
0
def see(var, wrapper, message):
    """Use your paranormal powers to determine the role or alignment of a player."""
    if wrapper.source in SEEN:
        wrapper.send(messages["seer_fail"])
        return

    target = get_target(var, wrapper, re.split(" +", message)[0], not_self_message="no_see_self")
    if target is None:
        return

    target = try_misdirection(var, wrapper.source, target)
    if try_exchange(var, wrapper.source, target):
        return

    targrole = get_main_role(target)
    trole = targrole # keep a copy for logging

    evt = Event("investigate", {"role": targrole})
    evt.dispatch(var, wrapper.source, target)
    targrole = evt.data["role"]

    aura = "blue"
    if targrole in Wolfteam:
        aura = "red"
    elif targrole in Neutral:
        aura = "grey"
    wrapper.send(messages["augur_success"].format(target, aura))
    debuglog("{0} (augur) SEE: {1} ({2}) as {3} ({4} aura)".format(wrapper.source, target, trole, targrole, aura))

    SEEN.add(wrapper.source)
Beispiel #12
0
def on_reconfigure_stats(evt, var, roleset, reason):
    from src.roles.helper.wolves import get_wolfchat_roles
    if reason != "howl" or not SCOPE:
        return

    evt2 = Event("get_role_metadata", {})
    evt2.dispatch(var, "lycanthropy_role")

    roles = {}

    wolfchat = get_wolfchat_roles(var)
    for role, count in roleset.items():
        if role in wolfchat or count == 0 or role not in SCOPE:
            continue
        if role in evt2.data and "role" in evt2.data[role]:
            roles[role] = evt2.data[role]["role"]
        else:
            roles[role] = "wolf"

    if roles and roleset in evt.data["new"]:
        evt.data["new"].remove(roleset)

    for role, new_role in roles.items():
        rs = roleset.copy()
        rs[role] -= 1
        rs[new_role] = rs.get(new_role, 0) + 1
        evt.data["new"].append(rs)
Beispiel #13
0
def consecrate(var, wrapper, message):
    """Consecrates a corpse, putting its spirit to rest and preventing other unpleasant things from happening."""
    alive = get_players()
    targ = re.split(" +", message)[0]
    if not targ:
        wrapper.pm(messages["not_enough_parameters"])
        return

    dead = set(var.ALL_PLAYERS) - set(alive)
    target, _ = users.complete_match(targ, dead)
    if target is None:
        wrapper.pm(messages["consecrate_fail"].format(targ))
        return

    # we have a target, so mark them as consecrated, right now all this does is silence a VG for a night
    # but other roles that do stuff after death or impact dead players should have functionality here as well
    # (for example, if there was a role that could raise corpses as undead somethings, this would prevent that from working)
    # regardless if this has any actual effect or not, it still removes the priest from being able to vote

    evt = Event("consecrate", {})
    evt.dispatch(var, wrapper.source, target)

    wrapper.pm(messages["consecrate_success"].format(target))
    debuglog("{0} (priest) CONSECRATE: {1}".format(wrapper.source, target))
    add_absent(var, wrapper.source, "consecrating")
    from src.votes import chk_decision
    from src.wolfgame import chk_win
    if not chk_win():
        # game didn't immediately end due to marking as absent, see if we should force through a lynch
        chk_decision(var)
Beispiel #14
0
def try_lynch_immunity(var, user) -> bool:
    if user in IMMUNITY:
        reason = IMMUNITY[user].pop() # get a random reason
        evt = Event("lynch_immunity", {"immune": False})
        evt.dispatch(var, user, reason)
        return evt.data["immune"]

    return False
Beispiel #15
0
def wolf_can_kill(var, wolf):
    # a wolf can kill if wolves in general can kill, and the wolf is a Killer
    # this is a utility function meant to be used by other wolf role modules
    nevt = Event("wolf_numkills", {"numkills": 1, "message": ""})
    nevt.dispatch(var)
    num_kills = nevt.data["numkills"]
    if num_kills == 0:
        return False
    wolfroles = get_all_roles(wolf)
    return bool(Wolf & Killer & wolfroles)
Beispiel #16
0
 def remove_user(self, user):
     self.users.remove(user)
     for mode in Features["PREFIX"].values():
         if mode in self.modes:
             self.modes[mode].discard(user)
             if not self.modes[mode]:
                 del self.modes[mode]
     del user.channels[self]
     if not user.channels: # Only fire if the user left all channels
         event = Event("cleanup_user", {})
         event.dispatch(var, user)
Beispiel #17
0
def remove_all_protections(var, target, attacker, attacker_role, reason, scope=All):
    """Remove all protections from a player."""
    if target not in PROTECTIONS:
        return

    for protector, entries in list(PROTECTIONS[target].items()):
        for cat, protector_role in entries:
            if scope & cat:
                evt = Event("remove_protection", {"remove": False})
                evt.dispatch(var, target, attacker, attacker_role, protector, protector_role, reason)
                if evt.data["remove"]:
                    PROTECTIONS[target][protector].remove((cat, protector_role))
Beispiel #18
0
    def wolf_kill(var, wrapper, message):
        """Kill one or more players as a wolf."""
        pieces = re.split(" +", message)
        targets = []
        orig = []

        nevt = Event("wolf_numkills", {"numkills": 1, "message": ""})
        nevt.dispatch(var)
        num_kills = nevt.data["numkills"]

        if not num_kills:
            if nevt.data["message"]:
                wrapper.pm(messages[nevt.data["message"]])
            return

        if len(pieces) < num_kills:
            wrapper.pm(messages["wolf_must_target_multiple"])
            return

        for targ in pieces[:num_kills]:
            target = get_target(var, wrapper, targ, not_self_message="no_suicide")
            if target is None:
                return

            if is_known_wolf_ally(var, wrapper.source, target):
                wrapper.pm(messages["wolf_no_target_wolf"])
                return

            if target in orig:
                wrapper.pm(messages["wolf_must_target_multiple"])
                return

            orig.append(target)
            target = try_misdirection(var, wrapper.source, target)
            if try_exchange(var, wrapper.source, target):
                return

            targets.append(target)

        KILLS[wrapper.source] = UserList(targets)

        if len(orig) > 1:
            # TODO: Expand this so we can support arbitrarily many kills (instead of just one or two)
            wrapper.pm(messages["player_kill_multiple"].format(*orig))
            msg = messages["wolfchat_kill_multiple"].format(wrapper.source, *orig)
            debuglog("{0} ({1}) KILL: {2} ({4}) and {3} ({5})".format(wrapper.source, rolename, *targets, get_main_role(targets[0]), get_main_role(targets[1])))
        else:
            wrapper.pm(messages["player_kill"].format(orig[0]))
            msg = messages["wolfchat_kill"].format(wrapper.source, orig[0])
            debuglog("{0} ({1}) KILL: {2} ({3})".format(wrapper.source, rolename, targets[0], get_main_role(targets[0])))

        send_wolfchat_message(var, wrapper.source, msg, Wolf, role=rolename, command="kill")
Beispiel #19
0
def on_chk_nightdone2(evt, var):
    if not evt.prevent_default:
        nevt = Event("wolf_numkills", {"numkills": 1})
        nevt.dispatch(var)
        num_kills = nevt.data["numkills"]
        wofls = [x for x in get_players(CAN_KILL) if x.nick not in var.SILENCED]
        if num_kills == 0 or len(wofls) == 0:
            return
        # flatten KILLS
        kills = set()
        for ls in KILLS.values():
            kills.update(ls)
        # check if wolves are actually agreeing
        if len(kills) != num_kills:
            evt.data["actedcount"] -= 1
Beispiel #20
0
def complete_role(var, role):
    from src.cats import ROLES
    if role not in ROLES:
        special_keys = {"lover"}
        evt = Event("get_role_metadata", {})
        evt.dispatch(var, "special_keys")
        special_keys = functools.reduce(lambda x, y: x | y, evt.data.values(), special_keys)
        if role.lower() in var.ROLE_ALIASES:
            matches = (var.ROLE_ALIASES[role.lower()],)
        else:
            matches = complete_match(role, ROLES.keys() | special_keys)
        if not matches:
            return []
        return matches
    return [role]
Beispiel #21
0
def who_reply(cli, bot_server, bot_nick, chan, ident, host, server, nick, status, hopcount_gecos):
    """Handle WHO replies for servers without WHOX support.

    Ordering and meaning of arguments for a bare WHO response:

    0 - The IRCClient instance (like everywhere else)
    1 - The server the requester (i.e. the bot) is on
    2 - The nickname of the requester (i.e. the bot)
    3 - The channel the request was made on
    4 - The ident of the user in this reply
    5 - The hostname of the user in this reply
    6 - The server the user in this reply is on
    7 - The nickname of the user in this reply
    8 - The status (H = Not away, G = Away, * = IRC operator, @ = Opped in the channel in 4, + = Voiced in the channel in 4)
    9 - The hop count and realname (gecos)

    This fires off the "who_result" event, and dispatches it with three
    arguments, the game state namespace, a Channel, and a User. Less
    important attributes can be accessed via the event.params namespace.

    """

    hop, realname = hopcount_gecos.split(" ", 1)
    hop = int(hop)
    # We throw away the information about the operness of the user, but we probably don't need to care about that
    # We also don't directly pass which modes they have, since that's already on the channel/user
    is_away = ("G" in status)

    modes = {Features["PREFIX"].get(s) for s in status} - {None}

    user = users._add(cli, nick=nick, ident=ident, host=host, realname=realname) # FIXME
    ch = None
    if not channels.predicate(chan): # returns True if it's not a channel
        ch = channels.add(chan, cli)

        if ch not in user.channels:
            user.channels[ch] = modes
            ch.users.add(user)
            for mode in modes:
                if mode not in ch.modes:
                    ch.modes[mode] = set()
                ch.modes[mode].add(user)

    event = Event("who_result", {}, away=is_away, data=0, ip_address=None, server=server, hop_count=hop, idle_time=None, extended_who=False)
    event.dispatch(var, ch, user)

    if ch is channels.Main and not users.exists(nick): # FIXME
        users.add(nick, ident=ident, host=host, account="*", inchan=True, modes=modes, moded=set())
Beispiel #22
0
def on_del_player(evt, var, user, mainrole, allroles, death_triggers):
    for h, v in list(KILLS.items()):
        if v is user:
            h.send(messages["hunter_discard"])
            del KILLS[h]
        elif h is user:
            del KILLS[h]
    if death_triggers and "dullahan" in allroles:
        pl = evt.data["pl"]
        targets = TARGETS[user].intersection(users._get(x) for x in pl) # FIXME
        if targets:
            target = random.choice(list(targets))
            prots = deque(var.ACTIVE_PROTECTIONS[target.nick])
            aevt = Event("assassinate", {"pl": evt.data["pl"], "target": target},
                    del_player=evt.params.del_player,
                    deadlist=evt.params.deadlist,
                    original=evt.params.original,
                    refresh_pl=evt.params.refresh_pl,
                    message_prefix="dullahan_die_",
                    source="dullahan",
                    killer=user.nick,
                    killer_mainrole=mainrole,
                    killer_allroles=allroles,
                    prots=prots)
            while len(prots) > 0:
                # an event can read the current active protection and cancel or redirect the assassination
                # if it cancels, it is responsible for removing the protection from var.ACTIVE_PROTECTIONS
                # so that it cannot be used again (if the protection is meant to be usable once-only)
                if not aevt.dispatch(user.client, var, user.nick, target.nick, prots[0]):
                    evt.data["pl"] = aevt.data["pl"]
                    if target is not aevt.data["target"]:
                        target = aevt.data["target"]
                        prots = deque(var.ACTIVE_PROTECTIONS[target.nick])
                        aevt.params.prots = prots
                        continue
                    return
                prots.popleft()

            target = target.nick # FIXME
            if var.ROLE_REVEAL in ("on", "team"):
                role = get_reveal_role(target)
                an = "n" if role.startswith(("a", "e", "i", "o", "u")) else ""
                channels.Main.send(messages["dullahan_die_success"].format(user, target, an, role))
            else:
                channels.Main.send(messages["dullahan_die_success_noreveal"].format(user, target))
            debuglog("{0} (dullahan) DULLAHAN ASSASSINATE: {1} ({2})".format(user, target, get_role(target)))
            evt.params.del_player(user.client, target, True, end_game=False, killer_role="dullahan", deadlist=evt.params.deadlist, original=evt.params.original, ismain=False)
            evt.data["pl"] = evt.params.refresh_pl(pl)
Beispiel #23
0
def on_del_player(evt, var, player, mainrole, allroles, death_triggers):
    if player in TARGETED.values():
        for x, y in list(TARGETED.items()):
            if y is player:
                del TARGETED[x]

    if death_triggers and "assassin" in allroles and player in TARGETED:
        target = TARGETED[player]
        del TARGETED[player]
        if target in evt.data["pl"]:
            prots = deque(var.ACTIVE_PROTECTIONS[target.nick])
            aevt = Event("assassinate", {"pl": evt.data["pl"], "target": target},
                del_player=evt.params.del_player,
                deadlist=evt.params.deadlist,
                original=evt.params.original,
                refresh_pl=evt.params.refresh_pl,
                message_prefix="assassin_fail_",
                source="assassin",
                killer=player,
                killer_mainrole=mainrole,
                killer_allroles=allroles,
                prots=prots)

            while len(prots) > 0:
                # an event can read the current active protection and cancel the assassination
                # if it cancels, it is responsible for removing the protection from var.ACTIVE_PROTECTIONS
                # so that it cannot be used again (if the protection is meant to be usable once-only)
                if not aevt.dispatch(var, player, target, prots[0]):
                    pl = aevt.data["pl"]
                    if target is not aevt.data["target"]:
                        target = aevt.data["target"]
                        prots = deque(var.ACTIVE_PROTECTIONS[target.nick])
                        aevt.params.prots = prots
                        continue
                    break
                prots.popleft()

            if not prots:
                if var.ROLE_REVEAL in ("on", "team"):
                    role = get_reveal_role(target)
                    an = "n" if role.startswith(("a", "e", "i", "o", "u")) else ""
                    message = messages["assassin_success"].format(player, target, an, role)
                else:
                    message = messages["assassin_success_no_reveal"].format(player, target)
                channels.Main.send(message)
                debuglog("{0} (assassin) ASSASSINATE: {1} ({2})".format(player, target, get_main_role(target)))
                evt.params.del_player(target, end_game=False, killer_role=mainrole, deadlist=evt.params.deadlist, original=evt.params.original, ismain=False)
                evt.data["pl"] = evt.params.refresh_pl(aevt.data["pl"])
Beispiel #24
0
def on_role_assignment(evt, var, gamemode, pl):
    # assign random targets to dullahan to kill
    if var.ROLES["dullahan"]:
        max_targets = math.ceil(8.1 * math.log(len(pl), 10) - 5)
        for dull in var.ROLES["dullahan"]:
            TARGETS[dull] = UserSet()
        dull_targets = Event("dullahan_targets", {"targets": TARGETS}) # support sleepy
        dull_targets.dispatch(var, var.ROLES["dullahan"], max_targets)

        for dull, ts in TARGETS.items():
            ps = pl[:]
            ps.remove(dull)
            while len(ts) < max_targets:
                target = random.choice(ps)
                ps.remove(target)
                ts.add(target)
Beispiel #25
0
def add_lycanthropy(var, target, prefix="lycan"):
    """Effect the target with lycanthropy. Fire the add_lycanthropy event."""
    if target in LYCANTHROPES:
        return

    if target in get_players() and Event("add_lycanthropy", {}).dispatch(var, target):
        LYCANTHROPES[target] = prefix
Beispiel #26
0
def end_who(cli, bot_server, bot_nick, target, rest):
    """Handle the end of WHO/WHOX responses from the server.

    Ordering and meaning of arguments for the end of a WHO/WHOX request:

    0 - The IRCClient instance (like everywhere else)
    1 - The server the requester (i.e. the bot) is on
    2 - The nickname of the requester (i.e. the bot)
    3 - The target the request was made against
    4 - A string containing some information; traditionally "End of /WHO list."

    This fires off the "who_end" event, and dispatches it with one
    argument: The channel or user the request was made to, or None
    if it could not be resolved.

    """

    try:
        target = channels.get(target)
    except KeyError:
        try:
            target = users.get(target)
        except KeyError:
            target = None
    else:
        target.dispatch_queue()

    old = _who_old.get(target.name, target)
    _who_old.clear()
    Event("who_end", {}, old=old).dispatch(target)
Beispiel #27
0
def on_role_assignment(evt, cli, var, gamemode, pl, restart):
    # assign random targets to dullahan to kill
    if var.ROLES["dullahan"]:
        max_targets = math.ceil(8.1 * math.log(len(pl), 10) - 5)
        for dull in var.ROLES["dullahan"]:
            TARGETS[dull] = set()
        dull_targets = Event("dullahan_targets", {"targets": TARGETS}) # support sleepy
        dull_targets.dispatch(cli, var, var.ROLES["dullahan"], max_targets)

        for dull, ts in TARGETS.items():
            ps = pl[:]
            ps.remove(dull)
            while len(ts) < max_targets:
                target = random.choice(ps)
                ps.remove(target)
                ts.add(target)
Beispiel #28
0
def add_disease(var, target):
    """Effect the target with disease. Fire the add_disease event."""
    if target in DISEASED or target not in get_players():
        return

    if Event("add_disease", {}).dispatch(var, target):
        DISEASED.add(target)
Beispiel #29
0
def see(var, wrapper, message):
    """Use your paranormal powers to determine the role or alignment of a player."""
    if wrapper.source in SEEN:
        wrapper.send(messages["seer_fail"])
        return

    target = get_target(var,
                        wrapper,
                        re.split(" +", message)[0],
                        not_self_message="no_see_self")
    if target is None:
        return

    target = try_misdirection(var, wrapper.source, target)
    if try_exchange(var, wrapper.source, target):
        return

    targrole = get_main_role(target)
    trole = targrole  # keep a copy for logging

    for i in range(2):  # need to go through loop twice
        iswolf = False
        if targrole in Cursed:
            targrole = "wolf"
            iswolf = True
        elif targrole in Safe | Innocent:
            targrole = var.HIDDEN_ROLE
        elif targrole in Wolf:
            targrole = "wolf"
            iswolf = True
        else:
            targrole = var.HIDDEN_ROLE

        if i:
            break

        evt = Event("see", {"role": targrole})
        evt.dispatch(var, wrapper.source, target)
        targrole = evt.data["role"]

    wrapper.send(messages["oracle_success"].format(
        target, "" if iswolf else "\u0002not\u0002 ",
        "\u0002" if iswolf else ""))
    debuglog("{0} (oracle) SEE: {1} ({2}) (Wolf: {3})".format(
        wrapper.source, target, trole, str(iswolf)))

    SEEN.add(wrapper.source)
Beispiel #30
0
    def transition_night_begin(self, evt, var):
        # don't do this n1
        if var.NIGHT_COUNT == 1:
            return
        villagers = get_players()
        lpl = len(villagers)
        addroles = self._role_attribution(var, villagers, False)

        # shameless copy/paste of regular role attribution
        for role, rs in var.ROLES.items():
            if role in self.SECONDARY_ROLES:
                continue
            rs.clear()
        # prevent wolf.py from sending messages about a new wolf to soon-to-be former wolves
        # (note that None doesn't work, so "player" works fine)
        for player in var.MAIN_ROLES:
            var.MAIN_ROLES[player] = "player"
        new_evt = Event("new_role", {
            "messages": [],
            "role": None,
            "in_wolfchat": False
        },
                        inherit_from=None)
        for role, count in addroles.items():
            selected = random.sample(villagers, count)
            for x in selected:
                villagers.remove(x)
                new_evt.data["role"] = role
                new_evt.dispatch(var, x, var.ORIGINAL_MAIN_ROLES[x])
                var.ROLES[new_evt.data["role"]].add(x)

        # for end of game stats to show what everyone ended up as on game end
        for role, pl in var.ROLES.items():
            if role in self.SECONDARY_ROLES:
                continue
            for p in pl:
                # discard them from all non-secondary roles, we don't have a reliable
                # means of tracking their previous role (due to traitor turning, exchange
                # totem, etc.), so we need to iterate through everything.
                for r in var.ORIGINAL_ROLES.keys():
                    if r in self.SECONDARY_ROLES:
                        continue
                    var.ORIGINAL_ROLES[r].discard(p)
                var.ORIGINAL_ROLES[role].add(p)
                var.FINAL_ROLES[p] = role
                var.MAIN_ROLES[p] = role
                var.ORIGINAL_MAIN_ROLES[p] = role
Beispiel #31
0
def see(cli, nick, chan, rest):
    """Use your paranormal senses to determine a player's doom."""
    role = get_role(nick)
    if nick in SEEN:
        pm(cli, nick, messages["seer_fail"])
        return
    victim = get_victim(cli, nick, re.split(" +", rest)[0], False)
    if not victim:
        return

    if victim == nick:
        pm(cli, nick, messages["no_see_self"])
        return
    if in_wolflist(nick, victim):
        pm(cli, nick, messages["no_see_wolf"])
        return

    doomsayer = users._get(nick)  # FIXME
    target = users._get(victim)  # FIXME

    evt = Event("targeted_command", {
        "target": target,
        "misdirection": True,
        "exchange": True
    })
    evt.dispatch(var, "see", doomsayer, target,
                 frozenset({"detrimental", "immediate"}))
    if evt.prevent_default:
        return
    victim = evt.data["target"].nick
    victimrole = get_role(victim)

    mode, mapping = random.choice(_mappings)
    pm(cli, nick, messages["doomsayer_{0}".format(mode)].format(victim))
    if mode != "sick" or nick not in var.IMMUNIZED:
        mapping[nick] = victim

    debuglog("{0} ({1}) SEE: {2} ({3}) - {4}".format(nick, role, victim,
                                                     victimrole, mode.upper()))
    relay_wolfchat_command(cli,
                           nick,
                           messages["doomsayer_wolfchat"].format(nick, victim),
                           ("doomsayer", ),
                           is_wolf_command=True)

    SEEN.add(nick)
Beispiel #32
0
def get_role(p):
    for role, pl in var.ROLES.items():
        if role in var.TEMPLATE_RESTRICTIONS.keys():
            continue  # only get actual roles
        if p in pl:
            return role
    # not found in player list, see if they're a special participant
    role = None
    if p in list_participants():
        evt = Event("get_participant_role", {"role": None})
        evt.dispatch(var, p)
        role = evt.data["role"]
    if role is None:
        raise ValueError(
            "Nick {0} isn't playing and has no defined participant role".
            format(p))
    return role
Beispiel #33
0
def who_reply(cli, bot_server, bot_nick, chan, ident, host, server, nick,
              status, hopcount_gecos):
    """Handle WHO replies for servers without WHOX support.

    Ordering and meaning of arguments for a bare WHO response:

    0 - The IRCClient instance (like everywhere else)
    1 - The server the requester (i.e. the bot) is on
    2 - The nickname of the requester (i.e. the bot)
    3 - The channel the request was made on
    4 - The ident of the user in this reply
    5 - The hostname of the user in this reply
    6 - The server the user in this reply is on
    7 - The nickname of the user in this reply
    8 - The status (H = Not away, G = Away, * = IRC operator, @ = Opped in the channel in 4, + = Voiced in the channel in 4)
    9 - The hop count and realname (gecos)

    This fires off the "who_result" event, and dispatches it with two
    arguments, a Channel and a User. Less important attributes can be
    accessed via the event.params namespace.

    """

    hop, realname = hopcount_gecos.split(" ", 1)
    # We throw away the information about the operness of the user, but we probably don't need to care about that
    # We also don't directly pass which modes they have, since that's already on the channel/user
    is_away = ("G" in status)

    modes = {Features["PREFIX"].get(s) for s in status} - {None}

    user = users.get(nick, ident, host, allow_bot=True, allow_none=True)
    if user is None:
        user = users.add(cli, nick=nick, ident=ident, host=host)

    ch = channels.get(chan, allow_none=True)
    if ch is not None and ch not in user.channels:
        user.channels[ch] = modes
        ch.users.add(user)
        for mode in modes:
            if mode not in ch.modes:
                ch.modes[mode] = set()
            ch.modes[mode].add(user)

    _who_old[user.nick] = user
    event = Event("who_result", {}, away=is_away, data=0, old=user)
    event.dispatch(ch, user)
Beispiel #34
0
def complete_role(var,
                  role: str,
                  remove_spaces: bool = False,
                  allow_special: bool = True) -> List[str]:
    """ Match a partial role or alias name into the internal role key.

    :param var: Game state
    :param role: Partial role to match on
    :param remove_spaces: Whether or not to remove all spaces before matching.
        This is meant for contexts where we truly cannot allow spaces somewhere; otherwise we should
        prefer that the user matches including spaces where possible for friendlier-looking commands.
    :param allow_special: Whether to allow special keys (lover, vg activated, etc.)
    :return: A list of 0 elements if the role didn't match anything.
        A list with 1 element containing the internal role key if the role matched unambiguously.
        A list with 2 or more elements containing localized role or alias names if the role had ambiguous matches.
    """
    from src.cats import ROLES  # FIXME: should this be moved into cats? ROLES isn't declared in cats.__all__

    role = role.lower()
    if remove_spaces:
        role = role.replace(" ", "")

    role_map = messages.get_role_mapping(reverse=True,
                                         remove_spaces=remove_spaces)

    special_keys = set()
    if allow_special:
        evt = Event("get_role_metadata", {})
        evt.dispatch(var, "special_keys")
        special_keys = functools.reduce(lambda x, y: x | y, evt.data.values(),
                                        special_keys)

    matches = complete_match(role, role_map.keys())
    if not matches:
        return []

    # strip matches that don't refer to actual roles or special keys (i.e. refer to team names)
    filtered_matches = []
    allowed = ROLES.keys() | special_keys
    for match in matches:
        if role_map[match] in allowed:
            filtered_matches.append(match)

    if len(filtered_matches) == 1:
        return [role_map[filtered_matches[0]]]
    return filtered_matches
Beispiel #35
0
def get_role(p):
    # FIXME: make the arg a user instead of a nick
    from src import users
    user = users._get(p)
    role = var.MAIN_ROLES.get(user, None)
    if role is not None:
        return role
    # not found in player list, see if they're a special participant
    if p in list_participants():
        evt = Event("get_participant_role", {"role": None})
        evt.dispatch(var, user)
        role = evt.data["role"]
    if role is None:
        raise ValueError(
            "User {0} isn't playing and has no defined participant role".
            format(user))
    return role
Beispiel #36
0
def kill_players(var, *, end_game: bool = True) -> bool:
    """
    Kill all players marked as dying.

    This function is not re-entrant; do not call it inside of a del_player or kill_players event listener.
    This function does not print anything to the channel; code which calls add_dying should print things as appropriate.

    :param var: The game state
    :param end_game: Whether or not to check for win conditions and perform state transitions (temporary)
    :returns: True if the game is ending (temporary)
    """
    t = time.time()

    with var.GRAVEYARD_LOCK: # FIXME
        if not var.GAME_ID or var.GAME_ID > t:
            #  either game ended, or a new game has started
            return

        dead = set()

        while DYING:
            player, (killer_role, reason, death_triggers) = DYING.popitem()
            main_role = get_main_role(player)
            reveal_role = get_reveal_role(player)
            all_roles = get_all_roles(player)
            # kill them off
            del var.MAIN_ROLES[player]
            for role in all_roles:
                var.ROLES[role].remove(player)
            dead.add(player)
            var.DEAD.add(player)
            # notify listeners that the player died for possibility of chained deaths
            evt = Event("del_player", {},
                        killer_role=killer_role,
                        main_role=main_role,
                        reveal_role=reveal_role,
                        reason=reason)
            evt_death_triggers = death_triggers and var.PHASE in var.GAME_PHASES
            evt.dispatch(var, player, all_roles, evt_death_triggers)

        # notify listeners that all deaths have resolved
        # FIXME: end_game is a temporary hack until we move state transitions into the event loop
        # (priority 10 listener sets prevent_default if end_game=True and game is ending; that's another temporary hack)
        # Once hacks are removed, this function will not have any return value and the end_game kwarg will go away
        evt = Event("kill_players", {}, end_game=end_game)
        return not evt.dispatch(var, dead)
Beispiel #37
0
def hvisit(var, wrapper, message):
    """Entrance a player, converting them to your team."""
    if VISITED.get(wrapper.source):
        wrapper.send(messages["succubus_already_visited"].format(VISITED[wrapper.source]))
        return

    target = get_target(var, wrapper, re.split(" +", message)[0], not_self_message="succubus_not_self")
    if not target:
        return

    evt = Event("targeted_command", {"target": target, "misdirection": True, "exchange": True})
    if not evt.dispatch(var, wrapper.source, target):
        return
    target = evt.data["target"]

    VISITED[wrapper.source] = target
    PASSED.discard(wrapper.source)

    if target not in get_all_players(("succubus",)):
        ENTRANCED.add(target)
        wrapper.send(messages["succubus_target_success"].format(target))
    else:
        wrapper.send(messages["harlot_success"].format(target))

    if wrapper.source is not target:
        if target not in get_all_players(("succubus",)):
            target.send(messages["notify_succubus_target"].format(wrapper.source))
        else:
            target.send(messages["harlot_success"].format(wrapper.source))

        revt = Event("succubus_visit", {})
        revt.dispatch(var, wrapper.source, target)

    debuglog("{0} (succubus) VISIT: {1} ({2})".format(wrapper.source, target, get_main_role(target)))
Beispiel #38
0
def immunize(var, wrapper, message):
    """Immunize a player, preventing them from turning into a wolf."""
    if not DOCTORS[wrapper.source]:
        wrapper.pm(messages["doctor_fail"])
        return

    target = get_target(var, wrapper, re.split(" +", message)[0], allow_self=True)
    if not target:
        return

    evt = Event("targeted_command", {"target": target, "misdirection": True, "exchange": True})
    if not evt.dispatch(var, wrapper.source, target):
        return

    target = evt.data["target"]

    doctor_evt = Event("doctor_immunize", {"message": "villager_immunized"})
    doctor_evt.dispatch(var, wrapper.source, target)

    wrapper.pm(messages["doctor_success"].format(target))

    target.send(messages["immunization_success"].format(messages[doctor_evt.data["message"]]))

    IMMUNIZED.add(target)
    DOCTORS[wrapper.source] -= 1
    status.remove_lycanthropy(var, target)
    status.remove_disease(var, target)

    debuglog("{0} (doctor) IMMUNIZE: {1} ({2})".format(wrapper.source, target, get_main_role(target)))
Beispiel #39
0
def hvisit(var, wrapper, message):
    """Entrance a player, converting them to your team."""
    if VISITED.get(wrapper.source):
        wrapper.send(messages["succubus_already_visited"].format(VISITED[wrapper.source]))
        return

    target = get_target(var, wrapper, re.split(" +", message)[0], not_self_message="succubus_not_self")

    if not target:
        return

    evt = Event("targeted_command", {"target": target, "misdirection": True, "exchange": False})
    evt.dispatch(var, "visit", wrapper.source, target, frozenset({"detrimental", "immediate"}))
    if evt.prevent_default:
        return
    target = evt.data["target"]

    VISITED[wrapper.source] = target
    PASSED.discard(wrapper.source)

    if target not in get_all_players(("succubus",)):
        ENTRANCED.add(target)
        wrapper.send(messages["succubus_target_success"].format(target))
    else:
        wrapper.send(messages["harlot_success"].format(target))

    if wrapper.source is not target:
        if target not in get_all_players(("succubus",)):
            target.send(messages["notify_succubus_target"].format(wrapper.source))
        else:
            target.send(messages["harlot_success"].format(wrapper.source))

        revt = Event("succubus_visit", {})
        revt.dispatch(var, wrapper.source, target)

        # TODO: split these into assassin, hag, and alpha wolf when they are split off
        if users._get(var.TARGETED.get(target.nick), allow_none=True) in get_all_players(("succubus",)): # FIXME
            msg = messages["no_target_succubus"].format(var.TARGETED[target.nick])
            del var.TARGETED[target.nick]
            if target in get_all_players(("village drunk",)):
                victim = random.choice(list(get_all_players() - get_all_players(("succubus",)) - {target}))
                msg += messages["drunk_target"].format(victim)
                var.TARGETED[target.nick] = victim.nick
            target.send(msg)

        if target.nick in var.HEXED and users._get(var.LASTHEXED[target.nick]) in get_all_players(("succubus",)): # FIXME
            target.send(messages["retract_hex_succubus"].format(var.LASTHEXED[target.nick]))
            var.TOBESILENCED.remove(wrapper.source.nick)
            var.HEXED.remove(target.nick)
            del var.LASTHEXED[target.nick]
        if users._get(var.BITE_PREFERENCES.get(target.nick), allow_none=True) in get_all_players(("succubus",)): # FIXME
            target.send(messages["no_kill_succubus"].format(var.BITE_PREFERENCES[target.nick]))
            del var.BITE_PREFERENCES[target.nick]

    debuglog("{0} (succubus) VISIT: {1} ({2})".format(wrapper.source, target, get_main_role(target)))
Beispiel #40
0
def on_transition_night_end(evt, var):
    wolves = get_players(Wolfchat)
    # roles allowed to talk in wolfchat
    talkroles = get_talking_roles(var)
    # condition imposed on talking in wolfchat (only during day/night, or no talking)
    # 0 = no talking
    # 1 = normal
    # 2 = only during day
    # 3 = only during night
    wccond = 1

    if var.RESTRICT_WOLFCHAT & var.RW_DISABLE_NIGHT:
        if var.RESTRICT_WOLFCHAT & var.RW_DISABLE_DAY:
            wccond = 0
        else:
            wccond = 2
    elif var.RESTRICT_WOLFCHAT & var.RW_DISABLE_DAY:
        wccond = 3

    cursed = get_all_players(("cursed villager", ))
    for wolf in wolves:
        role = get_main_role(wolf)
        msg = "{0}_notify".format(role.replace(
            " ", "_"))  # FIXME: Split into each role file

        wolf.send(messages[msg])

        if len(wolves) > 1 and role in talkroles:
            wolf.send(messages["wolfchat_notify_{0}".format(wccond)])

        if wolf in cursed:
            wolf.send(messages["cursed_notify"])

        if wolf not in KNOWS_MINIONS:
            minions = len(get_all_players(("minion", )))
            if minions > 0:
                wolf.send(messages["has_minions"].format(minions))
            KNOWS_MINIONS.add(wolf)

        wolf.send(messages["players_list"].format(get_wolflist(var, wolf)))
        nevt = Event("wolf_numkills", {"numkills": 1, "message": ""})
        nevt.dispatch(var)
        if role in Wolf & Killer and not nevt.data["numkills"] and nevt.data[
                "message"]:
            wolf.send(messages[nevt.data["message"]])
Beispiel #41
0
def on_transition_night_end(evt, var):
    chances = var.CURRENT_GAMEMODE.TOTEM_CHANCES
    max_totems = sum(x["shaman"] for x in chances.values())
    ps = get_players()
    shamans = get_players(("shaman", ))
    for s in list(LASTGIVEN):
        if s not in shamans:
            del LASTGIVEN[s]

    shamans = list(shamans)
    random.shuffle(shamans)
    for shaman in shamans:
        pl = ps[:]
        random.shuffle(pl)
        for given in itertools.chain.from_iterable(LASTGIVEN[shaman].values()):
            if given in pl:
                pl.remove(given)

        target = 0
        rand = random.random() * max_totems
        for t in chances:
            target += chances[t]["shaman"]
            if rand <= target:
                TOTEMS[shaman] = {t: 1}
                break
        event = Event("totem_assignment", {"totems": TOTEMS[shaman]})
        event.dispatch(var, "shaman")
        TOTEMS[shaman] = event.data["totems"]

        num_totems = sum(TOTEMS[shaman].values())
        if shaman.prefers_simple():
            shaman.send(messages["shaman_simple"].format("shaman"))
        else:
            if num_totems > 1:
                shaman.send(
                    messages["shaman_notify_multiple_known"].format("shaman"))
            else:
                shaman.send(messages["shaman_notify"].format("shaman"))
        tmsg = totem_message(TOTEMS[shaman])
        if not shaman.prefers_simple():
            for totem in TOTEMS[shaman]:
                tmsg += " " + messages[totem + "_totem"]
        shaman.send(tmsg)
        shaman.send(messages["players_list"].format(", ".join(p.nick
                                                              for p in pl)))
Beispiel #42
0
def on_new_role(evt, var, player, old_role):
    if player in TARGETS and old_role == "dullahan" and evt.data["role"] != "dullahan":
        del KILLS[:player:]
        del TARGETS[player]

    if player not in TARGETS and evt.data["role"] == "dullahan":
        ps = get_players()
        max_targets = math.ceil(8.1 * math.log(len(ps), 10) - 5)
        TARGETS[player] = UserSet()

        dull_targets = Event("dullahan_targets", {"targets": TARGETS[player]}) # support sleepy
        dull_targets.dispatch(var, player, max_targets)

        ps.remove(player)
        while len(TARGETS[player]) < max_targets:
            target = random.choice(ps)
            ps.remove(target)
            TARGETS[player].add(target)
Beispiel #43
0
def on_new_role(evt, var, player, old_role):
    if player in TARGETS and old_role == "dullahan" and evt.data["role"] != "dullahan":
        del KILLS[:player:]
        del TARGETS[player]

    if player not in TARGETS and evt.data["role"] == "dullahan":
        ps = get_players()
        max_targets = math.ceil(8.1 * math.log(len(ps), 10) - 5)
        TARGETS[player] = UserSet()

        dull_targets = Event("dullahan_targets", {"targets": TARGETS[player]}) # support sleepy
        dull_targets.dispatch(var, player, max_targets)

        ps.remove(player)
        while len(TARGETS[player]) < max_targets:
            target = random.choice(ps)
            ps.remove(target)
            TARGETS[player].add(target)
Beispiel #44
0
def on_role_assignment(evt, cli, var, gamemode, pl, restart):
    # assign random targets to dullahan to kill
    if var.ROLES["dullahan"]:
        max_targets = math.ceil(8.1 * math.log(len(pl), 10) - 5)
        for dull in var.ROLES["dullahan"]:
            TARGETS[users._get(dull)] = set() # FIXME
        dull_targets = Event("dullahan_targets", {"targets": TARGETS}) # support sleepy
        dull_targets.dispatch(cli, var, {users._get(x) for x in var.ROLES["dullahan"]}, max_targets) # FIXME

        players = [users._get(x) for x in pl] # FIXME

        for dull, ts in TARGETS.items():
            ps = players[:]
            ps.remove(dull)
            while len(ts) < max_targets:
                target = random.choice(ps)
                ps.remove(target)
                ts.add(target)
Beispiel #45
0
def vigilante_kill(var, wrapper, message):
    """Kill someone at night, but you die too if they aren't a wolf or win stealer!"""

    target = get_target(var, wrapper, re.split(" +", message)[0], not_self_message="no_suicide")

    orig = target
    evt = Event("targeted_command", {"target": target, "misdirection": True, "exchange": True})
    evt.dispatch(var, "kill", wrapper.source, target, frozenset({"detrimental"}))
    if evt.prevent_default:
        return
    target = evt.data["target"]

    KILLS[wrapper.source] = target
    PASSED.discard(wrapper.source)

    wrapper.send(messages["player_kill"].format(orig))

    debuglog("{0} (vigilante) KILL: {1} ({2})".format(wrapper.source, target, get_main_role(target)))
Beispiel #46
0
def on_transition_night_end(evt, var):
    for ass in get_all_players(("assassin",)):
        if ass in TARGETED:
            continue # someone already targeted

        pl = get_players()
        random.shuffle(pl)
        pl.remove(ass)

        ass_evt = Event("assassin_target", {"target": None})
        ass_evt.dispatch(var, ass, pl)

        if ass_evt.data["target"] is not None:
            TARGETED[ass] = ass_evt.data["target"]
            PREV_ACTED.add(ass)
        else:
            ass.send(messages["assassin_notify"])
            ass.send(messages["players_list"].format(pl))
Beispiel #47
0
def on_transition_day_begin(evt, var):
    # select a random target for VG if they didn't kill
    wolves = set(get_players(var.WOLFTEAM_ROLES))
    villagers = set(get_players()) - wolves
    for ghost, target in GHOSTS.items():
        if target[0] == "!" or ghost.nick in var.SILENCED:
            continue
        if ghost not in KILLS:
            choice = set()
            if target == "wolves":
                choice = wolves.copy()
            elif target == "villagers":
                choice = villagers.copy()
            evt = Event("vg_kill", {"pl": choice})
            evt.dispatch(var, ghost, target)
            choice = evt.data["pl"]
            if choice:
                KILLS[ghost] = random.choice(list(choice))
Beispiel #48
0
def remove_all_protections(var,
                           target,
                           attacker,
                           attacker_role,
                           reason,
                           scope=All):
    """Remove all protections from a player."""
    if target not in PROTECTIONS:
        return

    for protector, entries in list(PROTECTIONS[target].items()):
        for cat, protector_role in entries:
            if scope & cat:
                evt = Event("remove_protection", {"remove": False})
                evt.dispatch(var, target, attacker, attacker_role, protector,
                             protector_role, reason)
                if evt.data["remove"]:
                    PROTECTIONS[target][protector].remove(
                        (cat, protector_role))
Beispiel #49
0
def on_chk_nightdone(evt, var):
    nevt = Event("wolf_numkills", {"numkills": 1, "message": ""})
    nevt.dispatch(var)
    num_kills = nevt.data["numkills"]
    wofls = [x for x in get_players(Wolf & Killer) if not is_silent(var, x)]
    if not num_kills or not wofls:
        return

    fake = users.FakeUser.from_nick("@WolvesAgree@")
    evt.data["nightroles"].extend(wofls)
    evt.data["acted"].extend(KILLS)
    evt.data["nightroles"].append(fake)

    kills = set()
    for ls in KILLS.values():
        kills.update(ls)
    # check if wolves are actually agreeing
    if len(kills) == num_kills:
        evt.data["acted"].append(fake)
Beispiel #50
0
def on_transition_day_begin(evt, cli, var):
    # Select random totem recipients if shamans didn't act
    pl = list_players()
    for shaman in list_players(var.TOTEM_ORDER):
        if shaman not in SHAMANS and shaman not in var.SILENCED:
            ps = pl[:]
            if LASTGIVEN.get(shaman) in ps:
                ps.remove(LASTGIVEN.get(shaman))
            levt = Event("get_random_totem_targets", {"targets": ps})
            levt.dispatch(cli, var, shaman)
            ps = levt.data["targets"]
            if ps:
                target = random.choice(ps)
                totem.func(cli, shaman, shaman, target,
                           messages["random_totem_prefix"])  # XXX: Old API
            else:
                LASTGIVEN[shaman] = None
        elif shaman not in SHAMANS:
            LASTGIVEN[shaman] = None
Beispiel #51
0
def get_reveal_role(user):
    # FIXME: when clone is split, move this into an event
    role = get_main_role(user)
    if var.HIDDEN_CLONE and user in var.ORIGINAL_ROLES["clone"]:
        role = "clone"

    evt = Event("get_reveal_role", {"role": role})
    evt.dispatch(var, user)
    role = evt.data["role"]

    if var.ROLE_REVEAL != "team":
        return role

    if role in var.WOLFTEAM_ROLES:
        return "wolfteam player"
    elif role in var.TRUE_NEUTRAL_ROLES:
        return "neutral player"
    else:
        return "village member"
Beispiel #52
0
    def on_transition_night_end(evt, var):
        villagers = set(get_players(("priest", "doctor")))
        win_stealers = set(get_players(("fool", "monster", "demoniac")))
        neutrals = set(get_players(("turncoat", "jester")))

        special_evt = Event(
            "get_special", {
                "villagers": villagers,
                "wolves": set(),
                "win_stealers": win_stealers,
                "neutrals": neutrals
            })
        special_evt.dispatch(var)

        bold = "\u0002{0}\u0002".format

        targets = set()
        values = []
        plural = True
        for name in types:
            targets.update(special_evt.data[name])
            l = len(special_evt.data[name])
            if l:
                if not values and l == 1:
                    plural = False
                values.append("{0} {1}{2}".format(
                    bold(l), messages["mystic_{0}".format(name)],
                    "" if l == 1 else "s"))

        if len(values) > 2:
            value = " and ".join((", ".join(values[:-1]), values[-1]))
        else:
            value = " and ".join(values)
        msg = messages["mystic_info"].format("are" if plural else "is", value,
                                             " still", "")

        for mystic in get_all_players((rolename, )):
            LAST_COUNT[mystic] = (value, plural)
            if send_role:
                to_send = "{0}_{1}".format(
                    role, ("simple" if mystic.prefers_simple() else "notify"))
                mystic.send(messages[to_send])
            mystic.send(msg)
Beispiel #53
0
def on_chk_nightdone(evt, var):
    nevt = Event("wolf_numkills", {"numkills": 1, "message": ""})
    nevt.dispatch(var)
    num_kills = nevt.data["numkills"]
    wofls = [x for x in get_players(Wolf & Killer) if not is_silent(var, x)]
    if not num_kills or not wofls:
        return

    evt.data["nightroles"].extend(wofls)
    evt.data["actedcount"] += len(KILLS)
    evt.data["nightroles"].append(users.FakeUser.from_nick("@WolvesAgree@"))
    # check if wolves are actually agreeing or not;
    # only add to count if they actually agree
    # (this is *slighty* less hacky than deducting 1 from actedcount as we did previously)
    kills = set()
    for ls in KILLS.values():
        kills.update(ls)
    # check if wolves are actually agreeing
    if len(kills) == num_kills:
        evt.data["actedcount"] += 1
Beispiel #54
0
def see(var, wrapper, message):
    """Use your paranormal powers to determine the role or alignment of a player."""
    if wrapper.source in SEEN:
        wrapper.send(messages["seer_fail"])
        return

    target = get_target(var, wrapper, re.split(" +", message)[0], not_self_message="no_see_self")
    if target is None:
        return

    target = try_misdirection(var, wrapper.source, target)
    if try_exchange(var, wrapper.source, target):
        return

    targrole = get_main_role(target)
    trole = targrole # keep a copy for logging

    for i in range(2): # need to go through loop twice
        iswolf = False
        if targrole in Cursed:
            targrole = "wolf"
            iswolf = True
        elif targrole in Safe | Innocent:
            targrole = var.HIDDEN_ROLE
        elif targrole in Wolf:
            targrole = "wolf"
            iswolf = True
        else:
            targrole = var.HIDDEN_ROLE

        if i:
            break

        evt = Event("see", {"role": targrole})
        evt.dispatch(var, wrapper.source, target)
        targrole = evt.data["role"]

    wrapper.send(messages["oracle_success"].format(target, "" if iswolf else "\u0002not\u0002 ", "\u0002" if iswolf else ""))
    debuglog("{0} (oracle) SEE: {1} ({2}) (Wolf: {3})".format(wrapper.source, target, trole, str(iswolf)))

    SEEN.add(wrapper.source)
Beispiel #55
0
def try_protection(var, target, attacker, attacker_role, reason):
    """Attempt to protect the player, and return a list of messages or None."""
    prots = []
    for protector, entries in PROTECTIONS.get(target, {}).items():
        for scope, protector_role in entries:
            if attacker_role in scope:
                entry = (protector, protector_role, scope)
                prots.append(entry)

    try_evt = Event("try_protection", {"protections": prots, "messages": []})
    if not try_evt.dispatch(var, target, attacker, attacker_role, reason) or not try_evt.data["protections"]:
        return None

    protector, protector_role, scope = try_evt.data["protections"].pop(0)

    PROTECTIONS[target][protector].remove((scope, protector_role))

    prot_evt = Event("player_protected", {"messages": try_evt.data["messages"]})
    prot_evt.dispatch(var, target, attacker, attacker_role, protector, protector_role, reason)

    return prot_evt.data["messages"]
Beispiel #56
0
def try_exchange(var, actor, target):
    """Check if an exchange is happening. Return True if the exchange occurs."""
    if actor is target or target not in EXCHANGE:
        return False

    EXCHANGE.remove(target)

    role = get_main_role(actor)
    target_role = get_main_role(target)

    actor_role = change_role(var, actor, role, target_role, inherit_from=target)
    target_role = change_role(var, target, target_role, role, inherit_from=actor)

    if actor_role == target_role: # swap state of two players with the same role
        evt = Event("swap_role_state", {"actor_messages": [], "target_messages": []})
        evt.dispatch(var, actor, target, actor_role)

        actor.send(*evt.data["actor_messages"])
        target.send(*evt.data["target_messages"])

    return True
Beispiel #57
0
def investigate(var, wrapper, message):
    """Investigate a player to determine their exact role."""
    if wrapper.source in INVESTIGATED:
        wrapper.send(messages["already_investigated"])
        return

    target = get_target(var, wrapper, re.split(" +", message)[0], not_self_message="no_investigate_self")
    if target is None:
        return

    target = try_misdirection(var, wrapper.source, target)
    if try_exchange(var, wrapper.source, target):
        return

    targrole = get_main_role(target)

    evt = Event("investigate", {"role": targrole})
    evt.dispatch(var, wrapper.source, target)
    targrole = evt.data["role"]

    INVESTIGATED.add(wrapper.source)
    wrapper.send(messages["investigate_success"].format(target, targrole))
    debuglog("{0} (detective) ID: {1} ({2})".format(wrapper.source, target, targrole))

    if random.random() < var.DETECTIVE_REVEALED_CHANCE:  # a 2/5 chance (should be changeable in settings)
        # The detective's identity is compromised!
        wcroles = Wolfchat
        if var.RESTRICT_WOLFCHAT & var.RW_REM_NON_WOLVES:
            if var.RESTRICT_WOLFCHAT & var.RW_TRAITOR_NON_WOLF:
                wcroles = Wolf
            else:
                wcroles = Wolf | {"traitor"}

        wolves = get_all_players(wcroles)
        if wolves:
            for wolf in wolves:
                wolf.queue_message(messages["detective_reveal"].format(wrapper.source))
            wolf.send_messages()

        debuglog("{0} (detective) PAPER DROP".format(wrapper.source))
Beispiel #58
0
def on_new_role(evt, var, player, old_role):
    wcroles = get_wolfchat_roles(var)

    if old_role is None:
        # initial role assignment; don't do all the logic below about notifying other wolves and such
        if evt.data["role"] in wcroles:
            evt.data["in_wolfchat"] = True
        return

    sayrole = evt.data["role"]
    if sayrole in Hidden:
        sayrole = var.HIDDEN_ROLE
    an = "n" if sayrole.startswith(("a", "e", "i", "o", "u")) else ""

    if player in KILLS:
        del KILLS[player]

    if old_role not in wcroles and evt.data["role"] in wcroles:
        # a new wofl has joined the party, give them tummy rubs and the wolf list
        # and let the other wolves know to break out the confetti and villager steaks
        wofls = get_players(wcroles)
        evt.data["in_wolfchat"] = True
        if wofls:
            new_wolves = []
            for wofl in wofls:
                wofl.queue_message(messages["wolfchat_new_member"].format(player, an, sayrole))
            wofl.send_messages()
        else:
            return # no other wolves, nothing else to do

        pl = get_players()
        if player in pl:
            pl.remove(player)
        random.shuffle(pl)
        pt = []
        wevt = Event("wolflist", {"tags": set()})
        for p in pl:
            prole = get_main_role(p)
            wevt.data["tags"].clear()
            wevt.dispatch(var, p, player)
            tags = " ".join(wevt.data["tags"])
            if prole in wcroles:
                if tags:
                    tags += " "
                pt.append("\u0002{0}\u0002 ({1}{2})".format(p, tags, prole))
            elif tags:
                pt.append("{0} ({1})".format(p, tags))
            else:
                pt.append(p.nick)

        evt.data["messages"].append(messages["players_list"].format(", ".join(pt)))

        if var.PHASE == "night" and evt.data["role"] in Wolf & Killer:
            # inform the new wolf that they can kill and stuff
            nevt = Event("wolf_numkills", {"numkills": 1, "message": ""})
            nevt.dispatch(var)
            if not nevt.data["numkills"] and nevt.data["message"]:
                evt.data["messages"].append(messages[nevt.data["message"]])
Beispiel #59
0
def get_reveal_role(nick):
    if var.HIDDEN_TRAITOR and get_role(nick) == "traitor":
        role = var.DEFAULT_ROLE
    elif var.HIDDEN_AMNESIAC and nick in var.ORIGINAL_ROLES["amnesiac"]:
        role = "amnesiac"
    elif var.HIDDEN_CLONE and nick in var.ORIGINAL_ROLES["clone"]:
        role = "clone"
    else:
        role = get_role(nick)

    evt = Event("get_reveal_role", {"role": role})
    evt.dispatch(var, nick)
    role = evt.data["role"]

    if var.ROLE_REVEAL != "team":
        return role

    if role in var.WOLFTEAM_ROLES:
        return "wolf"
    elif role in var.TRUE_NEUTRAL_ROLES:
        return "neutral player"
    else:
        return "villager"