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 相关文章推荐
PyMongo安装使用笔记
Apr 27 Python
python读写ini配置文件方法实例分析
Jun 30 Python
python实现猜数字小游戏
Mar 24 Python
解决Python 中英文混输格式对齐的问题
Jul 16 Python
Python使用pickle模块报错EOFError Ran out of input的解决方法
Aug 16 Python
Pandas透视表(pivot_table)详解
Jul 22 Python
python模拟实现分发扑克牌
Apr 22 Python
PyCharm中配置PySide2的图文教程
Jun 18 Python
基于pytorch中的Sequential用法说明
Jun 24 Python
Python Selenium操作Cookie的实例方法
Feb 28 Python
python爬虫破解字体加密案例详解
Mar 02 Python
Python基础教程,Python入门教程(超详细)
Jun 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数据流应用的一个简单实例
2012/09/14 PHP
is_uploaded_file函数引发的不能上传文件问题
2013/10/29 PHP
浅析php工厂模式
2014/11/25 PHP
jquery数据验证插件(自制,简单,练手)实例代码
2013/10/24 Javascript
jquery实现树形二级菜单实例代码
2013/11/20 Javascript
JS替换文本域内的回车示例
2014/02/18 Javascript
JQuery中使用Ajax赋值给全局变量失败异常的解决方法
2014/08/18 Javascript
JavaScript iframe数据共享接口实现方法
2016/01/06 Javascript
JavaScript  cookie 跨域访问之广告推广
2016/04/20 Javascript
JavaScript:Date类型全面解析
2016/05/19 Javascript
当jquery ajax遇上401请求的解决方法
2016/05/19 Javascript
AngularJs $parse、$eval和$observe、$watch详解
2016/09/21 Javascript
jQuery实现边框动态效果的实例代码
2016/09/23 Javascript
关于JS中二维数组的声明方法
2016/09/24 Javascript
EasyUI学习之DataGird分页显示数据
2016/12/29 Javascript
vue.js将unix时间戳转换为自定义时间格式
2017/01/03 Javascript
jQuery插件echarts设置折线图中折线线条颜色和折线点颜色的方法
2017/03/03 Javascript
javascript函数的节流[throttle]与防抖[debounce]
2017/11/15 Javascript
vue实现压缩图片预览并上传功能(promise封装)
2019/01/10 Javascript
React中阻止事件冒泡的问题详析
2019/04/12 Javascript
JS中如何轻松遍历对象属性的方式总结
2019/08/06 Javascript
js模拟实现烟花特效
2020/03/10 Javascript
原生JavaScript创建不可变对象的方法简单示例
2020/05/07 Javascript
解决vue init webpack 下载依赖卡住不动的问题
2020/11/09 Javascript
Python字符串逐字符或逐词反转方法
2015/05/21 Python
Python即时网络爬虫项目启动说明详解
2018/02/23 Python
python 3调用百度OCR API实现剪贴板文字识别
2018/09/04 Python
六行python代码的爱心曲线详解
2019/05/17 Python
keras自定义损失函数并且模型加载的写法介绍
2020/06/15 Python
python正则表达式的懒惰匹配和贪婪匹配说明
2020/07/13 Python
Python 实现一个计时器
2020/07/28 Python
EJB发布WEB服务一般步骤
2012/10/31 面试题
安全生产工作汇报
2014/10/28 职场文书
学校党的群众路线教育实践活动总结材料
2014/10/30 职场文书
高二化学教学反思
2016/02/22 职场文书
智慧人生:永远不需要向任何人解释你自己
2019/08/20 职场文书