在蟒蛇的刽子手游戏

时间:2015-04-19 08:18:08

标签: python

萨拉姆大家,

因此,作为MIT ocw问题集的一部分,我正在尝试为python上的hangman游戏编写代码。这是迄今为止的代码:

WORDLIST_FILENAME = "words.txt"


def load_words ():

      print "Loading word list from file..."
      inFile = open ( WORDLIST_FILENAME, ' r ' , 0 ) 
      line=inFile.readline ( ) 
      line = str(line)
      wordlist = str.split(line)
      print "  ", len(wordlist), "words loaded"
      return wordlist

def choose_word(wordlist):
     return random.choice(wordlist)

wordlist =  [e [1:-4] for e in wordlist ] 
wordlist =  [str.lower (e) for e in wordlist ] 


def correct(word,guess):

    wordspace = ["_ "] * len(word)
    occur = word.count(guess)
    print "Occurences are", occur
    word = list(word)

    while occur > 0:

              print "First index is", word.index(guess)
              wordspace[word.index(guess)] = guess
              print wordspace
              print word
              occur -=1
     print ', '.join(wordspace)
     return word



def hangman():

     word = choose_word(wordlist)

     print "Welcome to Hangman, the interactive game!"
     print "I am thinking of a word", len(word), "letters long..."
     word = list(word)
     wordspace = ["_ "] * len(word)
     print ', '.join(wordspace)

    guessnumber = 8


    while guessnumber >= 1:

              guess = str(raw_input("Please make a guess..."))
              guessnumber -= 1

              if guess in word:

                        print "Yoy have guessed correctly!"
                        correct(word,guess)
              else:

                        print "Wrong!"

              print "You have", guessnumber, "guesses left."

现在您已经看过代码,让我告诉您问题:

总的来说,这段代码有潜力,但我遇到了这个困难:

正确的函数在空格中打印单词,除了正确猜出的字母,但未来的迭代不会保留。

例如,假设这个词是梯形图。如果玩家输入“d”,则可以显示正确的功能:

 _ _ d d _ _ 

哪个好。但假设玩家接下来输入“r”。代码原样可以显示:

_ _ _ _ _ r

但不是:

_ _ d d _ r

这就是我想要的。

另外,一旦完全猜到,我怎么能让游戏过期并打印整个单词?也许我应该在某个地方放置休息条件,但在哪里?

我该如何解决这个问题?

感谢和抱歉这个冗长的问题。

3 个答案:

答案 0 :(得分:0)

您需要存储有关已在某处猜到的字母的信息。在这种情况下,我建议事先制作一个空白列表并使用它。

guessedlist = []

def correct(word,guess):
    global guessedlist # You need to make guessedlist a global variable to have an access
    guessedlist = guessedlist + [guess]
    wordspace = []
    for i in word:
        if i in guessedlist:
            wordspace = wordspace + [i + ' ']
        else:
            wordspace = wordspace +['_ ']

# Now wordspace is an ordered list with mix of '_ '(unguessed) and guessed letters.
# I hope this might suit your needs

答案 1 :(得分:0)

import random
import string

WORDLIST_FILENAME = "words.txt"


def load_words():

    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def choose_word(wordlist):

    return random.choice(wordlist)


wordlist = load_words()


def is_word_guessed(secret_word, letters_guessed):

    guesword=''.join(letters_guessed)
    if secret_word==guesword:
        return True
    else:
        return False

def get_guessed_word(secret_word, letters_guessed):

    L=list(secret_word)
    count=-1
    for l in L:
        count+=1
        if l in letters_guessed:
            continue
        else:
            L[count]=('_ ')
    return ''.join(L)

def get_available_letters(letters_guessed):

    remain=list(string.ascii_lowercase)
    remainc=remain[:]
    for l in remainc:
        if l in letters_guessed:
            remain.remove(l) 
    return (''.join(remain)).strip()



def hangman(secret_word):

    secret_word=choose_word(wordlist)
    lenght=len(secret_word)
    print('Welcome to the game Hangman!')
    print('The Secret word has',lenght,'letters')
    print (lenght*'_ ')
    limit=lenght+4      
    guessed=[]
    guessedorig=[]
    count=0
    count1=0
    Guessed=[]
    while count< limit and is_word_guessed(secret_word, Guessed) == False :
        print( 'you have', limit-count,'guess left.')
        print('Available letters:',get_available_letters(guessedorig))
        if count==0 and count1==0:
            g=input('please guess a letter:')
        else:
            g=input('please guess another letter:')
        guessed.append(g)
        guessedorig.append(g)
        if g in secret_word:
            print('good guess:',get_guessed_word(secret_word,guessed))
            count1+=1
        else:
            guessed.remove(g)
            print('Ooops! That letter is not in my word',get_guessed_word(secret_word,guessed))
            count+=1
        Guessed=list(get_guessed_word(secret_word,guessed))
    if is_word_guessed(secret_word, Guessed) is True:
        print ('well done')
    else:
        print("sorry you could'nt guess my word this time",is_word_guessed(secret_word, guessed))
        print(secret_word)    

    input("Press enter to exit ;)")

答案 2 :(得分:-1)

作为我的python课程的一部分,我不得不使用MIT网站做同样的问题。我用以下代码完成了课程。

import random
import string
import re

WORDLIST_FILENAME = "words.txt"

def load_words():
    """
    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 choose_word(wordlist):
    """
    wordlist (list): list of words (strings)

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

wordlist = load_words()


print "WELCOME TO HANGMAN!"

print '                                            '

print '------------------------------------------'

print '                                            '

import random #for random.choice
word=random.choice(wordlist)
original=list(word)
temp=list(word)
guess=[] #null list
lettersguessed=[]
trial=int(0) #for keeping track of guessess
userinput=''
counter=int(0) #keeping track of position of element in list (if found)
underscore_list = [len(word)]


for i in range(len(original)): #creating the '_ _**....' list
    if (original[i]==' '):
        guess.append(" ") #(whitespace) for vowels
    else:
        guess.append("_") #_ for all other alphabets


guess_2 = ' '.join(guess)
print guess_2


while trial<8:
    userinput=str.lower(raw_input('Input : '))


    if not re.search(r'[A-Za-z]', userinput):
        print "That isn't a letter!", ' '.join(guess)
        continue

    if userinput in lettersguessed:  # test presence
        print "This letter has been guessed already!", ' '.join(guess)
        continue
    else:
        lettersguessed.append(userinput) # remember as used

    if len(userinput)>1: #checking for multiple characters
        print 'Error : Input only a single character', ' '.join(guess)
        continue




    if userinput in original:
        while userinput in temp: #loop for checking redundant characters
            counter=temp.index(userinput)
            guess[counter]=userinput
            temp.remove(userinput)
            temp.insert(counter,'_')

        counter=0

        for i in range(0,len(temp)): #checking for final guess match with original
            if temp[i]=='_':
                counter+=1



        if counter==len(original): #if guess matches original
            print 'Correct\t', word
            print 'You Survived!'
            trial=10
            break

        print 'Correct\t' , ' '.join(guess), '\tTrials left: ', (8-trial)




    else:
        trial+=1
        print 'Incorrect',' '.join(guess), '\tTrials left: ', (8-trial)
else:
    print 'You Died!! Try again!'
    print 'Correct answer was\t', word  

我希望这会有所帮助。如果它确实请投票。谢谢!