Python实现的简单hangman游戏实例
本文实例讲述了Python实现的简单hangman游戏。分享给大家供大家参考。具体如下:
#!/usr/bin/envpython
importrandom
importcPickle
classHangman(object):
'''Asimplehangmangamethattriestoimproveyourvocabularyabit'''
def__init__(self):
#thevariablesused,thisisnotnecessary
self.dumpfile=''#thedictionaryfile
self.dictionary={}#thepickleddict
self.words=[]#listofwordsused
self.secret_word=''#the'key'
self.length=0#lengthofthe'key'
self.keys=[]#inputsthatmatchthe'key'
self.used_keys=[]#keysthatarealreadyused
self.guess=''#player'sguess
self.mistakes=0#numberofincorrectinputs
returnself.load_dict()
#insertsomerandomhintsfortheplayer
definsert_random(self,length):
randint=random.randint
#3hints
iflength>=7:hint=3
else:hint=1
forxinxrange(hint):
a=randint(1,length-1)
self.keys[a-1]=self.secret_word[a-1]
deftest_input(self):
#iftheguessedlettermatches
ifself.guessinself.secret_word:
indexes=[ifori,iteminenumerate(self.secret_word)ifitem==self.guess]
forindexinindexes:
self.keys[index]=self.guess
self.used_keys.append(self.guess)
print"usedletters",set(self.used_keys),'\n'
#iftheguessedletterdidn'tmatch
else:
self.used_keys.append(self.guess)
self.mistakes+=1
print"usedletters",set(self.used_keys),'\n'
#loadthepickledworddictionaryandunpicklethem
defload_dict(self):
try:
self.dumpfile=open("~/python/hangman/wordsdict.pkl","r")
exceptIOError:
print"Couldn'tfindthefile'wordsdict.pkl'"
quit()
self.dictionary=cPickle.load(self.dumpfile)
self.words=self.dictionary.keys()
self.dumpfile.close()
returnself.prepare_word()
#randomlychooseawordforthechallenge
defprepare_word(self):
self.secret_word=random.choice(self.words)
#don'tcounttrailingspaces
self.length=len(self.secret_word.rstrip())
self.keys=['_'forxinxrange(self.length)]
self.insert_random(self.length)
returnself.ask()
#displaythechallenge
defask(self):
print''.join(self.keys),":",self.dictionary[self.secret_word]
print
returnself.input_loop()
#takeinputfromtheplayer
definput_loop(self):
#fourself.mistakesareallowed
chances=len(set(self.secret_word))+4
whilechances!=0andself.mistakes<5:
try:
self.guess=raw_input(">")
exceptEOFError:
exit(1)
self.test_input()
print''.join(self.keys)
if'_'notinself.keys:
print'welldone!'
break
chances-=1
ifself.mistakes>4:print'thewordwas',''.join(self.secret_word).upper()
returnself.quit_message()
defquit_message(self):
print"\n"
print"Press'c'tocontinue,oranyotherkeytoquitthegame."
print"Youcanalwaysquitthegamebypressing'Ctrl+D'"
try:
command=raw_input('>')
ifcommand=='c':returnself.__init__()#loopback
else:exit(0)
exceptEOFError:exit(1)
if__name__=='__main__':
game=Hangman()
game.__init__()
希望本文所述对大家的Python程序设计有所帮助。