1

我第一次真正尝试了一个 python 程序——一个字母猜谜游戏。

我已经完成了大部分工作,但我被困在最后一点

我想让游戏在用户回合和 AI 回合之间来回交替,直到世界完全展现。到目前为止,我都很好。在这一点上,我想让正确猜出最多字母的玩家赢得一分。电脑版主又选了一个词,重新开始。第一个获得五分的玩家赢得比赛。

我有一个在用户/AI 轮次之间交替的 while 循环,但是一旦这个词完全公开,我就不能让它正确中断?之后,只需将 userCorrectLetters 的数量与 aiCorrectLetters 的数量进行比较,并使用它来确定谁赢得了这一轮的分数,这应该非常简单。

然后我假设整个事情应该进入一个 while 循环,直到其中一名玩家达到 5 分才会中断。

我遇到的另一件事是如何禁止用户重新猜测已经解决的角色位置。

import random


#set initial values
player1points= 0
ai= 0
userCorrectLetters= []
aiCorrectLetters=[]
wrongLetters=[]
wrongPlace= []
correctLetters = []
endGame = False
allLetters = set(list('abcdefghijklmnopqrstuvwxyz'))
alreadyGuessed = set() 
userGuessPosition = 0
availLetters = allLetters.difference(alreadyGuessed)


#import wordlist, create mask
with open('wordlist.txt') as wordList:
    secretWord = random.choice(wordList.readlines()).strip()
print (secretWord)
secretWordLength = len(secretWord)








def displayGame():
    mask = '_'  * len(secretWord)
    for i in range (len(secretWord)):
        if secretWord[i] in correctLetters:
            mask = mask[:i] + secretWord[i] + mask [i+1:]
    for letter in mask:
        print (letter, end='')
    print (' ')
    print ('letters in word but not in correct location:', wrongPlace)
    print ('letters not in word:', wrongLetters)



    ##asks the user for a guess, assigns input to variable

def getUserGuess(alreadyGuessed):


    while True:
        print ('enter your letter')
        userGuess = input ()
        userGuess= userGuess.lower()
        if len(userGuess) != 1:
            print ('please enter only one letter')
        elif userGuess in alreadyGuessed:
            print ('that letter has already been guessed. try again')
        elif userGuess not in 'abcdefjhijklmnopqrstuvwxyz':
            print ('only letters are acceptable guesses. try again.')
        else:
            return userGuess

def newGame():
    print ('yay. that was great. do you want to play again? answer yes or no.')
    return input().lower().startswith('y')

def userTurn(wrongLetters, wrongPlace, correctLetters):
    print ('\n')

    displayGame ()
    print ('which character place would you like to guess. Enter number?')
    userGuessPosition = input ()
    if userGuessPosition not in ('123456789'):
        print ('please enter a NUMBER')
        userGuessPosition = input()
    slice1 = int(userGuessPosition) - 1  


    ##player types in letter
    guess = getUserGuess(wrongLetters + correctLetters)
    if guess== (secretWord[slice1:int(userGuessPosition)]):
        print ('you got it right! ')
        correctLetters.append(guess)
        userCorrectLetters.append(guess)
        displayGame()

    elif guess in secretWord:
            wrongPlace.append(guess) 
            print ('that letter is in the word, but not in that position')
            displayGame()

    else:
            wrongLetters.append(guess)
            print ('nope. that letter is not in the word')
            displayGame()




def aiTurn(wrongLetters,wrongPlace, correctLetters):
    print ('\n')
    print ("it's the computers turn")

    aiGuessPosition = random.randint(1, secretWordLength)

    aiGuess=random.sample(availLetters, 1)
    print ('the computer has guessed', aiGuess, "in position", + aiGuessPosition)
    slice1 = aiGuessPosition - 1
    if str(aiGuess) == (secretWord[slice1:userGuessPosition]):
            correctLetters.append(aiGuess)
            aiCorrectLetters.append(aiGuess)
            print ('this letter is correct ')
            return 
    elif str(aiGuess) in secretWord:
            wrongPlace.append(aiGuess)
            print ('that letter is in the word, but not in that position')
            return

    else:
            wrongLetters.append(aiGuess)
            print ('that letter is not in the word')
            return



wordSolved = False 
while wordSolved == False:

    userTurn(wrongLetters, wrongPlace, correctLetters)
    aiTurn(wrongLetters, wrongPlace, correctLetters)
    if str(correctLetters) in secretWord:
        break 
4

2 回答 2

2

问题在这里:

if str(correctLetters) in secretWord:

您可能期望str(['a', 'b', 'c'])返回“abc”,但事实并非如此。它返回"['a', 'b', 'c']"。您应该将该行替换为:

if "".join(correctLetters) in secretWord:

您的代码还有一个问题,除了这个:假设正确的单词是foobar. 如果用户猜出前 5 个字母,但顺序相反,correctLetters将为['a', 'b', 'o', 'o', 'f'],并且该行将if "".join(correctLetters) in secretWord:评估为因为Falseis 'aboof'not in 'foobar'

您可以通过替换为来解决该问题if "".join(correctLetters) in secretWord:

if len(correctLetters) > 4:

基本上,一旦用户猜对了 5 个字母,这将结束程序的执行。无需检查字母是否在 中secretWord,因为您已经在userTurn函数中执行此操作。

于 2013-04-09T19:03:43.110 回答
0

您正在将列表的字符串表示形式与 string 进行correctLetters比较secretWord。例如:

>>> secretWord = 'ab'
>>> correctLetters = ['a','b']
>>> str(correctLetters)
"['a', 'b']"
>>> str(correctLetters) in secretWord
False

尝试将由正确字母组成的字符串与秘密单词进行比较:

>>> ''.join(correctLetters) == secretWord
True
于 2013-04-09T19:06:01.083 回答