#!/usr/bin/env python3 """ A class and functions needed for playing handman. """ import os import random from module import commands, example class Hangman(): def __init__(self, bot): self.tries = 8 self.word = self._PickWord(bot) self.working = [x for x in self.word] self.blanks = list('_' * len(self.word)) def _PickWord(self, bot): with open(os.path.join(bot.static, "wordlist.txt"), "r") as file: word = random.choice(file.read().splitlines()) return word def update(self, guess): if not guess in self.word: return for n, char in enumerate(self.word): if char == guess: self.blanks[n] = guess def setup(bot): bot.memory["hangman"] = {} @commands("hangman", "hm") @example(".hangman --start") @example(".hm anus") def hangman(bot, trigger): """ Plays hangman. --start [-s] to start a new game, otherwise words are taken as attempts to solve and single characters are taken as guesses. """ if len(trigger.args) < 2: return bot.reply("Hang what?") if trigger.args[1] == "--start" or trigger.args[1] == "-s": if bot.memory["hangman"].get(trigger.channel): return bot.reply("There is already a game running in this channel.") bot.memory["hangman"][trigger.channel] = Hangman(bot) msg = f"{trigger.nick} has started a game of hangman! " \ + "Use '.hangman [guess]' to guess a letter or the entire word." bot.msg(msg) bot.msg("".join(bot.memory["hangman"][trigger.channel].blanks)) return if not bot.memory["hangman"].get(trigger.channel): msg = "There is no game currently running in this channel. " \ + "Use '.hangman --start' to start one" return bot.reply(msg) if len(trigger.args[1]) > 1: if trigger.args[1] == bot.memory["hangman"][trigger.channel].word: bot.msg(f"{trigger.nick} has won!") bot.msg(bot.memory["hangman"][trigger.channel].word) bot.memory["hangman"].pop(trigger.channel) return else: bot.memory["hangman"][trigger.channel].tries -= 1 msg = "Incorrect. " \ + f"{bot.memory['hangman'][trigger.channel].tries} tries left." bot.reply(msg) elif len(trigger.args[1]) == 1: if trigger.args[1] in bot.memory["hangman"][trigger.channel].word: bot.reply("Correct!") bot.memory["hangman"][trigger.channel].update(trigger.args[1]) else: bot.memory["hangman"][trigger.channel].tries -= 1 msg = "Incorrect. " \ + f"{bot.memory['hangman'][trigger.channel].tries} tries left." bot.reply(msg) if bot.memory["hangman"][trigger.channel].tries <= 0: bot.msg("Game over!") bot.msg(bot.memory['hangman'][trigger.channel].word) bot.memory["hangman"].pop(trigger.channel) else: bot.msg("".join(bot.memory["hangman"][trigger.channel].blanks))