-1

I'm trying to build a basic program where the computer selects a word out of a pre-existing list (called "words") and the user must guess the appropriate letters to guess the word. This is what the main function looks like so far:

def game():
    word = random.choice(words)
    while ' ' or '-' in word:
        word = random.choice(words)
        if ' ' or '-' not in word:
            break
    print(f'Hint: The chosen word is {len(word)} letters long')
    letters = list(word)
    progress = []
    while True:
        guess = str(input('Guess a letter: '))
        if len(guess) > 1:
            print('Sorry, guess a single letter: ')
        if guess in word:
            print(f'The letter {guess} is in the word')
            for i, j in enumerate(letters):
                if progress.count(guess) >= letters.count(guess):
                    break
                elif j == guess:
                    progress.insert(i, j)
            print('Current progress: ' + '-'.join(progress))
            if len(progress) == len(word):
                if letters[:] == progress[:]:
                    print('Congrats! You found the word: ' + str(word))
                    break
        elif guess not in word:
            print(f'The letter {guess} is not in the word: Try Again')
            continue

My issue is with the for loop where I use enumerate(y) and the respective "elif j == guess" condition. I noticed that when running the function, the code works if the letters that are repeated are successive (ex: in the word "chilly", if I type in "l", the function correctly displays the two l's and the game works as intended). However, if the letters are repeated separately (ex: the word "cologne"), the function doesn't insert the "l" between the two o's, and keeps the two o's together regardless, thus preventing the proper word from ever being guessed. Is there a different method I could use to fix this problem?

  • 4
    OT: `while ' ' or '-' in word` doesn't do what you think it does. The expression is parsed as though it were written `' ' or ('-' in word)`. But `' '` is "truthy"; the only "false" string is the empty string. So the `or` expression is always true, and the while loop would loop forever if it were not for the conditional break. However, the condition at line 5 suffers from the same bug, so the `if` always succeeds, terminating the loop. None of this accomplishes your goal. – rici Jan 01 '21 at 18:04
  • Not so OT: if you want other people (us, for example) to understand your code, please find variable names more meaningful than `x` and `y`. The code does not provide the slightest hint about what the purpose of those variables is. – rici Jan 01 '21 at 18:06
  • @rici Sorry about the vague variables names previously; edited them to "letters" and "progress". The purpose of the letters list is to split the word selected by the computer into its letters as separate indices, and the progress list keeps track of how many letters the user has correctly identified. Also, the purpose of the initial while loop at the top was to weed out words in the list that had hyphens or spaces in them. Is there a more effective way to do this? – perumal_sps Jan 01 '21 at 18:51

1 Answers1

0

You should remember the letters already guessed and simplyfiy the printing to any letter that you remember and use - for any other letter in the word.

Your errror stems from your list and counting method to remember which letters to print or not.

I fixed your incorrect if-condition (see How to test multiple variables against a value? for more on that).

import random 

# supply list of words to function to avoid globals
def game(words):
    word = random.choice(words)
    # fixed your check ... not sure why you do that
    while ' ' in word or '-' in word:
        word = random.choice(words)
        # no break needed, will break if no space/- in
    print(f'Hint: The chosen word is {len(word)} letters long')
    # remember which letters where guessed already
    guesses = set()

    while True:
        guess = input('Guess a letter: ') # no str needed it is already a str
        if len(guess) > 1:
            print('Sorry, guess a single letter: ')
            continue # back to while loop

        # add to guessed letters
        guesses.add(guess)

        # print message
        if guess in word:
            print(f'The letter {guess} is in the word')
        else:
            print(f'The letter {guess} is not in the word: Try Again')
            continue # back to while loop

        print('Current progress: ', end="")
        # assume we have all letters guessed
        done = True
        for idx, letter in enumerate(word):
            if letter in guesses:
                # print letter if already guessed
                print(letter, end="")
            else:
                # invalidate assumption and print -
                done = False
                print("-",end="")
        print()

        # if assumption not invalidated: done
        if done:
            print('Congrats! You found the word: ' + str(word))
            break

game(["eye", "ear", "egg", "anvil"])

Output:

Hint: The chosen word is 3 letters long
Guess a letter: The letter e is in the word
Current progress: e-e
Guess a letter: The letter r is not in the word: Try Again
Current progress: e-e
Guess a letter: The letter y is in the word 
Current progress: eye
Congrats! You found the word: eye
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69