I am making new program in Python (Mastermind). I have a problem with references of variables:
def user_turn():
try_counter = 1
user_code = []
guessed_code = random_code()
print("Twoja kolej na zgadywanie!")
while try_counter <= max_tries and user_code != guessed_code:
good_number, good_number_and_position = 0, 0
appearance_types_guessing_code = [0 for i in range(types)]
appearance_types_user_code = [0 for i in range(types)]
user_code = input("Próba nr {}: ".format(try_counter))
user_code = list(map(int, str(user_code)))
count_xos()
print_xos()
try_counter += 1
print_result_user_turn()
Body of the function print_xos()
:
def print_xos():
for i in range(good_number_and_position):
print("x", end='')
for i in range(good_number):
print("o", end='')
print("")
And my problem is that in function print_xos()
variables good_number
and good_number_and_position
are unknown, despite of fact I declared this variables in the while loop in the body of the function user_turn()
. How can I solve this problem? I don't want to send the reference as an argument of the function. In my opinion it isn't elegant. Is it possible to do it in another way?
EDIT:
OK, I changed a code a little bit then:
def user_turn():
try_counter = 1
user_code = []
guessed_code = random_code()
appearance_types_guessed_code = [0] * types
how_many_appearance(guessed_code, appearance_types_guessed_code)
print("Twoja kolej na zgadywanie!")
while try_counter <= max_tries and user_code != guessed_code:
good_number, good_number_and_position = 0, 0
appearance_types_user_code = [0] * types
user_code = input("Próba nr {}: ".format(try_counter))
user_code = list(map(int, str(user_code)))
how_many_appearance(user_code, appearance_types_user_code)
print(appearance_types_guessed_code, appearance_types_user_code)
count_xos(guessed_code, appearance_types_guessed_code, user_code, appearance_types_user_code, good_number, good_number_and_position)
print(good_number_and_position, good_number)
print_xos(good_number_and_position, good_number)
try_counter += 1
print_result_user_turn(guessed_code, user_code)
And the body of function count_xos:
def count_xos(guessed_code, appearance_types_guessed_code, user_code, appearance_types_user_code, good_number, good_number_and_position):
for i in range(len(appearance_types_guessed_code)):
good_number += np.min([appearance_types_guessed_code[i], appearance_types_user_code[i]])
for i in range(code_size):
if guessed_code[i] == user_code[i]:
good_number_and_position += 1
good_number -= 1
print(good_number_and_position, good_number)
And I got this output:
RUNDA 1
Twoja kolej na zgadywanie!
Próba nr 1: 0011
[0, 2, 0, 1, 0, 0, 0, 1, 0, 0] [2, 2, 0, 0, 0, 0, 0, 0, 0, 0]
1 1
0 0
You can be certain that function count_xos counts good_number, good_number_and_position counts properly. It should be 1 1, but I don't know why after running the method count_xos, variables good_number_and_position, good_number are not changed?