Day 039 - Project 39 : Hangman

If you have any questions, comments or issues with this project please post them here!

how are you breaking down the hangman problem?
I have used a set to detect if the answer and guess list of letters are the same.
but i dont think we have been taught to use sets yet.

1 Like
word = input("> ").strip().lower()
 
list = [ ]
counter = 6
def counter1():
  global counter 
  counter -= 1  
  return counter

  

def program():
  ask1 = input("Letter> ")
  print()
  if ask1.lower().strip() in list:
    print()
    print("\033[31m","You already picked this!","\033[0m")
    print()
    for index in range(len(word)):
      for index1 in range(len(list)):
        if list[index1] in word[index]:
          location1 = word.find(list[index1])
          print(word[location1], end='')
        else:
          print("_",end='')
    print()
    print()
    program()
      
  elif ask1.lower().strip() not in list: 
      if ask1 in word:
        list.append(ask1)
        
        for index in range(len(word)):
          for index1 in range(len(list)):
            if list[index1] in word[index]:
              location1 = word.find(list[index1])
              print(word[location1], end='')
            else:
              print("_",end='')
        print()
        print()
        program()

      else: 
        print("WRONG!!")
        print()
        for index in range(len(word)):
          for index1 in range(len(list)):
            if list[index1] in word[index]:
              location1 = word.find(list[index1])
              print(word[location1], end='')
            else:
              print("_",end='')
        print()
        print()
        if counter == 1:
          print(f"You lost!, The answer was >> {word}")
          exit()
        else:
          print(counter1(),"Attempts left")
          print()
        
        
        program()
        
    

program()

everytime I try to print out the string when the character is correct, it prints extra underscores for some reason… Please help

set is what I just learned in today’s lesson lol iv used another new list called guessed items and appended the words the users said you don’t need set at all but ya set is way easier than creating another hassle of appending

2 Likes

I noticed that both David’s solution and my own cannot handle words that contain the same letter multiple times. For example, if the word is ā€˜apple’ and the user has already picked the letter ā€˜p’, how can we allow them to select it again? Is there a way to solve this issue, or am I missing something?

1 Like

I think I just don’t know how Hangman works :joy::joy: Thought you’d have to guess the ā€œpā€ twice but nope all good.

1 Like

I am stuck actually :smiling_face_with_tear:

1 Like

Hey, @Marach welcome to the forums!

Can you please provide a link to your repl or your code?

1 Like
new = []
def work():
  for i in word:
    if i != guess:
      new.append('_')
    else:
      new.append(guess)
  print(new)
  for a in new:
    print(a, end='')

I am not fully done with the project though but I am stuck here, so I couldn’t go further. The issue I am having with this piece of function is that it only works for the first guess. For subsequent guesses, it starts afresh instead of just replacing the underscores with the new guesses. I tried printing out some of the supposedly hidden parts of the game so that I’ll see what they look like. I’ll still delete the lines when I am done. My head is actually full :joy: :sneezing_face:

1 Like

Here’s the full code :smiling_face_with_tear:

words = ['Ajah', 'name', 'Umerica', 'CheF', 'jAson']

new = [ ]
def work():
  for i in word:
    if i != guess:
      new.append('_')
    else:
      new.append(guess)
  print(new)
  for a in new:
    print(a, end='')    

import random
word = random.choice(words)
print(word)

while True:
  guess = input('\033[33mChoose a letter: \033[0m')
  if guess in word:
    work()
    print()
    print()
    
  else:
    print('Nope, not in there!')
    print()
    print()

I know that I am not getting a few things right, I need help cos my brain is tired since today :smiling_face_with_tear:

2 Likes
#im still a noob as well so do forgive my mistakes but I'm practicing Lol
#always import on 1st line 
import random

#from starting 2nd line you should have all your lists giving it .lower(),.upper() etc would help you comparing the case sensitive stuffs like if your later is small j big A then son and you've selected big J small s it won't work so .lower will lower all the characters in anything applied to it 
words = ['Ajah', 'name', 'Umerica', 'CheF', 'jAson'].lower()
picked= [ ]#im changing your new to picked its easier to understand that way 

#setting the random value to your word list before you begin to define on loop anything 
word = random.choice(words)

#starting loop
while True:
#here to we use.lower() for case sensitivity its actually good to use this on every inputs you make quite helpful this function is 
choseletter=input(chose a leter\n~).lower()
#if the letter is already picked we restart the loop and if its not already picked we append to our picked list 
if letter in picked:
print("already added")
#continue restarts the loop
continue
else:
#here were appending to our empty picked list from our input function like whatever letter we type it gets appended to it only once cuz we said if its already in the list we don't append we restart and avoid but if it's not in the list it gets appended!
picked.append(choseletter)

#if the letter in the random choice word aka got selected by the random choice function
if letter in word: 
print("we got a letter")
else:
print("try again")

#begining the loop for a single letter in your random chosen word ex A from ajah
for i in word:
#the for loop and if checks for each letter in the wordlist if the single word letter is in our picked list then we print the letter with no end, otherwise we print blank line "_"again no end means end =""
if i in picked:
print(i,end="")
else("_", end="")
1 Like

glad im not the only one struggling on this im new to all this but ive got a rough sort of draft need a little help heres the code.
some of the issues i need help with are.

if i print the title hangman it disappears after every input from the used and is replaced with the guesses

the guessed letters are printing at the top of the console where i want to put the title everything else seems to be running fine

import random,os,time
listofwords=[""]
guessp=[]
lives=6


pick=random.choice(listofwords)



while True:

  print("\nguesses",guessp,"\nlives",(lives))
  guess=input("\nenter a letter:>").lower().strip()
  os.system("clear")
  
  if guess in guessp:
    print("youve already tried that")
    time.sleep(1)
    os.system("clear")
    
    
  guessp.append(guess)

  if guess in pick:
    answer.append(guess)
    time.sleep(1)
    os.system("clear")
    
    
  else:
    print(f"nope thats not in the word.\n you have:{lives -1} lives remaing")
    time.sleep(1)
    lives-=1
    os.system("clear")

  fullword = True
  print()
  for i in pick:
    if i in guessp:
      print(i, end="")
    else:
      print("_", end="")
      fullword = False
      os.system("clear")
      
  if fullword:
    os.system("clear")
    print("\nyou win the answer is ",pick)
    break

  if lives == 0:
    print("you loose")

Here it is,

from colorama import Fore
import random
import os


def _rand_word():
    return random.choice(open("words.txt", "r").read().splitlines())


rand_word = _rand_word()
green = Fore.GREEN
red = Fore.RED
yellow = Fore.YELLOW

print("Try to guess the five-letter word in six or fewer attempts!\n")

for base_att in range(1, 7):
    base_guess = input().lower()

    for x in range(min(len(base_guess), 5)):
        if base_guess[x] == rand_word[x]:
            print(f"{green}{base_guess[x]}", end="")
        elif base_guess[x] in rand_word:
            print(f"{yellow}{base_guess[x]}", end="")
        else:
            print(f"{red}{base_guess[x]}", end="")
    os.system("clear")

    if base_guess == rand_word:
        print(f"{green}Correct!")
    elif base_att == 6:
        print(f"{red}You lost!")

a fully functional Python game in which you guess the word, similar to hangman and wordle. Simply modify it as you see fit. Make sure you get a list of 5 character words.

This was my solution to the project and, although it works, there could be some refinements made to it but that will have to wait for another day. This is just a longer version to help increase the pain. Just kidding.

import os
import time
import random

listOfWords = ["british", "suave", "integrity",
               "accent", "evil", "genius", "Downtown"]

word = []
guesses = 10
letterUsed = []

wordChosen = random.choice(listOfWords)

# print(wordChosen)

wordLength = len(wordChosen)
# create a list of underscores in word for each letter in the wordChosen
for i in range(0, wordLength):
    word.append("_")
print("".join(word))


while guesses > 0:
    # see if the letter is in wordChosen and in what position
    letter = input("Guess a letter: ")
    for i in range(wordLength):
        if letter == wordChosen[i]:
            # replace the underscore with the letter in the correct position
            word[i] = letter
            letterUsed.append(letter)

    guesses -= 1
    print(" ".join(word))
    print()

    print(f"You have {guesses} guesses left!")
    s = word
    x = "".join([str(i) for i in s])
    if x == wordChosen:
        print("You win!")
        break
    elif guesses < 0:
        print("You lose the word was: ", wordChosen)
        break

My completed code for the Hangman Project:

    import random

def printout_word():
    for i in word:
        if i in correct_lets:
            print(i, end="")
        else:
            print("_", end="")
    print()

listofwords = ['History', 'Clue', 'Words', 'Building', 'Time', 'Mountain', "british", "suave", "integrity", "accent", "evil", "genius", "Downtown" ]

correct_lets = []
num_rounds = 6

word = random.choice(listofwords).lower()

print("\033[1;35mHangman!!šŸ˜Ž\033[0m")
print()

while True:
    letter = input("\033[1;35mGuess a letter in the word:\033[1;0m ").lower()

    if letter in correct_lets:
        print("\033[1;31mThis letter is correct, but you already got it!🄱\033[1;0m")
        print()
        
    elif letter in word:
        correct_lets.append(letter)
        print("\033[1;32mYou found a letter!\033[0m")
        printout_word()
        print()
        if len(correct_lets) == len(word):
            print("\033[4mOMG!!! You won!šŸŽ‰")
            break

    else:
        print("\033[1;31mThis letter is not the word!\033[1;0m")
        num_rounds -= 1
        printout_word()
        print(f"\033[1;31mYou have {num_rounds} lives left!\033[0m")
        print()
        if num_rounds == 0:
            print("\033[1;31mYou ran out of lives!\033[1;0m")
            break  

    exit
1 Like

Hi Ian, in DAvid’s solution, he used ā€œallLeters = Trueā€ and then ā€œallLetters = Falseā€. May I know what is the function of these, please? Thanks!
Here’s his code:

import random, os, time

listOfWords = ["apple", "orange", "grapes", "pear"]
letterPicked = []
lives = 6

word = random.choice(listOfWords)

while True:
  time.sleep(1)
  os.system("clear")
  letter = input("Choose a letter: ").lower()
  
  if letter in letterPicked:
    print("You've tried that before")
    continue
    
  letterPicked.append(letter)
  
  if letter in word:
    print("You found a letter")
  else:
    print("Nope, not in there")
    lives -= 1
  
  allLetters = True. # what is the function of this, please?
  print()
  for i in word:
    if i in letterPicked:
      print(i, end="")
    else:
      print("_", end="")
      allLetters = False. #what is the function of this, please?
  print()

  if allLetters:
    print(f"You won with {lives} left!")
    break

  if lives<=0:
    print(f"You ran out of lives! The answer was {word}")
    break
  else:
    print(f"Only {lives} left")

Hi @Ching-LiLi thanks for your post!

The variable allLetters is being used as a boolean flag to determine if the game has been won or not. It starts off as true and remains that way if all letters picked are in the word string variable.

However if any of the letters picked are not in the word (shown by the else: section of code) then the variable allLetters is set to false and - later in the program - a different message is shown to the user.

Thanks, Ian for your reply.
Does that means the ā€œif allLetters:ā€ will run when the allLetter condition is True?
I don’t understand how the program is checking whether the game has been won or not. And I am really stuck here. Help! Truly appreciate you help.

Yep! When you use a variable in an if statement, it checks if the variable’s value evaluates to true, and since allLetter is a boolean it will always evaluate to either True or False. Hope this helped!

3 Likes