So I'm working my first project which hangman written in python every works like the visuals and the incorrect letters. However, It is unable to recognise the correct letter guessed.
import random
from hangman_visual import lives_visual_dict
import string
# random word
with open('random.txt', 'r') as f:
All_Text = f.read()
words = list(map(str, All_Text.split()))
WORD2GUESS = random.choice(words).upper()
letters = len(WORD2GUESS)
print("_" * letters)
word_letters = set(WORD2GUESS)
alphabet = set(string.ascii_uppercase)
lives = 7
used_letters = set()
# user input side
while len(word_letters) > 0 and lives > 0:
# letters used
# ' '.join(['a', 'b', 'cd']) --> 'a b cd'
print('You have', lives, 'lives left and you have used these letters: ', ' '.join(used_letters))
# what current word is (ie W - R D)
word_list = [letter if letter in used_letters else '-' for letter in WORD2GUESS]
print(lives_visual_dict[lives])
print('Current word: ', ' '.join(word_list))
user_letter = input('Guess a letter: ').upper()
if user_letter in alphabet - used_letters:
used_letters.add(user_letter)
if user_letter in WORD2GUESS:
used_letters.remove(user_letter)
print('')
else:
lives = lives - 1 # takes away a life if wrong
print('\nYour letter,', user_letter, 'is not in the word.')
elif user_letter in used_letters:
print('\nYou have already used that letter. Guess another letter.')
else:
print('\nThat is not a valid letter.')
if lives == 0:
print(lives_visual_dict[lives])
print('You died, sorry. The word was', WORD2GUESS)
else:
print('YAY! You guessed the word', WORD2GUESS, '!!')
I've tried this, but it still wont recognise the correct guess.
# what current word is (ie W - R D)
word_list = [letter if letter in used_letters else '-' for letter in WORD2GUESS]
print(lives_visual_dict[lives])
print('Current word: ', ' '.join(word_list))
Your error is this: When checking if the user_letter is in the WORD2GUESS, you falsely remove it from used_letters, but it has to stay in the set.
Also you are missing some way of escaping the while loop when fully guessing the word. That could be done at the same spot by checking if used_letters contain all the letters in WORD2GUESS.
Something like this:
import random
from hangman_visual import lives_visual_dict
import string
# random word
with open('random.txt', 'r') as f:
All_Text = f.read()
words = list(map(str, All_Text.split()))
WORD2GUESS = random.choice(words).upper()
letters = len(WORD2GUESS)
print("_" * letters)
word_letters = set(WORD2GUESS)
alphabet = set(string.ascii_uppercase)
lives = 7
used_letters = set()
# user input side
while len(word_letters) > 0 and lives > 0:
# letters used
# ' '.join(['a', 'b', 'cd']) --> 'a b cd'
print('You have', lives, 'lives left and you have used these letters: ', ' '.join(used_letters))
# what current word is (ie W - R D)
word_list = [letter if letter in used_letters else '-' for letter in WORD2GUESS]
print(lives_visual_dict[lives])
print('Current word: ', ' '.join(word_list))
user_letter = input('Guess a letter: ').upper()
if user_letter in alphabet - used_letters:
used_letters.add(user_letter)
if user_letter in WORD2GUESS:
print('\nThat is a correct letter.')
if set(WORD2GUESS).issubset(used_letters):
break
else:
lives = lives - 1 # takes away a life if wrong
print('\nYour letter,', user_letter, 'is not in the word.')
elif user_letter in used_letters:
print('\nYou have already used that letter. Guess another letter.')
else:
print('\nThat is not a valid letter.')
if lives == 0:
print(lives_visual_dict[lives])
print('You died, sorry. The word was', WORD2GUESS)
else:
print('YAY! You guessed the word', WORD2GUESS, '!!')
I am trying to write an Hangman game in Python, which I almost figure it out for simple words but when there is a duplicate it mess up with the return indexing. Here is the code:
def hangman_game():
words = ["aback", "abaft", "abandoned", "abashed", "aberrant", "abhorrent", "abiding", "abject", "ablaze", "able",
"abnormal", "aboard", "aboriginal", "abortive", "abounding", "abrasive", "abrupt", "absent", "absorbed",
"absorbing", "abstracted", "absurd", "abundant", "abusive", "acceptable", "accessible", "accidental",
"accurate", "acid", "acidic", "acoustic", "acrid", "actually", "ad hoc", "adamant", "adaptable", "addicted",
"adhesive", "adjoining", "adorable", "adventurous", "afraid", "aggressive", "agonizing", "agreeable", "ahead",
"ajar", "alcoholic", "alert", "alike", "alive", "alleged", "alluring", "aloof", "amazing", "ambiguous",
"ambitious", "amuck", "amused", "amusing", "ancient", "angry", "animated", "annoyed", "annoying", "anxious",
word = random.choice(words)
print(f'Random word = {word} (backtesting)')
letter_set = []
word_set = []
for i in word:
word_set.append(i)
print(f'Letter remaining to be found ={word_set}')
while len(letter_set) < len(word_set):
for i in word:
letter = input("Guess a letter: ")
if letter in word_set:
letter_set.insert(word.index(letter)), letter) # issue here
word_set.remove(letter)
print(f'Word with letters removed: {word}')
print(f"Letter {letter} found at word index: {word.index(letter)}")
print(f'Letters found in word: {letter_set}')
print(f'Word set = {word_set}')
else:
print(f'Letter not found in word: {word}')
print(letter_set)
print("".join(map(str, letter_set)))
When it find duplicates in word, it removes the letter who is a duplicate from word_set but not from word. So when it finds a word like "letter" it will insert "e" always at index[1]. So it will print like "leettr". I found out that sometimes it mess up with the index even if there are no duplicates, usually on longer words, but couldn't really figure out why.
I was thinking to make it so letter_set have a i number of "_" depending on the word by default, and than replacing it using word_set.
Any advice on how to return letter always to the right index?
You can refactor the code a little bit. For example you can make a list hidden_word that will contain the same amount of # as letters in word. User will be guessing the letter and you will reveal the letter in hidden word untill there isn't anything left to reveal. For example:
def hangman_game():
word = "letter" # <-- chose a random word here instead of hardcoding it
hidden_word = list("#" * len(word))
while "#" in hidden_word:
print("STATUS")
print("------")
print(word)
print(hidden_word)
print("------")
letter = input("Guess a letter: ")
for idx, (w, h) in enumerate(zip(word, hidden_word)):
if w == letter and h == "#":
hidden_word[idx] = letter
print("Letter found!")
break
else:
print("Letter not found!")
hangman_game()
Prints:
STATUS
------
letter
['#', '#', '#', '#', '#', '#']
------
Guess a letter: e
Letter found!
STATUS
------
letter
['#', 'e', '#', '#', '#', '#']
------
Guess a letter: e
Letter found!
STATUS
------
letter
['#', 'e', '#', '#', 'e', '#']
------
Guess a letter: t
Letter found!
STATUS
------
letter
['#', 'e', 't', '#', 'e', '#']
------
Guess a letter: t
Letter found!
STATUS
------
letter
['#', 'e', 't', 't', 'e', '#']
------
Guess a letter: r
Letter found!
STATUS
------
letter
['#', 'e', 't', 't', 'e', 'r']
------
Guess a letter: x
Letter not found!
STATUS
------
letter
['#', 'e', 't', 't', 'e', 'r']
------
Guess a letter: l
Letter found!
I copy my code here in case someone will need something similar in the future. `
`
def hangman_game():
new_game = input("Press enter for new game")
word = random.choice(words)
print(f'Random word = {word} (testing)')
letter_set = list("_" * len(word))
lives = 3
while "_" in letter_set:
letter = input("Guess a letter: ").upper()
letter_count = word.count(letter)
if letter.isnumeric() or len(letter) > 1:
print("Insert valid character: a-z")
for index, (find_word, hidden) in enumerate(zip(word, letter_set)): # create new list with "_"*len(word)
if find_word == letter.lower() and hidden == "_": # check if letter is found in word, and if it is already revealed
letter_set[index] = letter # change "_" at the found indexes with letter
print(f'Letter found!')
if len(letter) > 1:
lives += 1
print(f"One letter at the time! ")
if letter.lower() not in word and letter.isnumeric() == False:
lives -= 1
print(f"Letter not found! Lives = {lives}")
if lives == 0:
print(f"YOU LOST! \n")
hangman_game()
if letter_count >= 1:
letter_set[index] = letter.upper()
print(f'Your word is: {" ".join(map(str, letter_set))}')
print("YOU WON \n")
hangman_game()
hangman_game() #wrong copied indentation
I've written a hangman program in python. The program is finished, but I have a problem with my main function. If I set a win or loss, it no longer execute my print statements from before. This means that if I have to guess a word, for example, it doesn't fill in the last letter in the placeholder, it just breaks out the loop without filling in the last letter. The same goes with my hangman. If I don't have any more attempts left, it won't finish drawing my hangman (just leave out the last part). Who knows why that is? Please help
Here is my code:
##### HANGMAN IN PYTHON #####
count_attempts = 0
guess_word = []
def guidance():
print('Welcome to Hangman in Python!')
print('''The point here is to guess a word by trying out letter combinations and
defining them with ENTER.''')
print('''For each word, you have 10 tries! If you can not solve the word,
the game is over.''')
print('You have 9 attempts to guess the word.')
print('Have fun!')
print('')
def user_word():
userinput = str(input("Type in the word you want to be guessed: "))
for character in userinput:
if character.isdigit():
print('There is a number in your word!')
userinput = str(input('Please try again: '))
return userinput.upper()
def change(userinput):
global guess_word
list_WordToBeGuessed = list(userinput)
for characters in list_WordToBeGuessed:
guess_word.append(' _')
def play_game(userinput):
global count_attempts
length_word = len(userinput)
user_guessed = []
print('Word to guess: ', *guess_word)
print("")
list_WordToBeGuessed = list(userinput)
guess = str(input('Guess a letter: ')).upper()
for number in guess:
if number.isdigit():
guess = str(input('Input not valid. Guess a letter: ')).upper()
if guess in user_guessed:
print('You have already given this letter. ')
elif guess in list_WordToBeGuessed:
user_guessed.append(guess)
print("You've guessed a letter correctly!")
for i in range(0, length_word):
if list_WordToBeGuessed[i] == guess:
guess_word[i] = guess
else:
count_attempts += 1
user_guessed.append(guess)
print('Sry your given letter is not in the word!')
print("You have failed", count_attempts, "of 5 attempts")
def draw_hangman(count_attempts):
print('-------' )
print(' | ' + ('|' if count_attempts > 0 else ''))
print(' | ' + ('O' if count_attempts > 1 else ''))
print(' | ' + ('/ \\' if count_attempts > 2 else ''))
print(' | ' + ('|' if count_attempts > 3 else ''))
print('--- ' + ('/ \\' if count_attempts > 4 else ''))
print("")
def main():
guidance()
userinput = user_word()
change(userinput)
while True:
draw_hangman(count_attempts)
play_game(userinput)
if count_attempts >= 5:
print("You haven't any attempts left. Bad luck")
break
elif ' _' not in guess_word:
print("")
print('You won, congratulation!')
break
main()
you are breaking out of a loop before it can draw the hangman and word.
in the endgame conditions, you can simply call draw_hangman(count_atttempts) before each print statement and change(userinput) as well.
Edit:
You will have to redraw the word as well. Since this is built into your play_game() function it is difficult, but you can use
for i in guess_word:
guess = guess + i + " "
print(guess)
before the print statements along with the draw_hangman(count_attempts) change you made before. Please note you will need to create a new variable called guess in your main() function prior to adding this code.
Since you have a "break" in your endgame condition, the loop stops and last "draw_hangman(count_attempts)" is not called. You can simply add "draw_hangman(count_attempts)" before "print("You haven't any attempts left. Bad luck")"
I am trying to create a Lingo game in Python where the user has 2 minutes to guess as many correct 5 letter words as possible. I use the random class and a text file to generate a random 5 letter word. However, after the user correctly guesses the word, I do not know how to generate a new 5 letter word. I am thinking I generate it inside the while loop for the timer, but I am not sure. I am still learning about python and this is my first time writing a "game" program. Any ideas or suggestions?
import random
from collections import Counter
import time
file = "words.txt" #File with 5 letter words
f = open(file, 'r')
lines = f.readlines()
randomword = random.choice(lines) #generate random 5 letter word from file
numletters = Counter(randomword)
word = [randomword[0], '_', '_', '_', '_']#part of word that is being shown to user
score = 0 #user score
print(randomword[0])
#print(randomword)
timer = 120 #amount of time game runs for
start_time = time.time() #remember when game started
while(time.time() - start_time < timer): #2 minutes is given to guess as many 5 letter words as possible
for i in range(1,6): #take 5 guesses at what random word is
guess = input("Guess the word: ")
for j in range(1,5): #check to see if other 4 letters of random word match the letters in the user guess word
numguess = Counter(guess)
if(guess[j] == randomword[j] and word[j] == '_'): #replace empty character with letter of random word if correctly guessed
word[j] = randomword[j]
elif(guess[j] in randomword and word[j] == '_'): #replace empty character with uppercase letter of guessed letter if that letter is in the randomword
word[j] = guess[j].upper()
elif(guess[j] in randomword and numguess[guess[j]] > numletters[guess[j]] and word[j] == '_'): #guessed letter gets replaced with '_' if max number of that letter is already in word
word[j] = '_'
elif(guess[j] == randomword[j] and word[j] != '_'): #replace uppercase letter with correctly guessed letter in word
word[j] = randomword[j]
elif(guess[j] == randomword[j] and guess[j].upper() in word): #upper case letter is guessed in correct spot, but no other letters are correcty guessed
word[word.index(word[j].upper())] = '_'
else: #no correct letters are guessed
word[j] = '_'
answer = word[0] + ' ' + word[1] + ' ' + word[2] + ' ' + word[3] + ' ' + word[4]
print(answer)
if(answer == randomword[0] + ' ' + randomword[1] + ' ' + randomword[2] + ' ' + randomword[3] + ' ' + randomword[4]):
print("You are correct!")
score += 100 #user scores 100 points for each correctly guessed word
break
if(answer != randomword[0] + ' ' + randomword[1] + ' ' + randomword[2] + ' ' + randomword[3] + ' ' + randomword[4]):
print("You are incorrect! You get 0 points for this word")
print("The correct word is: " + randomword.strip())
print("Your final score is " + str(score)) #print final score
enter this code into python. it uses an if statement to re-create the same variable with random.randint
import random
condition = True #saying the condition is true
randomthing = random.randint(1,10) # selecting a random number
print(randomthing, "is the first digit") #printing out the first randomly generated digit
if condition == True:
randomthing = random.randint(1,10)# regenerating the number
print(randomthing, "is the second number. if it is the same re run it") # printing out the second generated number
let me know if i can do more help
I'm working in Python 3.x and am fairly new, so I hope what I am asking makes sense. I am supposed to be focusing on for loops and strings for this word-guessing game.
Here's the (jumbled/lengthy/cluttered) code I have so far:
import sys
import random
def Main():
PlayAgain = "y"
print("COP 1000 Project 4 - Courtney Kasonic - Guess the Word Game")
print("I'm thinking of a word; can you guess what it is?")
while PlayAgain == "y":
Words = "apple alphabet boomarang cat catharsis define decide elephant fish goat horizon igloo jackelope ketchup loop limousine monkey night octopus potato quick rebel separate test underway violin world yellow zebra".split()
SecretWord = random.choice(Words)
MissedLetters = ""
CorrectLetters = ""
ChosenWord = GetWord(Words)
Guess = FiveLetters(CorrectLetters+MissedLetters)
for Guess in ChosenWord:
CorrectLetters = CorrectLetters + Guess
ShowWord(CorrectLetters, ChosenWord)
for i in ChosenWord:
CLetters = ""
if Guess in ChosenWord:
Blanks = "_" * len(SecretWord)
for i in range(len(SecretWord)):
if SecretWord[i] in CLetters:
Blanks = Blanks[i] + SecretWord[i]
print(Blanks)
print(CLetters)
def GetWord(List):
SecretWord = random.choice(List)
return(SecretWord)
**def FiveLetters(LettersGuessed):
a = 2
if a > 1:
print("Enter five letters to check: ",end="")
Guess = input()
if len(Guess) != 5:
print("Please enter five letters.")
elif Guess in LettersGuessed:
print("You already guessed that letter.")
elif Guess not in "abcdefghijklmnopqrstuvwxyz":
print("Please enter a letter.")
else:
return(Guess)**
def ShowWord(CLetters, SecretWord):
print("\nHere is the word showing the letters that you guessed:\n")
CLetters = ""
Blanks = "_" * len(SecretWord)
for i in range(len(SecretWord)):
if SecretWord[i] in CLetters:
Blanks = Blanks[i] + SecretWord[i]
print(Blanks)
print(CLetters)
return(Blanks, SecretWord, CLetters)
def CheckLetters(Letters):
Letters = "a b c d e f g h i j k l m n o p q r s t u v w x y z".split()
for Letters in Word:
print(Letters)
return(Letters)
Main()
The bolded area is where I am having problems. Only five letters can be entered to "check" to see if they are in the secret word. It will only accept input like "abcde". It will not accept input like "aaaaa" or "muihi" i.e. it won't accept guesses that are not in order or have more than one of the same letter.
I am also having trouble with the underscores. Not sure if the code I have for it up there is correct or not. The letters that are guessed correctly will not replace the appropriate underscore.
Ex: Secret Word = dog. If I guess the letters "mopfe" (though I can't because of issue above) then it will print out "_ _ _" without the "o".
You will inevitably ask more questions, assuming you don't want to fail. If you ask those questions on StackOverflow you should probably read the FAQ. Since you are using python you should probably also read the style guide (i.e. PEP 8), it was mentioned in the comments. This code, while incomplete, will get you started.
import sys
import random
def main():
play_again = "y"
print("COP 1000 Project 4 - Courtney Kasonic - Guess the Word Game")
print("I'm thinking of a word; can you guess what it is?")
words = "apple alphabet boomarang cat catharsis define decide elephant fish goat horizon igloo jackelope ketchup loop limousine monkey night octopus potato quick rebel separate test underway violin world yellow zebra".split()
secret_word = random.choice(words)
correct_letters = ""
while play_again == "y":
guess = five_letters(correct_letters)
for letter in guess:
if letter in secret_word:
correct_letters += letter
show_word(correct_letters, secret_word)
def five_letters(letters_guessed):
guess = raw_input("Enter five letters to check: ")
if len(guess) != 5:
print("Please enter five letters.")
elif guess in letters_guessed:
print("You already guessed that letter.")
elif guess not in "abcdefghijklmnopqrstuvwxyz":
print("Please enter a letter.")
else:
return guess
def show_word(correct_letters, secret_word):
print("\nHere is the word showing the letters that you guessed:\n")
word_display = ""
for index, letter in enumerate(secret_word):
if letter in correct_letters:
word_display += letter
else:
word_display += "_"
print word_display
if __name__ == "__main__":
main()