CONSOLE-BASED HANGMAN GAME

Objective:
Implement a console-based Hangman game where one player secretly inputs a target word (hidden via getpass) and another guesses letters. The program validates characters (including Spanish accents/ñ), tracks correct/incorrect guesses, and ends with win/lose messages.

How it works:

  1. Capture hidden word: Use getpass.getpass() to receive the secret word without echoing it, convert to lowercase, and store it safely.

  2. Validate alphabet: Check allowed characters by ensuring every symbol in the secret word belongs to a predefined alphabet (including á, é, í, ó, ú, ñ); exit if any invalid character is found.

  3. Initialize state: Set attempts and sets by defining remaining attempts (6), a set for correctly guessed letters, and another set for incorrect guesses.

  4. Render masked word: Build the display string each loop by joining revealed letters if guessed, or _ otherwise, and print current word, failed letters, and remaining attempts.

  5. Check victory: Compare progress vs. target; if the masked word equals the secret, announce success and terminate the program.

  6. Read and pre-validate input: Accept one-letter guesses (or "salir" to quit); enforce single-character length and membership in the allowed alphabet, otherwise prompt again.

  7. Handle repeats and update: Prevent duplicate guesses by checking both guessed-letters sets; add the letter to the appropriate set and decrement attempts only on a miss.

  8. Resolve game end: Lose on zero attempts by revealing the correct word; otherwise continue the loop until the player wins, quits, or expends all attempts.


import getpass

abecedario = "abcdefghijklmñopqrstuvwxyzáéíóú" # Añadimos tildes
adivinar_palabra = getpass.getpass("¡Juguemos al ahorcado! Dime que palabra tienen que adivinar, pero escóndela!:").lower() # De esta manera, ocultamos la palabra mientras la ponemos.
if not all(letra in abecedario for letra in adivinar_palabra): # Verifica que todas las letras estén en abecedario.
    print("Ese no es un carácter válido. Vuelve a empezar.")
    exit()

def ahorcado():
    intentos = 6 # Variables fuera del bucle
    letra_adivinada = set() # Set vacío para letras acertadas
    letras_falladas = set()
    
    while intentos > 0:
        palabra = "".join([letra if letra in letra_adivinada else "_" for letra in adivinar_palabra]) 
        print(f"Palabra actual: {palabra}")
        print(f"Letras falladas: {', '.join(letras_falladas)}")
        print(f"Intentos restantes: {intentos}")

        if palabra == adivinar_palabra:  
            print("¡Enhorabuena, has ganado!")
            exit()

        letra_seleccionada = input("Elige una letra o pulsa salir para finalizar:").lower()

        if letra_seleccionada == "salir":
             exit()

        if len(letra_seleccionada) != 1  or letra_seleccionada not in abecedario: 
            print("Carácter inválido. Vuelve a intentarlo.")
            continue # Vuelve al bucle directamente

        if letra_seleccionada in letras_falladas or letra_seleccionada in letra_adivinada:
            print(f"¡Cuidado! Ya has elegido esta letra: {letra_seleccionada}.")
            continue
        
        if letra_seleccionada in adivinar_palabra:
            print("Has certado la letra!")
            letra_adivinada.add(letra_seleccionada)

        elif letra_seleccionada not in adivinar_palabra:
            print("Esa letra no está!")
            letras_falladas.add(letra_seleccionada)
            intentos -= 1

    if intentos == 0:
        print(f"¡Has gastado todos tus intentos, has perdido! La palabra era: {adivinar_palabra}")
        exit()
    
ahorcado()
Scroll al inicio