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程序与MySQL的教程
Apr 29 Python
python递归删除指定目录及其所有内容的方法
Jan 13 Python
开源软件包和环境管理系统Anaconda的安装使用
Sep 04 Python
Python MySQLdb 使用utf-8 编码插入中文数据问题
Mar 13 Python
Python Tkinter 简单登录界面的实现
Jun 14 Python
numpy数组广播的机制
Jul 12 Python
Django实现WebSSH操作物理机或虚拟机的方法
Nov 06 Python
Python hashlib加密模块常用方法解析
Dec 18 Python
Pandas时间序列:时期(period)及其算术运算详解
Feb 25 Python
基于Python绘制个人足迹地图
Jun 01 Python
python 基于卡方值分箱算法的实现示例
Jul 17 Python
python 图像增强算法实现详解
Jan 24 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设计模式 php实现装饰器模式(decorator)
2015/12/07 PHP
thinkPHP框架实现的简单计算器示例
2018/12/07 PHP
laravel 解决后端无法获取到前端Post过来的值问题
2019/10/22 PHP
YII2框架中查询生成器Query()的使用方法示例
2020/03/18 PHP
THREE.JS入门教程(1)THREE.JS使用前了解
2013/01/24 Javascript
jQuery的显示和隐藏方法与css隐藏的样式对比
2013/10/18 Javascript
js 模式窗口(模式对话框和非模式对话框)的使用介绍
2014/07/17 Javascript
javascript+HTML5的canvas实现七夕情人节3D玫瑰花效果代码
2015/08/04 Javascript
分类解析jQuery选择器
2016/11/23 Javascript
nodeJS实现路由功能实例代码
2017/06/08 NodeJs
Node.js 回调函数实例详解
2017/07/06 Javascript
基于JavaScript实现选项卡效果
2017/07/21 Javascript
vue-cli如何引入bootstrap工具的方法
2017/10/19 Javascript
axios中cookie跨域及相关配置示例详解
2017/12/20 Javascript
Webpack框架核心概念(知识点整理)
2017/12/22 Javascript
[03:06]3分钟带你回顾DOTA2完美盛典&完美大师赛
2017/12/06 DOTA
[56:46]Liquid vs IG 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
python开发之函数定义实例分析
2015/11/12 Python
Python绑定方法与非绑定方法详解
2017/08/18 Python
关于Python正则表达式 findall函数问题详解
2018/03/22 Python
Python读写docx文件的方法
2018/05/08 Python
Python实现猜年龄游戏代码实例
2020/03/25 Python
Python修改DBF文件指定列
2020/12/19 Python
HTML5所有标签汇总及标签意义解释
2015/03/12 HTML / CSS
美国最受欢迎的度假目的地优惠套餐:BookVIP
2018/09/27 全球购物
澳大利亚便宜隐形眼镜购买网站:QUICKLENS Australia
2018/10/06 全球购物
车辆维修工自我评价怎么写
2013/09/20 职场文书
计算机通信工程专业毕业生推荐信
2013/12/24 职场文书
公务员转正考察材料
2014/02/07 职场文书
保护环境的标语
2014/06/09 职场文书
教师个人读书活动总结
2014/07/08 职场文书
医院2014国庆节活动策划方案
2014/09/21 职场文书
投诉书格式范本
2015/07/02 职场文书
不知如何爱孩子,这些方法教会您
2019/08/06 职场文书
Redis 报错 error:NOAUTH Authentication required
2022/05/15 Redis
Nginx配置使用详解
2022/07/07 Servers