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 29 Python
简单介绍Python中的try和finally和with方法
May 05 Python
python脚本设置系统时间的两种方法
Feb 21 Python
Flask框架实现给视图函数增加装饰器操作示例
Jul 16 Python
python: 自动安装缺失库文件的方法
Oct 22 Python
python分块读取大数据,避免内存不足的方法
Dec 10 Python
PyTorch 1.0 正式版已经发布了
Dec 13 Python
情人节快乐! python绘制漂亮玫瑰
Aug 18 Python
Django中Middleware中的函数详解
Jul 18 Python
tensorflow模型保存、加载之变量重命名实例
Jan 21 Python
python自动下载图片的方法示例
Mar 25 Python
Python 实现一行输入多个数字(用空格隔开)
Apr 29 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简单的留言板与回复功能具体实现
2014/02/19 PHP
PHP+jquery+CSS制作头像登录窗(仿QQ登陆)
2016/10/20 PHP
js文字滚动停顿效果代码
2008/06/28 Javascript
一个可以随意添加多个序列的tag函数
2009/07/21 Javascript
javascript实现控制浏览器全屏
2015/03/30 Javascript
jQuery实现可关闭固定于底(顶)部的工具条菜单效果
2015/11/06 Javascript
js简单实现调整网页字体大小的方法
2016/07/23 Javascript
js自定义弹框插件的封装
2020/08/24 Javascript
JS一个简单的注册页面实例
2017/09/05 Javascript
jQuery响应滚动条事件功能示例
2017/10/14 jQuery
react-router4按需加载(踩坑填坑)
2019/01/06 Javascript
Vue如何获取数据列表展示
2019/12/11 Javascript
vue父子模板传值问题解决方法案例分析
2020/02/26 Javascript
微信小程序实现多选框功能的实例代码
2020/06/24 Javascript
分享15个最受欢迎的Python开源框架
2014/07/13 Python
Python进阶篇之字典操作总结
2016/11/16 Python
Django之PopUp的具体实现方法
2019/08/31 Python
python应用文件读取与登录注册功能
2019/09/23 Python
TensorFlow索引与切片的实现方法
2019/11/20 Python
PyCharm 专业版安装图文教程
2020/02/20 Python
法国最大电子商务平台:Cdiscount
2018/03/13 全球购物
Web Service面试题:如何搭建Axis2的开发环境
2012/06/20 面试题
Sql面试题
2013/03/20 面试题
如何理解transaction事务的概念
2015/05/27 面试题
自荐信格式写作方法有哪些呢
2013/11/20 职场文书
自我鉴定四大框架
2014/01/17 职场文书
高一新生军训方案
2014/05/12 职场文书
公司总经理助理岗位职责
2014/07/09 职场文书
如何写观后感
2015/06/19 职场文书
幼儿园元旦主持词
2015/07/06 职场文书
2015年教学副校长工作总结
2015/07/22 职场文书
小学生安全教育主题班会
2015/08/12 职场文书
mysql死锁和分库分表问题详解
2021/04/16 MySQL
Java实现带图形界面的聊天程序
2022/06/10 Java/Android
Python绘制散点图之可视化神器pyecharts
2022/07/07 Python