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中的filter和lambda函数的使用
Apr 07 Python
初步理解Python进程的信号通讯
Apr 09 Python
python实现的简单抽奖系统实例
May 22 Python
Python实现给qq邮箱发送邮件的方法
May 28 Python
python中requests小技巧
May 10 Python
python 表达式和语句及for、while循环练习实例
Jul 07 Python
Python(Django)项目与Apache的管理交互的方法
May 16 Python
CentOS下Python3的安装及创建虚拟环境的方法
Nov 28 Python
python tkinter实现屏保程序
Jul 30 Python
解决jupyter notebook 前面书写后面内容消失的问题
Apr 13 Python
关于keras中keras.layers.merge的用法说明
May 23 Python
python 检测图片是否有马赛克
Dec 01 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中mysql模块部分功能的简单封装
2011/09/30 PHP
php fsockopen伪造post与get方法的详解
2013/06/14 PHP
JavaScript 空位补零实现代码
2010/02/26 Javascript
ExtJS 工具栏 分页事件参数
2010/03/05 Javascript
javascript 设计模式之单体模式 面向对象学习基础
2010/04/18 Javascript
js关闭父窗口时关闭子窗口
2013/04/01 Javascript
javascript抽象工厂模式详细说明
2014/12/16 Javascript
JavaScript的Vue.js库入门学习教程
2016/05/23 Javascript
JavaScript 对象字面量讲解
2016/06/06 Javascript
Extjs 中的 Treepanel 实现菜单级联选中效果及实例代码
2017/08/22 Javascript
深入研究React中setState源码
2017/11/17 Javascript
浅谈Postman解决token传参的问题
2018/03/31 Javascript
Vue表单类的父子组件数据传递示例
2018/05/03 Javascript
Vue中使用ElementUI使用第三方图标库iconfont的示例
2018/10/11 Javascript
ES6箭头函数和扩展实例分析
2020/05/23 Javascript
Python中字典的setdefault()方法教程
2017/02/07 Python
django在接受post请求时显示403forbidden实例解析
2018/01/25 Python
python爬取微信公众号文章
2018/08/31 Python
Django中如何防范CSRF跨站点请求伪造攻击的实现
2019/04/28 Python
python实现图片转字符画
2021/02/19 Python
详解HTML5中的Communication API基本使用方法
2016/01/29 HTML / CSS
美国婚戒购物网站:Anjays Designs
2017/06/28 全球购物
财务会计专业毕业生自荐信
2013/10/02 职场文书
园林设计师自荐信
2013/11/18 职场文书
应急处置方案
2014/06/16 职场文书
党的群众路线教育实践活动心得体会(医院)
2014/11/03 职场文书
市场部经理岗位职责
2015/02/02 职场文书
小学三八妇女节活动总结
2015/02/06 职场文书
研究生个人学年总结
2015/02/14 职场文书
2015年防汛工作总结
2015/05/15 职场文书
故意伤害罪辩护词
2015/05/21 职场文书
交通肇事罪辩护词
2015/05/21 职场文书
学会掌握自己命运的十条黄金法则:
2019/08/08 职场文书
CSS布局之浮动(float)和定位(position)属性的区别
2021/09/25 HTML / CSS
Mysql分库分表之后主键处理的几种方法
2022/02/15 MySQL
SONY600GR,国产收音机厂商永远的痛
2022/04/05 无线电