My code is:
import random
WORDS = ('python', 'football', 'facebook', 'photo') #list of words that will be riddled
word = random.choice(WORDS)
correct = word
jumble = ''
hint = 'hint'
score = 0
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):] #creating jumble of correct words
print('Welcome to the game "Anagrams"')
print('Here`s your anagram:', jumble) #Welcoming and giving a jumble to a player
guess = input('\nTry to guess the original word: ')
if guess == correct:
score += 5
print('You won! Congratulations!') #end of game in case of right answer
if guess == hint: #situation if player asks a hint
if correct == WORDS[0]:
print('snake')
elif correct == WORDS[1]:
print('sport game')
elif correct == WORDS[2]:
print('social network')
elif correct == WORDS[3]:
print('picture of something')
score += 1
while guess != correct and guess != '': #situation if player is not correct
print('Sorry, you`re wrong :(')
guess = input('Try to guess the original word: ')
print('Thank you for participating in game.')
print('Your score is', score)
input('\nPress Enter to end')
When asking hint string :
'Sorry, you`re wrong :('
repeats.
It looks like:
Try to guess the original word: hint
sport game
Sorry, you`re wrong :(
How to make this string appear only in case of wrong guess?
change you last while to this:
while guess != correct and guess != '':
guess = input("Sorry, you`re wrong:( ")
In your code, when the player types hint the player gets a hint, but then the program tests the 'hint' string against the correct word. Of course, 'hint' isn't the correct answer, so your program tells them that it's wrong.
Just for fun, I've optimized your code a little, and improved the scoring logic. :)
Your letter-jumbling for loop is quite clever, but there's a more efficient way to do this, using the random.shuffle function. This function shuffles a list, in place. So we need to convert the chosen word into a list, shuffle it, and then join the list back into a string.
I've also replaced your hints logic. Rather than having to do a whole bunch of if tests to see which hint goes with the current word it's much simpler just to store each word and its associated hint as a tuple.
import random
#Words that will be riddled, and their hints
all_words = (
('python', 'snake'),
('football', 'sport game'),
('facebook', 'social network'),
('photo', 'picture of something'),
)
#Randomly choose a word
word, hint = random.choice(all_words)
#Jumble up the letters of word
jumble = list(word)
random.shuffle(jumble)
jumble = ''.join(jumble)
print('Welcome to the game "Anagrams"\n')
print('You may ask for a hint by typing hint at the prompt')
print('Wrong guesses cost 2 points, hints cost 1 point\n')
print("Here's your anagram:", jumble)
score = 0
while True:
guess = input('\nTry to guess the original word: ')
if guess == word:
score += 5
print('You won! Congratulations!')
break
if guess == 'hint':
#Deduct a point for asking for a hint
score -= 1
print(hint)
continue
#Deduct 2 points for a wrong word
score -= 2
print('Sorry, you`re wrong :(')
print('Thank you for participating in game.')
print('Your score is', score)
input('\nPress Enter to end')
Your special logic for a correct guess and for the special input "hint" is only run once on the very first guess. Your loop for incorrect values always runs after that. I think you want to move all the logic into the loop:
while True: # loop forever until a break statement is reached
guess = input('\nTry to guess the original word: ')
if guess == correct:
score += 5
print('You won! Congratulations!')
break # stop looping
if guess == hint: # special case, asking for a hint
if correct == WORDS[0]:
print('snake')
elif correct == WORDS[1]:
print('sport game')
elif correct == WORDS[2]:
print('social network')
elif correct == WORDS[3]:
print('picture of something')
score += 1
else: #situation if player is not correct, and not askng for a hint
print('Sorry, you`re wrong :(')
I've left out the situation where your code would exit the loop on an empty input. If you want that, you should add it explicitly as an extra case, with a break statement.
Lets try to fix some problems:
this
if guess == hint: #situation if player asks a hint
should probably be
elif guess == hint: #situation if player asks a hint
And also this seems wrong to me
while guess != correct and guess != '': #situation if player is not correct
print('Sorry, you`re wrong :(')
guess = input('Try to guess the original word: ')
should be probably changed into that (indentation is important):
guess = input('Try to guess the original word: ')
if guess != correct and guess != '': #situation if player is not correct
print('Sorry, you`re wrong :(')
I have not tried this corrections in a complete program.
Related
I'm writing a word guessing game like, what I'm expecting is that results appear in uppercase when is on the right spot. Until now, I write the program and it completely works but, let me show you... This is how it goes:
print("Welcome to the word guessing game!")
print(" ")
secret_word = "heaven"
guess_count = 0
display = '_'*len(secret_word)
(len(secret_word)-1)
word = ["_"] * len(secret_word)
while True:
guess = input("What is your guess? ")
for i in range(len(secret_word)):
if guess == secret_word[i]:
word[i] = guess
if guess == secret_word:
print("")
print("You guessed it!")
break
else:
print("".join(word))
guess_count = guess_count+1
print(f"It took you {guess_count} guesses")
So, I'm not sure where to put the uppercase function.
Since the letters are not present at all in the secret word, it shows an "_".
The letters that are present in the secret word, but in a different spot should be shown as lowercase.
The Letters that are present in the secret word at that exact spot, shown in uppercase.
I tried to find the answer on YT and other sites without success. I just want to understand which functions using (.uppercase) I can use to make it.
Hope you can help me, guys. Thanks in advance!
I do not understand. In your code, it seems as though the guess is a single character, but you do not ask for the spot which is needed to determine if it must be uppercase or lowercase. I tried to answer your question based on wordle, so I guessed the player would have to enter a word.
You'd need something like:
for i in range(len(secret_word)):
if guess[i] = secret_word[i]:
word[i] = guess[i].upper()
elif guess[i] in secret_word:
word[i] = guess[i].lower
I'm trying to store the guesses so that I can make code for if you have already guessed that letter and also to make code for when they get all of the letters correct. I may be stuck on that part, too, since I don't know how to check if the letters correspond to the letters in the wordname list, especially when it isn't even ordered.
So, I am looking for some code that would store the guesses and also something that can check if all of the correct letters have been guessed. I am thinking it may have something to do with the enumerate() function, but I am not sure since I have never used it before and have only just heard about it.
Also, for your information, the game is hangman if that helps.
wordname = word_choosing()
wordnamelength = len(wordname)
wordnamelist = list(wordname)
def letter_guess1():
sleep(1)
tries = 5
print(f"{oppositeplayer}, the word is {wordnamelength} letters long")
while tries > 0:
guess1 = input("Make your guess: ")
if guess1 in wordnamelist:
print("Congrats, that is correct")
letternum = wordnamelist.index(guess1)
letternum += 1
print(f"This letter is number {letternum}")
elif guess1 not in wordnamelist:
tries -= 1
print(f"You have {tries} left")
if guess1 == "quit".lower():
exit()
return tries
tries = letter_guess1()
I think set is very suitable in this situation. Keep the letters of the word being guessed as a set and add the guess to another set. Then, you can check if the word was guessed correctly by using the intersection of both sets.
Something like that:
wordname = word_choosing()
wordnamelength = len(wordname)
wordnamelist = list(wordname)
def letter_guess1():
sleep(1)
tries = 5
print(f"{oppositeplayer}, the word is {wordnamelength} letters long")
word_set = set(wordname)
guessed_letters = set()
while tries > 0:
guess = input("Make your guess: ")
if guess in guessed_letters:
print("You already guessed this letter")
continue
guessed_letters.add(guess)
if guess in word_set:
print("Congrats, that is correct")
letternum = wordnamelist.index(guess)
letternum += 1
print(f"This letter is number {letternum}")
elif guess not in word_set:
tries -= 1
print(f"You have {tries} left")
if word_set.intersection(guessed_letters) == word_set:
print("You have won!")
if guess == "quit".lower():
exit()
return tries
tries = letter_guess1()
When I run the code, the 3rd guess gives me an output of High/Low. On the 3rd try, I don't need it to tell me if I'm high or low. How can I fix the problem with out using "while" loops or "range." We haven't covered these two keywords yet.
python
print("You have 3 tries to guess the letter.")
letter = "F"
tries = 0
# [ ] create letter_guess() function, call the function to test
def letter_guess(tries):
if not tries == 3:
guess = input("Guess a letter: ")
tries = tries + 1
check = check_guess (guess,letter)
if check == True:
print('Winner')
else:
letter_guess(tries)
else:
print ("GAME OVER!")
pass
# def check_guess(guess,letter)
def check_guess (guess, letter):
#if else to see if correct letter
if letter == guess.upper():
print ("correct")
return True
elif letter < guess.upper():
print ("You are wrong, guess lower.")
return False
elif letter > guess.upper():
print ("You are wrong, guess higher.")
return False
else:
print("Invalid response!")
return False
letter_guess(tries)
One way to get result similar to a loop is to use recursion. But if you have not done loops yet, you almost certainly have not done recursion. So just use straightforward code.
The tricky part is that you need to ask for a guess, input the guess, and check for a correct guess three times, once for each guess. However, you need to give feedback on whether the guess is high or low only two times. Therefore, you cannot put those actions in the same function. Just split them into separate functions, and handle each guess in your main routine. No need to count guesses--the position in the main routine makes that clear.
"""Guess-a-letter game."""
def get_guess(letter):
"""Get a guess an note if it is correct. If correct, return None.
Otherwise, return the guess."""
guess = input("Guess a letter: ").upper()
if guess == letter:
print("Correct: You win!")
return None
else:
return guess
def give_feedback(guess, letter):
"""Give feedback on a wrong guess."""
if letter < guess:
print("You are wrong, guess lower.")
else:
print("You are wrong, guess higher.")
def letter_guess():
# Store the letter for the user to guess.
letter = "F"
# Introduce the game.
print("You have 3 tries to guess the letter.")
# Handle the first guess.
guess = get_guess(letter)
if guess is None:
return # Success!
give_feedback(guess, letter)
# Handle the second guess.
guess = get_guess(letter)
if guess is None:
return # Success!
give_feedback(guess, letter)
# Handle the third and last guess.
guess = get_guess(letter)
if guess is None:
return # Success!
print("You were wrong three times. GAME OVER!")
letter_guess()
So I have a quick question about the below code. In the program it will display a series of dashes to match the random word selected. When the player guesses, the program goes through a loop that checks the guess. My question is, and what I'm really confused over, is how does the program know to replace the exact dash needed to display an accurate and partially revealed word? and what is new += so_far[i] doing? overall, that section really confuses me and I would greatly appreciate some clarification. Thanks!
MAX_WRONG = len(HANGMAN) - 1
# creating list of random words
WORDS = ("TECHNOLOGY", "PYTHON", "SCRIPT", "PROCESSOR", "RANDOM", "COMPUTING")
# initialize variables
word = random.choice(WORDS)
so_far = "-" * len(word) # one dash for every letter in the word to be guessed
wrong = 0 # number of wrong guesses made
used = [] # letters already guessed
# creating the main loop
print("Welcome to Hangman. Good luck!")
while wrong < MAX_WRONG and so_far != word:
print(HANGMAN[wrong])
print("\nYou've used the following letters:\n", used)
print("\nSo far, the word is:\n", so_far)
# getting the player's guess
guess = input("\n\nEnter your guess: ")
guess = guess.upper()
while guess in used:
print("You've already guessed the letter", guess)
guess = input("\nEnter your guess: ")
guess = guess.upper()
used.append(guess)
# checking the guess
if guess in word:
print("\nYes!", guess, "is in the word!")
# create a new so_far to include guess
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new
else:
print("\nSorry,", guess, "isn't in the word.")
wrong += 1
# ending the game
if wrong == MAX_WRONG:
print(HANGMAN[wrong])
print("\nYou lose!")
else:
print("\nYou guessed it!")
print("The word was:", word)
ext()
You are looking out for this section in the code which does that
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new
Say if you guess the word 'S' and say if the word to be guessed is 'Super'
Initial state
Sofar : -----
During the iteration process a variable 'new' is assigned the value for each word match. if not matched take that value from so_far[i]
In our case
Length of word = len('Super') = 5
Iter 1: will only go to ig loop since 'S' occurs only once.
This means all other iterations go to else condition and since all so_far[i] has '-' as values.
So after the first loop of iteration your values look like this
new: S----
At the end of loop reassign new to so_far. This means now 'so_far' variable has changed from '-----' to 'S----'.
I suggest you to use a pdb to debug above the for loop and get the details when you get to such doubts in future.
Hope this helps.
I am making a hang man game. I am trying to cycle through a word and have all the repeats in the letter be appended to my list. For example the word "hello": if the user types in "l" I want all the l's to be added to my list. Right now it is only finding one "l" and if the user types an "l" again it finds the second "l".
I also want the user not to be able to type in another letter if they previously already typed it in.
I have two lists one for right guesses and wrong guesses that store every guess. For example if a user types in "h" in "hello"
"h" is a right guess so it appends to [h] but if they type in "h" again it adds it to the list so it says ["h","h"]. The wrong box works the same way but for words that are wrong. If they type in "z" for the word "hello" it says ["z"] in the wrong box.
Here is my code:
import random
user_input = ""
turns = 5
print("Welcome to Advanced Hang Man!")
print("Use your brain to unscramble the word without seeing its order!")
words = ["hello","goolge","czar","gnat","relationship","victor","patric","gir","foo","cheese"]
# Picks a random word from the list and prints the length of it
random_word = (random.choice(words))
random_word_legnth = (len(random_word))
print("Hint! The length of the word is",random_word_legnth)
hold_random_word = [i for i in random_word]
while turns != 0 and set(right_guess) != set(hold_random_word):
user_input = input("Please type your guess one letter at a time:")
right_guess = []
wrong_guess = []
#Calculating every input
if len(user_input) == 1 and user_input.isalpha():
for i in user_input:
if i in hold_random_word:
right_guess.append(i)
else:
wrong_guess.append(i)
print("Correct guess", ''.join(right_guess))
print("Wrong guess", ''.join(wrong_guess))
I'm not sure what your direct question is, but thinking about a hangman game you want to take the users guess and parse the entire word or phrase they are guessing to see if their guess matches anywhere in the word. I made a hang man game below that will function as expected (minus any error handling) Let me know if any parts confuse you, and i can explain
import random
wordcomp = []
wordguess = []
#this is a word bank for all puzzles, they are randomly chosen
word_bank = ['guess this phrase', 'Lagrange', 'foo', 'another phrase to guess']
# This loop stores each letter in a list, and generates a blank list with correct spaces and blanks for user
rand_word = random.randrange(4)
for i in word_bank[rand_word]:
wordcomp.append(i)
if i == ' ':
wordguess.append(' ')
else:
wordguess.append('__')
print('I am thinking of a word,' , wordguess , ' it has ', len(wordguess), ' characters total, GOOD LUCK \n')
wordlist = wordcomp
count = 0
placeletter = 0
wrongguess = []
guesscount = 0
while wordlist != wordguess:
guess = input('please input a lower case letter within the english alphabet!') ##Check that input is one character, and lower case
guesscount = guesscount + 1
# This for loop scans through to see if the letter that was guessed is in the actual puzzle, and places in the correct spot!!
for t in wordcomp:
if t == guess:
wordguess[placeletter] = guess
placeletter = placeletter + 1
# This check tells them they already guessed that letter... then makes fun of them
if guess in wordguess:
pass
else:
wrongguess.append(guess)
while wrongguess.count(guess) > 1:
wrongguess.remove(guess)
print('you guessed the letter ' , guess , ' already, are you person that suffers short term memory loss...')
print('The word I am thinking of: ' , wordguess)
print('The letters you have already guess are: ', wrongguess)
placeletter = 0
# This tells them they finished the puzzle and the number of guesses it took, if its over 26, it calls them stupid for obvious reasons...
if guesscount >= 26:
print('you are an idiot if it took you more than 26 guesses..... now take a minute, sit silently, and think about why you are idiot if it took over 26 guesses... for hangman... where you guess the letters of the alphabet... YOU GET IT, stupid')
elif guesscount < 26:
print('Congrats you solved the puzzle, w00t!!')
if len(user_input) == 1 and user_input.isalpha():
for i in user_input:
if i in hold_random_word and i not in right_guess:
right_guess.append(i)
elif i not in hold_random_word or i not in wrong_guess:
wrong_guess.append(i)
elif i in hold_random_word:
# here user types something that is already typed and is a right_guess
pass
else:
# Types something wrong, that was already typed
pass
print("Correct guess", ''.join(right_guess))
print("Wrong guess", ''.join(wrong_guess))
It is not clear how you are taking inputs, but I think this code can be further optimized. Give it a shot.
Edit 1:
import random
user_input = ""
turns = 5
print("Welcome to Advanced Hang Man!")
print("Use your brain to unscramble the word without seeing its order!")
words = ["hello","goolge","czar","gnat","relationship","victor","patric","gir","foo","cheese"]
random_word = (random.choice(words))
random_word_legnth = (len(random_word))
print("Hint! The length of the word is",random_word_legnth)
hold_random_word = [i for i in random_word]
# This condition can lead to issues in situations like this - abc and aabbcc [sorry couldn't quickly come up with a good actual example :)]
while turns != 0 and set(right_guess) != set(hold_random_word):
user_input = input("Please type your guess one letter at a time:").strip()
right_guess = []
wrong_guess = []
#Calculating every input
if len(user_input) == 1 and user_input.isalpha():
# user_input is 1 letter so for i in user_input will execute only once
# Use the if structure as defined above
if user_input in hold_random_word:
right_guess.append(i)
else:
# this is missing
turns -= 1
wrong_guess.append(i)
print("Correct guess", ''.join(right_guess))
print("Wrong guess", ''.join(wrong_guess))
elif len(user_input) > 1:
print("Please type only one letter at a time")
elif not user_input.isalpha():
print("Please enter only valid English letters")
else:
# handle this however you want :)
pass