mirror of
https://github.com/coding-horror/basic-computer-games.git
synced 2025-12-23 07:29:02 -08:00
Refactoring player turn and computer turn to separate methods. Computer turn logic previously ignored counting turns. Computer turn previously gave up the round if the user enters "inconsistent information" about the computers guess when it should have restarted the computers turn. Refactoring to remove usage of 'flag' variables to control program flow.
This commit is contained in:
@@ -37,19 +37,24 @@ computer_score = 0
|
|||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
global human_score, computer_score
|
|
||||||
|
|
||||||
current_round = 1
|
current_round = 1
|
||||||
|
|
||||||
while current_round <= NUM_ROUNDS:
|
while current_round <= NUM_ROUNDS:
|
||||||
print(f"Round number {current_round}")
|
print(f"Round number {current_round}")
|
||||||
|
human_turn()
|
||||||
|
computer_turn()
|
||||||
|
current_round += 1
|
||||||
|
print_score(is_final_score=True)
|
||||||
|
sys.exit()
|
||||||
|
|
||||||
|
|
||||||
|
def human_turn() -> None:
|
||||||
|
global human_score
|
||||||
num_moves = 1
|
num_moves = 1
|
||||||
guesses: List[List[Union[str, int]]] = []
|
guesses: List[List[Union[str, int]]] = []
|
||||||
turn_over = False
|
|
||||||
print("Guess my combination ...")
|
print("Guess my combination ...")
|
||||||
secret_combination = int(POSSIBILITIES * random.random())
|
secret_combination = int(POSSIBILITIES * random.random())
|
||||||
answer = possibility_to_color_code(secret_combination)
|
answer = possibility_to_color_code(secret_combination)
|
||||||
while num_moves < 10 and not turn_over:
|
while True:
|
||||||
print(f"Move # {num_moves} Guess : ")
|
print(f"Move # {num_moves} Guess : ")
|
||||||
user_command = input("Guess ")
|
user_command = input("Guess ")
|
||||||
if user_command == "BOARD":
|
if user_command == "BOARD":
|
||||||
@@ -67,58 +72,41 @@ def main() -> None:
|
|||||||
else:
|
else:
|
||||||
guess_results = compare_two_positions(user_command, answer)
|
guess_results = compare_two_positions(user_command, answer)
|
||||||
if guess_results[1] == NUM_POSITIONS: # correct guess
|
if guess_results[1] == NUM_POSITIONS: # correct guess
|
||||||
turn_over = True
|
|
||||||
print(f"You guessed it in {num_moves} moves!")
|
print(f"You guessed it in {num_moves} moves!")
|
||||||
human_score = human_score + num_moves
|
human_score = human_score + num_moves
|
||||||
print_score()
|
print_score()
|
||||||
|
return # from human turn, triumphant
|
||||||
else:
|
else:
|
||||||
print(
|
print(
|
||||||
"You have {} blacks and {} whites".format(
|
"You have {} blacks and {} whites".format(
|
||||||
guess_results[1], guess_results[2]
|
guess_results[1], guess_results[2]
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
num_moves = num_moves + 1
|
|
||||||
guesses.append(guess_results)
|
guesses.append(guess_results)
|
||||||
if not turn_over: # RAN OUT OF MOVES
|
num_moves += 1
|
||||||
|
|
||||||
|
if num_moves > 10: # RAN OUT OF MOVES
|
||||||
print("YOU RAN OUT OF MOVES! THAT'S ALL YOU GET!")
|
print("YOU RAN OUT OF MOVES! THAT'S ALL YOU GET!")
|
||||||
print(f"THE ACTUAL COMBINATION WAS: {answer}")
|
print(f"THE ACTUAL COMBINATION WAS: {answer}")
|
||||||
human_score = human_score + num_moves
|
human_score = human_score + num_moves
|
||||||
print_score()
|
print_score()
|
||||||
|
return # from human turn, defeated
|
||||||
|
|
||||||
# COMPUTER TURN
|
|
||||||
turn_over = False
|
def computer_turn() -> None:
|
||||||
inconsistent_information = False
|
global computer_score
|
||||||
while not turn_over and not inconsistent_information:
|
while True:
|
||||||
all_possibilities = [1] * POSSIBILITIES
|
all_possibilities = [1] * POSSIBILITIES
|
||||||
num_moves = 1
|
num_moves = 1
|
||||||
inconsistent_information = False
|
|
||||||
print("NOW I GUESS. THINK OF A COMBINATION.")
|
print("NOW I GUESS. THINK OF A COMBINATION.")
|
||||||
input("HIT RETURN WHEN READY: ")
|
input("HIT RETURN WHEN READY: ")
|
||||||
while num_moves < 10 and not turn_over and not inconsistent_information:
|
while True:
|
||||||
found_guess = False
|
possible_guess = find_first_solution_of(all_possibilities)
|
||||||
possible_guess = int(POSSIBILITIES * random.random())
|
if possible_guess < 0: # no solutions left :(
|
||||||
if (
|
|
||||||
all_possibilities[possible_guess] == 1
|
|
||||||
): # random guess is possible, use it
|
|
||||||
found_guess = True
|
|
||||||
else:
|
|
||||||
for i in range(possible_guess + 1, POSSIBILITIES):
|
|
||||||
if all_possibilities[i] == 1:
|
|
||||||
found_guess = True
|
|
||||||
possible_guess = i
|
|
||||||
break
|
|
||||||
if not found_guess:
|
|
||||||
for i in range(0, possible_guess):
|
|
||||||
if all_possibilities[i] == 1:
|
|
||||||
found_guess = True
|
|
||||||
possible_guess = i
|
|
||||||
break
|
|
||||||
if not found_guess: # inconsistent info from user
|
|
||||||
print("YOU HAVE GIVEN ME INCONSISTENT INFORMATION.")
|
print("YOU HAVE GIVEN ME INCONSISTENT INFORMATION.")
|
||||||
print("TRY AGAIN, AND THIS TIME PLEASE BE MORE CAREFUL.")
|
print("TRY AGAIN, AND THIS TIME PLEASE BE MORE CAREFUL.")
|
||||||
turn_over = True
|
break # out of inner while loop, restart computer turn
|
||||||
inconsistent_information = True
|
|
||||||
else:
|
|
||||||
computer_guess = possibility_to_color_code(possible_guess)
|
computer_guess = possibility_to_color_code(possible_guess)
|
||||||
print(f"My guess is: {computer_guess}")
|
print(f"My guess is: {computer_guess}")
|
||||||
blacks_str, whites_str = input(
|
blacks_str, whites_str = input(
|
||||||
@@ -128,11 +116,11 @@ def main() -> None:
|
|||||||
whites = int(whites_str)
|
whites = int(whites_str)
|
||||||
if blacks == NUM_POSITIONS: # Correct guess
|
if blacks == NUM_POSITIONS: # Correct guess
|
||||||
print(f"I GOT IT IN {num_moves} MOVES")
|
print(f"I GOT IT IN {num_moves} MOVES")
|
||||||
turn_over = True
|
|
||||||
computer_score = computer_score + num_moves
|
computer_score = computer_score + num_moves
|
||||||
print_score()
|
print_score()
|
||||||
else:
|
return # from computer turn
|
||||||
num_moves += 1
|
|
||||||
|
# computer guessed wrong, deduce which solutions to eliminate.
|
||||||
for i in range(0, POSSIBILITIES):
|
for i in range(0, POSSIBILITIES):
|
||||||
if all_possibilities[i] == 0: # already ruled out
|
if all_possibilities[i] == 0: # already ruled out
|
||||||
continue
|
continue
|
||||||
@@ -142,14 +130,26 @@ def main() -> None:
|
|||||||
)
|
)
|
||||||
if (blacks != comparison[1]) or (whites != comparison[2]):
|
if (blacks != comparison[1]) or (whites != comparison[2]):
|
||||||
all_possibilities[i] = 0
|
all_possibilities[i] = 0
|
||||||
if not turn_over: # COMPUTER DID NOT GUESS
|
|
||||||
|
if num_moves == 10:
|
||||||
print("I USED UP ALL MY MOVES!")
|
print("I USED UP ALL MY MOVES!")
|
||||||
print("I GUESS MY CPU IS JUST HAVING AN OFF DAY.")
|
print("I GUESS MY CPU IS JUST HAVING AN OFF DAY.")
|
||||||
computer_score = computer_score + num_moves
|
computer_score = computer_score + num_moves
|
||||||
print_score()
|
print_score()
|
||||||
current_round += 1
|
return # from computer turn, defeated.
|
||||||
print_score(is_final_score=True)
|
num_moves += 1
|
||||||
sys.exit()
|
|
||||||
|
|
||||||
|
def find_first_solution_of(all_possibilities: List[int]) -> int:
|
||||||
|
"""Scan through all_possibilities for first remaining non-zero marker,
|
||||||
|
starting from some random position and wrapping around if needed.
|
||||||
|
If not found return -1."""
|
||||||
|
start = int(POSSIBILITIES * random.random())
|
||||||
|
for i in range(0, POSSIBILITIES):
|
||||||
|
solution = (i + start) % POSSIBILITIES
|
||||||
|
if all_possibilities[solution]:
|
||||||
|
return solution
|
||||||
|
return -1
|
||||||
|
|
||||||
|
|
||||||
# 470
|
# 470
|
||||||
@@ -172,7 +172,6 @@ def print_board(guesses) -> None:
|
|||||||
print(f"{idx + 1}\t{guess[0]}\t{guess[1]} {guess[2]}")
|
print(f"{idx + 1}\t{guess[0]}\t{guess[1]} {guess[2]}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def possibility_to_color_code(possibility: int) -> str:
|
def possibility_to_color_code(possibility: int) -> str:
|
||||||
"""Accepts a (decimal) number representing one permutation in the realm of
|
"""Accepts a (decimal) number representing one permutation in the realm of
|
||||||
possible secret codes and returns the color code mapped to that permutation.
|
possible secret codes and returns the color code mapped to that permutation.
|
||||||
@@ -182,7 +181,7 @@ def possibility_to_color_code(possibility: int) -> str:
|
|||||||
color_code: str = ""
|
color_code: str = ""
|
||||||
pos: int = NUM_COLORS ** NUM_POSITIONS # start with total possibilities
|
pos: int = NUM_COLORS ** NUM_POSITIONS # start with total possibilities
|
||||||
remainder = possibility
|
remainder = possibility
|
||||||
for i in range(NUM_POSITIONS - 1, 0, -1): # process all but the last digit
|
for _ in range(NUM_POSITIONS - 1, 0, -1): # process all but the last digit
|
||||||
pos = pos // NUM_COLORS
|
pos = pos // NUM_COLORS
|
||||||
color_code += COLOR_LETTERS[remainder // pos]
|
color_code += COLOR_LETTERS[remainder // pos]
|
||||||
remainder = remainder % pos
|
remainder = remainder % pos
|
||||||
|
|||||||
Reference in New Issue
Block a user