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中的多线程编程
Apr 09 Python
在Python中使用列表生成式的教程
Apr 27 Python
用C++封装MySQL的API的教程
May 06 Python
numpy 进行数组拼接,分别在行和列上合并的实例
May 08 Python
基于Python列表解析(列表推导式)
Jun 23 Python
Python3标准库总结
Feb 19 Python
Pandas删除数据的几种情况(小结)
Jun 21 Python
python Django 创建应用过程图示详解
Jul 29 Python
Python logging设置和logger解析
Aug 28 Python
python图形用户接口实例详解
Dec 16 Python
python随机模块random使用方法详解
Feb 14 Python
Python socket连接中的粘包、精确传输问题实例分析
Mar 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之对抗Web扫描器的脚本技巧
2008/10/01 PHP
php数组相加 array(“a”)+array(“b”)结果还是array(“a”)
2012/09/19 PHP
php shell超强免杀、减少体积工具实现代码
2012/10/16 PHP
PHP中的Memcache详解
2014/04/05 PHP
php实现的九九乘法口诀表简洁版
2014/07/28 PHP
PHP中的表达式简述
2016/05/29 PHP
JavaScript 设计模式 安全沙箱模式
2010/09/24 Javascript
基于JavaScript实现继承机制之构造函数方法对象冒充的使用详解
2013/05/07 Javascript
2则自己编写的jQuery特效分享
2015/02/26 Javascript
浅析JS操作DOM的一些常用方法
2016/05/13 Javascript
Bootstrap常用组件学习(整理)
2017/03/24 Javascript
es6 字符串String的扩展(实例讲解)
2017/08/03 Javascript
React中使用collections时key的重要性详解
2017/08/07 Javascript
深入理解与使用keep-alive(配合router-view缓存整个路由页面)
2018/09/25 Javascript
JavaScript学习笔记之图片库案例分析
2019/01/08 Javascript
vue里的data要用return返回的原因浅析
2019/05/28 Javascript
JavaScript实现拖拽功能
2020/02/11 Javascript
JS通过识别id、value值对checkbox设置选中状态
2020/02/19 Javascript
Vue点击切换Class变化,实现Active当前样式操作
2020/07/17 Javascript
对Python中的@classmethod用法详解
2018/04/21 Python
Django框架实现的简单分页功能示例
2018/12/04 Python
python从子线程中获得返回值的方法
2019/01/30 Python
Python 隐藏输入密码时屏幕回显的实例
2019/02/19 Python
python定时复制远程文件夹中所有文件
2019/04/30 Python
python PyAutoGUI 模拟鼠标键盘操作和截屏功能
2019/08/04 Python
python用线性回归预测股票价格的实现代码
2019/09/04 Python
Pytorch高阶OP操作where,gather原理
2020/04/30 Python
HTML5 Canvas锯齿图代码实例
2014/04/10 HTML / CSS
凯特方迪化妆品官网:Kat Von D Beauty
2016/11/15 全球购物
暑期教师培训方案
2014/06/07 职场文书
承诺书样本
2014/08/30 职场文书
初二学生评语大全
2014/12/26 职场文书
2015年技术工作总结范文
2015/04/20 职场文书
运动会开幕式新闻稿
2015/07/17 职场文书
2019单位介绍信怎么写
2019/06/24 职场文书
正确使用MySQL update语句
2021/05/26 MySQL