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, '!!')
Related
I tried to make a simple version of the hangman game. But when I run it, I can't add the letters in order.
The 'count' variable may be the problem. Any can help me ?
Thank you! :)
word = 'houses'# <--just for testing
word = list(word)
print(word)
p2 = ' __ ' * len(word)
p2 = p2.split()
print(p2)
lives = len(word)
print("lives: ", lives)
count = 0
while word != p2:
letter = input("enter a letter: ")
if letter in word:
for x in word:
if x == letter:
p2[count] = letter
#print("cont: ", count)
else:
continue
count+=1
print("p2: ",p2)
else:
lives -= 1
print("You have {} lives left".format(lives))
if lives == 0:
break
Well i wasn't able to understand your point of view about the Hangman but following code is the optimized form of your code and also the my playing interpretation of this game e.g. how this should be played
word = 'houses'# <--just for testing
word = list(word)
print(word)
p2 = ' __ ' * len(word)
p2 = p2.split()
print(p2)
lives = len(word)
print("lives: ", lives)
while word != p2:
letter = input("enter a letter: ")
if letter in word and letter not in p2:
locations = [i for i, x in enumerate(word) if x == letter ]
for location in locations:
p2[location] = letter
print("p2: ",p2)
else:
lives -= 1
print("You have {} lives left".format(lives))
if lives == 0:
break
print('You LOST' if lives == 0 else 'You WON')
Screenshot of the Both Executions of the game (Win & Loss)
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
For the most part it seems to be working, but not how I'm trying to get it to work. When I run it I am allowed unlimited tries to guess every single letter in the word until I spell out the word.
But that's not what I am going for, I'm trying to give the users 5 guesses with single letters if the letter is in the word then it will tell them "Yes", there is a(n) (users guess) in my word, but if the letter is not in my word then it will tell them "No", there is not a(n) (users guess) in my word.
After 5 attempt's at guessing different letters I want them to have to guess the full word but I can't figure out how.
This is what I have now:
import random
def get_word():
words = ['cat', 'dog', 'man', 'fox', 'jar']
return random.choice(words).upper()
def check(word,guesses,guess):
status = ''
matches = 0
for letter in word:
if letter in guesses:
status += letter
else:
status += '*'
if letter == guess:
matches += 1
count = 0
limit = 5
if matches > 1:
print ('Yes! there is a(n)',guess,' in my word.')
guesses += guess
elif matches ==1:
print ('Yes! there is a(n)',guess,' in my word.')
guesses += guess
while count > limit:
input('What do you think my word is')
else:
print('No, there is not a(n)',guess,' in my word.')
guesses += guess
while count > limit:
input('What do you think my word is')
return status
def main():
word = get_word()
guesses = ""
guessed = False
print ('I am thinking of a 3 letter word with no repeating letters. You get five guesses of the letters in my word and then you have to guess the word.')
while not guessed:
text = 'Guess a letter in my word:'
guess = input(text)
guess = guess.upper()
count = 0
limit = 5
if guess in guesses:
print ('You already guessed "' + guess + '"')
elif len(guess) == len(word):
guesses += guess
if guess == word:
guessed = True
else:
print('No, there is not a(n) "' + guess + '"')
elif len(guess) == 1:
guesses += guess
result = check(word,guesses,guess)
if result == word:
guessed = True
else:
print (result)
else:
print ('Invalid entry.')
print ('Yes! you correctly guessed')
main()
For starters while not guessed: will continue until guessed is true -> the word was guessed. Next if you want there to be 5 guesses then an answer guess you want to do for i in range(0, 5): then run your guess logic replacing
if result == word:
guessed = True
with
if result == word:
guessed = true
break
to break out of the loop on a correct guess. Then to allow a guess afterwards, outside of the loop, check if already guessed and allow a guess if not.
Also as a side note you should check that they enter one character with something like
guess = input(text)
while len(guess) != 1:
guess = input(text)
I tried to mostly keep your original code and trail of thought. The main changes I made was getting rid of the check-function as I felt it didn't do anything too useful. I also changed the guessed-variable into a list, and utilized it's properties for your evaluations.
import random
def get_word():
words = ['cat', 'dog', 'man', 'fox', 'jar']
return random.choice(words).upper()
def main():
word = get_word()
guesses = []
guessed = False
print('I am thinking of a 3 letter word with no repeating letters.'
' You get five guesses of the letters in my word and then you have'
' to guess the word.\n')
while not guessed and len(guesses)<5:
text = 'Guess a letter in my word:\n'
guess = input(text)
guess = guess.upper()
if guess in guesses:
print ('You already guessed "', guess, '"\n')
elif len(guess) > 1:
guesses.append(guess)
if guess == word:
guessed = True
else:
print('No, ', guess, 'is not the word!\n')
elif len(guess) == 1:
guesses.append(guess)
if guess in word:
print('Yes there is a(n) ', guess, 'in the word!\n')
else:
print('No, there is not a(n)', guess, 'in the word!\n')
else:
print ('Invalid entry.\n')
if guessed:
print ('You correctly guessed the word!\n')
else:
correct_guesses = [guess for guess in guesses if guess in word]
print('Last chance, what is the full word? (HINT: You have'
'correctly guessed ', str(correct_guesses), ')"')
fword = input()
if fword.upper() == word:
print('You correctly guessed the word!\n')
else: print('Tough luck! You are out of chances! The correct'
'word was ', word, '\n')
main()
playing = True
while playing:
print('Would you like to play again?')
answ = input()
if answ.upper() == 'YES':
main()
else:
print('Thank you for playing.')
playing = False
So I'm writing a hangman program and I'm having trouble getting the current guesses to display as underscores with the correct letters guessed replacing an underscore. I can get the function to work once (thats the insert_letter function) and I know its just replacing every time it goes through the loop, but I can't return the new current without quitting the loop so if someone could offer another way to get the guesses to keep updating that would be great!
def insert_letter(letter, current, word):
current = "_" * len(word)
for i in range (len(word)):
if letter in word[i]:
current = current[:i] + letter + current[i+1:]
return current
def play_hangman(filename, incorrect):
words = read_words(filename)
secret_word = random.choice(words)
num_guess = 0
letters_guessed = set()
letter = input("Please enter a letter: ")
while num_guess < incorrect:
letter = input()
if letter in secret_word:
current = insert_letter(letter, current, secret_word)
print(current)
else:
num_guess += 1
current = "_" * len(secret_word)
print(current)
letters_guessed.add(letter)
You didn't show the code for your insert_letter() function so I wrote an alternative -- display_remaining(). Give this a try:
import random, sys
def play_hangman(filename, incorrect):
words = read_words(filename)
secret_word = random.choice(words)
num_guess = 0
letters_guessed = set()
while num_guess < incorrect:
letter = input("Please enter a letter: ")
letters_guessed.add(letter)
current = display_remaining(secret_word, letters_guessed)
print(current)
if not letter in secret_word:
print("Incorrect guess.")
num_guess += 1
if not '_' in current:
print("Congratulations! You've won!")
sys.exit(0)
print("Sorry. You've run out of guesses. Game over.")
def display_remaining(word, guessed):
replaced = word[:]
for letter in word:
if (not letter == '_') and letter not in guessed:
replaced = replaced.replace(letter, '_', 1)
return replaced
def read_words(filename):
with open(filename, 'rU') as f:
return [line.strip() for line in f]
if __name__ == '__main__':
play_hangman('words.txt', 6)
NOTE: With this implementation, your words file shouldn't have any words containing the underscore character.
I am brand new to Python but a have a littel Matlab and C++ background. Please Help!!!!
I am having problems with my hangman code. If a word has multiple of the same letter in I cannot figure out how to get it to switch all of them. I have a couple tries with some of them commented out.
import random
import time
import sys
def pickWord():
words = [line.strip() for line in open('word_list.txt')]
word = random.choice(words)
word = word.lower()
return word
def checkLetter(word, input):
if input not in word:
in_letter = 0
else:
in_letter = 1
return in_letter
def check_input(input):
if input.isaplha() == False :
input = raw_input('Your input was not a letter, please enter a letter: ')
elif len(input) > 0:
input = raw_input('Your entry was longer than 1 letter, please enter one letter: ')
else:
input = input
return input
#main function
running = 'y'
print('Lets Play Hangman!\n\n ------------------------ \n\nGenerating a Random word \n\n')
while running == 'y':
word = pickWord()
letters = list(word)
time.sleep(3)
print ('The word has been chosen\n\n')
print '%s' % word
start = raw_input('Are you ready to start?(y/n)')
start = start.lower()
if start == 'n':
print('Well, too damn bad. Here We go!\n\n **************************\n\n')
elif start == 'y':
print('Awesome, lets begin!\n\n*********************************\n\n')
else:
print('You did not enter y or n, sorry you are not allowed to play!')
sys.exit()
i = 0
print ('The word has %d letters in it') % len(word)
input = raw_input('What is your first guess: ')
input = input.lower()
correct = ['_'] * len(word)
print ' '.join(correct)
while correct != letters and i <= 5:
'''if input in letters:
for input in letters:
location = letters.index(input)
correct[location] = input
print('You guessed the correct letter! Your input %s is in the word at the %d spot.') % (input, location)
print ' '.join(correct)
elif input not in letters:
print('You guessed wrong :(')
i = i + 1
guesses = 6 - i
print('You have %d guesses left.') % guesses
guesses = 0
else:
print('You did not enter a valid letter, please try again.')'''
'''for j in letters:
if j == input:
location = letters.index(j)
correct[location] = j
print '%s' % ' '.join(correct)
print '%d' % location
print '%s' % j
if j == input:
location = letters.index(j)
correct[location] = j
print('You guessed the correct letter! Your input %s is in the word at the %d spot.') % (input, location)
print ' '.join(correct)'''
if input not in letters:
i = i + 1
guesses = 6 - i
print("You guessed incorrectly. You have %d guesses left.") % guesses
input = raw_input('What is your next guess: ')
input = input.lower()
if correct == letters:
print('Congrats! You won the game!')
else:
print('You lost. :(')
running = raw_input('Do you want to play again? (y/n)').lower()
In your attempt, the loop is stopping when it finds the first match of input to letters.
the following code will work:
guess = raw_input('What is your first guess: ')
word = "wordword"
letters = list(word)
correct = ['_']* len(word)
for x, y in enumerate(word):
if guess == y:
correct[x] = y
Your mistakes
In your first attempt:
if input in letters:
for input in letters:
you are checking if input is in letters, which is fine, but if this returns True, inputs original value is lost, and is reassigned as you loop through the elements of letters.
eg
>>>input = "w"
>>>word = "word"
>>>if input in word:
... for input in word:
... print(input)
w
o
r
d
your second attempt
for j in letters:
if j == input:
location = letters.index(j)
is a lot closer to being successful, however location = letters.index(j) is always going to equal the index of the first match of j, and thus will not assign all matched values of input.