簡體   English   中英

跟蹤玩家參與策划的嘗試次數?

[英]keeping track of how many attempts player takes in mastermind?

我有應該運行一個名為mastermind的虛擬游戲的代碼,並且在嘗試以某種方式跟蹤玩家進行幾次嘗試的方式時遇到了問題。

我已經嘗試將其添加為變量,但是除了0之外,它沒有其他任何值,我希望有一種在每次函數顯示反饋運行時增加該值的方法。 有沒有更好的方法來實現這一目標?

這是我的代碼:

import random

def getGuessFromUser(guess):
    player_guess.clear()
    for g in guess:
        player_guess.append(g)
    return player_guess

#the players code does not match up to the color code
def displayFeedback():

    while attempts < 10 and player_guess != color_code:
        for i in range(4):
            if player_guess[i] == color_code[i] and player_guess != color_code:
                feedback[i] = color_code[i]
            if player_guess[i] != color_code[i] and player_guess[i] in color_code and player_guess[i] not in feedback:
                feedback[i] = 'W'
            if player_guess[i] != color_code[i] and player_guess[i] in colors and player_guess[i] not in color_code:
                feedback[i] = '_'
        print(printNicely(feedback))
        #getGuessFromUser(input('Guess: ' + '\n'))
        guessD()
    else:
        finalScoreCodebreaker()

#while the players guess is not valid
def errorMessage():

    if len(player_guess) != len(color_code):
        getGuessFromUser((input('Error ' + '\n')))
    if printNicely(player_guess) != printNicely(player_guess).upper():
        getGuessFromUser((input('Error ' + '\n')))
    for x in range(4):
        if player_guess[x] not in colors:
            getGuessFromUser((input('Error ' + '\n')))
    else:
        displayFeedback()
        #attempts(attempts)

#if player guesses on first try or if they run out of attempts
def finalScoreCodebreaker():
    if attempts >= 10:
        print("Color code was: " + str(printNicely(color_code)))
        print('Score: -' + str(10 - attempts))
    if player_guess == color_code:
        print("Score: -" + str(10 - attempts))

#returns as string
def printNicely(self):
    return ''.join(self)

def guessD():
    guess = getGuessFromUser(input('guess: '))


colors = ["R", "G", "Y", "P", "B", "O"]
attempts = 0
color_code = random.sample(colors, 4)
feedback = ['_', '_', '_', '_']
player_guess = []

guessD()
print(printNicely(color_code))
errorMessage()

通過添加全局變量,您走在正確的軌道上( attempts = 0 )。 下一步是在感興趣的函數中添加一行以增加attempts 但是,在執行此操作之前,由於attempts超出了所關注功能的范圍,因此在遞增功能之前,必須將其聲明為功能內的全局變量。

總結一下,將以下兩行添加到displayFeedback的頂部:

global attempts
attempts += 1
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM