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 Web开发框架Django
Jun 30 Python
跟老齐学Python之编写类之二方法
Oct 11 Python
在Linux下使用Python的matplotlib绘制数据图的教程
Jun 11 Python
Python聚类算法之基本K均值实例详解
Nov 20 Python
Python中的函数作用域
May 07 Python
用Python实现筛选文件脚本的方法
Oct 27 Python
在Python 中同一个类两个函数间变量的调用方法
Jan 31 Python
Python3.7下安装pyqt5的方法步骤(图文)
May 12 Python
Python 如何在字符串中插入变量
Aug 01 Python
python 批量下载bilibili视频的gui程序
Nov 20 Python
虚拟环境及venv和virtualenv的区别说明
Feb 05 Python
python实现简易名片管理系统
Apr 11 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采集速度探究总结(原创)
2008/04/18 PHP
php中使用$_REQUEST需要注意的一个问题
2013/05/02 PHP
百度地图API使用方法详解
2015/08/25 PHP
PHP 数组黑名单/白名单实例代码详解
2019/06/04 PHP
一些技巧性实用js代码小结
2009/10/14 Javascript
教你如何使用node.js制作代理服务器
2014/11/26 Javascript
JavaScript中对象property的读取和写入方法介绍
2014/12/30 Javascript
PHP配置文件php.ini中打开错误报告的设置方法
2015/01/09 PHP
Javascript基础知识盲点总结之函数
2016/05/15 Javascript
AngularJS基础 ng-include 指令示例讲解
2016/08/01 Javascript
AngularJS深入探讨scope,继承结构,事件系统和生命周期
2016/11/02 Javascript
使用JS正则表达式 替换括号,尖括号等
2016/11/29 Javascript
jQuery插件HighCharts绘制2D带Label的折线图效果示例【附demo源码下载】
2017/03/08 Javascript
基于JavaScript实现表格滚动分页
2017/11/22 Javascript
vue中改变选中当前项的显示隐藏或者状态的实现方法
2018/02/08 Javascript
AngularJS $http post 传递参数数据的方法
2018/10/09 Javascript
使用JavaScript保存文本文件到本地的两种方法
2019/01/22 Javascript
vue自定义标签和单页面多路由的实现代码
2020/05/03 Javascript
[53:10]Secret vs Pain 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/20 DOTA
Python数据分析之双色球中蓝红球分析统计示例
2018/02/03 Python
python利用高阶函数实现剪枝函数
2018/03/20 Python
python调用Matplotlib绘制分布点并且添加标签
2018/05/31 Python
python 使用opencv 把视频分割成图片示例
2019/12/12 Python
css3实例教程 一款纯css3实现的发光屏幕旋转特效
2014/12/07 HTML / CSS
数据库什么时候应该被重组
2012/11/02 面试题
Why we need EJB
2016/10/20 面试题
电大物流学生的自我评价
2013/10/25 职场文书
如何打造一封优秀的留学推荐信
2014/01/25 职场文书
《在大海中永生》教学反思
2014/02/24 职场文书
给校长的一封建议书
2014/03/12 职场文书
服务承诺书格式
2014/05/21 职场文书
中药学自荐信
2014/06/15 职场文书
设计专业毕业生求职信
2014/06/25 职场文书
小学关爱留守儿童活动方案
2014/08/25 职场文书
如果用一句诗总结你的上半年,你会用哪句呢?
2019/07/16 职场文书
nginx常用命令放入shell脚本详解
2021/03/31 Servers