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之开始真正编程
Sep 12 Python
Python编程中的for循环语句学习教程
Oct 14 Python
使用Nginx+uWsgi实现Python的Django框架站点动静分离
Mar 21 Python
Python简单定义与使用字典dict的方法示例
Jul 25 Python
Python中一些不为人知的基础技巧总结
May 19 Python
redis之django-redis的简单缓存使用
Jun 07 Python
Python使用logging模块实现打印log到指定文件的方法
Sep 05 Python
python实现QQ批量登录功能
Jun 19 Python
python移位运算的实现
Jul 15 Python
Python基于Faker假数据构造库
Nov 30 Python
Python实现Word文档转换Markdown的示例
Dec 22 Python
使用Python爬虫爬取小红书完完整整的全过程
Jan 19 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 ci框架中加载css和js文件失败的解决方法
2014/03/03 PHP
php的单例模式及应用场景详解
2021/02/27 PHP
20款效果非常棒的 jQuery 插件小结分享
2011/11/18 Javascript
eval的两组性能测试数据
2012/08/17 Javascript
js实现div的切换特效上一个下一个
2014/02/11 Javascript
JQuery为元素添加样式的实现方法
2016/07/20 Javascript
JavaScript定时器setTimeout()和setInterval()详解
2017/08/18 Javascript
vue+swiper实现侧滑菜单效果
2017/12/28 Javascript
Node.Js生成比特币地址代码解析
2018/04/21 Javascript
vue路由守卫+登录态管理实例分析
2019/05/21 Javascript
Vue路由前后端设计总结
2019/08/06 Javascript
js中Function引用类型常见有用的方法和属性详解
2019/12/11 Javascript
python爬虫框架talonspider简单介绍
2017/06/09 Python
matlab中实现矩阵删除一行或一列的方法
2018/04/04 Python
python中的decimal类型转换实例详解
2019/06/26 Python
Django中信号signals的简单使用方法
2019/07/04 Python
postman模拟访问具有Session的post请求方法
2019/07/15 Python
python通过移动端访问查看电脑界面
2020/01/06 Python
PyCharm刷新项目(文件)目录的实现
2020/02/14 Python
python 异步async库的使用说明
2020/05/04 Python
Pytorch通过保存为ONNX模型转TensorRT5的实现
2020/05/25 Python
解决numpy矩阵相减出现的负值自动转正值的问题
2020/06/03 Python
Python ADF 单位根检验 如何查看结果的实现
2020/06/03 Python
Python中lru_cache的使用和实现详解
2021/01/25 Python
意大利咖啡、浓缩咖啡和浓缩咖啡机:illy caffe
2019/03/20 全球购物
如何让Java程序执行效率更高
2014/06/25 面试题
个人能力自我鉴赏
2014/01/25 职场文书
仓管员岗位责任制
2014/02/19 职场文书
《陶罐和铁罐》教学反思
2014/02/19 职场文书
社团2014年植树节活动总结
2014/03/11 职场文书
给老婆的道歉信
2015/01/20 职场文书
2015国庆节66周年演讲稿
2015/03/20 职场文书
2015年客服工作总结范文
2015/04/02 职场文书
2016企业先进集体事迹材料
2016/02/25 职场文书
大学生如何逃脱“毕业季创业队即散伙”魔咒?
2019/08/19 职场文书
一篇文章带你了解Python和Java的正则表达式对比
2021/09/15 Python