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实现的几个常用排序算法实例
Jun 16 Python
Python字典的核心底层原理讲解
Jan 24 Python
树莓派与PC端在局域网内运用python实现即时通讯
Jun 22 Python
Django框架 Pagination分页实现代码实例
Sep 04 Python
python使用正则来处理各种匹配问题
Dec 22 Python
解决Jupyter Notebook开始菜单栏Anaconda下消失的问题
Apr 13 Python
Python实现寻找回文数字过程解析
Jun 09 Python
Python enumerate() 函数如何实现索引功能
Jun 29 Python
Python使用grequests并发发送请求的示例
Nov 05 Python
python SOCKET编程基础入门
Feb 27 Python
Python使用sql语句对mysql数据库多条件模糊查询的思路详解
Apr 12 Python
Python机器学习三大件之一numpy
May 10 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 gd2 上传图片/文字水印/图片水印/等比例缩略图/实现代码
2010/05/15 PHP
支持中文字母数字、自定义字体php验证码代码
2012/02/27 PHP
php实现贪吃蛇小游戏
2016/07/26 PHP
PHP生成及获取JSON文件的方法
2016/08/23 PHP
javascript编程起步(第二课)
2007/02/27 Javascript
JavaScript作用域与作用域链深入解析
2013/12/06 Javascript
js字符串转换成数字与数字转换成字符串的实现方法
2014/01/08 Javascript
javascript操作excel生成报表全攻略
2014/05/04 Javascript
JavaScript中使用Object.create()创建对象介绍
2014/12/30 Javascript
jQuery+Ajax+PHP+Mysql实现分页显示数据实例讲解
2015/09/27 Javascript
完美的js div拖拽实例代码
2016/09/24 Javascript
自己封装的一个原生JS拖动方法(推荐)
2016/11/22 Javascript
微信分享调用jssdk实例
2017/06/08 Javascript
vue.js学习之vue-cli定制脚手架详解
2017/07/02 Javascript
使用Vue制作图片轮播组件思路详解
2018/03/21 Javascript
JavaScript分步实现一个出生日期的正则表达式
2018/03/22 Javascript
Vue中computed、methods与watch的区别总结
2019/04/10 Javascript
使用 Vue cli 3.0 构建自定义组件库的方法
2019/04/30 Javascript
angular4应用中输入的最小值和最大值的方法
2019/05/17 Javascript
Vue.js自定义指令学习使用详解
2019/10/19 Javascript
在vue中实现echarts随窗体变化
2020/07/27 Javascript
js实现电灯开关效果
2021/01/19 Javascript
[01:04:48]VGJ.S vs TNC Supermajor 败者组 BO3 第一场 6.6
2018/06/07 DOTA
python抓取京东价格分析京东商品价格走势
2014/01/09 Python
python-序列解包(对可迭代元素的快速取值方法)
2019/08/24 Python
Python爬取豆瓣视频信息代码实例
2019/11/16 Python
python中if及if-else如何使用
2020/06/02 Python
Canvas图片分割效果的实现
2019/07/29 HTML / CSS
什么是SCM(软件配置管理)
2014/08/16 面试题
金融专业推荐信
2013/11/14 职场文书
《唯一的听众》教学反思
2014/02/20 职场文书
安全生产月标语
2014/10/07 职场文书
三孔导游词
2015/02/05 职场文书
2015年万圣节活动总结
2015/03/24 职场文书
现役军人家属慰问信
2015/03/24 职场文书
谢师宴家长致辞
2015/07/27 职场文书