Python Guess the Word Game - python

Describing the game if you know what means word guessing dont bother to read
Hey! I know I opened a question about that earlier but again Im stuck in another situation. I making a game that there is a list full of words and computer choses a random word in it. And program asking to person guess a letter. If it is in letter it should write the letter in exact order in that word. Lets say our word is word.
If user input is "w", program will print "w___" and again
if user says "o" program will print "wo__" like that.
What is the issue?
I did achieve to print if user input in that word and in which order in that word but when user guess again when he got right in first letter my print variable refreshing and prints just last guessed letter.
Let me explain
My word again "word" and user guess "w" letter first.
So program will print "w___"
But when user guess again and lets say he/she guessed "o" this time.
Program prints just "_.o__" but not w.
What I want to do
Program should keep the last data as "w___" and add "o" letter to second place.
Program should have an if statment and two variables. First is guess_count and other is error_count.
If player guessed right increase guess_count by one and
if guess_count == 5 # word's total letter number: print("Win"), break the loop
If player guessed wrong increase error_count by one and
if error_count == 3 # if player type 3 wrong letter: print("Lose"), break the loop
My code
Create a loop
run = True
while run:
Create a namelist and chose a random name
name_list = ["sound"]
pick_word = random.choice(name_list)
Create a while loop again # whole code is under this
while True:
Get user input
user_input = input("Guess a letter: ")
Creating if statment if for if input len > 1 get error
Whole if true code in there
if len(user_input) == 1:
*Create a variable that gets user input in order of word as number.
(I cant say that sentence in english)
index = pick_word.index(user_input)
Replace the order number to user input
word_tracker[index] = user_input
Create a string to print it
word = "".join(word_tracker)
Print it
print(word)
Increase guess_count
count += 1
If guess_count is 5 break the loop
if count == 5:
If guess not in word
except ValueError:
print("You couldnt guess the letters.")
guessing += 1
if guessing == 3:
print("Peh")
exit()
If guessed letter not 1 character
else:
print("You allowed to type just one letter")
I hope I wont get ban haha

try changing
word_tracker[index] = user_input
to
word_tracker.append(user_input)
That is if 'word_tracker' is a list

Related

how do I stop a function to iterate through all items in a list

I am writing a simple word guessing game in python. Instead of using a list, I have all the words for the game in a .txt file called as the parameter of a function. The list itself is fine.
The game requires the user to enter a letter. Once the letter is entered, if it matched one of the words that is randomly selected by the random function, it gives points accordingly.
The problem is that when the function runs, the entered letter by the user iterates through all the words in the list. How do I fix this issue?
def guess_game(data):
word = random.choice(data)
print("alright, guess the first letter:")
ans = input("Enter a letter to guess: ")
print(ans)
counter = 0
tries = 15 #how many tries a user is allowed to make
for match in word:
if ans in match:
counter += 10
tries -= 1
print("That's right, 10 points added")
print(f"You have {tries} tries left. ")
elif ans not in match:
counter -= 10
tries -= 1
print("That's wrong, 10 points deducted")
print(f"You have {tries} tries left. ")
few ideas:
make a loop over your "tries" - the player can play until that is 0
the player has to provide the letter inside this loop
check for the letter provided by the player using
if ans in word
Here is my suggestion:
import random
print('Hi, welcome to the guessing game, wanna play?')
answer = input('Enter yes or no: ')
#just added a list to test
data = ['hello', 'coffee', 'tea']
word = random.choice(data)
if answer == "yes".lower():
print("OK, let's play")
print("alright, guess the first letter:")
counter = 0
tries = 15 # how many tries a user is allowed to make
while tries > 0:
ans = input("Enter a letter to guess: ")
print(ans)
if ans in word:
counter += 10
tries -= 1
print("That's right, 10 points added")
print(f"You have {tries} tries left. ")
elif ans not in word:
counter -= 10
tries -= 1
print("That's wrong, 10 points deducted")
print(f"You have {tries} tries left. ")
elif answer == "no".lower():
print("OK, have a good day")
else:
print('Please enter yes or no')
You could also make a list of letter that were already guessed so you can give the player feedback as soon as they found all the needed letters.
Not sure if I understand this completely, but if word is just a word like "apple" or "cat", then your function shouldn't be iterating through your entire list (your list being data). This function iterates through each letter of the randomized word (like "apple") and checks if the inputted letter is equal to any of the letters in that word.
The 'in' keyword itself checks only the first occurrence of a variable in a collection.
However if you want to be more specific, assign your entered word to a variable and then use break keyword after it matches under the if statement while iterating through the list.

How do I get the value of a variable to decrease by 1 every time the user enters something incorrect?

This is a python program exercise called guess the word from codehs.com. It basically works like hangman. The user has 10 lives and I'm trying to decrease the lives by one when the user guesses an incorrect letter. However, it always says there are 9 incorrect guesses remaining no matter how many times a user guesses an incorrect letter. How do I fix the program so that it decreases by one all the way down to 0 incorrect guesses left? Furthermore, how do I say that the user lost and terminate the program when he/she has zero incorrect guesses left? Thanks so much.
#initializes the secret word and starts with empty dashes list
secret_word = "eggplant"
dashes_list = []
def get_guess():
#prompts user for a guess
guess = input("Guess: ")
dashes = "-"
guesses_left=10
#if the guess is not one character
if len(guess) != 1:
print ("Your guess must have exactly one character!")
#if the guess is not lowercase
elif not guess.islower():
print ("Your guess must be a lowercase letter!")
#assigns this position_of_letter variable to be used later
position_of_letter = 0
for letter in secret_word:
if guess == letter:
print ("Letter is in secret word.")
update_dashes(secret_word, dashes, guess)
return
else:
position_of_letter += 1
if position_of_letter == len(secret_word):
print ("Letter is not in the secret word.")
if guesses_left==0:
print("You lose. The word was "+secret_word)
guesses_left-=1
print (str(guesses_left)+" incorrect guesses left.")
#This goes through the word and makes sure to update
#the dashes at the right place
def update_dashes(secret_word, dashes, guess):
position_of_letter_dashes_list = 0
for letter in secret_word:
if letter == guess:
dashes_list[position_of_letter_dashes_list] = guess
position_of_letter_dashes_list += 1
#adds a dash mark for each letter so there is now a list of dashes
for i in range(len(secret_word)):
dashes_list.append("-")
#The .join breaks the dashes list into a continuous string of dashes
#The "" is there so that nothing comes before each dash
while True:
print ("".join(dashes_list))
get_guess()
if "-" not in dashes_list:
print("Congrats! You win. The word was "+secret_word+".")
break
You are re-initializing number of guesses_left=10 each time so the value of guesses_left is not decreasing with every incorrect guess. You can initialize its value outside the get_guess() as a global variable or pass it as a parameter to this function.

How to store user inputted strings in a variable and then see if those inputs are contained in a word

I'm trying to make a hangman game. At the moment I'm still trying to figure out how to store users inputted strings in a variable.
I need this because if a user guesses the word before the ten guesses it keeps asking them for another letter.
I've tried creating a variable and then updating the variable as the user entered more letters. However that doesn't work in cases the user doesn't enter all the letters in the correct order the program is obviously not going to recognize this as the correct word.
Basically I need a way to store the inputted strings (one letter at a time) and to be able to check if all of those letters are contained in the five letter word.
import random
print("Welcome to hangman, guess the five letter word")
words =["china", "ducks", "glass"]
correct_word = (random.choice(words))
trials = 10
for trial in range(trials):
guess = input(str("Enter Character:"))
if (len(guess) > 1):
print("You are not allowed to enter more than one character at a time")
continue
if guess in correct_word:
print("Well done " + guess + " is in the list!")
else:
print("Sorry " + guess + " is not included")
It seems like a set is what you need.
You start with an empty set() and add the letter every time. To check if the letters are enough, use saved_set == set(correct_word).
With the help of an auxiliar list, this little guy will do the trick (I put some comments to better explain what I did):
import random
import sys
print("Welcome to hangman, guess the five letter word")
words =["china", "ducks", "glass"]
correct_word = (random.choice(words))
trials = 10
trial = 0
#the list starts empty, since the user didn't guessed any letter
guessed_letters = []
while(trial < trials):
guess = input(str("Enter Charcter:"))
if (len(guess) > 1):
print("You are not allowed to enter more than one charcter at a time")
continue
if (guess in correct_word) and (guess not in guessed_letters):
#once our user guesses a letter that he didn't guessed before, it will be added to our list of guessed letters
print("Well done " + guess + " is in the list!")
guessed_letters += guess
#in here we compare the size of the list with the size of the correct_word without duplicates
#if it's the same size, boom: the user won!
if (len(guessed_letters) == len(set(correct_word))):
print("Congratulations! You won!")
sys.exit()
else:
#just to avoid confusing the user with duplicate letters
if (guess in guessed_letters):
print("You already tried letter " + guess + "! Try another letter")
trial -= 1
else:
print("Sorry " + guess + " is not included")
print("Remaining chances: " + str(trials - trial))
trial += 1
print("\n\n\nGame over!!!!")
All you need is to replace:
guess = input(str("Enter Charcter:"))
by:
guess = str(sys.stdin.readline().rstrip('\n'))

Correcting user input to meet a specific requirement for Hangman

I need the user input to only equal 1 character but there is a bug in the code that lets me enter more than one character at a time. I need to be able to prompt the user to say you can only enter one character at a time and then go back to let them enter the character but without the character counting toward the game.
print ("lets play guess this word.") #time to play
secret_word = input("Enter a secret word to guess: ") # gather the secret word
secret_word = secret_word.lower() # convert to lower
guesses = "" # this is the string that will show what has been guessed later
turns = 6 # how many chances they get to enter a wrong character.
# a very very tricky while loop.
while turns > 0: # will be true until the turns counter makes turns = 0
count = 0 # this count determines wether to print _ or the character
for char in secret_word: # looking at characters in the secret word
if char in guesses: # this is used to display the correct letters and _'s
print (char, end="")
else:
print ("_ ",end="") # this print the _ for every char in secretword
count += 1 # ends the for loop continues to the next part
if count == 0: # you won the game end the loop.
print ()
print ("You win")
break
print ()
print ()
print ()
guess = input("guess a character:")
count2 = 0
if len(guess) > 1:
count2 += 1
while count2 > 0:
print ("you can only guess 1 character at a time")
count2 -= 1
guess = guess.lower() #lower # it is time to guess the letters.
guesses += guess
if guess not in secret_word: # if statement for if guess is not in word
turns -= 1 # subtract from turns
print ()
print ()
print ("Wrong")
print ("Letters guessed so far: ",guesses) # end of loop show guessed letters
print ("You have", + turns, 'more guesses') # show turns left
if turns == 0: # END GAME
print ("The word was",secret_word,"You Loose")
Screenshot showing the code does work in Python:
I also need help with making it only accept 1 character at a time and also no numbers. I also added this part of code while trying to accomplish this task but it does not stop the multiple characters being entered from counting toward the word.
count2 = 0
if len(guess) > 1:
count2 += 1
while count2 > 0:
print ("you can only guess 1 character at a time")
count2 -= 1
Here is my output:
lets play guess this word.
Enter a secret word to guess: computer
_ _ _ _ _ _ _ _
guess a character:abcdefghijklmnopqrstuvwxyz
you can only guess 1 character at a time
Wrong
Letters guessed so far: abcdefghijklmnopqrstuvwxyz
You have 5 more guesses
computer
You win
All you're missing is the statement to loop back around after warning if the user enters invalid input. With the structure you've got, the statement you want is continue, which jumps to the next iteration of a loop:
while turns > 0:
# Print current guesses; get input; etc...
# Check for invalid input
if len(guess) > 1:
print("you can only guess 1 character at a time")
continue # This makes us return to the top of the while loop.
# We definitely have valid input by the time we get here, so handle the new guess.
This is simplified a little from your version; I've taken out count2, for instance, because it wasn't doing anything important. But the premise is the same: after you warn the user about their invalid input, you need to ask for new input--jump to the top of the loop--instead of just moving ahead.

How to hide/reveal letters in python game?

I'm new to coding and am currently trying to make a simplified game of Hangman using Python 3. For the most part, I have it down, except for the most important part, how to hide the letters of the random word, and then how to reveal them once guessed. Mainly, I just need a quick answer. Any help would be greatly appreciated. Here's my code so far (sorry if it's long, like I said, I relatively new at this, and thanks again!):
import random
#list of words for game
hangmanWords = ("Halloween","Hockey","Minnesota","Vikings","Twins","Timberwolves","Wild","Playstation","Achievement","Minecraft","Metallica","Portal","Xbox","Guitar")
#randomizes the word chosen for game
index = random.randint(0,len(hangmanWords)-1)
#assigns radomized word to variable
randomWord = hangmanWords[index]
'''
menu function, provides user with choices for game, user chooses via imput
'''
def menu():
print("""
Welcome to Hangman!
Select a difficulty:
1. Easy (9 Misses)
2. Medium (7 Misses)
3. Advanced (5 Misses)
4. Exit Game
""")
selection = int(input("What difficulty do you pick (1-4)?: "))
return selection
'''
the function for easy mode, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets 9 guesses to figure out word, correct guesses don't
count, returns player to main menu when they lose
'''
def easyMode():
wrongGuesses = 0
listOfGuesses = []
print(randomWord)
while(wrongGuesses != 9):
x = input("Enter a letter: ")
if x.lower() in randomWord.lower():
print(x,"is in the word!")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
else:
print(x,"is not in the word.")
wrongGuesses += 1
print(wrongGuesses, "wrong guesses.")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
print("You lost the game!")
return x
'''
the function for medium mode, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets 7 guesses to figure out word, correct guesses don't
count, returns player to main menu when they lose
'''
def medium():
wrongGuesses = 0
listOfGuesses = []
print(randomWord)
while(wrongGuesses != 7):
x = input("Enter a letter: ")
if x.lower() in randomWord.lower():
print(x,"is in the word!")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
else:
print(x,"is not in the word.")
wrongGuesses += 1
print(wrongGuesses, "wrong guesses.")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
print("You lost the game!")
return x
'''
the function for advanced mode, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets 5 guesses to figure out word, correct guesses don't
count, returns player to main menu when they lose
'''
def advanced():
wrongGuesses = 0
listOfGuesses = []
print(randomWord)
while(wrongGuesses != 5):
x = input("Enter a letter: ")
if x.lower() in randomWord.lower():
print(x,"is in the word!")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
else:
print(x,"is not in the word.")
wrongGuesses += 1
print(wrongGuesses, "wrong guesses.")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
print("You lost the game!")
return x
'''
main function, deals with what happens depending on
what the player selected on the menu
'''
def main():
select = menu()
while(select != 4):
if(select == 1):
easyMode()
elif(select == 2):
medium()
elif(select == 3):
advanced()
select = menu()
print("You don't want to play today? :'(")
main()
If you want to try it out yourself, then please don't see the code yet. Like in hangman, we get to see our progress (partially guessed word), you should create another variable that holds such a string. And, with every correct guess, you should update this string accordingly. The string obviously starts out as ##### or ***** according to the length of the word to be guessed.
With several improvements, I present to you, Hangman!
All credits go to you of course!
import random
#list of words for game
hangmanWords = ("Halloween","Hockey","Minnesota","Vikings","Twins","Timberwolves","Wild","Playstation","Achievement","Minecraft","Metallica","Portal","Xbox","Guitar")
#assigns radomized word to variable
randomWord = random.choice(hangmanWords)
'''
menu function, provides user with choices for game, user chooses via imput
'''
def menu():
print("""
Welcome to Hangman!
Select a difficulty:
1. Easy (9 Misses)
2. Medium (7 Misses)
3. Advanced (5 Misses)
4. Exit Game
""")
selection = int(input("What difficulty do you pick (1-4)?: "))
return selection
def game(mode):
'''
the game function, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets guesses according to value passed as per mode,
to figure out the word, correct guesses don't count,
returns player to main menu when they lose
'''
modes = {1:9, 2:7, 3:5} # Matches mode to guesses
guesses = modes[mode]
wrongGuesses = 0
listOfGuesses = []
# print(randomWord) Dont't print the solution!!
# Get a random word which would be guessed by the user
to_guess = random.choice(hangmanWords)
to_guess = to_guess.lower()
# The correctly guessed part of the word that we print after every guess
guessed = "#"*len(to_guess) # e.g. "Hangman" --> "#######"
while(wrongGuesses != guesses):
x = input("Word - %s . Guess a letter: "%guessed).lower()
if x in to_guess:
print(x,"is in the word!")
listOfGuesses.append(x)
# Now replace the '#' in 'guessed' to 'x' as per our word 'to_guess'
new_guessed = ""
for index, char in enumerate(to_guess):
if char == x:
new_guessed += x
else:
new_guessed += guessed[index]
guessed = new_guessed # Change the guessed word according to new guess
# If user has guessed full word correct, then he has won!
if guessed == to_guess:
print("You have guessed the word! You win!")
print("The word was %s"%to_guess)
return True # return true on winning
else:
print("Letters guessed so far:", listOfGuesses, "\n")
else:
print(x,"is not in the word.")
wrongGuesses += 1
print("Wrong guesses:", wrongGuesses)
listOfGuesses.append(x)
print("Letters guessed so far:", listOfGuesses, "\n")
print("You lost the game!")
print("The word was %s"%to_guess)
return False # return false on loosing
'''
main function, deals with what happens depending on
what the player selected on the menu
'''
def main():
select = menu()
while(select != 4):
game(select)
select = menu()
print("You don't want to play today? :'(")
main()
Wherever you see copy-paste or code repetition, it's not Pythonic! Try to avoid repetition, especially in functions. (like your easy, medium & hard functions)
The other answer implements it for you, but I'll walk you through the methodology so you can improve as a programmer.
You're going to want two lists, one that has the full word, and one that has the list you want to display. You can either make a binary list that is the same length as the word, or you can make a "display list", that is full of underscores, until the correct letter is guessed.
The display list method should look something like this and is easier to impliment:
To initialize displaylist:
for _ in range(len(randomword)):
displaylist.append("_")
Then within the if statement:
for i in range(len(randomword)):
if x == randomword[i]:
displaylist[i] = x
And then to print, you would need something like this:
print(''.join(displaylist))
Another improvement you could make is making a separate function that checks your word so that you can most effectively use modular programming. This would cut down on code complexity, redundancy, and make it easier to implement changes.

Categories