Python实现的简单hangman游戏实例
作者:不吃皮蛋 发布时间:2021-04-11 19:26:47
标签:Python,游戏
本文实例讲述了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]
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程序设计有所帮助。


猜你喜欢
- 背景介绍Pandas的DataFrame和Series在Matplotlib基础上封装了一个简易的绘图函数,使得数据处理过程中方便可视化查看
- 在Linux系统下Python连接Redis的基本配置方法具体操作步骤系统环境:OS:Oracle Linux Enterprise 5.6
- 线性逻辑回归本文用代码实现怎么利用sklearn来进行线性逻辑回归的计算,下面先来看看用到的数据。这是有两行特征的数据,然后第三行是数据的标
- 前言随着我们不断地在一个文件中添加新的功能, 就会使得文件变得很长。 即便使用了继承,也抑制不住类的成长。为了解决这一问题,我们可以将类存储
- 引入:通常,钓鱼网站本质是本质搭建一个跟正常网站一模一样的页面,用户在该页面上完成转账功能转账的请求确实是朝着正常网站的服务端提交,唯一不同
- 如果你是一位ASP爱好者,你一定想过ASP的执行效率如何?大家都知道ASP效率和CGI的比,在访问量少的时候,它们是不相上下的,有时可能CG
- Session StaticObjects 集合StaticObjects 集合包含 Session 对象范围中用 <OBJECT&g
- 安装了pycharm之后有一个新装的python解释器,顶替了之前系统的python那样的话,原来利用pip安装的一些库会无法import.
- element换肤所有主题色和基础色均可自主配置1.element-ui官方提供的动态切换主题方法换肤 但此方法只可修改$&ndas
- 有时在我们注册账户、登陆系统时,当所有验证通过方可提交 这就需要Jquery来实现表单验证,今天分享给小伙伴们一段基于Jquery实现表单验
- goroutine简介goroutine是go语言中最为NB的设计,也是其魅力所在,goroutine的本质是协程,是实现并行计算的核心。g
- 删除字符串中不需要的内容1、strip()方法strip:默认是去掉首尾的空白字符,但是也可以指定其他字符;lstrip:只去掉左边的;rs
- 本脚本为本人在性能测试过程中编写,用于对进程状态的监控,也可以用于日常的监控,适用性一般,扩展性还行# -*- coding: UTF-8
- 本文实例讲述了ThinkPHP框架下微信支付功能总结。分享给大家供大家参考,具体如下:摘要此文主要为个人解决 ThinkPHP3.2.3 下
- 原理 采集程序实际上是通过了XML中的XMLHTTP组件调用其它网站上的网页。比如新闻采集程序,很多都是调用了sina的新闻网页,并且对其中
- 密钥密码'''如密钥短语密码为: university -> universty明文: abcdefghijk
- By: 吴垠 Date: 2007-09-07 Version: 0.5 Email: lazy.fox.wu#gmail.com Home
- Deferred对象结构Deferred由一系列成对的回调链组成,每一对都包含一个用于处理成功的回调(callbacks)和一个用于处理错误
- 1、自动化代码中,用到了哪些设计模式?单例设计模式工厂模式PO设计模式数据驱动模式面向接口编程设计模式2、什么是断言( Assert) ?断
- 1.图例legend基础语法及用法legend语法参数如下: matplotlib.pyplot.legend(*args, **