WIP listeners, switch to f strings, and overall rewrite

pull/147/head
bobloy 4 years ago
parent a2eaf55515
commit 7109471c35

@ -49,7 +49,7 @@ CATEGORY_COUNT = []
def role_embed(idx, role, color):
embed = discord.Embed(
title="**{}** - {}".format(idx, str(role.__name__)),
title=f"**{idx}** - {role.__name__}",
description=role.game_start_message,
color=color,
)
@ -82,7 +82,7 @@ def setup():
if 0 < k <= 6:
ROLE_PAGES.append(
discord.Embed(
title="RANDOM:Town Role", description="Town {}".format(v), color=0x008000
title="RANDOM:Town Role", description=f"Town {v}", color=0x008000
)
)
CATEGORY_COUNT.append(k)
@ -95,7 +95,7 @@ def setup():
ROLE_PAGES.append(
discord.Embed(
title="RANDOM:Werewolf Role",
description="Werewolf {}".format(v),
description=f"Werewolf {v}",
color=0xFF0000,
)
)
@ -107,7 +107,7 @@ def setup():
if 20 < k <= 26:
ROLE_PAGES.append(
discord.Embed(
title="RANDOM:Neutral Role", description="Neutral {}".format(v), color=0xC0C0C0
title=f"RANDOM:Neutral Role", description="Neutral {v}", color=0xC0C0C0
)
)
CATEGORY_COUNT.append(k)
@ -306,14 +306,14 @@ def say_role_list(code_list, rand_roles):
for role in rand_roles:
if 0 < role <= 6:
role_dict["Town {}".format(ROLE_CATEGORIES[role])] += 1
role_dict[f"Town {ROLE_CATEGORIES[role]}"] += 1
if 10 < role <= 16:
role_dict["Werewolf {}".format(ROLE_CATEGORIES[role])] += 1
role_dict[f"Werewolf {ROLE_CATEGORIES[role]}"] += 1
if 20 < role <= 26:
role_dict["Neutral {}".format(ROLE_CATEGORIES[role])] += 1
role_dict[f"Neutral {ROLE_CATEGORIES[role]}"] += 1
for k, v in role_dict.items():
embed.add_field(name=k, value="Count: {}".format(v), inline=True)
embed.add_field(name=k, value=f"Count: {v}", inline=True)
return embed

@ -18,6 +18,7 @@ log = logging.getLogger("red.fox_v3.werewolf.game")
HALF_DAY_LENGTH = 24 # FixMe: to 120 later for 4 minute days
class Game:
"""
Base class to run a single game of Werewolf
@ -119,10 +120,10 @@ class Game:
if len(self.players) != len(self.roles):
await ctx.maybe_send_embed(
"Player count does not match role count, cannot start\n"
"Currently **{} / {}**\n"
"Use `{}ww code` to pick a new game"
"".format(len(self.players), len(self.roles), ctx.prefix)
f"Player count does not match role count, cannot start\n"
f"Currently **{len(self.players)} / {len(self.roles)}**\n"
f"Use `{ctx.prefix}ww code` to pick a game setup\n"
f"Use `{ctx.prefix}buildgame` to generate a new game"
)
self.roles = []
return False
@ -147,9 +148,7 @@ class Game:
await player.member.add_roles(*[self.game_role])
except discord.Forbidden:
await ctx.send(
"Unable to add role **{}**\nBot is missing `manage_roles` permissions".format(
self.game_role.name
)
f"Unable to add role **{self.game_role.name}**\nBot is missing `manage_roles` permissions"
)
return False
@ -353,9 +352,7 @@ class Game:
await self.speech_perms(self.village_channel, target.member) # Only target can talk
await self.village_channel.send(
"**{} will be put to trial and has 30 seconds to defend themselves**".format(
target.mention
),
f"**{target.mention} will be put to trial and has 30 seconds to defend themselves**",
allowed_mentions=discord.AllowedMentions(everyone=False, users=[target]),
)
@ -364,10 +361,10 @@ class Game:
await self.speech_perms(self.village_channel, target.member, undo=True) # No one can talk
message: discord.Message = await self.village_channel.send(
"Everyone will now vote whether to lynch {}\n"
f"Everyone will now vote whether to lynch {target.mention}\n"
"👍 to save, 👎 to lynch\n"
"*Majority rules, no-lynch on ties, "
"vote both or neither to abstain, 15 seconds to vote*".format(target.mention),
"vote both or neither to abstain, 15 seconds to vote*",
allowed_mentions=discord.AllowedMentions(everyone=False, users=[target]),
)
@ -385,25 +382,31 @@ class Game:
else:
embed = discord.Embed(title="Vote Results", color=0x80FF80)
embed.add_field(name="👎", value="**{}**".format(up_votes), inline=True)
embed.add_field(name="👍", value="**{}**".format(down_votes), inline=True)
embed.add_field(name="👎", value=f"**{up_votes}**", inline=True)
embed.add_field(name="👍", value=f"**{down_votes}**", inline=True)
await self.village_channel.send(embed=embed)
if down_votes > up_votes:
await self.village_channel.send("**Voted to lynch {}!**".format(target.mention))
await self.village_channel.send(
f"**Voted to lynch {target.mention}!**",
allowed_mentions=discord.AllowedMentions(everyone=False, users=[target]),
)
await self.lynch(target)
self.can_vote = False
else:
await self.village_channel.send("**{} has been spared!**".format(target.mention))
await self.village_channel.send(
f"**{target.mention} has been spared!**",
allowed_mentions=discord.AllowedMentions(everyone=False, users=[target]),
)
if self.used_votes >= self.day_vote_count:
await self.village_channel.send("**All votes have been used! Day is now over!**")
self.can_vote = False
else:
await self.village_channel.send(
"**{}**/**{}** of today's votes have been used!\n"
"Nominate carefully..".format(self.used_votes, self.day_vote_count)
f"**{self.used_votes}**/**{self.day_vote_count}** of today's votes have been used!\n"
"Nominate carefully.."
)
self.ongoing_vote = False
@ -513,14 +516,14 @@ class Game:
status = "*[Dead]*-"
if with_roles or not player.alive:
embed.add_field(
name="ID# **{}**".format(i),
value="{}{}-{}".format(status, player.member.display_name, str(player.role)),
name=f"ID# **{i}**",
value=f"{status}{player.member.display_name}-{player.role}",
inline=True,
)
else:
embed.add_field(
name="ID# **{}**".format(i),
value="{}{}".format(status, player.member.display_name),
name=f"ID# **{i}**",
value=f"{status}{player.member.display_name}",
inline=True,
)
@ -553,7 +556,7 @@ class Game:
return
if await self.get_player_by_member(member) is not None:
await channel.send("{} is already in the game!".format(member.mention))
await channel.send(f"{member.display_name} is already in the game!")
return
self.players.append(Player(member))
@ -563,14 +566,12 @@ class Game:
await member.add_roles(*[self.game_role])
except discord.Forbidden:
await channel.send(
"Unable to add role **{}**\nBot is missing `manage_roles` permissions".format(
self.game_role.name
)
f"Unable to add role **{self.game_role.name}**\nBot is missing `manage_roles` permissions"
)
await channel.send(
"{} has been added to the game, "
"total players is **{}**".format(member.mention, len(self.players))
f"{member.display_name} has been added to the game, "
f"total players is **{len(self.players)}**"
)
async def quit(self, member: discord.Member, channel: discord.TextChannel = None):
@ -584,14 +585,16 @@ class Game:
if self.started:
await self._quit(player)
await channel.send("{} has left the game".format(member.mention))
await channel.send(
f"{member.mention} has left the game",
allowed_mentions=discord.AllowedMentions(everyone=False, users=[member]),
)
else:
self.players = [player for player in self.players if player.member != member]
await member.remove_roles(*[self.game_role])
await channel.send(
"{} chickened out, player count is now **{}**".format(
member.mention, len(self.players)
)
f"{member.mention} chickened out, player count is now **{len(self.players)}**",
allowed_mentions=discord.AllowedMentions(everyone=False, users=[member]),
)
async def choose(self, ctx, data):
@ -698,7 +701,8 @@ class Game:
author.mention,
target.member.mention,
required_votes - self.vote_totals[target_id],
)
),
allowed_mentions=discord.AllowedMentions(everyone=False, users=[author, target]),
)
else:
self.vote_totals[target_id] = 0
@ -930,7 +934,7 @@ class Game:
name = func.__name__ if name is None else name
if not asyncio.iscoroutinefunction(func):
raise TypeError('Listeners must be coroutines')
raise TypeError("Listeners must be coroutines")
if name in self.listeners:
if priority in self.listeners[name]:
@ -942,7 +946,6 @@ class Game:
# self.listeners[name].sort(reverse=True)
# def remove_wolf_listener(self, func, name=None):
# """Removes a listener from the pool of listeners.
#

@ -64,13 +64,13 @@ def wolflistener(name=None, priority=0):
class WolfListenerMeta(type):
def __new__(mcs, cls, *args, **kwargs):
name, bases = args
def __new__(mcs, *args, **kwargs):
name, bases, attrs = args
listeners = {}
need_at_msg = "Listeners must start with at_ (in method {0.__name__}.{1})"
new_cls = super().__new__(cls, name, bases, **kwargs)
new_cls = super().__new__(mcs, name, bases, attrs, **kwargs)
for base in reversed(new_cls.__mro__):
for elem, value in base.__dict__.items():
if elem in listeners:
@ -85,8 +85,8 @@ class WolfListenerMeta(type):
except AttributeError:
continue
else:
if not elem.startswith("at_"):
raise TypeError(need_at_msg.format(mcs, elem))
# if not elem.startswith("at_"):
# raise TypeError(need_at_msg.format(base, elem))
listeners[elem] = value
listeners_as_list = []

@ -34,4 +34,4 @@ class Player:
try:
await self.member.send(message) # Lets do embeds later
except discord.Forbidden:
await self.role.game.village_channel.send("Couldn't DM {}, uh oh".format(self.mention))
await self.role.game.village_channel.send(f"Couldn't DM {self.mention}, uh oh", allowed_mentions=discord.AllowedMentions(users=[self.member]))

@ -128,7 +128,7 @@ class Role(WolfListener):
"""
return "Default"
@wolflistener("at_game_start")
@wolflistener("at_game_start", priority=1)
async def _at_game_start(self, data=None):
if self.channel_id:
await self.game.register_channel(self.channel_id, self)

@ -1,7 +1,11 @@
import logging
from werewolf.listener import wolflistener
from werewolf.night_powers import pick_target
from werewolf.role import Role
log = logging.getLogger("red.fox_v3.werewolf.role.seer")
class Seer(Role):
rand_choice = True # Determines if it can be picked as a random role (False for unusually disruptive roles)
@ -93,7 +97,5 @@ class Seer(Role):
self.see_target, target = await pick_target(self, ctx, data)
await ctx.send(
"**You will attempt to see the role of {} tonight...**".format(
target.member.display_name
)
f"**You will attempt to see the role of {target.member.display_name} tonight...**"
)

@ -1,7 +1,11 @@
import logging
from werewolf.listener import wolflistener
from werewolf.night_powers import pick_target
from werewolf.role import Role
log = logging.getLogger("red.fox_v3.werewolf.role.shifter")
class Shifter(Role):
"""
@ -130,7 +134,5 @@ class Shifter(Role):
self.shift_target, target = await pick_target(self, ctx, data)
await ctx.send(
"**You will attempt to see the role of {} tonight...**".format(
target.member.display_name
)
f"**You will attempt to see the role of {target.member.display_name} tonight...**"
)

@ -1,7 +1,11 @@
import logging
from werewolf.listener import wolflistener
from werewolf.role import Role
from werewolf.votegroups.wolfvote import WolfVote
log = logging.getLogger("red.fox_v3.werewolf.role.vanillawerewolf")
class VanillaWerewolf(Role):
rand_choice = True
@ -56,7 +60,9 @@ class VanillaWerewolf(Role):
async def _at_game_start(self, data=None):
if self.channel_id:
print("Wolf has channel_id: " + self.channel_id)
await self.game.register_channel(self.channel_id, self, WolfVote) # Add VoteGroup WolfVote
await self.game.register_channel(
self.channel_id, self, WolfVote
) # Add VoteGroup WolfVote
await self.player.send_dm(self.game_start_message)

@ -1,5 +1,9 @@
import logging
from werewolf.role import Role
log = logging.getLogger("red.fox_v3.werewolf.role.villager")
class Villager(Role):
rand_choice = True # Determines if it can be picked as a random role (False for unusually disruptive roles)

@ -1,7 +1,10 @@
import logging
import random
from werewolf.votegroup import VoteGroup
log = logging.getLogger("red.fox_v3.werewolf.votegroup.wolfvote")
class WolfVote(VoteGroup):
"""
@ -77,7 +80,7 @@ class WolfVote(VoteGroup):
self.killer = random.choice(self.players)
await self.channel.send(
"{} has been selected as tonight's killer".format(self.killer.member.display_name)
f"{self.killer.member.display_name} has been selected as tonight's killer"
)
async def _at_night_end(self, data=None):
@ -90,7 +93,7 @@ class WolfVote(VoteGroup):
if vote_list:
target_id = max(set(vote_list), key=vote_list.count)
print("Target id: {}\nKiller: {}".format(target_id, self.killer.member.display_name))
log.debug("Target id: {target_id}\nKiller: {self.killer.member.display_name}")
if target_id is not None and self.killer:
await self.game.kill(target_id, self.killer, random.choice(self.kill_messages))
await self.channel.send(

@ -62,7 +62,7 @@ class Werewolf(Cog):
code = await gb.build_game(ctx)
if code != "":
await ctx.send("Your game code is **{}**".format(code))
await ctx.send(f"Your game code is **{code}**")
else:
await ctx.send("No code generated")

Loading…
Cancel
Save