I can't figure out why my while loop won't break to finish the hangman program. I've included the whole program to give you some context. It will print the game over message, but not the win message
import random
import os
import time
def playGame():
wordList = ["dog", "bird", "chair", "computer", "elephant", "school"]
letterList=[]
underscoreList=[]
guessesLeft = 6
word = random.choice(wordList)
#print(word)
for letter in word:
letterList.append(letter)
underscoreList.append("_")
#print(letterList)
#print(underscoreList)
while guessesLeft > 0:
#os.system('clear') #clears screen
print(underscoreList)
print("You Have" , guessesLeft, "Guesses Remaining")
userGuess = (input("Please enter a letter... \n>")).lower()
if len(userGuess) != 1 or not userGuess.isalpha():
print("Please Enter A Single Letter Only")
time.sleep(1)
elif userGuess in letterList:
print(userGuess, "is there")
time.sleep(1)
for position, letter in enumerate(letterList):
if letter == userGuess:
underscoreList[position] = userGuess
elif '_' not in underscoreList:
break
else:
print("Not In Word")
time.sleep(2)
guessesLeft -= 1
if guessesLeft > 0:
print("Congratulations you have guessed the word " , word)
else:
print("You Loser")
playGame()
Just have to move the elif to the beginning of the code. So now it checks before continuing the program.
import random
import os
import time
def playGame():
wordList = ["dog", "bird", "chair", "computer", "elephant", "school"]
letterList=[]
underscoreList=[]
guessesLeft = 6
word = random.choice(wordList)
#print(word)
for letter in word:
letterList.append(letter)
underscoreList.append("_")
#print(letterList)
#print(underscoreList)
while guessesLeft > 0:
#os.system('clear') #clears screen
if '_' not in underscoreList:
break
print(underscoreList)
print("You Have" , guessesLeft, "Guesses Remaining")
userGuess = (input("Please enter a letter... \n>")).lower()
if len(userGuess) != 1 or not userGuess.isalpha():
print("Please Enter A Single Letter Only")
time.sleep(1)
elif userGuess in letterList:
print(userGuess, "is there")
time.sleep(1)
for position, letter in enumerate(letterList):
if letter == userGuess:
underscoreList[position] = userGuess
else:
print("Not In Word")
time.sleep(2)
guessesLeft -= 1
if guessesLeft > 0:
print("Congratulations you have guessed the word " , word)
else:
print("You Loser")
playGame()
Related
I am trying to make a game where the user inputs a word with only three guesses available, but instead it keeps allowing four guesses which I don't want.
When i input a word and my guess_count reaches 3, i am supposed to be sent this msg "You have no more guesses, you lose!" then ask if i want to retry but instead it lets me play one more time thereby exceeding the guess_limit
Here is my code
secret_word = "loading"
guess_word = ""
guess_count = 0
guess_limit = 3
end = False
print("Welcome to the guessing game\nYou have 3 guesses")
guess_word = input("Enter a word: ")
def end_msg(msg):
print(msg)
retry = input("Do you want to play again? ")
if (retry == "yes") :
global end, guess_word, guess_count
end = False
guess_word = ""
guess_count = 0
print("Welcome to the guessing game\\nYou have 3 guesses")
guess_word = input("Enter a word: ")
else:
end = True
while (not(end)) :
if (guess_word != secret_word and guess_count \< guess_limit):
guess_count += 1
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_word = input("Try again: ")
elif (guess_count == 3):
end_msg("You have no more guesses, you lose!")
else:
end_msg("Correct, you win")
I see your query already answered above, In case you want I have adapted your code to make it more organized and structured into two functions
playagain - which asks after winning/losing if the user wants to play the game again
play - the actual program to play the game
I removed some redundancies like end = False variable you used and could have also removed some other variables like guess_limiter (by just assigning the guess limit value in the actual program) but I wanted to retain your code as much as possible in case for your understanding, hope this helps
def playagain():
play_again = input("Do you want to play again? (y/n) ")
if play_again == 'y':
return play()
elif play_again == 'n':
print("Thank you for playing")
else:
print("incorrect input please try again")
playagain()
def play():
secret_word = "loading"
guess_word = ""
guess_count = 1
guess_limit = 3
print("Welcome to the guessing game\nYou have 3 guesses")
while (guess_count != guess_limit + 1):
guess_word = input("Enter a word: ")
if guess_word == secret_word:
print("Correct, you win")
playagain()
break
elif guess_count == guess_limit:
print("You have no more guesses, you lose!")
playagain()
break
else:
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_count += 1
play()
You are getting this bug because you wrote guess_limit = 3. You know Programs count from 0, so you need to enter 1 less from your desire try. It should be guess_limit = 2.
And also you wrote elif (guess_count == 3) :, thats mean if guess_count == 3 your will get "You have no more guesses, you lose!" even, user put the right answer. so it should be
elif (guess_word != secret_word and guess_count == 2):
so your final code should be:
secret_word = "loading"
guess_word = ""
guess_count = 0
guess_limit = 2
end = False
print("Welcome to the guessing game\nYou have 3 guesses")
guess_word = input("Enter a word: ")
def end_msg (msg) :
print(msg)
retry = input("Do you want to play again? ")
if (retry == "yes") :
global end, guess_word, guess_count
end = False
guess_word = ""
guess_count = 0
print("Welcome to the guessing game\\nYou have 3 guesses")
guess_word = input("Enter a word: ")
else:
end = True
while (not(end)) :
if (guess_word != secret_word and guess_count < guess_limit) :
guess_count += 1
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_word = input("Try again: ")
elif (guess_word != secret_word and guess_count == 2) :
end_msg("You have no more guesses, you lose!")
else:
end_msg("Correct, you win")
print("\t \t \t What's the password?")
print("\t you have 5 chances to get it right! \n")
secret_word = "green"
guess = ""
guess_count = 0
guess_limit = 5
out_of_guesses = False
hintA = "Ashtons' favorite color"
print("Here is a hint: "+ hintA)
#while loop
while guess != secret_word and not (out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1
#elif guess_count == 2:
#print("Here is a hint: "+ hintA)
else:
out_of_guesses = True
if out_of_guesses:
print("You have been locked out!")
else:
print("Correct password!")
I don't how to add a hint after like 2 or 3 guesses because without it would be impossible to do. Also the stuff in # was my attempt
you can try something like this :
print("\t \t \t What's the password?")
print("\t you have 5 chances to get it right! \n")
secret_word = "green"
guess = ""
guess_count = 0
guess_limit = 5
out_of_guesses = False
hintA = "Ashtons' favorite color"
#while loop
while guess != secret_word and not (out_of_guesses):
if guess_count < guess_limit:
if guess_count == 2:
print("Here is a hint: "+ hintA)
guess = input("Enter guess: ")
guess_count += 1
#elif guess_count == 2:
#print("Here is a hint: "+ hintA)
else:
out_of_guesses = True
if out_of_guesses:
print("You have been locked out!")
else:
print("Correct password!")
Move your input outside the if...else statements and change the position of the if...else statements.
print("\t \t \t What's the password?")
print("\t you have 5 chances to get it right! \n")
secret_word = "green"
guess = ""
guess_count = 0
guess_limit = 5
out_of_guesses = False
hintA = "Ashtons' favorite color"
#while loop
while guess != secret_word and not (out_of_guesses):
guess = input("Enter guess: ")
if guess_count == 2:
print("Here is a hint: "+ hintA)
guess_count+=1
elif guess_count != guess_limit:
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print("You have been locked out!")
else:
print("Correct password!")
Output:
What's the password?
you have 5 chances to get it right!
Enter guess: red
Enter guess: blue
Enter guess: yellow
Here is a hint: Ashtons' favorite color
Enter guess: purple
Enter guess: beige
Enter guess: light green
You have been locked out!
secret_word, guess_limit, hintA = "green", 5, "Here is a hint: Ashtons' favorite color"
print("\t\t\tWhat's the password?\n\tyou have " + str(guess_limit) + " chances to get it right!\n")
for i in range(guess_limit):
if i > guess_limit // 2: # more than half of the attempts are exhausted
print(hintA)
if input("Enter guess: ") == secret_word:
print("Correct password!")
break
else:
print("You have been locked out!")
I am trying to make a small texted based game in which the player has to guess a word. If the secret word is water and the player guesses barge, the game should display -Ar-e, because those are the letters that are in common and since a is also in the correct place, it is shown as a capital letter.
from random import randint
def lingo():
fp = open("wordsEn.txt","r")
words = []
while True:
buffer = fp.readline()
if buffer == "":
break
else:
words.append(buffer[:-1])
secret_word = list(words[randint(0,len(words)-1)])
display_word = []
rand_num = randint(0,len(secret_word)-1)
compare_word = []
for i in range(len(secret_word)):
if i == rand_num:
display_word.append(secret_word[i])
compare_word.append(secret_word[i])
else:
display_word.append("-")
compare_word.append("-")
print(secret_word)
for i in range(5):
print(display_word)
print(compare_word)
if compare_word == secret_word:
break
else:
while True:
guess = input("guess: ")
if guess.isalpha() == False:
print("Only letters")
elif len(guess) > len(secret_word):
print("Too long")
elif len(guess) < len(secret_word):
print("Too short")
else:
break
for j in range(len(guess)):
print(guess[j])
print(guess[j] in secret_word)
if guess[j] in secret_word:
print("I am in")
if guess[j] == secret_word[j]:
display_word[j] == guess[j].upper()
compare_word[j] == guess[j]
else:
display_word[j] == guess[j]
else:
print("I am out")
continue
lingo()
I have to write a code in Python where it is about playing the game hangman. Currently my code cannot replace the "_" with the guessed letters properly, where it only replaces one and doesn't show all of the guessed letters.
My code is below:
import random
word = random.choice(["bread", "clouds", "plane"])
guess = 0
correct_guess = 0
play_again = True
print(word)
name = input("Hello, what's your name? ")
print('Hello', name)
status = input('Do you wish to play hangman? Yes/No ')
hyphens = print('_ ' * (len(word)))
if status == 'No' 'no' 'N' 'n':
exit()
while play_again is True:
letter = input('Guess a letter: ')
if letter in word:
guess = guess + 1
correct_guess = correct_guess + 1
print('You guessed a letter correctly!')
position = word.find(letter)
print("The letter is in position", position + 1, "out of", len(word), "in the word. Guess Count:", guess)
if position == 0:
print(letter, "_ _ _ _")
if position == 1:
print("_", letter, "_ _ _ ")
if position == 2:
print("_ _", letter, "_ _ ")
if position == 3:
print("_ _ _", letter, "_ ")
if position == 4:
print("_ _ _ _", letter)
else:
guess = guess + 1
print("That letter isn't in the word. Guess Count:", guess)
if guess == 10:
print('Bad luck. You lost.')
play = input('Do you want to play again? ')
if play == 'No' 'no' 'N' 'n':
exit()
if correct_guess == 5:
print('Congratulations! You have guessed the word! The word was', word + '.')
play = input('Do you want to play again? ')
if play == 'No' 'no' 'N' 'n':
exit()
Your help is very much appreciated. Also, I don't know a lot about programming and I am fairly new to it.
James
you can't write expression like :
if status == 'No' 'no' 'N' 'n':
the correct way is:
if play == 'No' or play == 'no' or play == 'N' or play == 'n':
or:
if play in ['No' ,'no', 'N' ,'n']
one solution:
import random
word = random.choice(["bread", "clouds", "plane"])
print(word)
name = input("Hello, what's your name? ")
print('Hello', name)
status = input('Do you wish to play hangman? Yes/No ')
def play():
if status == 'No' or status == 'no' or status == 'N' or status == 'n':
print ("Goodbye")
return # exit
else:
print('_ ' * (len(word))) # _ _ _ _ _
guess = 0
correct_guess = 0
play_again = True
pos_list = ['_' for x in range(len(word))] # define list where you will put your guessed letters ['_', '_', '_', '_', '_']
while play_again is True:
letter = input('Guess a letter: ')
if letter in word:
guess = guess + 1
correct_guess = correct_guess + 1
print('You guessed a letter correctly!')
position = word.find(letter)
print("The letter is in position", position + 1, "out of", len(word), "in the word. Guess Count:", guess)
pos_list[position] = letter # save letter at position # ['_', '_', '_', 'a', '_']
print (' '.join(pos_list)) # _ _ _ a _
else:
guess = guess + 1
print("That letter isn't in the word. Guess Count:", guess)
if guess == 10:
print('Bad luck. You lost.')
play = input('Do you want to play again? ')
if play == 'No' or play == 'no' or play == 'N' or play == 'n':
print("Goodbye")
return
else:
print('_ ' * (len(word)))
if correct_guess == len(word):
print('Congratulations! You have guessed the word! The word was', word + '.')
play = input('Do you want to play again? ')
if play == 'No' or play == 'no' or play == 'N' or play == 'n':
print("Goodbye")
return
else:
print('_ ' * (len(word)))
play()
Cleaned it up a bit, removing duplicated code. Also that problematic condition:
if status == 'No' 'no' 'N' 'n':
Changed it to:
if status.lower().startswith("n"):
Also important to lower the letter input by the user. Here a full working code.
import random
import re
def start():
status = input('Do you wish to play hangman? Yes/No ')
if status.lower().startswith("n"):
return True
# Computer chooses word
word = random.choice(["bread", "clouds", "plane"])
# Setup game vars
guess = []
game_status = ["_"] * len(word)
while True:
print(" ".join(game_status))
letter = input('Guess a letter: ').lower()
if letter in guess:
print("You already tried that one.")
continue
guess.append(letter)
if letter in word:
print('You guessed a letter correctly!')
positions = [m.start() for m in re.finditer(letter, word)]
for pos in positions:
game_status[pos] = letter
else:
print("That letter isn't in the word.")
if len(guess) == 10:
print(f'Bad luck {name}. You lost. The word was: {word}.')
return
if "_" not in game_status:
print(f'Congratulations {name}! You have guessed the word! The word was {word}.')
return
# Welcome
name = input("Hello, what's your name? ")
print('Hello', name)
while True:
stop = start()
if stop:
break
print("Goodbye!")
What I am trying to do is to read a text file from a user and then run the game with that particular file. I know that it will be more easier to have functions but I don't know how to modify the whole code with functions.
How can I run the game with that text file inputted by user?
import random
import sys
choice = None
while choice != "0":
print('''
--------------------
Welcome to Hangman
--------------------
Please select a menu option:
0 - Exit
1 - Enter a new text file to be read:
2 - Play Game
''')
choice= input("Enter you choice: ")
if choice == "0":
sys.exit("Exiting from Python")
elif choice =="1":
newIn = []
fileInput = input("Enter a new text file name: ")
newIn = open(fileInput).readlines()
newIn=List
elif choice == "2":
List = open("words_for_hangman.txt").readlines()
print('''
Now select your difficulty level:
0 - EASY
1 - INTERMEDIATE
2 - HARD
''')
level= input("Enter your choice: ")
if level == "0":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 10
guessed = []
elif level == "1":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 7
guessed = []
elif level == "2":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 5
guessed = []
while lives != 0 and hidden_word != word:
print("\n-------------------------------")
print("The word is")
print(hidden_word.replace("_"," _ "))
print("\nThere are", len(word), "letters in this word")
print("So far the letters you have guessed are: ")
print(' '.join(guessed))
print("\n You have", lives,"lives remaining")
guess = input("\n Guess a letter: \n")
guess = guess.upper()
if len(guess) > 1:
guess = input("\n You can only guess one letter at a time!\n Try again: ")
guess = guess.upper()
elif guess== " ":
guess = input("\n You need to input a letter, not a space!\n Come on let's try again: ")
guess = guess.upper()
while guess in guessed:
print("\n You have already guessed that letter!")
guess = input("\n Please take another guess: ")
guess = guess.upper()
guessed.append(guess)
if guess in word:
print('''-------------------------------
''')
print("Well done!", guess.upper(),"is in the word")
word_so_far = ""
for i in range (len(word)):
if guess == str(word[i]):
word_so_far += guess
else:
word_so_far += hidden_word[i]
hidden_word = word_so_far
else:
print('''-------------------------------
''')
print("Sorry, but", guess, "is not in the word")
lives -= 1
if lives == 0:
print("GAME OVER! You have no lives left")
else:
print("\n CONGRATULATIONS! You have guessed the word")
print("The word was", word)
print("\nThank you for playing Hangman")
else:
choice = print("\n That is not a valid option! Please try again!")
choice = input("Choice: ")
At first sight, there are two mistakes in the program
The lines
newIn = open(fileInput).readlines()
newIn=List
first read the file into the variable newIn and then remove the content of newIn by setting it to the content of List. I guess you wanted to do
List = open(fileInput).readlines()
as you did in the second part.
The second mistake is that the whole game is played only when the user presses 2. Try moving the whole block beginning with
while lives != 0 and hidden_word != word:
to the left, so that block is entered either when the user presses 1 or 2. Also, if you do this, the else at the end of the program should go right before the while lives != 0...
First keep all your files in a folder and run this file..
For choice 1: Give your new.txt file or try with same file of option two.(words_for_hangman.txt) but it will be easy for your if you keep all your files in same folder.
import random
import sys
choice = None
while choice != "0":
print('''
--------------------
Welcome to Hangman
--------------------
Please select a menu option:
0 - Exit
1 - Enter a new text file to be read:
2 - Play Game
''')
choice= input("Enter you choice: ")
if choice == "0":
sys.exit("Exiting from Python")
elif choice =="1":
newIn = []
fileInput = input("Enter a new text file name: ")
newIn = open(fileInput).readlines()
newIn=List
elif choice == "2":
List = open("words_for_hangman.txt").readlines()
print('''
Now select your difficulty level:
0 - EASY
1 - INTERMEDIATE
2 - HARD
''')
level= input("Enter your choice: ")
if level == "0":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 10
guessed = []
elif level == "1":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 7
guessed = []
elif level == "2":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 5
guessed = []
while lives != 0 and hidden_word != word:
print("\n-------------------------------")
print("The word is")
print(hidden_word.replace("_"," _ "))
print("\nThere are", len(word), "letters in this word")
print("So far the letters you have guessed are: ")
print(' '.join(guessed))
print("\n You have", lives,"lives remaining")
guess = input("\n Guess a letter: \n")
guess = guess.upper()
if len(guess) > 1:
guess = input("\n You can only guess one letter at a time!\n Try again: ")
guess = guess.upper()
elif guess== " ":
guess = input("\n You need to input a letter, not a space!\n Come on let's try again: ")
guess = guess.upper()
while guess in guessed:
print("\n You have already guessed that letter!")
guess = input("\n Please take another guess: ")
guess = guess.upper()
guessed.append(guess)
if guess in word:
print('''-------------------------------
''')
print("Well done!", guess.upper(),"is in the word")
word_so_far = ""
for i in range (len(word)):
if guess == str(word[i]):
word_so_far += guess
else:
word_so_far += hidden_word[i]
hidden_word = word_so_far
else:
print('''-------------------------------
''')
print("Sorry, but", guess, "is not in the word")
lives -= 1
if lives == 0:
print("GAME OVER! You have no lives left")
else:
print("\n CONGRATULATIONS! You have guessed the word")
print("The word was", word)
print("\nThank you for playing Hangman")
else:
choice = print("\n That is not a valid option! Please try again!")
choice = input("Choice: ")