Python实现的简单hangman游戏实例


Posted in Python onJune 28, 2015

本文实例讲述了Python实现的简单hangman游戏。分享给大家供大家参考。具体如下:

#!/usr/bin/env python
import random 
import cPickle 
class Hangman(object):
  '''A simple hangman game that tries to improve your vocabulary a bit '''
  def __init__(self):
    # the variables used, this is not necessary
    self.dumpfile = ''    #the dictionary file
    self.dictionary = {}   #the pickled dict
    self.words = []     #list of words used
    self.secret_word = ''  #the 'key'
    self.length = 0     #length of the 'key'
    self.keys = []      #inputs that match the 'key'
    self.used_keys = []   #keys that are already used
    self.guess = ''     #player's guess
    self.mistakes = 0    #number of incorrect inputs
    return self.load_dict()
  #insert some random hints for the player
  def insert_random(self, length):
    randint = random.randint
    # 3 hints
    if length >= 7: hint = 3
    else: hint = 1
    for x in xrange(hint):
        a = randint(1, length - 1)
        self.keys[a-1] = self.secret_word[a-1]
  def test_input(self):
    #if the guessed letter matches
    if self.guess in self.secret_word:
      indexes = [i for i, item in enumerate(self.secret_word) if item == self.guess]
      for index in indexes:
        self.keys[index] = self.guess
        self.used_keys.append(self.guess)
        print "used letters ",set(self.used_keys),'\n'
    #if the guessed letter didn't match
    else:
      self.used_keys.append(self.guess)
      self.mistakes += 1
      print "used letters ",set(self.used_keys),'\n'
  # load the pickled word dictionary and unpickle them  
  def load_dict(self):
    try :
      self.dumpfile = open("~/python/hangman/wordsdict.pkl", "r")
    except IOError:
      print "Couldn't find the file 'wordsdict.pkl'"
      quit()
    self.dictionary = cPickle.load(self.dumpfile)
    self.words = self.dictionary.keys()
    self.dumpfile.close()
    return self.prepare_word()
  #randomly choose a word for the challenge
  def prepare_word(self):
    self.secret_word = random.choice(self.words)
    #don't count trailing spaces
    self.length = len(self.secret_word.rstrip())
    self.keys = ['_' for x in xrange(self.length)]
    self.insert_random(self.length)
    return self.ask()
  #display the challenge
  def ask(self):
    print ' '.join(self.keys), ":", self.dictionary[self.secret_word] 
    print 
    return self.input_loop()
  #take input from the player
  def input_loop(self):
    #four self.mistakes are allowed
    chances = len(set(self.secret_word)) + 4     
    while chances != 0 and self.mistakes < 5:
      try:
        self.guess = raw_input("> ")
      except EOFError:
        exit(1)
      self.test_input()
      print ' '.join(self.keys)
      if '_' not in self.keys:
        print 'well done!'
        break
      chances -= 1
    if self.mistakes > 4: print 'the word was', ''.join(self.secret_word).upper()
    return self.quit_message()
  def quit_message(self):
    print "\n"
    print "Press 'c' to continue, or any other key to quit the game. "
    print "You can always quit the game by pressing 'Ctrl+D'"
    try:
      command = raw_input('> ')
      if command == 'c': return self.__init__() #loopback
      else : exit(0)
    except EOFError: exit(1)
if __name__ == '__main__':
  game = Hangman()
  game.__init__()

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
python实现在pickling的时候压缩的方法
Sep 25 Python
轻松掌握python设计模式之策略模式
Nov 18 Python
Python基础教程之tcp socket编程详解及简单实例
Feb 23 Python
简单实现python收发邮件功能
Jan 05 Python
简单实现python画圆功能
Jan 25 Python
Python多继承原理与用法示例
Aug 23 Python
Python实现生成密码字典的方法示例
Sep 02 Python
python自动发微信监控报警
Sep 06 Python
Python json转字典字符方法实例解析
Apr 13 Python
为什么说python适合写爬虫
Jun 11 Python
python not运算符的实例用法
Jun 30 Python
Python办公自动化PPT批量转换操作
Sep 15 Python
python实现矩阵乘法的方法
Jun 28 #Python
python实现的用于搜索文件并进行内容替换的类实例
Jun 28 #Python
python实现简单ftp客户端的方法
Jun 28 #Python
基于进程内通讯的python聊天室实现方法
Jun 28 #Python
python实现的简单RPG游戏流程实例
Jun 28 #Python
python实现自动登录人人网并采集信息的方法
Jun 28 #Python
Python实现将绝对URL替换成相对URL的方法
Jun 28 #Python
You might like
php出现Cannot modify header information问题的解决方法大全
2008/04/09 PHP
PHP+ajax 无刷新删除数据
2010/02/20 PHP
PHP开发微信支付的代码分享
2014/05/25 PHP
2个比较经典的PHP加密解密函数分享
2014/07/01 PHP
PHP验证信用卡卡号是否正确函数
2015/05/27 PHP
Joomla数据库操作之JFactory::getDBO用法
2016/05/05 PHP
用javascript实现改变TEXTAREA滚动条和按钮的颜色,以及怎样让滚动条变得扁平
2007/04/20 Javascript
jquery提示 &quot;object expected&quot;的解决方法
2009/12/13 Javascript
jQuery简单实现网页选项卡特效
2014/11/24 Javascript
javascript+canvas制作九宫格小程序
2014/12/28 Javascript
JavaScript学习笔记之基础语法
2015/01/22 Javascript
JavaScript操作DOM元素的childNodes和children区别
2015/04/01 Javascript
通过javascript进行UTF-8编码的实现方法
2016/06/27 Javascript
深入理解JavaScript中Ajax
2016/08/02 Javascript
使用React实现轮播效果组件示例代码
2016/09/05 Javascript
JavaScript之Date_动力节点Java学院整理
2017/06/28 Javascript
详解从Vue.js源码看异步更新DOM策略及nextTick
2017/10/11 Javascript
浅谈Vue SSR 的 Cookies 问题
2017/11/20 Javascript
axios简单实现小程序延时loading指示
2018/07/30 Javascript
详解从react转职到vue开发的项目准备
2019/01/14 Javascript
JS浅拷贝和深拷贝原理与实现方法分析
2019/02/28 Javascript
python实现挑选出来100以内的质数
2015/03/24 Python
Python检测一个对象是否为字符串类的方法
2015/05/21 Python
python实现比较文件内容异同
2018/06/22 Python
python生成九宫格图片
2018/11/19 Python
Python实现的企业粉丝抽奖功能示例
2019/07/26 Python
python实现的Iou与Giou代码
2020/01/18 Python
Python基于smtplib协议实现发送邮件
2020/06/03 Python
基于python+selenium自动健康打卡的实现代码
2021/01/13 Python
世界上最好的威士忌和烈性酒购买网站:The Whisky Exchange
2016/11/20 全球购物
DOUGLAS波兰:在线销售香水和化妆品
2020/07/05 全球购物
企业宣传策划方案
2014/05/29 职场文书
新兵入伍心得体会
2014/09/04 职场文书
党员检讨书范文
2014/12/27 职场文书
受资助学生感谢信
2015/01/21 职场文书
CSS 鼠标选中文字后改变背景色的实现代码
2023/05/21 HTML / CSS