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发送各种形式的邮件的方法汇总
Nov 09 Python
Python性能提升之延迟初始化
Dec 04 Python
Django REST为文件属性输出完整URL的方法
Dec 18 Python
Linux下python制作名片示例
Jul 20 Python
记一次python 内存泄漏问题及解决过程
Nov 29 Python
Python多进程写入同一文件的方法
Jan 14 Python
python利用Opencv实现人脸识别功能
Apr 25 Python
Python学习笔记之Django创建第一个数据库模型的方法
Aug 07 Python
python lambda表达式在sort函数中的使用详解
Aug 28 Python
python多进程(加入进程池)操作常见案例
Oct 21 Python
Tensorflow使用Anaconda、pycharm安装记录
Jul 29 Python
matplotlib 画动态图以及plt.ion()和plt.ioff()的使用详解
Jan 05 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
苏联队长,苏联超人蝙蝠侠,这些登场的“山寨”英雄真的很严肃
2020/04/09 欧美动漫
php文件缓存类用法实例分析
2015/04/22 PHP
PHP中的静态变量及static静态变量使用详解
2015/11/05 PHP
JavaScript之Getters和Setters 平台支持等详细介绍
2012/12/07 Javascript
jquery滚动组件(vticker.js)实现页面动态数据的滚动效果
2013/07/03 Javascript
javascript中的3种继承实现方法
2016/01/27 Javascript
浅谈jQuery 中的事件冒泡和阻止默认行为
2016/05/28 Javascript
JS实现兼容各种浏览器的获取选择文本的方法【测试可用】
2016/06/21 Javascript
微信小程序 地图定位简单实例
2016/10/14 Javascript
web打印小结
2017/01/11 Javascript
javascript中apply/call和bind的使用
2017/02/15 Javascript
微信小程序tabbar不显示解决办法
2017/06/08 Javascript
JavaScript从原型到原型链深入理解
2019/06/03 Javascript
微信小程序从注册账号到上架(图文详解)
2019/07/17 Javascript
如何在Angular8.0下使用ngx-translate进行国际化配置
2019/07/24 Javascript
layui实现三级导航菜单
2019/07/26 Javascript
js设计模式之代理模式及订阅发布模式实例详解
2019/08/15 Javascript
微信小程序实现3D轮播图效果(非swiper组件)
2019/09/21 Javascript
Vue.js实现大屏数字滚动翻转效果
2019/11/29 Javascript
vue实现图片上传预览功能
2019/12/23 Javascript
python追加元素到列表的方法
2015/07/28 Python
Python3.7黑帽编程之病毒篇(基础篇)
2020/02/04 Python
django 多数据库及分库实现方式
2020/04/01 Python
Jupyter Notebook打开任意文件夹操作
2020/04/14 Python
对Python 字典元素进行删除的方法
2020/07/31 Python
python与idea的集成的实现
2020/11/20 Python
新西兰床上用品和家居用品购物网站:Adairs
2018/04/27 全球购物
大学生毕业求职找工作的自我评价
2013/09/29 职场文书
中学实习教师自我鉴定
2013/12/12 职场文书
挂职思想汇报
2013/12/31 职场文书
清华大学自主招生自荐信
2014/01/29 职场文书
总经理助理职责
2014/02/04 职场文书
共筑中国梦演讲稿
2014/04/23 职场文书
学习党的群众路线剖析材料
2014/10/09 职场文书
会议新闻稿
2015/07/17 职场文书
python opencv检测直线 cv2.HoughLinesP的实现
2021/06/18 Python