简体   繁体   English

python字母猜谜游戏

[英]python letter guessing game

I'm got the bulk of my first real attempt at a python program--a letter guessing game. 我在python程序的第一次真正尝试中有大量的工作-一个猜字母游戏。

I've got the bulk of the work done, but I'm stuck on the last little bit 我已经完成了大部分工作,但最后一刻我被困住了

I want to make it so that the game alternates back and forth between user and AI turns, until the world has been fully revealed. 我想做到这一点,以便游戏在用户和AI回合之间来回切换,直到世界被完全揭示出来为止。 I'm good so far up to here. 到目前为止我很好。 At this point, I want to make it so the player to guess the most letters correctly wins a point. 在这一点上,我想做到这一点,以便玩家猜测最多的字母正确地赢得一个点。 The computer moderator picks another word and starts again. 计算机主持人选择另一个单词,然后重新开始。 The first player to five points wins the game. 第一个获得5分的玩家赢得比赛。

I have a while loop that alternates between user/AI turns, but I can't get it to break properly once the word has been fully unveiled? 我有一个while循环,可以在用户/ AI轮流之间交替,但是一旦这个单词被完全揭示出来,我就无法使其正常中断吗? After that it should be pretty simple to just compare the number of userCorrectLetters to the number of aiCorrectLetters and use that to determine who wins the point for the round. 之后,仅将userCorrectLetters的数量与aiCorrectLetters的数量进行比较,并使用它来确定谁赢得了本轮比赛,应该非常简单。

Then I assume the entire thing should go inside a while loop that doesn't break until one of the players has reached 5 points. 然后,我认为整个事情应该进入一个while循环,直到一个玩家达到5分时才中断。

The other thing I'm having problems with is how to disallow the user from re-guessing a character position that has already been solved. 我遇到的另一件事是如何禁止用户重新猜测已经解决的字符位置。

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 

The problem is here: 问题在这里:

if str(correctLetters) in secretWord:

You might expect that str(['a', 'b', 'c']) returns 'abc' but it does not. 您可能希望str(['a', 'b', 'c'])返回'abc',但不会。 It returns "['a', 'b', 'c']" . 它返回"['a', 'b', 'c']" You should replace that line with: 您应该将该行替换为:

if "".join(correctLetters) in secretWord:

There is one more problem with your code, except for this one: Let's say the correct word is foobar . 您的代码还有一个问题,除了这一问题之外:假设正确的单词是foobar If the user guesses the first 5 letters, but in reversed order, correctLetters will be ['a', 'b', 'o', 'o', 'f'] , and the line if "".join(correctLetters) in secretWord: will evaluate to False bacause 'aboof' is not in 'foobar' . 如果用户猜到了前5个字母,但顺序相反,则correctLetters将为['a', 'b', 'o', 'o', 'f'] ,而该行为if "".join(correctLetters) in secretWord:将评估为False 'aboof'不在'foobar'

You could fix that problem by replacing if "".join(correctLetters) in secretWord: with: 您可以通过将if "".join(correctLetters) in secretWord:替换为:来解决该问题:

if len(correctLetters) > 4:

Basically, this will end the execution of the program as soon as the user guesses 5 correct letters. 基本上,一旦用户猜出5个正确的字母,这将结束程序的执行。 There is no need to check if the the letters are in secretWord , because you already do that in userTurn function. 无需检查字母是否在secretWord ,因为您已经在userTurn函数中执行过此userTurn

You are comparing the string representation of the list correctLetters to the string secretWord . 您正在将列表correctLetters的字符串表示形式与字符串secretWord For example: 例如:

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

Try comparing a string made of the correct letters to the secret word: 尝试将由正确字母组成的字符串与秘密单词进行比较:

>>> ''.join(correctLetters) == secretWord
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM