I have this code that should run a virtual game called mastermind and I'm having problems trying to code in a way to keep track of how many attempts the player takes.
I've added in attempts as a variable but it has no value except for 0 and I would like a way to increment the value each time the function display feedback is run. Is there a better way to achieve this?
Here is my code:
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()
You were on the right track by adding a global variable ( attempts = 0
). The next step is to add a line in the function of interest that increments attempts
. Before doing this, however, since attempts
is out of scope for the function of interest, you must declare it as a global variable within the function before you increment it.
To summarize, add the following two lines to the top of displayFeedback
:
global attempts
attempts += 1
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.