Reputation: 55
Greetings fellow Coders! Quick disclaimer i'm new to the world of coding and currently learning Python, happy for all the infos and help i get!
So i'm trying to code the mastermind game if your are not familiar with it here is a wikipedia arcticle: Text
Im trying to work with global variables, but everytime the global variable is used in a function it dosent return it into the global variable the variable just sets back to its original value.
If u need more info from me please let me know! looking forward to hearing from you.
import random
colors = "YORPGB"
global secret
global round
global hits
global close
def gen_random_secret():
secret = ""
for i in range(4):
n = random.randrange(6)
secret += colors[n]
return secret
def get_guess(force_valid_input):
while True:
guess = input(f"Available letters: {colors}\nPut in a 4-letter Word with the available letters, there can be duplicates! ").upper()
if len(guess) ==4:
return guess
else:
if not force_valid_input:
return None
print("Wrong Input try again!")
def check_guess(guess,secret):
hits = 0
close = 0
for i in range(4):
if guess[i] == secret[i]:
hits += 1
for color in colors:
close += min(secret.count(color),guess.count(color))
close = close - hits
return hits, close
def start_game():
print("Welcome to the Mastermind game!\nGenerating random code...")
round = 1
history = []
hits = 0
close = 0
secret = gen_random_secret()
while round<=12:
guess = get_guess(True)
check_guess(guess,secret)
print(f"Hits: {hits} Close: {close}\n")
if hits == 4:
break
round += 1
history.append((guess,hits,close))
print()
for row in history:
for color in row[0]:
print(f" {color}", end="")
print(f" | {row[1]} {row[2]}")
print()
if hits == 4:
print(f"Congratz u guessed it the code was: {secret}")
else:
print(f"You ran out off attempts, you lose bitch!\n the secret Word was {secret}")
start_game()
Upvotes: 0
Views: 1895
Reputation: 2301
You must call global
within the function to let the function know to use the global variable.
For example:
def gen_random_secret():
global secret
secret = ""
for i in range(4):
n = random.randrange(6)
secret += colors[n]
return secret
Instead of:
global secret
def gen_random_secret():
secret = ""
for i in range(4):
n = random.randrange(6)
secret += colors[n]
return secret
Upvotes: 1