Alex Bossi
Alex Bossi

Reputation: 11

How to override lists?

I have a question. I'm programming the gallows game. Everything's fine, but I'm stuck with something. The user selects a letter, which will be displayed on the screen and in the corresponding box. But every time the user selects a letter, the, Those I used to choose are gone.

You can see:

import pyfiglet
import random
import os

def start():
    print(pyfiglet.figlet_format("BIENVENIDO AL JUEGO DEL AHORCADO"))
    print("""
    ¡ A D I V I N A   L A   P A L A B R A !
    """)

def game():
    with open("./archivos/data.txt", "r", encoding="utf-8") as f:
        palabras = list(f)
        palabra = random.choice(palabras)
        palabra = palabra.replace("\n", "") 
    
    letras = [i for i in palabra]
    guiones = []

    for i in letras:
        guiones.append("_")
    
    print(" ".join(guiones))
    print("")

    guiones = []
    while guiones != letras:
        letra = input("Elige una letra: ")
        
        
        for i in palabra:  
            if i == letra:
                guiones.append(letra)
            else:
                guiones.append("_")   
        print(" ".join(guiones)) 
          
        guiones.clear() 



        

def run():
    start()
    game()

if __name__ == "__main__":
    run()

Upvotes: 1

Views: 56

Answers (1)

zwitsch
zwitsch

Reputation: 359

Since You are working with lists (which are mutable), You can flip the "_" to the guessed letter and not touch the rest of guiones. To do so, one solution is to use an index to access the list at the given position, like in the code snippet below :

#   guiones = [] do NOT clear guiones!

    while guiones != letras:
        letra = input("Elige una letra: ")
        
        
        for i in range(len(palabra)):  
            if palabra[i] == letra:
                guiones[i] =letra

        print(" ".join(guiones)) 
          

Upvotes: 1

Related Questions