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字符串关键点
Dec 13 Python
实现python版本的按任意键继续/退出
Sep 26 Python
python 换位密码算法的实例详解
Jul 19 Python
Python2和Python3中print的用法示例总结
Oct 25 Python
Python 内置函数memoryview(obj)的具体用法
Nov 23 Python
Python发送邮件功能示例【使用QQ邮箱】
Dec 04 Python
python调用函数、类和文件操作简单实例总结
Nov 29 Python
Python实现常见的几种加密算法(MD5,SHA-1,HMAC,DES/AES,RSA和ECC)
May 09 Python
python 如何使用find和find_all爬虫、找文本的实现
Oct 16 Python
python 遍历磁盘目录的三种方法
Apr 02 Python
教你怎么用Python操作MySql数据库
May 31 Python
基于Python实现nc批量转tif格式
Aug 14 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实现无限级分类 | 树型显示分类关系
2006/11/19 PHP
php 设计模式之 单例模式
2008/12/19 PHP
PHP iconv 函数转gb2312的bug解决方法
2009/10/11 PHP
php下正则来匹配dede模板标签的代码
2010/08/21 PHP
php实现利用phpexcel导出数据
2013/08/24 PHP
一个可以显示阴历的JS代码
2007/03/05 Javascript
中文字符串截取的js函数代码
2013/04/17 Javascript
jQuery.lazyload+masonry改良图片瀑布流代码
2014/06/20 Javascript
Nodejs实现批量下载妹纸图
2015/05/28 NodeJs
jQuery判断多个input file 都不能为空的例子
2015/06/23 Javascript
jQuery 翻页组件yunm.pager.js实现div局部刷新的思路
2016/08/11 Javascript
vue-router 导航钩子的具体使用方法
2017/08/31 Javascript
解决layui 复选框等内置控件不显示的问题
2018/08/14 Javascript
在vue中读取本地Json文件的方法
2018/09/06 Javascript
4个顶级开源JavaScript图表库
2018/09/29 Javascript
详解小程序不同页面之间通讯的解决方案
2018/11/23 Javascript
Vue2.x Todo之自定义指令实现自动聚焦的方法
2019/01/08 Javascript
Vue 后台管理类项目兼容IE9+的方法示例
2019/02/20 Javascript
微信小程序云开发之使用云数据库
2019/05/17 Javascript
Python使用修饰器执行函数的参数检查功能示例
2017/09/26 Python
python设置环境变量的作用和实例
2019/07/09 Python
全面了解django的缓存机制及使用方法
2019/07/22 Python
python批量图片处理简单示例
2019/08/06 Python
python3 tkinter实现添加图片和文本
2019/11/26 Python
Django Model中字段(field)的各种选项说明
2020/05/19 Python
举例详解CSS3中的Transition
2015/07/15 HTML / CSS
Grow Gorgeous美国官网:只要八天,体验唤醒毛囊后新生的茂密秀发
2018/06/04 全球购物
一个C/C++编程面试题
2013/11/10 面试题
主要的Ajax框架都有什么
2013/11/14 面试题
销售人员中英文自荐信
2013/09/22 职场文书
《那片绿绿的爬山虎》教学反思
2014/02/27 职场文书
文明村创建实施方案
2014/03/27 职场文书
个人作风建设剖析材料
2014/10/11 职场文书
工会积极分子个人总结
2015/03/03 职场文书
护士医德医风心得体会
2016/01/25 职场文书
Java 轮询锁使用时遇到问题
2022/05/11 Java/Android