[英]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.