python_by_example/final/fin02.py
2023-11-22 11:54:37 -03:00

80 lines
3.0 KiB
Python

from random import choice
from common.common import clear
def fin_02():
"""You are going to make an on-screen version of the board game 'Mastermind'.
The computer will automatically generate four colours from a list of
possible colours (it should be possible for the computer to randomly
select the same colour more than once). For instance, the computer may
choose 'red', 'blue', 'red', 'green'. This sequence should not be
displayed to the user. After this is done the user should enter their
choice of four colours from the same list the computer used. For
instance, they may choose 'pink', 'blue', 'yellow' and 'red'. After the
user has made their selection, the program should display how many
colours they got right in the correct position and how many colours they
got right but in the wrong position. In the example above, it should
display the message 'Correct colour in the correct place: 1' and 'Correct
colour but in the wrong place: 1'. The user continues guessing until they
correctly enter the four colours in the order they should be in. At the
end of the game it should display a suitable message and tell them how
many guesses they took."""
colours = {
'NEGRO': "\033[0;30;1;47m",
'PURPURA': "\033[1;35m",
'CIAN': "\033[0;1;36m",
'ROJO': "\033[1;31m",
'VERDE': "\033[1;32m",
'AMARILLO': "\033[1;33m",
'AZUL': "\033[1;34m",
'BLANCO': "\033[1;37m",
'END': "\033[0m"
}
secrets = []
guesses = []
tries = 0
for _ in range(4):
secrets.append(choice(list(colours.keys())[:-1]))
#print(colours[secrets[i]]+"█████"+secrets[i]+"█████"+colours['END'])
print("\n COLORES\n")
for color in list(colours.keys())[:-1]:
print(' '+color.capitalize(), end=' ')
print()
def guess_colours():
guesses.clear()
print("\nIngresa 4 colores de la lista")
cont = 1
while len(guesses) < 4:
resp = input(f"Ingresa el color nro. {cont}: ").upper()
if resp in list(colours.keys())[:-1]:
guesses.append(resp)
cont += 1
print()
def check_colours():
ok_guess = 0
for i, guess in enumerate(guesses):
if guess in secrets:
print(colours[guess]+f"{guess} está en los colores", end='')
if guess == secrets[i]:
print(", en está misma posición"+colours["END"])
ok_guess +=1
else:
print(", en otra posición"+colours["END"])
else:
print(f"{guess} no está entre los colores")
print()
if ok_guess == 4:
return True
else:
return False
win = False
while not win:
guess_colours()
win = check_colours()
tries += 1
print(f"Ganaste en {tries} intentos")