Added Hangman

This commit is contained in:
Vincent Foley 2004-01-07 03:02:03 +00:00
parent 989783c07c
commit 58d86e7cd8

View File

@ -38,6 +38,9 @@ import plugins
import os
import string
import time
import copy
import random
import sqlite
@ -45,6 +48,8 @@ import conf
import utils
import privmsgs
import callbacks
import configurable
import ircutils
def configure(onStart, afterConnect, advanced):
@ -93,10 +98,18 @@ def addWord(db, word, commit=False):
db.commit()
class Words(callbacks.Privmsg):
class Words(callbacks.Privmsg, configurable.Mixin):
def __init__(self):
callbacks.Privmsg.__init__(self)
configurable.Mixin.__init__(self)
self.dbHandler = WordsDB(os.path.join(conf.dataDir, 'Words'))
try:
dictfile = os.path.join(conf.dataDir, 'dict')
self.wordList = file(dictfile).readlines()
self.gotDictFile = True
except IOError:
self.gotDictFile = False
self.gameon = False
def add(self, irc, msg, args):
"""<word> [<word>]
@ -159,6 +172,174 @@ class Words(callbacks.Privmsg):
else:
irc.reply(msg, 'That word has no anagrams I could find.')
###
# HANGMAN
###
configurables = configurable.Dictionary(
[('tries', configurable.IntType, 6, 'Number of tries to guess a word'),
('prefix', configurable.StrType, '-= HANGMAN =-',
'Prefix string of the hangman plugin'),
('timeout', configurable.IntType, 300, 'Time before a game times out')]
)
dicturl = 'http://www.unixhideout.com/freebsd/share/dict/words'
games = ircutils.IrcDict()
validLetters = [chr(c) for c in range(ord('a'), ord('z')+1)]
def letterPositions(self, letter, word):
"""
Returns a list containing the positions of letter in word.
"""
lst = []
for i in xrange(len(word)):
if word[i] == letter:
lst.append(i)
return lst
def addLetter(self, letter, word, pos):
"""
Replaces all characters of word at positions contained in pos
by letter.
"""
newWord = []
for i in xrange(len(word)):
if i in pos:
newWord.append(letter)
else:
newWord.append(word[i])
return ''.join(newWord)
def endGame(self, channel):
self.games[channel]['gameon'] = False
def triesLeft(self, n):
"""
Returns the number of tries and the correctly pluralized try/tries
"""
return utils.nItems('try', n)
def letterArticle(self, letter):
"""
Returns 'a' or 'an' to match the letter that will come after
"""
anLetter = 'aefhilmnorsx'
if letter in anLetter:
return 'an'
else:
return 'a'
def letters(self, irc, msg, args):
"""takes no arguments
Returns unused letters
"""
channel = msg.args[0]
game = self.games[channel]
irc.reply(msg, '%s %s' % (game['prefix'], ' '.join(game['unused'])))
def newhangman(self, irc, msg, args):
"""takes no arguments
Creates a new game of hangman
"""
if not self.gotDictFile:
irc.error(msg, '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] = {}
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(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)
# 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']:
self.endGame(channel)
self.newhangman(irc, msg, args)
else:
irc.error(msg, 'Sorry, there is already a game going on. '
'%s left before timeout.' % utils.nItems('seconds',
int(game['timeout'] - secondsEllapsed)))
def guess(self, irc, msg, args):
"""<single letter>|<whole word>
Try to guess a single letter or the whole word. If you try to guess
the whole word and you are wrong, you automatically lose.
"""
channel = msg.args[0]
game = self.games[channel]
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()
# 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(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
else:
irc.reply(msg,'%sNo, there is no %s' % (game['prefix'],`letter`),
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(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
else:
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(msg, 'That is not a valid character.')
# User input an invalid word (different length from hidden word)
else:
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(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(msg, '%sYou lose! The word was %s' %
(game['prefix'], game['hidden']), prefixName=False)
self.endGame(channel)
###
# END HANGMAN
###
Class = Words