Cleaned Hangman code:

- Made it work with the Word db
  - Used a HangmanGame class instead of a dict for states
  - Changed lines that were too long
This commit is contained in:
Vincent Foley 2004-01-08 05:19:31 +00:00
parent 530aec2be0
commit b44c7b50e5

View File

@ -39,7 +39,6 @@ import plugins
import os
import string
import time
import copy
import random
import sqlite
@ -97,6 +96,26 @@ def addWord(db, word, commit=False):
if commit:
db.commit()
class HangmanGame:
def __init__(self):
self.gameOn = False
self.timeout = 0
self.timeGuess = time.time()
self.tries = 0
self.prefix = ''
self.guessed = False
self.unused = [chr(c) for c in range(ord('a'), ord('z')+1)]
self.hidden = ''
self.guess = ''
def getWord(self):
dbHandler = WordsDB(os.path.join(conf.dataDir, 'Words'))
db = dbHandler.getDb()
cur = db.cursor()
cur.execute("""SELECT word FROM words ORDER BY random() LIMIT 1""")
word = cur.fetchone()[0]
return word
class Words(callbacks.Privmsg, configurable.Mixin):
def __init__(self):
@ -121,11 +140,11 @@ class Words(callbacks.Privmsg, configurable.Mixin):
raise callbacks.ArgumentError
for word in args:
if word.translate(string.ascii, string.ascii_letters):
irc.error('Word must contain only letters.')
irc.error(msg, 'Word must contain only letters.')
return
else:
addWord(self.dbHandler.getDb(), word, commit=True)
irc.replySuccess()
irc.reply(msg, conf.replySuccess)
def crossword(self, irc, msg, args):
"""<word>
@ -137,16 +156,16 @@ class Words(callbacks.Privmsg, configurable.Mixin):
db = self.dbHandler.getDb()
cursor = db.cursor()
if '%' in word:
irc.error('"%" isn\'t allowed in the word.')
irc.error(msg, '"%" isn\'t allowed in the word.')
return
cursor.execute("""SELECT word FROM words
WHERE word LIKE %s
ORDER BY word""", word)
words = [t[0] for t in cursor.fetchall()]
if words:
irc.reply(utils.commaAndify(words))
irc.reply(msg, utils.commaAndify(words))
else:
irc.reply('No matching words were found.')
irc.reply(msg, 'No matching words were found.')
def anagram(self, irc, msg, args):
"""<word>
@ -161,16 +180,16 @@ class Words(callbacks.Privmsg, configurable.Mixin):
sorted = ''.join(L)
cursor.execute("""SELECT id FROM sorted_words WHERE word=%s""", sorted)
if cursor.rowcount == 0:
irc.reply('That word has no anagrams I could find.')
irc.reply(msg, 'That word has no anagrams I could find.')
else:
id = cursor.fetchone()[0]
cursor.execute("""SELECT words.word FROM words
WHERE sorted_word_id=%s""", id)
if cursor.rowcount > 1:
words = [t[0] for t in cursor.fetchall()]
irc.reply(utils.commaAndify(words))
irc.reply(msg, utils.commaAndify(words))
else:
irc.reply('That word has no anagrams I could find.')
irc.reply(msg, 'That word has no anagrams I could find.')
###
# HANGMAN
@ -209,7 +228,7 @@ class Words(callbacks.Privmsg, configurable.Mixin):
return ''.join(newWord)
def endGame(self, channel):
self.games[channel]['gameon'] = False
self.games[channel].gameOn = False
def triesLeft(self, n):
"""
@ -234,48 +253,41 @@ class Words(callbacks.Privmsg, configurable.Mixin):
"""
channel = msg.args[0]
game = self.games[channel]
irc.reply('%s %s' % (game['prefix'], ' '.join(game['unused'])))
irc.reply(msg, '%s %s' % (game.prefix, ' '.join(game.unused)))
def newhangman(self, irc, msg, args):
def hangman(self, irc, msg, args):
"""takes no arguments
Creates a new game of hangman
"""
if not self.gotDictFile:
irc.error('You do not currently have a dict file, you can get'
' one at: %s' % self.dicturl)
return
channel = msg.args[0]
# Fill our dictionary of games
if channel not in self.games:
self.games[channel] = {}
self.games[channel] = HangmanGame()
game = self.games[channel]
# We only start a new game if no other game is going on right now
if 'gameon' not in game:
game['gameon'] = True
game['timeout'] = self.configurables.get('timeout', channel)
game['timeguess'] = time.time()
game['tries'] = self.configurables.get('tries', channel)
game['prefix'] = self.configurables.get('prefix', channel) + ' '
game['guessed'] = False
game['unused'] = copy.copy(self.validLetters)
game['hidden'] = random.choice(self.wordList).lower().strip()
game['guess'] = '_' * len(game['hidden'])
irc.reply('%sOkay ladies and gentlemen, you have '
if not game.gameOn:
game.gameOn = True
game.timeout = self.configurables.get('timeout', channel)
game.tries = self.configurables.get('tries', channel)
game.prefix = self.configurables.get('prefix', channel) + ' '
game.hidden = game.getWord()
game.guess = '_' * len(game.hidden)
irc.reply(msg, '%sOkay ladies and gentlemen, you have '
'a %s-letter word to find, you have %s!' %
(game['prefix'], len(game['hidden']),
self.triesLeft(game['tries'])), prefixName=False)
(game.prefix, len(game.hidden),
self.triesLeft(game.tries)), prefixName=False)
# So, a game is going on, but let's see if it's timed out. If it is
# we create a new one, otherwise we inform the user
else:
secondsEllapsed = time.time() - game['timeguess']
if secondsEllapsed > game['timeout']:
secondsEllapsed = time.time() - game.timeGuess
if secondsEllapsed > game.timeout:
self.endGame(channel)
self.newhangman(irc, msg, args)
else:
irc.error('Sorry, there is already a game going on. '
irc.error(msg, 'Sorry, there is already a game going on. '
'%s left before timeout.' % utils.nItems('seconds',
int(game['timeout'] - secondsEllapsed)))
int(game.timeout - secondsEllapsed)))
def guess(self, irc, msg, args):
"""<single letter>|<whole word>
@ -285,58 +297,57 @@ class Words(callbacks.Privmsg, configurable.Mixin):
"""
channel = msg.args[0]
game = self.games[channel]
if not game['gameon']:
irc.error('There is no hangman game going on right now.')
if not game.gameOn:
irc.error(msg, 'There is no hangman game going on right now.')
return
letter = privmsgs.getArgs(args)
game['timeguess'] = time.time()
game.timeGuess = time.time()
# User input a valid letter that hasn't been already tried
if letter in game['unused']:
del game['unused'][game['unused'].index(letter)]
if letter in game['hidden']:
irc.reply('%sYes, there is %s %s' % (game['prefix'],
if letter in game.unused:
del game.unused[game.unused.index(letter)]
if letter in game.hidden:
irc.reply(msg, '%sYes, there is %s %s' % (game.prefix,
self.letterArticle(letter), `letter`), prefixName=False)
game['guess'] = self.addLetter(letter, game['guess'],
self.letterPositions(letter, game['hidden']))
if game['guess'] == game['hidden']:
game['guessed'] = True
game.guess = self.addLetter(letter, game.guess,
self.letterPositions(letter, game.hidden))
if game.guess == game.hidden:
game.guessed = True
else:
irc.reply('%sNo, there is no %s' % (game['prefix'],`letter`),
irc.reply(msg,'%sNo, there is no %s' % (game.prefix,`letter`),
prefixName=False)
game['tries'] -= 1
irc.reply('%s%s (%s left)' % (game['prefix'], game['guess'],
self.triesLeft(game['tries'])), prefixName=False)
game.tries -= 1
irc.reply(msg, '%s%s (%s left)' % (game.prefix, game.guess,
self.triesLeft(game.tries)), prefixName=False)
# User input a valid character that has already been tried
elif letter in self.validLetters:
irc.error('That letter has already been tried.')
irc.error(msg, 'That letter has already been tried.')
# User tries to guess the whole word or entered an invalid input
else:
# The length of the word tried by the user and that of the hidden
# word are same, so we assume the user wants to guess the whole
# word
if len(letter) == len(game['hidden']):
if letter == game['hidden']:
game['guessed'] = True
if len(letter) == len(game.hidden):
if letter == game.hidden:
game.guessed = True
else:
irc.reply('%syou did not guess the correct word '
'and you lose a try' % game['prefix'],
prefixName=False)
game['tries'] -= 1
irc.reply(msg, '%syou did not guess the correct word '
'and you lose a try' % game.prefix, prefixName=False)
game.tries -= 1
else:
# User input an invalid character
if len(letter) == 1:
irc.error('That is not a valid character.')
# User input an invalid word (different length from hidden word)
irc.error(msg, 'That is not a valid character.')
# User input an invalid word (len(try) != len(hidden))
else:
irc.error('That is not a valid word guess.')
irc.error(msg, 'That is not a valid word guess.')
# Verify if the user won or lost
if game['guessed'] and game['tries'] > 0:
irc.reply('%sYou win! The word was indeed %s' %
(game['prefix'], game['hidden']), prefixName=False)
if game.guessed and game.tries > 0:
irc.reply(msg, '%sYou win! The word was indeed %s' %
(game.prefix, game.hidden), prefixName=False)
self.endGame(channel)
elif not game['guessed'] and game['tries'] == 0:
irc.reply('%sYou lose! The word was %s' %
(game['prefix'], game['hidden']), prefixName=False)
elif not game.guessed and game.tries == 0:
irc.reply(msg, '%sYou lose! The word was %s' %
(game.prefix, game.hidden), prefixName=False)
self.endGame(channel)
###
# END HANGMAN