MOOC:计算机科学及Python编程导论

Study : Introduction to Computer Science and Programming Using Python

Problem Set 3 hangman:

# 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 = "C:/Users/y50/6.00.1x Files/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...
    i=0
    n=0
    copy=[]
    num=range(len(secretWord))
    for letter in secretWord:
        copy.append(letter)    
    while i<len(lettersGuessed):
        count=0
        if lettersGuessed[i] in secretWord:
            for letter in copy:
                if letter==lettersGuessed[i]:
                    count+=1
            num.remove(copy.index(lettersGuessed[i]))
            if count>1:
                while n<(count-1):   
                    copy[copy.index(lettersGuessed[i])]=0
                    num.remove(copy.index(lettersGuessed[i]))
                    n+=1
        i+=1
        if num==[]:
            return True   
    return False


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.

>>> secretWord = 'apple' 
>>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
>>> print getGuessedWord(secretWord, lettersGuessed)
'_ pp_ e'
    '''
    # FILL IN YOUR CODE HERE...
    i=0
    n=0
    copy=[]
    copy1=['_ ']*len(secretWord)
    for letter in secretWord:
        copy.append(letter)    
    while i<len(lettersGuessed):
        count=0
        if lettersGuessed[i] in secretWord:
            for letter in copy:
                if letter==lettersGuessed[i]:
                    count+=1
            if count==1:
                copy1[copy.index(lettersGuessed[i])]=lettersGuessed[i]
            elif count>1:
                while n<count: 
                    copy1[copy.index(lettersGuessed[i])]=lettersGuessed[i]
                    copy[copy.index(lettersGuessed[i])]=0
                    n+=1
        i+=1
        if copy1==copy:
            a=''.join(copy1)
            return a
    a=''.join(copy1)
    return a

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...
    allletter=string.ascii_lowercase
    copy=[]
    for letter in allletter:
        copy.append(letter)
    for letter in lettersGuessed:
        copy.remove(letter)
    availableletters=''.join(copy)
    return availableletters

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...
    lettersGuessed=[]
    mistakesMade=0
    maxguess=8
    print('Welcome to the game, Hangman!')
    print('I am thinking of a word that is '+str(len(secretWord))+' letters long.')
    while mistakesMade<maxguess:
        print('You have '+str(maxguess-mistakesMade)+' guesses left.')
        print('Available letters: '+getAvailableLetters(lettersGuessed))
        guess=raw_input('Please guess a letter: ')
        guessInLowerCase = guess.lower()
        if guessInLowerCase in lettersGuessed:
            print("Oops! You've already guessed that letter: "+getGuessedWord(secretWord, lettersGuessed))
        else:
            lettersGuessed.append(guessInLowerCase)
            if guessInLowerCase in secretWord:
                print("Good guess: " +getGuessedWord(secretWord, lettersGuessed))
                if isWordGuessed(secretWord, lettersGuessed):
                    break
            else:
                print("Oops! That letter is not in my word: " +getGuessedWord(secretWord, lettersGuessed))
                mistakesMade+=1
    if isWordGuessed(secretWord, lettersGuessed):
        print('Congratulations, you won!')
    else:
        print('Sorry, you ran out of guesses. The word was else. ')
        print('The word was: '+secretWord)


# 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)
def game():
    hangman(chooseWord(wordlist))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值