Python : Hang Man game - python

I am making a hang man game. I am trying to cycle through a word and have all the repeats in the letter be appended to my list. For example the word "hello": if the user types in "l" I want all the l's to be added to my list. Right now it is only finding one "l" and if the user types an "l" again it finds the second "l".
I also want the user not to be able to type in another letter if they previously already typed it in.
I have two lists one for right guesses and wrong guesses that store every guess. For example if a user types in "h" in "hello"
"h" is a right guess so it appends to [h] but if they type in "h" again it adds it to the list so it says ["h","h"]. The wrong box works the same way but for words that are wrong. If they type in "z" for the word "hello" it says ["z"] in the wrong box.
Here is my code:
import random
user_input = ""
turns = 5
print("Welcome to Advanced Hang Man!")
print("Use your brain to unscramble the word without seeing its order!")
words = ["hello","goolge","czar","gnat","relationship","victor","patric","gir","foo","cheese"]
# Picks a random word from the list and prints the length of it
random_word = (random.choice(words))
random_word_legnth = (len(random_word))
print("Hint! The length of the word is",random_word_legnth)
hold_random_word = [i for i in random_word]
while turns != 0 and set(right_guess) != set(hold_random_word):
user_input = input("Please type your guess one letter at a time:")
right_guess = []
wrong_guess = []
#Calculating every input
if len(user_input) == 1 and user_input.isalpha():
for i in user_input:
if i in hold_random_word:
right_guess.append(i)
else:
wrong_guess.append(i)
print("Correct guess", ''.join(right_guess))
print("Wrong guess", ''.join(wrong_guess))

I'm not sure what your direct question is, but thinking about a hangman game you want to take the users guess and parse the entire word or phrase they are guessing to see if their guess matches anywhere in the word. I made a hang man game below that will function as expected (minus any error handling) Let me know if any parts confuse you, and i can explain
import random
wordcomp = []
wordguess = []
#this is a word bank for all puzzles, they are randomly chosen
word_bank = ['guess this phrase', 'Lagrange', 'foo', 'another phrase to guess']
# This loop stores each letter in a list, and generates a blank list with correct spaces and blanks for user
rand_word = random.randrange(4)
for i in word_bank[rand_word]:
wordcomp.append(i)
if i == ' ':
wordguess.append(' ')
else:
wordguess.append('__')
print('I am thinking of a word,' , wordguess , ' it has ', len(wordguess), ' characters total, GOOD LUCK \n')
wordlist = wordcomp
count = 0
placeletter = 0
wrongguess = []
guesscount = 0
while wordlist != wordguess:
guess = input('please input a lower case letter within the english alphabet!') ##Check that input is one character, and lower case
guesscount = guesscount + 1
# This for loop scans through to see if the letter that was guessed is in the actual puzzle, and places in the correct spot!!
for t in wordcomp:
if t == guess:
wordguess[placeletter] = guess
placeletter = placeletter + 1
# This check tells them they already guessed that letter... then makes fun of them
if guess in wordguess:
pass
else:
wrongguess.append(guess)
while wrongguess.count(guess) > 1:
wrongguess.remove(guess)
print('you guessed the letter ' , guess , ' already, are you person that suffers short term memory loss...')
print('The word I am thinking of: ' , wordguess)
print('The letters you have already guess are: ', wrongguess)
placeletter = 0
# This tells them they finished the puzzle and the number of guesses it took, if its over 26, it calls them stupid for obvious reasons...
if guesscount >= 26:
print('you are an idiot if it took you more than 26 guesses..... now take a minute, sit silently, and think about why you are idiot if it took over 26 guesses... for hangman... where you guess the letters of the alphabet... YOU GET IT, stupid')
elif guesscount < 26:
print('Congrats you solved the puzzle, w00t!!')

if len(user_input) == 1 and user_input.isalpha():
for i in user_input:
if i in hold_random_word and i not in right_guess:
right_guess.append(i)
elif i not in hold_random_word or i not in wrong_guess:
wrong_guess.append(i)
elif i in hold_random_word:
# here user types something that is already typed and is a right_guess
pass
else:
# Types something wrong, that was already typed
pass
print("Correct guess", ''.join(right_guess))
print("Wrong guess", ''.join(wrong_guess))
It is not clear how you are taking inputs, but I think this code can be further optimized. Give it a shot.
Edit 1:
import random
user_input = ""
turns = 5
print("Welcome to Advanced Hang Man!")
print("Use your brain to unscramble the word without seeing its order!")
words = ["hello","goolge","czar","gnat","relationship","victor","patric","gir","foo","cheese"]
random_word = (random.choice(words))
random_word_legnth = (len(random_word))
print("Hint! The length of the word is",random_word_legnth)
hold_random_word = [i for i in random_word]
# This condition can lead to issues in situations like this - abc and aabbcc [sorry couldn't quickly come up with a good actual example :)]
while turns != 0 and set(right_guess) != set(hold_random_word):
user_input = input("Please type your guess one letter at a time:").strip()
right_guess = []
wrong_guess = []
#Calculating every input
if len(user_input) == 1 and user_input.isalpha():
# user_input is 1 letter so for i in user_input will execute only once
# Use the if structure as defined above
if user_input in hold_random_word:
right_guess.append(i)
else:
# this is missing
turns -= 1
wrong_guess.append(i)
print("Correct guess", ''.join(right_guess))
print("Wrong guess", ''.join(wrong_guess))
elif len(user_input) > 1:
print("Please type only one letter at a time")
elif not user_input.isalpha():
print("Please enter only valid English letters")
else:
# handle this however you want :)
pass

Related

Why do I get an index error whenever the program prints out a past guess list from the user?

I have to build a wordle project. Everything is fine except the fact that whenever past user guesses are printed on the terminal, i get a list out of index error. I have tried adding a word to the list already because I thought the error is happening because of index zero, however it's not working.
Here is my code. Also, ignore the ANSI escape codes.
My code:
import random as random
play_again="Y"
while play_again=="Y":
count=0
list_words=[]
my_file = open("usaWords.txt", "r")
data = my_file.read()
# replacing end splitting the text
# when newline ('\n') is seen.
word_list = data.split("\n")
my_file.close()
#generating a random number
random_word=(random.choice(word_list))
#re-generating a random number if duplicates or if digits less than 3
#converting number into set because they dont allow duplicates
while len((random_word)) !=5:
random_word=(random.choice(word_list))
print('\u001b[47;1m' + '\033[31m'+'Welcome to Wordle! You have six chances to guess the five-letter word. A letter G means you got that letter correct and in the right position. A letter Y means you matched that letter, but it is in the wrong position.A letter B means that letter does not appear in the correct word')
def user_input():
user_guess=input('Please enter your guess: ')
guess_bad=True # Repeating below until the user gives a good input
while guess_bad:
if len(user_guess) !=5: #this should make sure that all digits can be converted to integers!
print('Must contain five letters or more.')
user_guess = input('Please enter a 5-letter word:')
# elif len(set(str(user_guess))) <5:
# print('No duplicates.')
# user_guess = input('Please enter a 5-letter word. No duplicates:')
else:
guess_bad=False
return user_guess
#Docstring required within each function:
"""
Description of function: This function will convert the words into lists to compare and output the answer to user. It also takes in the number of tries and outputs the count.
return: The number of tries.
"""
def add_user_lists(colored_guesses)->int:
background='\u001b[47;1m'
user_guess=user_input()
random_word_list=[]
past_guess=['none']
past_guess.append(user_guess)
user_input_list=[]
for letter in str(random_word):
random_word_list.append(letter)
for letter in str(user_guess):
user_input_list.append(letter)
# Just to check the answers:
print(random_word_list)
print(user_input_list)
#save the colors here
colored_guess=['B','B','B','B','B']
#For storing the old guesses
#This does greens
for i in range (0, len(random_word_list)):
if random_word_list[i]==user_input_list[i]:
colored_guess[i]='G'
elif random_word_list[i] in user_input_list:
colored_guess[i]='Y'
else:
colored_guess[i]='B'
#now you do all of the yellows
colored_guesses.append(colored_guess)
for i in range(len(colored_guesses)):
print(f"{background} Guess {i+1} is {past_guess[i+1]} colors are {''.join(colored_guesses[i])}")
return colored_guesses
colored_guesses=[]
temp=[]
while len(temp)<6 and ['G','G','G','G','G'] not in temp:
temp=add_user_lists(colored_guesses)
if len(temp) >=6:
print("You lost.")
elif ['G','G','G','G','G'] in temp:
print(f'you won! it took {len(temp)} tries!')
play_again=(input("Do you want to play again? Y if yes, N if no: "))
I'm expecting to get responses like:
What is your guess? truck
Guess 1: slice BBBBY
Guess 2: truck BYBBB
What is your guess? delay
Guess 1: slice BBBBY
Guess 2: truck BYBBB
Guess 3: delay BYBYB
What is your guess? wheat
Guess 1: slice BBBBY
Guess 2: truck BYBBB
Guess 3: delay BYBYB
Guess 4: wheat BBYYB
The problem is that colored_guesses is longer then past_guess
So you can't index a non-existing index past_guess[i+1]
You probably want to iterate over past_guess instead.
If you wish to hold the past_guess you should append and not reset it every time.
Here is a small fix:
def add_user_lists(colored_guesses, past_guess)->int:
background='\u001b[47;1m'
user_guess=user_input()
random_word_list=[]
past_guess.append(user_guess)
user_input_list=[]
for letter in str(random_word):
random_word_list.append(letter)
for letter in str(user_guess):
user_input_list.append(letter)
# Just to check the answers:
print(random_word_list)
print(user_input_list)
#save the colors here
colored_guess=['B','B','B','B','B']
#For storing the old guesses
#This does greens
for i in range (0, len(random_word_list)):
if random_word_list[i]==user_input_list[i]:
colored_guess[i]='G'
elif random_word_list[i] in user_input_list:
colored_guess[i]='Y'
else:
colored_guess[i]='B'
#now you do all of the yellows
colored_guesses.append(colored_guess)
for i in range(len(past_guess)):
print(f"{background} Guess {i} is {past_guess[i]} colors are {''.join(colored_guesses[i])}")
return colored_guesses
colored_guesses=[]
temp=[]
past_guess=[]
while len(temp)<6 and ['G','G','G','G','G'] not in temp:
temp=add_user_lists(colored_guesses, past_guess)
if len(temp) >=6:
print("You lost.")
elif ['G','G','G','G','G'] in temp:
print(f'you won! it took {len(temp)} tries!')
play_again=(input("Do you want to play again? Y if yes, N if no: "))

why does the index of "list_of_letters" not update for every while loop with "guessed_letter_string"? The problem occurs in the Try: section

Hangman. As you probobly understand i am new to coding and python, sorry for bad code.
The best way i can think of to describe this problem is through the following way: In the "try:" section i try to index = list_of_letters.index(guesssed_letter_string). i want to check if the guessed_letter_string is in list_of_letters: i earlier in the code translate the input from well the only input() in the code to guessed_letter_string (its the same thing). when you input a letter in the middel of the word it works like index[3] but when you input the first letter in the word the index locks at 0 and every other letter replaces it. is there a way to fix this
import random
list_of_words = ["mom", "dad", "sister", "brother"]
random_word = random.choice(list_of_words)
list_of_letters = list(random_word)
print(random_word)
print(list_of_letters)
rounds_failed = 1
rounds_max = 16
list_of_letters_guessed = []
under_grejer = []
count_of_right_letters_list = []
print(f"You have {rounds_max - rounds_failed} rounds left to find out the word")
for every in list_of_letters:
under_grejer.extend("_")
while True:
if rounds_failed == rounds_max:
print("To many attempts, no more rounds")
break
if len(list_of_letters) == 0:
print("YOU FUCKING WON")
break
print(f"This is round: {rounds_failed}")
print(" ".join(under_grejer))
print("Letters that are correct(not in order): "+", ".join(count_of_right_letters_list))
print("List of letters guessed: "+", ".join(list_of_letters_guessed))
guess = input("NAME A Letter: ")
guess_letters_list = (list(guess))
guess_count_letters = len(guess_letters_list)
if guess_count_letters > 1:
print("Dummy you just need to input a letter, nothing else")
guesssed_letter_string = " ".join(guess_letters_list)
try:
index = list_of_letters.index(guesssed_letter_string)
print("Congrats you got the letter: " + guesssed_letter_string)
print(f"thats the {index + 1}nd letter in the word")
rounds_failed += 1
count_of_right_letters_list.extend(guesssed_letter_string)
print(index)
list_of_letters.pop(index)
under_grejer[index] = guesssed_letter_string
except ValueError:
print("try again mate that letter was not in the word")
list_of_letters_guessed.append(guesssed_letter_string)
rounds_failed += 1
continue
It's not about the first letter only. Your problem is that with list_of_letters.pop(index) you remove the guessed letter form list_of_letters; parts of your code rely on this to check if you guessed all occurrences of that letter before already, but on the other hand this reduces the index of all letters behind the guessed one for later iterations.
For example, for brother, if you guess r it correctly says position 2, but if you then guess o next, it again says position 2 because your list_of_letters now reads ["b","o","t","h","e","r"].
You could either try to work with list_of_letters_org = list_of_letters.copy() which you will never change, and pick the right one for every task, or you could for example change the program structure by adding a list of booleans that store which letters were guessed already.

Hangman game. How to slice strings to change original value

I am very new to python and I am attempting to make a hangman game.
I would like to change a string to show the number of guessed letters but for some reason I keep on getting weird results. Here is my code:
import random
guesses_left = 9
def show_guesses_left():
print("You have", guesses_left, "guesses left")
wordlist = ['nerd', 'python', 'great', 'happy', 'programmer', 'long', 'short', 'stupid']
word = random.choice(wordlist)
wordwin = word
hidden_word = ["?" for q in word]
letters_guessed = ''.join(hidden_word)
print("Welcome to Hangman!!")
print("My word is", len(word), "letters long")
print(wordwin)
print(letters_guessed)
def request_guess():
global guesses_left
global word
global letters_guessed
x = input(f"What is your guess? \n{letters_guessed}")
if x in word:
print("Great you guessed a letter")
t = word.find(x)
word = word.replace(x, "")
print(t)
letters_guessed = letters_guessed[:t] + letters_guessed[t:t+1].replace('?', x) + letters_guessed[t+1:]
elif type(x) is not str or len(x) > 1:
print("Invalid guess, Your guess must be 1 letter long")
else:
print("Wrong!")
guesses_left -= 1
show_guesses_left()
def start_game():
global letters_guessed
global word
global guesses_left
letters_guessed = ''.join(hidden_word)
while True:
if guesses_left > 0 and len(word) != 0:
request_guess()
elif len(word) == 0:
print(f"YOU WIN!!!, the word was {wordwin}")
break
else:
print("You lose! Better luck next time!")
break
start_game()
I keep on getting this result where it only works for the for some letters and the placing is wrong. Here is my result:
Welcome to Hangman!!
My word is 4 letters long
long
????
What is your guess?
????l
Great you guessed a letter
0
What is your guess?
l???n
Great you guessed a letter
1
What is your guess?
ln??o
Great you guessed a letter
0
What is your guess?
ln??g
Great you guessed a letter
0
YOU WIN!!!, the word was long
Why cant i just slice the string change one character and slice the rest?
Why does it work the first time and not the second?
If anybody can explain to me what is going on it would be appreciated
Solution
import random
guesses_left = 9
def show_guesses_left():
print("You have", guesses_left, "guesses left")
wordlist = ['nerd', 'python', 'great', 'long', 'short', 'stupid', 'happy', 'programmer']
word = random.choice(wordlist)
wordwin = list(word)
hidden_word = list('?' * len(word))
letters_guessed = ''.join(hidden_word)
print("Welcome to Hangman!!")
print("My word is", len(word), "letters long")
print(letters_guessed)
def request_guess():
global guesses_left
global word
global letters_guessed
x = input("\nWhat is your guess?\n" + letters_guessed + "\n")
if x in word:
print("\nGreat you guessed a letter")
for i, j in enumerate(word):
if j == x:
hidden_word[i] = j
letters_guessed = ''.join(hidden_word)
print(letters_guessed + "\n")
elif type(x) is not str or len(x) > 1:
print("Invalid guess, Your guess must be 1 letter long")
else:
print("\nWrong!")
guesses_left -= 1
show_guesses_left()
def start_game():
global letters_guessed
global word
global guesses_left
letters_guessed = ''.join(hidden_word)
while True:
if guesses_left > 0 and letters_guessed != word:
request_guess()
elif letters_guessed == word:
print("YOU WIN!!!, the word was " + word)
break
else:
print("\nYou lose! Better luck next time!")
break
start_game()
Notes
Got it to work!
Sorry short on time will be back to help more, but take a look around. I used some different methods than you originally had, seems like there was a issue with your letters_guessed not revealing letters past a letter already guessed. This will work for double letters as well, which also seemed to be an issued with your original code.
Again sorry, will be back to explain more!
The main problem is the code you use to get the index of the guessed letter:
t = word.find(x)
word = word.replace(x, "")
This shortens word after each correct guess, so t will not be the desired value after the first correct guess.
However, even if you fix this, you will still not properly handle the case that the guessed letter occurs multiple times.
Here is a short example that shows how to solve both problems:
answer = 'long'
hidden = '?' * len(answer)
print("Welcome to hangman!")
while True:
guess = input("Guess a letter: ")
result = ''
if guess in answer:
for answer_letter, hidden_letter in zip(answer, hidden):
if guess == answer_letter:
result += guess
else:
result += hidden_letter
hidden = result
print(hidden)
if hidden == answer:
print("You guessed it!")
break
The main problem is that you are basing that splicing on a variable that you modify on the go. In particular, the variable word, where you look for the position of x, the guessed letter. The position is correct until word gets modified in length, as you replace the letter with an empty string.
An easy fix for that is to simply change the replace statement, and put either an empty space, or another character, that the user would not normally put. In my example, I would replace:
word = word.replace(x, "")
with
word = word.replace(x, " ")
That of course breaks the program exit logic: you can never win.
There is still another issue, that is multiple occurrences of the same letter are not accounted properly. In fact, the program loops until exhaustion, when multiple instances of the same letter are in word.
That is due to the fact that find will only reveal the position of the first instance of a given letter, and you don't account for possible duplicates.
There are several ways to fix that, but I think the main issue is identified.
For an alternate implementation, check https://eval.in/1051220

Why doesnt my Code work? (Simple "Guess the Word"-Game in Python) [duplicate]

This question already has an answer here:
Python "if" statement not working
(1 answer)
Closed 4 years ago.
I'm learning Python for fun at the moment, and it went all well until now. I'm trying to extend the "Guess the Word"-Game, for example being able to let the Player choose a Word by himself (when 2 People play, 1 chooses the Word, the other guesses) I bet that my Mistake is obvious to me as soon as you point it out, but I'm gonna ask anyway. Well, here is the Code. I put in the entire Program, even tough only the top part should matter. I just put in the rest because it isn't much and maybe you guys can understand it better then.
print("Do you wish to set the Word yourself, or let the program choose?")
user_input = input("1 for own Input - 0 for Program-Input")
if user_input == 1:
Keyword = input("Type in the Word you want to use!")
else:
Keyword = "castle"
word = list(Keyword)
length = len(word)
right = list ("_" * length)
used_letters = list()
finished = False
while finished == False:
guess = input("Guess a Letter!")
if guess not in Keyword:
print("This letter is not in the word. Sorry...")
for letter in word:
if letter == guess:
index = word.index(guess)
right[index] = guess
word[index] = "_"
if guess in used_letters[0:100]:
print("You already used that letter before!")
else:
used_letters.append(guess)
list.sort(used_letters)
print(right)
print("Used letters:")
print(used_letters)
if list(Keyword) == right:
print("You win!")
finished = True
input('Press ENTER to exit')
My problem is, I wanna add the Function to be able to choose if you want to set a Word yourself, or use the word the Program has, defined as "Keyword". But no matter what I input, it always starts with "Guess a Letter" instead of skipping down to where the program sets the Keyword. Thank you in advance for your answers! :)
There's 2 issues with your code.
You put the entire block of code into the else statement. This means that if the if user_input == 1: block ever executed, you would only ask your user for a word and then the program would end because the else statement would be skipped.
You are using if user_input == 1: as your check and this will never be true because user inputs are always read in as strings. A string 1 will never equal the integer 1. This is why your program always skips to the else statement. You need to do if int(user_input) == 1:
Whenever you collect a user's input using the input function, it is a string, not int. this means you will have to either parse the value into an int or evaluate it with a string.
option 1: parsing to int:
user_input = int(input("1 for own Input - 0 for Program-Input"))
option 2: evaluating with string:
if user_input == "1":
input returns a string not a integer so it can never be equal to 1 instead it will be equal to "1".
Plus the code for the user guessing only runs when the program chooses the word so it needs to be unindented.
As a side note your code currently registered capital letters as being different from lower case, you can fix this by putting a .lower() after each input which will turn all capital letters into lowercase.
print("Do you wish to set the Word yourself, or let the program choose?: ")
user_input = input("1 for own Input - 0 for Program-Input")
if user_input == "1":
Keyword = input("Type in the Word you want to use: ").lower()
else:
Keyword = "castle"
word = list(Keyword)
length = len(word)
right = list ("_" * length)
used_letters = list()
finished = False
while finished == False:
guess = input("Guess a Letter: ").lower()
if guess not in Keyword:
print("This letter is not in the word. Sorry...")
for letter in word:
if letter == guess:
index = word.index(guess)
right[index] = guess
word[index] = "_"
if guess in used_letters[0:100]:
print("You already used that letter before!")
else:
used_letters.append(guess)
list.sort(used_letters)
print(right)
print("Used letters:")
print(used_letters)
if list(Keyword) == right:
print("You win!")
finished = True
input('Press ENTER to exit')

Checking through a variable to see if it doesn't contains anymore strings

def main():
#word = input("Word to guess for player 2:")
word = ['h','e','l','l','o']
word2 = "hello"
#make a list of _ the same length as the word
display =[]
for i in range (0,len(word)):
display.append("_")
chances = int(input("Number of chances to guess word:"))
if len(word)== 11:
print ("Your word is too long. It has to be 10 charecters or less")
else:
word = word
if chances < len(word):
answer = input("Your word is {0} letters long , are you sure you don't want more chances? Yes or no?". format (len(word)))
if answer == "no":
chances= int(input("Number of chances:"))
else:
chances = chances
("Ok then lets continue with the game")
print ("Player 2, you have {0} chances to guess the word.". format (chances))
won = False
underscore = False
while chances > 0 and won == False and underscore == False:
guess = input("Enter your guess: ")
gC=False
for i in range (0,len(word)):
if guess == word[i]:
gC=True
display[i]=guess
if not gC:
chances = chances - 1
display2 = ""
for i in display:
display2 = display2 + i + " "
For some reason the code doesn't work when I state my while loop as the game continues to go on until the user runs out of guess'. Does anybody have any suggestions as to how I can fix this?
You never set won to True when the user wins the game by guessing all the letters.
This is not an answer to your original question, instead more of a code-review, but maybe you'll find it useful.
word = list('hello') # replaces manual splitting of string into letters
display = [ '_' ] * len(word) # replaces build-up using for-loop
chances = input("Number ... ") # already returns int if the user enters an int
# but will evaluate any valid python expression the
# user enters; this is a security risk as what
# ever is done this way will be done using your
# permissions
chances = int(raw_input("Number ...")) # probably what you wanted
...
else:
word = word # does nothing. remove this line and the "else:" above
chances -= 1 # replaces 'chances = chances - 1' and does the same
display2 = ' '.join(display) # replaces the for-loop to build display2
Furthermore I suggest to use better names. Variables like display2 or gC aren't very helpful in this context. In professional programming you always have to keep in mind that you are writing your code (also or even mainly) for the next developer who has to maintain it. So make it readable and understandable. Choose names like displayString or guessedCorrectly instead.

Categories

Resources