注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

見るところ花にあらずと云ふことなし

褎然举首

 
 
 

日志

 
 

Game Hangman in Python  

2015-07-03 23:04:58|  分类: Python |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
6001x的作业。
能运行Python的朋友可以玩玩看~
不过要自己建一个words.txt文件调用。

# 6.00 Problem Set 3
# Hangman game
#

# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)

import random
import string

WORDLIST_FILENAME = "words.txt"

def loadWords():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print "Loading word list from file..."
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r', 0)
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = string.split(line)
    print "  ", len(wordlist), "words loaded."
    return wordlist

def chooseWord(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code
# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()


def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    # FILL IN YOUR CODE HERE...
    if len(secretWord)==0 or len(lettersGuessed)==0:
            return False
    else:
       
        def cmp2(secretWord,lettersGuessed):
            result=True
            for c in secretWord:
                result=result and c in lettersGuessed
            return result
        return   cmp2(secretWord,lettersGuessed)

def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    # FILL IN YOUR CODE HERE...
    result=''
    for c in secretWord:
         if c  in lettersGuessed:
              result=result+c
         else:
              result=result+'_ '
    return result


def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''
    # FILL IN YOUR CODE HERE...
    str1=''

    import string
    str1=str1+string.ascii_lowercase
    print str1
    n=0
    def cut(str1):
    
        if len(str1)==0:
            return ''
        elif str1[n] in lettersGuessed:
            return cut(str1[1:])
        else:
            return str1[n]+cut(str1[1:])
    return cut(str1)

def hangman(secretWord):
    '''
    secretWord: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many 
      letters the secretWord contains.

    * Ask the user to supply one guess (i.e. letter) per round.

    * The user should receive feedback immediately after each guess 
      about whether their guess appears in the computers word.

    * After each round, you should also display to the user the 
      partially guessed word so far, as well as letters that the 
      user has not yet guessed.

    Follows the other limitations detailed in the problem write-up.
    '''
    # FILL IN YOUR CODE HERE...
    lengthofsecretWord=len(secretWord)
    print 'Welcome to the game Hangman!'
    print 'I am thinking of a word that is '+str(lengthofsecretWord)+' letters long.'
    print '-----------'
    print 'You have 8 guesses left.'
    print 'Available Letters: abcdefghijklmnopqrstuvwxyz'
    
    guess=[]
  
    def isWordGuessed2(secretWord, lettersGuessed):
      '''
      secretWord: string, the word the user is guessing
      lettersGuessed: list, what letters have been guessed so far
      returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
      '''
      # FILL IN YOUR CODE HERE...
      if len(secretWord)==0 or len(lettersGuessed)==0:
            return False
      else:
       
        def cmp2(secretWord,lettersGuessed):
            result=False
            for c in secretWord:
                result=result or c in lettersGuessed
            return result
      return   cmp2(secretWord,lettersGuessed)

    n=8
    while n>0:
      guessinput=raw_input('Please guess a letter: ')
      guessinput=guessinput.lower()
      
      #print isWordGuessed(secretWord,guessinput)

          
      if isWordGuessed2(secretWord,guessinput):

          if guessinput in guess:
            
            #print guess
            #print guessinput
            print "Oops! You\'ve already guessed that letter: "+getGuessedWord(secretWord, guess)
            print '------------'
            print 'You have '+str(n)+' guesses left.'
            print 'Available letters: '+getAvailableLetters(guess)
          else:
              
            guess.append(guessinput)  
            #print guess 
            if getGuessedWord(secretWord, guess)==secretWord:
                    print 'Good guess: '+getGuessedWord(secretWord, guess)
                    print '------------'
                    print 'Congratulations, you won!'
                    break 
            else:
                    print 'Good guess: '+getGuessedWord(secretWord, guess)
                    print '------------'
                    print 'You have '+str(n)+' guesses left.'
                    print 'Available letters: '+getAvailableLetters(guess)
      else: 
            if guessinput in guess:
            
                   #print guess
                   #print guessinput
                   print "Oops! You\'ve already guessed that letter: "+getGuessedWord(secretWord, guess)
                   print '------------'
                   print 'You have '+str(n)+' guesses left.'
                   print 'Available letters: '+getAvailableLetters(guess)
                   
            else:       
                  guess.append(guessinput)                 
               
                  print 'Oops! That letter is not in my word: '+  getGuessedWord(secretWord, guess)
                  print '------------'
                  n-=1
                  if n>0:
                     print 'You have '+str(n)+' guesses left.'
                     print 'Available letters: '+getAvailableLetters(guess)
                  else:
                     print 'Sorry, you ran out of guesses. The word was else. '



# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)

# secretWord = chooseWord(wordlist).lower()
# hangman(secretWord)
hangman(chooseWord(wordlist))
  评论这张
 
阅读(166)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017