v3 initial commit

pull/5/head
Bobloy 7 years ago
parent 95837f8abf
commit 1d493b8e9d

@ -0,0 +1,7 @@
from .hangman import Hangman
def setup(bot):
n = Hangman(bot)
bot.add_cog(n)
bot.add_listener(n._on_react, "on_reaction_add")

@ -1,11 +1,11 @@
import discord import discord
import os import os
from collections import defaultdict
from discord.ext import commands from discord.ext import commands
from random import randint from random import randint
from .utils.dataIO import dataIO from redbot.core import Config, checks, RedContext
from .utils import checks
class Hangman: class Hangman:
@ -13,190 +13,187 @@ class Hangman:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.path = "data/Fox-Cogs/hangman" self.config = Config.get_conf(self, identifier=1049711010310997110)
self.file_path = "data/Fox-Cogs/hangman/hangman.json" default_guild = {
self.answer_path = "data/hangman/hanganswers.txt" "theface": ':thinking:',
self.the_data = dataIO.load_json(self.file_path) }
self.winbool = False
self.config.register_guild(**default_guild)
self.the_data = defaultdict(lambda:{"running": False, "hangman": 0, "guesses": [], "trackmessage": False, "answer": ''})
self.answer_path = "hangman/data/hanganswers.txt"
self.winbool = defaultdict(lambda: False)
self.letters = "🇦🇧🇨🇩🇪🇫🇬🇭🇮🇯🇰🇱🇲🇳🇴🇵🇶🇷🇸🇹🇺🇻🇼🇽🇾🇿" self.letters = "🇦🇧🇨🇩🇪🇫🇬🇭🇮🇯🇰🇱🇲🇳🇴🇵🇶🇷🇸🇹🇺🇻🇼🇽🇾🇿"
self.navigate = "🔼🔽" self.navigate = "🔼🔽"
self._updateHanglist()
self.hanglist = {}
def _updateHanglist(self):
self.hanglist = ( async def _update_hanglist(self):
"""> for guild in self.bot.guilds:
\_________ theface = await self.config.guild(guild).theface()
|/ self.hanglist[guild] = (
| """>
| \_________
| |/
| |
| |
|\___ |
""", |
|
"""> |\___
\_________ """,
|/ |
| """>
| \_________
| |/ |
| |
| |
|\___ |
H""", |
|
"""> |\___
\_________ H""",
|/ |
| """+self.the_data["theface"]+""" """>
| \_________
| |/ |
| | """+theface+"""
| |
|\___ |
HA""", |
|
"""> |\___
\________ HA""",
|/ |
| """+self.the_data["theface"]+""" """>
| | \________
| | |/ |
| | """+theface+"""
| | |
|\___ | |
HAN""", |
|
|\___
"""> HAN""",
\_________
|/ |
| """+self.the_data["theface"]+""" """>
| /| \_________
| | |/ |
| | """+theface+"""
| | /|
|\___ | |
HANG""", |
|
|\___
"""> HANG""",
\_________
|/ |
| """+self.the_data["theface"]+""" """>
| /|\ \_________
| | |/ |
| | """+theface+"""
| | /|\
|\___ | |
HANGM""", |
|
|\___
HANGM""",
""">
\________
|/ |
| """+self.the_data["theface"]+""" """>
| /|\ \________
| | |/ |
| / | """+theface+"""
| | /|\
|\___ | |
HANGMA""", | /
|
|\___
"""> HANGMA""",
\________
|/ |
| """+self.the_data["theface"]+""" """>
| /|\ \________
| | |/ |
| / \ | """+theface+"""
| | /|\
|\___ | |
HANGMAN""") | / \
|
def save_data(self): |\___
"""Saves the json""" HANGMAN""")
dataIO.save_json(self.file_path, self.the_data)
@commands.group(aliases=['sethang'], pass_context=True) @commands.group(aliases=['sethang'], pass_context=True)
@checks.mod_or_permissions(administrator=True) @checks.mod_or_permissions(administrator=True)
async def hangset(self, ctx): async def hangset(self, ctx):
"""Adjust hangman settings""" """Adjust hangman settings"""
if ctx.invoked_subcommand is None: if not ctx.invoked_subcommand:
await self.bot.send_cmd_help(ctx) await ctx.send_help()
@hangset.command(pass_context=True) @hangset.command(pass_context=True)
async def face(self, ctx, theface): async def face(self, ctx: commands.Context, theface):
message = ctx.message message = ctx.message
#Borrowing FlapJack's emoji validation (https://github.com/flapjax/FlapJack-Cogs/blob/master/smartreact/smartreact.py) #Borrowing FlapJack's emoji validation (https://github.com/flapjax/FlapJack-Cogs/blob/master/smartreact/smartreact.py)
if theface[:2] == "<:": if theface[:2] == "<:":
theface = [r for server in self.bot.servers for r in server.emojis if r.id == theface.split(':')[2][:-1]][0] theface = [r for r in self.bot.emojis if r.id == theface.split(':')[2][:-1]][0]
try: try:
# Use the face as reaction to see if it's valid (THANKS FLAPJACK <3) # Use the face as reaction to see if it's valid (THANKS FLAPJACK <3)
await self.bot.add_reaction(message, theface) await message.add_reaction(theface)
self.the_data["theface"] = str(theface)
self.save_data()
self._updateHanglist()
await self.bot.say("Face has been updated!")
except discord.errors.HTTPException: except discord.errors.HTTPException:
await self.bot.say("That's not an emoji I recognize.") await ctx.send("That's not an emoji I recognize.")
return
await self.config.guild(ctx.guild).theface.set(theface)
await self._update_hanglist()
await ctx.send("Face has been updated!")
@commands.command(aliases=['hang'], pass_context=True) @commands.command(aliases=['hang'], pass_context=True)
async def hangman(self, ctx, guess: str=None): async def hangman(self, ctx, guess: str=None):
"""Play a game of hangman against the bot!""" """Play a game of hangman against the bot!"""
if guess is None: if guess is None:
if self.the_data["running"]: if self.the_data[ctx.guild]["running"]:
await self.bot.say("Game of hangman is already running!\nEnter your guess!") await ctx.send("Game of hangman is already running!\nEnter your guess!")
self._printgame() self._printgame(ctx.channel)
"""await self.bot.send_cmd_help(ctx)""" """await self.bot.send_cmd_help(ctx)"""
else: else:
await self.bot.say("Starting a game of hangman!") await ctx.send("Starting a game of hangman!")
self._startgame() self._startgame(ctx.guild)
await self._printgame() await self._printgame(ctx.channel)
elif not self.the_data["running"]: elif not self.the_data[ctx.guild]["running"]:
await self.bot.say("Game of hangman is not yet running!\nStarting a game of hangman!") await ctx.send("Game of hangman is not yet running!\nStarting a game of hangman!")
self._startgame() self._startgame(ctx.guild)
await self._printgame() await self._printgame(ctx.channel)
else: else:
await self._guessletter(guess) await self._guessletter(guess, ctx.channel)
def _startgame(self, guild):
def _startgame(self):
"""Starts a new game of hangman""" """Starts a new game of hangman"""
self.the_data["answer"] = self._getphrase().upper() self.the_data[guild]["answer"] = self._getphrase().upper()
self.the_data["hangman"] = 0 self.the_data[guild]["hangman"] = 0
self.the_data["guesses"] = [] self.the_data[guild]["guesses"] = []
self.winbool = False self.winbool[guild] = False
self.the_data["running"] = True self.the_data[guild]["running"] = True
self.the_data["trackmessage"] = False self.the_data[guild]["trackmessage"] = False
self.save_data()
def _stopgame(self): def _stopgame(self, guild):
"""Stops the game in current state""" """Stops the game in current state"""
self.the_data["running"] = False self.the_data[guild]["running"] = False
self.save_data()
async def _checkdone(self, channel):
async def _checkdone(self, channel=None): if self.winbool[channel.guild]:
if self.winbool: await channel.send("You Win!")
if channel: self._stopgame(channel.guild)
await self.bot.send_message(channel, "You Win!") return
else:
await self.bot.say("You Win!")
self._stopgame()
if self.the_data["hangman"] >= 7:
if channel:
await self.bot.send_message(channel, "You Lose!\nThe Answer was: **"+self.the_data["answer"]+"**")
else:
await self.bot.say("You Lose!\nThe Answer was: **"+self.the_data["answer"]+"**")
self._stopgame() if self.the_data[channel.guild]["hangman"] >= 7:
await channel.send("You Lose!\nThe Answer was: **"+self.the_data[channel.guild]["answer"]+"**")
self._stopgame(channel.guild)
def _getphrase(self): def _getphrase(self):
"""Get a new phrase for the game and returns it""" """Get a new phrase for the game and returns it"""
@ -206,7 +203,6 @@ class Hangman:
outphrase = "" outphrase = ""
while outphrase == "": while outphrase == "":
outphrase = phrases[randint(0, len(phrases)-1)].partition(" (")[0] outphrase = phrases[randint(0, len(phrases)-1)].partition(" (")[0]
# outphrase = phrases[randint(0,10)].partition(" (")[0]
return outphrase return outphrase
def _hideanswer(self): def _hideanswer(self):
@ -234,27 +230,19 @@ class Hangman:
return out_str return out_str
async def _guessletter(self, guess, channel=None): async def _guessletter(self, guess, channel):
"""Checks the guess on a letter and prints game if acceptable guess""" """Checks the guess on a letter and prints game if acceptable guess"""
if not guess.upper() in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or not len(guess) == 1: if guess.upper() not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or len(guess) != 1:
if channel: await channel.send("Invalid guess. Only A-Z is accepted")
await self.bot.send_message(channel, "Invalid guess. Only A-Z is accepted")
else:
await self.bot.say("Invalid guess. Only A-Z is accepted")
return return
if guess.upper() in self.the_data["guesses"]: if guess.upper() in self.the_data[channel.guild]["guesses"]:
if channel: await channel.send("Already guessed that! Try again")
await self.bot.send_message(channel, "Already guessed that! Try again")
else:
await self.bot.say("Already guessed that! Try again")
return return
if guess.upper() not in self.the_data[channel.guild]["answer"]:
if not guess.upper() in self.the_data["answer"]:
self.the_data["hangman"] += 1 self.the_data["hangman"] += 1
self.the_data["guesses"].append(guess.upper()) self.the_data[channel.guild]["guesses"].append(guess.upper())
self.save_data()
await self._printgame(channel) await self._printgame(channel)
@ -290,66 +278,46 @@ class Hangman:
async def _reactmessage_menu(self, message): async def _reactmessage_menu(self, message):
"""React with menu options""" """React with menu options"""
await self.bot.clear_reactions(message) await message.clear_reactions()
await self.bot.add_reaction(message, self.navigate[0]) await message.add_reaction(self.navigate[0])
await self.bot.add_reaction(message, self.navigate[-1]) await message.add_reaction(self.navigate[-1])
async def _reactmessage_am(self, message): async def _reactmessage_am(self, message):
await self.bot.clear_reactions(message) await message.clear_reactions()
for x in range(len(self.letters)): for x in range(len(self.letters)):
if x in [i for i,b in enumerate("ABCDEFGHIJKLM") if b not in self._guesslist()]: if x in [i for i,b in enumerate("ABCDEFGHIJKLM") if b not in self._guesslist()]:
await self.bot.add_reaction(message, self.letters[x]) await message.add_reaction(self.letters[x])
await self.bot.add_reaction(message, self.navigate[-1]) await message.add_reaction(self.navigate[-1])
async def _reactmessage_nz(self, message): async def _reactmessage_nz(self, message):
await self.bot.clear_reactions(message) await self.bot.clear_reactions(message)
for x in range(len(self.letters)): for x in range(len(self.letters)):
if x in [i for i,b in enumerate("NOPQRSTUVWXYZ") if b not in self._guesslist()]: if x in [i for i,b in enumerate("NOPQRSTUVWXYZ") if b not in self._guesslist()]:
await self.bot.add_reaction(message, self.letters[x+13]) await message.add_reaction(self.letters[x+13])
await self.bot.add_reaction(message, self.navigate[0]) await message.add_reaction(self.navigate[0])
async def _printgame(self, channel=None): async def _printgame(self, channel):
"""Print the current state of game""" """Print the current state of game"""
cSay = ("Guess this: " + str(self._hideanswer()) + "\n" cSay = ("Guess this: " + str(self._hideanswer()) + "\n"
+ "Used Letters: " + str(self._guesslist()) + "\n" + "Used Letters: " + str(self._guesslist()) + "\n"
+ self.hanglist[self.the_data["hangman"]] + "\n" + self.hanglist[self.the_data["hangman"]] + "\n"
+ self.navigate[0]+" for A-M, "+self.navigate[-1]+" for N-Z") + self.navigate[0]+" for A-M, "+self.navigate[-1]+" for N-Z")
if channel:
message = await self.bot.send_message(channel, cSay) message = await channel.send(cSay)
else:
message = await self.bot.say(cSay)
self.the_data["trackmessage"] = message.id self.the_data["trackmessage"] = message.id
self.save_data()
await self._reactmessage_menu(message) await self._reactmessage_menu(message)
await self._checkdone(channel) await self._checkdone(channel)
def check_folders():
if not os.path.exists("data/Fox-Cogs"):
print("Creating data/Fox-Cogs folder...")
os.makedirs("data/Fox-Cogs")
if not os.path.exists("data/Fox-Cogs/hangman"):
print("Creating data/Fox-Cogs/hangman folder...")
os.makedirs("data/Fox-Cogs/hangman")
def check_files():
if not dataIO.is_valid_json("data/Fox-Cogs/hangman/hangman.json"):
dataIO.save_json("data/Fox-Cogs/hangman/hangman.json", {"running": False, "hangman": 0, "guesses": [], "theface": "<:never:336861463446814720>", "trackmessage": False})
def setup(bot): def setup(bot):
check_folders()
check_files()
n = Hangman(bot) n = Hangman(bot)
bot.add_cog(n) bot.add_cog(n)
bot.add_listener(n._on_react, "on_reaction_add") bot.add_listener(n._on_react, "on_reaction_add")

Loading…
Cancel
Save