Python实现的简单hangman游戏实例

本文实例讲述了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程序设计有所帮助。

(0)

相关推荐

  • python实现的生成随机迷宫算法核心代码分享(含游戏完整代码)

    完整代码下载:http://xiazai.jb51.net/201407/tools/python-migong.rar 最近研究了下迷宫的生成算法,然后做了个简单的在线迷宫游戏.游戏地址和对应的开源项目地址可以通过上面的链接找到.开源项目中没有包含服务端的代码,因为服务端的代码实在太简单了.下面将简单的介绍下随机迷宫的生成算法.一旦理解后你会发现这个算法到底有多简单. 1.将迷宫地图分成多个房间,每个房间都有四面墙. 2.让"人"从地图任意一点A出发,开始在迷宫里游荡.从A房间的1/

  • Python新手实现2048小游戏

    接触 Python 不久,看到很多人写2048,自己也捣鼓了一个,主要是熟悉Python语法. 程序使用Python3 写的,代码150行左右,基于控制台,方向键使用输入字符模拟. 演示图片 2048.py # -*- coding:UTF-8 -*- #! /usr/bin/python3 import random v = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] def display(v, score): '''显示

  • python简单猜数游戏实例

    本文实例讲述了python简单猜数游戏.分享给大家供大家参考.具体实现方法如下: #!/usr/bin/env python import random number = random.randint(0,100) print "Hello,Number guessing Game: betwween 0 and 100 inclusive." guessString = raw_input("guess a number: ") guess = int(guess

  • python实现的简单RPG游戏流程实例

    本文实例讲述了python实现的简单RPG游戏流程.分享给大家供大家参考.具体如下: #RPG rpg = True whp = 100 mahp = 100 hhp = 100 MHP = 10 def dgrnd () : wa = raw_input ("What does Warrior do?") ma = raw_input ("What does Mage do?") ha = raw_input ("What does Healer do?

  • python实现的简单猜数字游戏

    本文实例讲述了python实现的简单猜数字游戏.分享给大家供大家参考.具体如下: 给定一个1-99之间的数,让用户猜数字,当用户猜错时会提示用户猜的数字是过大还是过小,知道用户猜对数字为止,猜对数字用的次数越少成绩越好. import random n = random.randint(1, 99) guess = int(raw_input("Enter an integer from 1 to 99: ")) while n != "guess": print

  • 用Python编写一个简单的俄罗斯方块游戏的教程

    俄罗斯方块游戏,使用Python实现,总共有350+行代码,实现了俄罗斯方块游戏的基本功能,同时会记录所花费时间,消去的总行数,所得的总分,还包括一个排行榜,可以查看最高记录. 排行榜中包含一系列的统计功能,如单位时间消去的行数,单位时间得分等. 附源码: from Tkinter import * from tkMessageBox import * import random import time #俄罗斯方块界面的高度 HEIGHT = 18 #俄罗斯方块界面的宽度 WIDTH = 10

  • Python实现的简单算术游戏实例

    本文实例讲述了Python实现的简单算术游戏.分享给大家供大家参考.具体实现方法如下: #!/usr/bin/env python from operator import add, sub from random import randint, choice ops = {'+': add, '-':sub} #定义一个字典 MAXTRIES = 2 def doprob(): op = choice('+-') #用choice从'+-'中随意选择操作符 nums = [randint(1,

  • Python加pyGame实现的简单拼图游戏实例

    本文实例讲述了Python加pyGame实现的简单拼图游戏.分享给大家供大家参考.具体实现方法如下: import pygame, sys, random from pygame.locals import * # 一些常量 WINDOWWIDTH = 500 WINDOWHEIGHT = 500 BACKGROUNDCOLOR = (255, 255, 255) BLUE = (0, 0, 255) BLACK = (0, 0, 0) FPS = 40 VHNUMS = 3 CELLNUMS

  • python实现的简单文本类游戏实例

    本文实例讲述了python实现的简单文本类游戏实现方法.分享给大家供大家参考.具体实现方法如下: ############################################################ # - My version on the game "Dragon Realm". # - taken from the book "invent with python" by Al Sweigart. # - thanks for a grea

  • Python写的贪吃蛇游戏例子

    第一次用Python写这种比较实用且好玩的东西,权当练手吧 游戏说明: * P键控制"暂停/开始"* 方向键控制贪吃蛇的方向 源代码如下: 复制代码 代码如下: from Tkinter import *import tkMessageBox,sysfrom random import randint class Grid(object):    def __init__(self,master=None,window_width=800,window_height=600,grid_

随机推荐