Generating a New Random Word After a Condition is Met - python

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

Related

Hangman written in python doesnt recognise correct letters guessed :/

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, '!!')

How do I add a specific letter to a variable and then make it a string

I am trying to make a hangman game and I am not fully sure on how to add a specific letter to a variable.
For example, adding a letter that someone chose through the pythons' input prompt to a variable. Here is the code I am working on:
import random
import time
word_list = ['that', 'poop', 'situation', 'coding', 'python', 'turtle', 'random', 'passive', 'neutral', 'factor', 'time']
word_chosen = random.choice(word_list)
your_name = input("What is your name?")
time.sleep(1)
print("Hello " + your_name + ", lets play some hangman!, The amount of letters in the word is below!")
guesses = 7
time.sleep(1)
hidden_word = ""
for i in word_chosen:
hidden_word += "-"
while True:
n = 1
time.sleep(1)
print("Your word is: " + hidden_word)
print("___________")
print("|")
print("|")
print("|")
print("|")
print("|")
print("|")
print("|")
characters = (word_chosen)
time.sleep(1)
letters_correct = ""
characters_guessed = input("Type in the letters you think are in this word!")
for i in characters:
hidden_word == characters_guessed
if characters_guessed == characters:
print(hidden_word + characters)
else:
int(guesses) - int(n)
print("Nope, sorry.")
I have modified your code #Noob and made it work. Instead of using strings I have made lists of chosen_word ,characters and characters_guessed .In this code you can even enter more than one word at a time. It automatically fillsup the repitive words and will tell the user if he or she has won or lost the game.
import random
import time
word_list = ['that', 'poop', 'situation', 'coding', 'python', 'turtle', 'random', 'passive', 'neutral', 'factor', 'time']
word_chosen = random.choice(word_list)
your_name = input("What is your name?")
time.sleep(1)
print("Hello " + your_name + ", lets play some hangman!, The amount of letters in the word is below!")
guesses = 7
time.sleep(1)
hidden_word = [" - " for i in range(len(word_chosen))]
while guesses>0:
time.sleep(1)
print("Your word is: "+ "".join(hidden_word))
print("___________")
for i in range(7):
print("|")
characters = list(word_chosen)
time.sleep(1)
letters_correct = ""
characters_guessed = input("Type in the letters you think are in this word!").split()
for j in characters_guessed:
if j not in characters:
guesses-=1
print(f"Wrong guess, {j} is not in the word")
else:
for i in characters:
if i==j:
find_position=0
for k in range(characters.count(i)):
hidden_word[characters.index(i,find_position)]=j
find_position+=characters.index(i,find_position)+1
if " - " not in hidden_word:
print("Congratulations, you have won the game.The word was {chosen_word}")
break
elif guesses==0:
print("Opps!! out of guesses. You have lost the game.")
Python strings do not support item assignment, so I would use an array of strings and then use "".join(hidden_word) when you want to print the word out. You can loop over the chosen word and then when that letter matches the input letter, fill in that position in your hidden_word array.
Here's how I would adapt your code to get the game to run:
import random
import time
word_list = ['that', 'poop', 'situation', 'coding', 'python', 'turtle', 'random', 'passive', 'neutral', 'factor', 'time']
word_chosen = random.choice(word_list)
your_name = input("What is your name?")
time.sleep(1)
print("Hello " + your_name + ", lets play some hangman!, The amount of letters in the word is below!")
guesses = 7
won = False
hidden_word = ["|"] * len(word_chosen)
while guesses > 0:
print("Your word is: " + "".join(hidden_word))
print("___________")
for _ in range(5):
print("|")
guessed = input("Type in the letters you think are in this word!")
for c in guessed:
for i in range(0, len(word_chosen)):
if word_chosen[i] == c:
hidden_word[i] = c
if "|" not in hidden_word:
won = True
break
guesses -= 1
if won:
print(f'Word found: {"".join(hidden_word)}')
else:
print(f'Nope, sorry - word was {word_chosen}')
So to answer your original question, I assign the string that is input to guessed. I then loop over each letter in guessed, and check it against each position in chosen_word. If the letter at that position is a match, I change the placeholder | to the chosen letter. Once no placeholders are left, the game is won.
If you wanted to limit the user to only inputting one character at a time, I would take a look at this thread for example on how to adapt input() to handle this.

Python hangman replacing

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.

Python: Hangman game problems

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.

What's wrong with this string equality comparison? (Python)

My code is for a simple hangman type game where the user is supposed to guess the a random word from a list letter by letter or guess the whole word. The comparison for when the user guesses the whole word doesn't execute. I hardcoded one of the possible random words into my code below as an example:
guess = "----"
letterCount = 8
letter = ""
x = 0
while letterCount > 0:
temp1 = "word"
letter = input("Guess a letter in the word or attempt to guess the whole word: ")
if (len(letter) > 1):
print ("this is the test word: word, this is letter:" + letter)
if letter == "word":
print ("You win!!!")
letterCount = 0
else:
x = temp1.find(letter)
while x != -1:
x = temp1.find(letter)
temp1 = temp1[:(x + 1)].replace(letter, '0') + temp1[(x + 1):]
guess = guess[:(x + 1)].replace('-', letter) + guess[(x + 1):]
print (("Your guess is now: " + guess))
letterCount = letterCount - 1
x = 0
If I guess the "word", it tells me that I guess word, it points out that I guess the word I should, but the if statement that should tell me I won never executes. Am I comparing these strings properly or is the problem something else?
>>> while letterCount > 0:
... temp1 = "word"
... letter = input("Guess a letter in the word or attempt to guess the whole word: ")
... if (len(letter) > 1):
... print ("this is the test word: word, this is letter:" + letter)
... if letter == "word":
... print ("You win!!!")
... letterCount = 0
... else:
... x = temp1.find(letter)
... while x != -1:
... x = temp1.find(letter)
... temp1 = temp1[:(x + 1)].replace(letter, '0') + temp1[(x + 1):]
... guess = guess[:(x + 1)].replace('-', letter) + guess[(x + 1):]
... print (("Your guess is now: " + guess))
... letterCount = letterCount - 1
... x = 0
...
Guess a letter in the word or attempt to guess the whole word: "word"
this is the test word: word, this is letter:word
You win!!!
>>>
You need to cast your input as a String for the String comparison test to work.

Categories

Resources