how to congratulate player with using hint and without using it differently - python

i would like to know how to tell the computer to print different input for player using hint
and for someone who doesn't used it to congratulate them
import random
words = dict(
python = "type of snake",
honda = "type of car",
spanish = "type of language",)
word = list(words)
var = random.choice(word)
score = 0
chance = 5
x = list(var)
random.shuffle(x)
jumble = "".join(x)
print("the jumble word is :", jumble,)
while True:
guess = input(" this is my guess :")
if guess == "hint":
print(words[var])
if guess == var:
print("well done you only used ", score,"to guessed it ")
break
else:
print("try again")
score +=1
if score == chance:
print("better luck next time")
break

What about adding a boolean, say hintUsed, that keeps track of whether or not the user used a hint:
hintUsed = False
while True:
guess = input(" this is my guess :")
if guess == "hint":
hintUsed = True # change hintUsed to True !!
print(words[var])
And then, to congratulate:
if guess == var:
if hintUsed:
#print a message
else:
#print another message
break

Related

Trying to link my user name input and menu to my game function in python hangman

I'm trying to link my ask_for_name() and menu() functions to my play() function but where
ever I place the function headings it doesn't seem to work or get called. The game starts up first and at the end of gameplay asks if you want to restart, yes or no, If you click no, it goes back to what I want at the beginning of my game, my user-input asking for name and the menu, press 1 to play the game and 2 for instructions. When I click 1 the game wont start and throws an error message, does anyone know what I'm missing here? I'm new to python and seem to keep going in circles with this problem, the code is mentioned below:
def ask_for_name():
while True:
name = input(YELLOW_COLOR + "Please Enter Your Name:\n")
if not name.isalpha():
print("Name must be letters only\n")
else:
print(f"Hello {name}, Welcome to Chris's Hangman and Good Luck!\n")
menu()
return name
def menu():
"""
menu function which gives the user two options
- Press 1 to play or 2 for instructions
- only accepts valid keys or error message comes up
"""
while True:
user_input = input("Press P to Play game\nPress I for Instructions\n").upper()
if user_input == "P":
play()
elif user_input == "I":
print(
"1.The computer will generate a random word and it's\n"
"your task to guess the letters from the word.\n"
"2.To guess, type a letter of your choice and hit enter.\n"
"3.If you guess correctly, the letter will be revealed.\n"
"4.If you guess incorrectly, you will lose a life and \n"
" the Hangman will start to appear.\n"
"5.You have 8 lives to guess the correct word.\n"
"Good Luck!\n")
enter_input = input("Press Enter to go back to the menu\n").upper()
if enter_input == "":
menu()
else:
print(RED_COLOR + "Oops look's like you pressed the wrong key!\n")
else:
print("Invalid Character, please try again!\n")
word = "dog" #random.choice(WORDS)
word = word.upper()
reveal = list(len(word)*'_')
lives = 8
game_is_won = False
def check_letter(letter, word):
global reveal
for i in range(0,len(word)):
letter = word[i]
if guess == letter:
reveal[i] = guess
if '_' not in reveal:
return True
else:
return False
def restart_game():
"""
Gives player option to restart, otherwise returns to menu
"""
game_restart = False
while not game_restart:
restart = input("Would you like to play again?"
"Y/N").upper()
try:
if restart == "Y":
game_restart = True
play()
elif restart == "N":
game_restart = True
print("\n")
header()
ask_for_name()
menu()
else:
raise ValueError(
"You must type in Y or N"
)
except ValueError as e:
print("\n You must type in Y or N Please try again.\n")
def play():
os.system("clear")
header()
print(hangman[8-lives])
print(' '.join([str(e) for e in reveal]))
print(f"You have {lives} lives")
while game_is_won == False and lives > 0:
play()
guess = input('Guess a letter or an entire word:')
guess = guess.upper()
if guess == word:
game_is_won = True
reveal = word
elif len(guess) == 1 and guess in word:
game_is_won = check_letter(guess, word)
else:
lives -= 1
if game_is_won:
player_won()
print("WELL DONE")
else:
player_lost()
print(f"YOU FAILED the word was: {word}")
restart_game()
Since there were portions of the game program missing, I filled in the missing bits with some placeholder functions. After trying out the game and seeing where it appeared to get stuck, I made some tweaks to it to make it function in the spirit of a hangman game. Following is the tweaked code for your analysis.
import os
word = "dog" #random.choice(WORDS)
word = word.upper()
reveal = list(len(word)*'_')
lives = 8
game_is_won = False
hangman = [] # Added this so as to make the game work - temporary
for g in range(0,8):
hangman.append('-')
def header():
return
def ask_for_name():
while True:
name = input("Please Enter Your Name:\n")
if not name.isalpha():
print("Name must be letters only\n")
else:
print(f"Hello {name}, Welcome to Chris's Hangman and Good Luck!\n")
menu()
break # Added this to get out of the while loop
return name
def menu():
while True:
user_input = input("Press P to Play game\nPress I for Instructions\n").upper()
if user_input == "P":
lives = 8
game_is_won = False
break
elif user_input == "I":
print("1.The computer will generate a random word and it's\n"
"your task to guess the letters from the word.\n"
"2.To guess, type a letter of your choice and hit enter.\n"
"3.If you guess correctly, the letter will be revealed.\n"
"4.If you guess incorrectly, you will lose a life and \n"
" the Hangman will start to appear.\n"
"5.You have 8 lives to guess the correct word.\n"
"Good Luck!\n")
enter_input = input("Press Enter to go back to the menu\n").upper()
if enter_input == "":
pass
#menu()
else:
print("Oops look's like you pressed the wrong key!\n")
else:
print("Invalid Character, please try again!\n")
def check_letter(guess, word):
global reveal
for i in range(0,len(word)):
letter = str(word[i])
if guess == letter:
reveal[i] = guess
if '_' not in reveal:
return True
else:
return False
def restart_game(): # Added return of decision
"""
Gives player option to restart, otherwise returns to menu
"""
game_restart = False
while not game_restart:
restart = input("Would you like to play again?" "Y/N/Q ").upper() # Added a quit option
try:
if restart == "Y":
return True
elif restart == "N":
game_restart = True
print("\n")
header()
ask_for_name()
#menu()
return True
elif restart == "Q":
return False
else:
raise ValueError("You must type in Y or N")
except ValueError as e:
print("\n You must type in Y or N Please try again.\n")
def player_won(): # Added this to make the game work
print("Yea!")
return
def player_lost(): # Added this to make the game work
print("Boohoo")
return
def play():
os.system("clear")
header()
print(hangman[8-lives])
print(' '.join([str(e) for e in reveal]))
print(f"You have {lives} lives")
header()
ask_for_name()
while game_is_won == False and lives > 0:
play()
guess = input('Guess a letter or an entire word:')
guess = guess.upper()
if guess == word:
game_is_won = True
reveal = word
elif len(guess) == 1 and guess in word:
game_is_won = check_letter(guess, word)
else:
lives -= 1
if game_is_won:
player_won()
print("WELL DONE")
else:
if lives <= 0:
player_lost()
print(f"YOU FAILED the word was: {word}")
if game_is_won == True or lives <=0: # Conditioned restart
if restart_game() == True:
game_is_won = False
lives = 8
reveal = list(len(word)*'_')
The key bits were adjusting some of the "if" tests to allow for life decrements, prompting for a name, prompting the menu, and restarts.
Here is a quick sample at the terminal.
-
_ _ _
You have 8 lives
Guess a letter or an entire word:Dog
Yea!
WELL DONE
Would you like to play again?Y/N/Q Q
Give those a try.

question regarding secret number python game

I'm wondering what´s happening with my code, because I want to print just in the end if we found the secret number, but I get it every time.
import random
answer = random.randint(1, 101)
user_winner = False
attempts = 0
attempt_word = ""
#Game Loop( the body of the loop inside)
while user_winner != True:
#User input
guess = input("Can you guess a number between 1 and 100? ")
#Check The user Input
try:
guess_number = int(guess)
except:
print("You should write a number!")
quit()
#Increase attempt count
attempts += 1
#check the user answer against the secret number
if guess_number == answer:
user_winner = True
elif guess_number > answer:
print("The number is Smaller!!")
else:
print("The number is Bigger!!")
#Get the spelling of the "attempt" word
if attempts == 1:
attempt_word = " attempt"
else:
attempt_word = " attempts"
#Display the result
print("Congratulations!! You did it in " + str(attempts) + attempt_word)
we should not be able to see it (print) unless we get the right result
If you try to simulate the code in your loop top to bottom, you will see that the final print line is always read at the end, because there's nothing stopping it from reaching that point. You are going to want to either wrap it around a condition (e.g. if/else):
if user_winner == True:
print( "Congratulations!! You did it in " + str( attempts ) + attempt_word )
You can also consider placing the print line under an already existent if statement that you wrote:
if guess_number == answer:
print( "Congratulations!! You did it in " + str( attempts ) + attempt_word )
elif ...
However, since Python reads it from top to bottom, you would also need to move the block of code you have handling the attempt_word variable.
The problem is that the congratulations part is not in an if statement and so prints every time a number is input. You can either move that up to the first if statement or leave it where it is but put it inside a new if statement.
First solution is you move the congratulations part up to where you first test to see if it's correct like this:
#setup
import random
answer = random.randint(1, 101)
user_winner = False
attempts = 0
attempt_word = ""
#Game Loop( the body of the loop inside)
while user_winner != True:
#User input
guess = input("Can you guess a number between 1 and 100? ")
#Check The user Input
try:
guess_number = int(guess)
except:
print("You should write a number!")
quit()
#Increase attempt count
attempts += 1
#check the user answer against the secret number
if guess_number == answer:
user_winner = True
#Get the spelling of the "attempt" word
if attempts == 1:
attempt_word = " attempt"
else:
attempt_word = " attempts"
#Display the result
print("Congratulations!! You did it in " + str(attempts) + attempt_word)
elif guess_number > answer:
print("The number is Smaller!!")
else:
print("The number is Bigger!!")
Or for the second solution you test to see if you get the correct result a second time before printing congratulations like this:
#setup
import random
answer = random.randint(1, 101)
user_winner = False
attempts = 0
attempt_word = ""
#Game Loop( the body of the loop inside)
while user_winner != True:
#User input
guess = input("Can you guess a number between 1 and 100? ")
#Check The user Input
try:
guess_number = int(guess)
except:
print("You should write a number!")
quit()
#Increase attempt count
attempts += 1
#check the user answer against the secret number
if guess_number == answer:
user_winner = True
elif guess_number > answer:
print("The number is Smaller!!")
else:
print("The number is Bigger!!")
#Get the spelling of the "attempt" word
if attempts == 1:
attempt_word = " attempt"
else:
attempt_word = " attempts"
#Display the result
if guess_number == answer:
print("Congratulations!! You did it in " + str(attempts) + attempt_word)

Trying to get the number of tries to start at 1 and not 0

Whenever you run the game and start guessing it asks first what is guess #0? I'm trying to get it to display "what is guess #1?" but. at the same time keep the number of guesses equal to the number guessed (if that makes sense). Here's my code so far:
import random
def play_game(name, lower=1, upper=10):
secret = random.randint(lower, upper)
tries = 0
print("-----------------------------\n"
"Welcome, {}!\n"
"I am thinking of a number\n"
"between {} and {}.\n"
"Let's see how many times it\n"
"will take you to guess!\n"
"-----------------------------".format(name, lower, upper))
# Main loop
guessing_numbers = True
while guessing_numbers:
guess = input("What is guess #{}?\n".format(tries))
while not guess.isdigit():
print("[!] Sorry, that isn't a valid input.\n"
"[!] Please only enter numbers.\n")
guess = input("What is guess #{}?\n".format(tries))
guess = int(guess)
tries += 1
if guess < secret:
print("Too low. Try again!")
elif guess > secret:
print("Too high. Try again!")
else:
guessing_numbers = False
if tries == 1:
guess_form = "guess"
else:
guess_form = "guesses"
print("--------------------------\n"
"Congratulations, {}!\n"
"You got it in {} {}!\n"
"--------------------------\n".format(name,tries,guess_form))
if tries < 3:
# Randomly chooses from an item in the list
tries_3 = ["Awesome job!","Bravo!","You rock!"]
print (random.choice(tries_3))
# ---
elif tries < 5:
tries_5 = ["Hmmmmmpff...","Better luck next time.","Ohhh c'mon! You can do better than that."]
print (random.choice(tries_5))
elif tries < 7:
tries_7 = ["You better find something else to do..","You can do better!","Maybe next time..."]
print (random.choice(tries_7))
else:
tries_8 = ["You should be embarrassed!","My dog could do better. Smh...","Even I can do better.."]
print (random.choice(tries_8))
choice = input("Would you like to play again? Y/N?\n")
if "y" in choice.lower():
return True
else:
return False
def main():
name = input("What is your name?\n")
playing = True
while playing:
playing = play_game(name)
if __name__ == "__main__":
main()
I have the number of "tries" set to 0 at the beginning. However, if I set that to 1 then play the game and it only takes me 3 tries it will display that it took me 4 tries. so I'm not sure what to do. Still somewhat new to python so I would love some help
Anywhere that you have input("What is guess #{}?\n".format(tries)), use guess = input("What is guess #{}?\n".format(tries+1)). (adding +1 to tries in the expression, but not changing the variable itself)

hangman game in python after trying to exit after playing one round

If I play one round of the game and select the option to quit, the game finishes, BUT, if I play a second round and try to quit, the game continues and the user is prompted to enter a guess again, instead of terminating the game.
It seems to be stuck in a loop.
Here is my code:
from random import randint
def core_game():
def init_hangman():
hangman = []
for x in range(7):
hangman.append([" "] * 7)
hangman[0][0] = "_"
hangman[0][1] = "_"
hangman[0][2] = "_"
hangman[1][3] = "|"
return hangman
hangman = init_hangman()
def print_hangman():
for x in hangman:
print(str.join("", x))
def get_input(guess):
your_guess = input(guess)
if your_guess in guessed_letters:
print("You already guessed that letter!")
return get_input(guess)
elif your_guess.isalpha() and len(your_guess) == 1:
return your_guess
else:
print("Please guess a single letter!")
return get_input(guess)
words_list = ["monkey", "cow"]
city_list = ["Amarillo", "Houston"]
lists = ["animals", "cities"]
random_list = randint(0,1)
random_word = randint(0,1)
if lists[random_list] == "cities":
rand_list = city_list
elif lists[random_list] == "animals":
rand_list = words_list
word = rand_list[random_word]
guessed = ""
guessed_letters = []
hang = 6
Cont = True
for letter in word:
guessed += "-"
print("\n\n\nWELCOME TO HANGMAN!")
print("The category is: ", lists[random_list])
print("The secret word: ", guessed, "is", len(guessed), "letters")
while Cont:
your_guess = get_input("\nEnter your guess: ")
if your_guess in word.lower():
for x in range(len(word)):
if word[x].lower() == your_guess.lower():
guessed = guessed[:x] + word[x] + guessed[x+1:]
guessed_letters.append(your_guess)
print("\nThe secret word: ", guessed)
if guessed.lower() == word.lower():
print("\n\nCongratulations, you guessed the word!")
play_again = input("\nWould you like to play again?(y/n) ")
if play_again == "y" or play_again == "yes":
core_game()
else:
Cont = False
else:
hang -= 1
guessed_letters.append(your_guess)
print("\nGuessed letters: ", guessed_letters)
if hang == 5:
hangman[2][3] = "O"
print_hangman()
print(guessed)
elif hang == 4:
hangman[3][3] = "|"
print_hangman()
print(guessed)
elif hang == 3:
hangman[3][2] = "-"
print_hangman()
print(guessed)
elif hang == 2:
hangman[3][4] = "-"
print_hangman()
print(guessed)
elif hang == 1:
hangman[4][2] = "/"
print_hangman()
print(guessed)
elif hang == 0:
hangman[4][4] = "\\"
print_hangman()
print("Game Over!")
print("The word was: ", word)
play_again = input("Would you like to play again?(y/n) ")
if play_again == "y" or play_again == "yes":
core_game()
else:
Cont = False
core_game()
The main function is core_game() and this is called when the program is run.
Okay- yes, I like the game- played it in the browser at trinket.io
Then I walked through an entire game here. Use this to debug your code, step by step and you can view all of the variables, lists etc. as well as enter input and view output.
The reason that your game is repeating is because:
1) In the function core_game you have the following code:
if play_again == "y" or play_again == "yes":
core_game()
This means that when you select yes after the first game, you are opening another "instance" of the function- you can see this if you trace through the code. You can also see this in the screenshot below (f19).
2) after you play the second game (remember that the first instance is still open) and select "n", this causes the "Cont" variable to change to False, but only in the second instance. The "while" is closed then, and the code goes back to the first instance where Cont is still True. You can also see both instances in the screenshot, and the state of each value of "Cont". The closed frame is "greyed out".
3) The program resumes in the first instance of the core_game at the start of the while loop, and the user is prompted to enter a guess.
This is difficult to see until you trace through the code, but I have included a snapshot here where you can (I hope) see what I mean.
So the issue is that you are calling the function from within itself.
Consider something more like this:
def core_game():
print("I was called")
while Cont:
ans = ("Do you wish to play a game? (Y/N)")
if ans[0].lower() == "y": # works for Y, y, Yup, Yeah, Yes etc.
core_game()
else:
Cont = False
PS
there are other really good reference sources out there, such as this as well.
Never give up- you'll find the step-thru really handy, and you might try Rice Universities MOOC on Coursera at some later stage.

Hangman with Arrays in Python 3.2

import random
GameWords = ['COMPUTER', 'PYTHON', 'RUBY', 'DELPHI', 'LAPTOP', 'IDEALS', 'PERL']
#Program will pick a word to use
word = random.randint(0,6)
ChosenWord = GameWords[word]
ChosenWord = list(ChosenWord)
#This will generate a playfield
playField = "_" * len(ChosenWord)
playField = list(playField)
#Array for bad guesses
BadGuess = "_" * len(ChosenWord) * 2
BadGuess = list(BadGuess)
print(" Bad Guesses", BadGuess)
print("\n Hidden Word ", playField, end = "")
#Get the number of letters in the word
WordLength = len(ChosenWord)
#Give two times the number of letters in a word for guessing.
NumChances = WordLength * 2
print("")
print("\n Number of Chances", NumChances)
print("\n This is number of letters in word", WordLength, "\n")
#Need a loop for the guess
flag = True
GoodCounter = 0
b = 0
while flag == True:
#Input a player's guess into two diffrent arrays
#Array for bad guess one for good guess
PlayerGuess = input("\n Guess a letter: ")
PlayerGuess = PlayerGuess.upper()
#Player cannot enter more than one letter
if len(PlayerGuess) != 1:
print("Please enter a single letter.")
#If the player do not enter a letter
elif PlayerGuess not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
print("Please enter a LETTER.")
#If the player guess wrong
# b is used for indexing
elif PlayerGuess not in ChosenWord:
for b in range(0):
if ChosenWord[b] != PlayerGuess:
BadGuess[b] = PlayerGuess
b = b + 1
print("this is b", b)
print("You have guessed wrong")
print("Letters you have missed", BadGuess)
NumChances = NumChances - 1
print("You have", NumChances, "left!")
if NumChances == 0:
flag = False
print("You have lost!")
else:
flag = True
#If the player guess correctly
# i is used for indexing
elif PlayerGuess in ChosenWord:
for i in range(WordLength):
if ChosenWord[i] == PlayerGuess:
playField[i] = PlayerGuess
print("\n Letters you have HIT! ", playField, end = "")
print("You have guessed correctly")
GoodCounter = GoodCounter + 1
if GoodCounter >= WordLength:
flag = False
print("You have won!")
else:
flag = True
Now I have a new problem my BadGuess array will not display the letters on the play field. I tried to use the same code I used for the playField array but it did not work.
What do I need to do to get the bad guesses to be stored in the BadGuess array and display on the play field?
I don't know if this is what you're asking, but if you want all the bad guesses stored in the array, you have to increment the bad variable.
If you want to replace the blanks, there are many ways to do so, but I'd create a loop that tests to see if a letter is the same as in the word at a given index, and then replace it in the array if it does.
Something like:
for i in range(WordLength):
if ChosenWord[i] == playerGuess:
playField[i] = playerGuess
Hope this helps.

Categories

Resources