首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >python loops,双人游戏

python loops,双人游戏
EN

Stack Overflow用户
提问于 2013-04-07 23:19:00
回答 1查看 6.1K关注 0票数 0

我正在用python完成我的第一个简单程序,这是一个双人(用户vs计算机AI)单词/字母猜测游戏。

我已经完成了大部分代码,但我正在尝试整理我的循环,以便游戏可以在用户和AI之间正确地交替。我想让游戏在用户和人工智能之间来回交替,直到世界完全暴露出来。在这一点上,猜对最多字母的玩家赢得一分。计算机主持人选择另一个单词,然后重新开始。第一个得五分的玩家赢得比赛。

我不知道从哪里开始。总的来说,我仍然是python/coding的新手,我很难理解事件发生的顺序。我知道我需要某种类型的主循环,只要单词还没有完全显示出来,它就保持True,但仅此而已。

另外,任何其他关于如何优化下面的代码或以任何方式清理它的建议都将不胜感激!

代码语言:javascript
运行
复制
import random


#set initial values
player1points= 0
ai= 0
userCorrectLetters= ''
aiCorrectLetters=''
wrongLetters=''
wrongPlace= ''
correctLetters = ''
notInWord = ''
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')


userTurn=True     
while userTurn == True:
    displayGame ()
    print ('which character place would you like to guess. Enter number?')
    userGuessPosition = int(input())

    slice1 = userGuessPosition - 1  


    ##player types in letter
    guess = getUserGuess(wrongLetters + correctLetters)
    if guess== (secretWord[slice1:userGuessPosition]):
        correctLetters = correctLetters + guess
        print ('you got it right! ')
        displayGame()
        break
    elif guess in secretWord:
            wrongPlace = wrongPlace + guess 
            print ('that letter is in the word, but not in that position')
            displayGame()
            break
    else:
            wrongLetters = wrongLetters + guess
            print ('nope. that letter is not in the word')
            displayGame()
            break

print ("it's the computers turn")

aiTurn=True

while aiTurn == True:
    aiGuessPosition = random.randint(1, secretWordLength)
    print (aiGuessPosition)

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


    displayGame() 
    break     
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-07 23:36:00

看起来它只会转两圈然后退出?

发生的情况是,它命中您的第一个while循环,并开始计算其中的代码。它做了一些事情,然后命中break,这会让你跳出循环,并在第一个循环结束后继续执行。然后,它对第二个循环做同样的事情,到达程序的末尾并退出。

我建议进行以下重构:

  1. while循环下的所有内容放入两个函数user_play中,然后执行一个类似于

的循环

代码语言:javascript
运行
复制
usr_pts = 0
cmp_pts = 0

while (usr_pts < 5 and cmp_pts < 5):
    solved_word = False
    # set up word
    user_turn = False
    user_correct_guess = 0
    ai_correct_guess = 0
    while not solved_word:
        user_turn = not user_turn
        if user_turn:
            guess = play_user(...)
        else:
            guess = computer_play(...)
        # what ever accounting you need to do
        is_guess_in_word = test_guess_in_word(guess, ...)
        if is_guess_in_word:
            if user_turn:
                user_correct_guess += 1
            else:
                ai_correct_guess += 1
        solved_word = sort_out_if_word_solved(...)

    if user_correct_guess > ai_correct_guess:
        usr_pts += 1
    elif user_correct_guess < ai_correct_guess:
        cmp_pts +=1
    else:
        # a tie
        pass
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15864005

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档