我有这个代码应该运行一个名为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()
答案 0 :(得分:0)
通过添加全局变量(attempts = 0
),您走在了正确的轨道上。下一步是在感兴趣的函数中添加一行,增加attempts
。但是,在执行此操作之前,由于attempts
超出了感兴趣的函数的范围,因此在递增函数之前必须将其声明为函数中的全局变量。
总结一下,将以下两行添加到displayFeedback
的顶部:
global attempts
attempts += 1
...