Switching key value pairs of nested list only works for the first list

I am trying to make a simple CLI CLI game that requires raw input and nested list validation for any matching pairs.

Here's the method that does the check:

def check_answer(guess):
    print gboard
    for k in gboard:
        if guess == k[0]:
            k[0],k[1] = k[1],k[0]
            print_board()
            promp_name()
        else:
            promp_name()

      

The method that gboard does:

def generate_board():
    """ Makes the board """
    board = len(fword) 
    for i in range(board):
        gboard.append([fword[int(i)], '_'])
    print_board()

      

This will simply make a list that looks something like this:

gboard = [['p','_'],['y','_'],['t','_'],['h','_'],['o','_'],['n','_']]

      

The pcb method just prints the gboard value pairs:

def print_board():
    final_layout = ''
    for key, value in gboard:
        final_layout+=value

    print final_layout

      

When the first value is guessed correctly: print_board does what it should do and returns the first open letter:

p_____

      

The problem is that I am assuming anything outside the first letter like y. When this happens, I'll be back:

p_____

      

Unlike

py____

      

Basically, key / value pairs are toggled only in the first list. Sorry for including a lot of code, I just don't know what part of the problem. Thank!

EDIT: In case it matters, here's the prompt_name function:

def promp_name():
    user_input = raw_input("Enter a letter: \n")
    user_input = user_input.lower()
    user_guess(user_input)

      

user_guess only checks the guess and then calls check_answer:

user_guess (input)

Also, gboard is a global variable defined in the main class

+3


source to share


1 answer


It seems that the problem is different. If you find that the first item in the gboard is a mismatch, the other part is executed which recursively calls check_answer () after the input is entered, so it only checks the first item in the gboard list.

You most likely don't want to do the else part until you are sure that none of the letters in gboard match. So you want to move the code to a different part outside of the loop, and maybe use a flag to indicate whether it should run or not (this is a flag indicating whether there were any matches or not).




It can be seen from the comments that you are doing a recursive method, so you need to make sure you return after calling promp_name () (if you are reconfiguring, you don't need a flag). Example -

def check_answer(guess):
    print gboard
    for k in gboard:
        if guess == k[0]:
            k[0],k[1] = k[1],k[0]
            print_board()
            return promp_name()
    return promp_name()

      

+2


source







All Articles