CAH: fix missing import

This commit is contained in:
oddluck 2020-04-28 22:02:49 +00:00
parent 55484b7c7d
commit e26ef66af8
4 changed files with 144 additions and 92 deletions

View File

@ -42,19 +42,23 @@ import importlib
__version__ = "2020.02.24+git"
# XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.Author('James Scott', 'jazzahn', '')
__maintainer__ = getattr(supybot.authors, 'oddluck',
supybot.Author('oddluck', 'oddluck', 'oddluck@riseup.net'))
__author__ = supybot.Author("James Scott", "jazzahn", "")
__maintainer__ = getattr(
supybot.authors,
"oddluck",
supybot.Author("oddluck", "oddluck", "oddluck@riseup.net"),
)
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
# This is a url where the most recent plugin package can be downloaded.
__url__ = 'https://github.com/oddluck/limnoria-plugins/'
__url__ = "https://github.com/oddluck/limnoria-plugins/"
from . import config
from . import plugin
importlib.reload(plugin) # In case we're being reloaded.
# Add more reloads here if you add third-party modules and want them to be
# reloaded when this plugin is reloaded. Don't forget to import them as well!

View File

@ -31,25 +31,28 @@
from random import choice
import os
import json
from . import test
# Settings you change
card_folder = 'cards'
answer_cards_file_names = ['answer_main', 'custom_answer_cards']
question_cards_file_name = ['question_main', 'custom_question_cards']
blank_format = '__________'
card_folder = "cards"
answer_cards_file_names = ["answer_main", "custom_answer_cards"]
question_cards_file_name = ["question_main", "custom_question_cards"]
blank_format = "__________"
# Settings that are used
# this is one level higher than it should be
base_directory = os.path.dirname(os.path.abspath(__file__))
class Deck(object):
def __init__(self):
self.answerDb = self.parse_card_file('answer')
self.questionDb = self.parse_card_file('question')
self.answerDb = self.parse_card_file("answer")
self.questionDb = self.parse_card_file("question")
def parse_card_file(self, card_type):
card_type_map = {'answer': answer_cards_file_names, 'question': question_cards_file_name}
card_type_map = {
"answer": answer_cards_file_names,
"question": question_cards_file_name,
}
# Read text file into a list containing only strings of text for the card
card_text_list = []
@ -71,7 +74,7 @@ class Deck(object):
# Prepare card text by removing control chars
card = card.rstrip()
# Figure out how many answers are required for a question card
if card_type == 'question':
if card_type == "question":
answers = self.count_answers(card)
card_object_list.append(Card(index, card_type, card, answers=answers))
else:
@ -86,14 +89,17 @@ class Deck(object):
return blanks
def drawCard(self, typeOfCard):
typeMap = {'answer': self.answerDb, 'question': self.questionDb}
typeMap = {"answer": self.answerDb, "question": self.questionDb}
type = typeMap[typeOfCard]
card = choice(type)
type.remove(card)
return card
def __repr__(self):
return json.dumps({'questions': len(self.questionDb), 'answers': len(self.answerDb)})
return json.dumps(
{"questions": len(self.questionDb), "answers": len(self.answerDb)}
)
class Card(object):
def __init__(self, id, type, text, **kwargs):
@ -102,6 +108,7 @@ class Card(object):
self.text = text
for key, value in kwargs.items():
setattr(self, key, value)
def __str__(self):
return self.text
@ -129,8 +136,8 @@ class Game(object):
else:
raise IndexError
self.question = self.deck.drawCard('question')
return {'question': self.question, 'hands': self.players}
self.question = self.deck.drawCard("question")
return {"question": self.question, "hands": self.players}
def end_round(self, winner_name, cards_played):
self.score_keeping(winner_name)
@ -155,15 +162,17 @@ class Game(object):
cardRange = list(range(5))
while cardInput not in cardRange:
try:
cardInput = int(input('%s Pick a Card: ' % player)) - 1
cardInput = int(input("%s Pick a Card: " % player)) - 1
except ValueError:
pass
class Round(object):
def __init__(self, deck, players):
self.question = deck.drawCard('question')
self.question = deck.drawCard("question")
self.players = players
class PlayerHand(object):
def __init__(self, deck):
self.card_list = []
@ -171,7 +180,7 @@ class PlayerHand(object):
def deal_hand(self, deck):
while len(self.card_list) < 5:
card = deck.drawCard('answer')
card = deck.drawCard("answer")
self.card_list.append(card)
def text_list(self):
@ -181,25 +190,28 @@ class PlayerHand(object):
return card_text
def showHand(self):
print('%s' % self.text_list())
print("%s" % self.text_list())
if __name__ == "__main__":
game = Game(['Bear','Swim', 'Jazz'])
print("\nGame started with the following players: %s \n" % list(game.players.keys()))
game = Game(["Bear", "Swim", "Jazz"])
print(
"\nGame started with the following players: %s \n" % list(game.players.keys())
)
round = game.next_round()
print("The first question is: %s \n" % game.question.text)
print("Swim's hand the easy way:")
game.players['Swim'].showHand()
game.players["Swim"].showHand()
print("\nJazz's hand in a weird way")
round['hands']['Jazz'].showHand()
round["hands"]["Jazz"].showHand()
print("\nBear's hand the hard way:")
for index, card in enumerate(game.players['Bear'].card_list):
print('%s: %s' % (index + 1, card.text))
for index, card in enumerate(game.players["Bear"].card_list):
print("%s: %s" % (index + 1, card.text))
print("\nEnd the round by picking a random cards amd winner: %s" % str(test.build_end_round_data(game)))
print(
"\nEnd the round by picking a random cards amd winner: %s"
% str(test.build_end_round_data(game))
)

View File

@ -31,16 +31,18 @@
import supybot.conf as conf
import supybot.registry as registry
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified himself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('CAH', True)
conf.registerPlugin("CAH", True)
CAH = conf.registerPlugin('CAH')
CAH = conf.registerPlugin("CAH")
# This is where your configuration variables (if any) should go. For example:
# conf.registerGlobalValue(Cah, 'someConfigVariableName',
# registry.Boolean(False, """Help for someConfigVariableName."""))

View File

@ -46,6 +46,7 @@ import time
import os
import re
class CAH(callbacks.Plugin):
"""Cards Against Humanity"""
@ -58,6 +59,7 @@ class CAH(callbacks.Plugin):
class CAHGame(object):
"""docstring for Game"""
def __init__(self, irc, channel, numrounds=5):
self.irc = irc
self.channel = channel
@ -74,7 +76,9 @@ class CAH(callbacks.Plugin):
self.cardsPlayed = {}
def initGame(self):
schedule.addEvent(self.startgame, time.time() + 60, "start_game_%s" % self.channel)
schedule.addEvent(
self.startgame, time.time() + 60, "start_game_%s" % self.channel
)
###### UTIL METHODS ##########
@ -92,8 +96,14 @@ class CAH(callbacks.Plugin):
enumeratedHand = []
cah = self.game
for position, card in enumerate(cah.players[nick].card_list):
enumeratedHand.append("\x02\x031,00%s: %s\x0F" % (position + 1, card.text))
self._notice(nick, "White Cards: %s Please respond with playcard <number> [number]" % (', '.join(enumeratedHand)))
enumeratedHand.append(
"\x02\x031,00%s: %s\x0F" % (position + 1, card.text)
)
self._notice(
nick,
"White Cards: %s Please respond with playcard <number> [number]"
% (", ".join(enumeratedHand)),
)
def _displayPlayedCards(self):
channel = self.channel
@ -121,7 +131,6 @@ class CAH(callbacks.Plugin):
else:
return (highscore[0], False)
def _tallyVotes(self, votes):
ties = []
winningCanidate = []
@ -144,7 +153,6 @@ class CAH(callbacks.Plugin):
return (winningCanidate[randint(0, len(winningCanidate) - 1)], True)
return (winningCanidate[0], False)
###### END UTIL METHODS #######
###### PRE GAME LOGIC ########
@ -192,7 +200,10 @@ class CAH(callbacks.Plugin):
self._printBlackCard(self.channel)
for nick in self.players:
self._msgHandToPlayer(nick)
self._msg(channel, "The white cards have been sent to players, you have 60 seconds to choose.")
self._msg(
channel,
"The white cards have been sent to players, you have 60 seconds to choose.",
)
self.acceptingWhiteCards = True
# TODO: do we need a round flag?
schedule.addEvent(self.endround, time.time() + 60, "round_%s" % channel)
@ -207,8 +218,11 @@ class CAH(callbacks.Plugin):
winner = self._findHighScore(cah.score)
for name, score in cah.score.items():
formattedScores.append("%s: %d" % (name, score))
self._msg(channel, "Game Over! %s is the Winner! Scores: %s " % (winner[0][0], ", ".join(formattedScores)))
self._msg(
channel,
"Game Over! %s is the Winner! Scores: %s "
% (winner[0][0], ", ".join(formattedScores)),
)
def endround(self):
channel = self.channel
@ -236,12 +250,12 @@ class CAH(callbacks.Plugin):
game.votes = {}
game.voted = []
game.voting = True
self._msg(channel, "Please Vote on your favorite. votecard <number> to vote, the entire channel can vote.")
self._msg(
channel,
"Please Vote on your favorite. votecard <number> to vote, the entire channel can vote.",
)
schedule.addEvent(self.stopcardvote, time.time() + 60, "vote_%s" % channel)
def stopcardvote(self):
# TODO: NOt quite done here
@ -252,7 +266,9 @@ class CAH(callbacks.Plugin):
print(winner)
game.game.end_round(winner[0][0], self.cardsPlayed)
game.voted = []
game._msg(self.channel, "%s wins the round!" % ircutils.bold(winner[0][0]))
game._msg(
self.channel, "%s wins the round!" % ircutils.bold(winner[0][0])
)
# game._msg(self.channel, "%s wins the round with %s" % (ircutils.bold(winner[0][0]), ircutils.bold(filledCard)))
game.nextround()
@ -271,6 +287,7 @@ class CAH(callbacks.Plugin):
schedule.removeEvent("start_game_%s" % self.channel)
except:
pass
Class = CAHGame
###### CHANNEL COMMANDS ######
@ -298,7 +315,14 @@ class CAH(callbacks.Plugin):
else:
if len(game.players) < game.maxPlayers:
game.players.append(nick)
irc.reply("Added, Spots left %d/%d. Current Players %s" % (game.maxPlayers - len(game.players), game.maxPlayers, ', '.join(game.players)))
irc.reply(
"Added, Spots left %d/%d. Current Players %s"
% (
game.maxPlayers - len(game.players),
game.maxPlayers,
", ".join(game.players),
)
)
else:
irc.reply("Too many players")
if len(game.players) > 1:
@ -319,7 +343,10 @@ class CAH(callbacks.Plugin):
if channel in self.games:
irc.reply("There is a game running currently.")
else:
irc.reply("Who wants to play IRC Aganst Humanity? To play reply with: playing", prefixNick=False)
irc.reply(
"Who wants to play IRC Aganst Humanity? To play reply with: playing",
prefixNick=False,
)
self.games[channel] = self.CAHGame(irc, channel, numrounds)
self.games[channel].initGame()
@ -333,14 +360,14 @@ class CAH(callbacks.Plugin):
text = args[1].capitalize().strip()
if args[0] == "question":
card_file = "custom_question_cards"
text = re.sub(r'_+', blank_format, text)
text = re.sub(r"_+", blank_format, text)
elif args[0] == "answer":
card_file = "custom_answer_cards"
else:
irc.reply("Specify type of card as either question or answer.")
return
path = os.path.abspath(os.path.join(base_directory, card_folder, card_file))
with open(path, 'w') as file_handle:
with open(path, "w") as file_handle:
file_handle.writelines([text])
def stopcah(self, irc, msg, args):
@ -364,11 +391,17 @@ class CAH(callbacks.Plugin):
elif nick in game.cardsPlayed:
irc.reply("You already played, GET OUT.")
elif len(args) < game.game.question.answers:
irc.reply("Hey shitbag I need more cards, this is a %s card question." % game.game.question.answers)
irc.reply(
"Hey shitbag I need more cards, this is a %s card question."
% game.game.question.answers
)
elif len(args) > game.game.question.answers:
if game.gane.question.answers == 1:
irc.reply("I only want one card you idiot.")
irc.reply("Woah there tiger, I only need %s cards." % game.game.question.answers)
irc.reply(
"Woah there tiger, I only need %s cards."
% game.game.question.answers
)
elif len(args) == game.game.question.answers:
game.playcard(nick, args)
else:
@ -398,6 +431,7 @@ class CAH(callbacks.Plugin):
else:
irc.reply("A Game is not running, or the time is not to vote.")
Class = CAH