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.
Related
I am a beginner in Python and I am making Hangman game project
So whenever I try to put the same alphabet twice it takes 2 lives
instead of just taking one
because both conditions are getting true.
My code is running fine but output is coming wrong due to both
conditions in if statement
given is satisfied
here is my code below
import time #importinf random module
#from hangman_art import logo #importing logo which i have in my PC, you ignore.
print("Welcome to HANGMAN")
#print(logo) #printing the logo which imported
user = input("\nWhat's Your Name : ") # take input for user name
print(f"\nHello {user}! Best Of Luck") #just for code to feel good.
x = (input("\nReady to play??? : ")) #input from user weather he/she wants to play or no.
if x == "yes" or x =="YES" or x =="Yes" or x == "y" or x == "Y": print("\nGame Loading in
3..2..1")
else:
print("\nOk Sadly ending the game!! BYE BYE")
exit()
#time.sleep(3)
print("\nGame Start!!")
#time.sleep(1)
print("\nRules as follows :-\n1. Guess the right word letter by letter.\n2. You only got 6
lives.\n3. Do not repeat the same alphabet entry it will reduce your life.\n4. Enjoy the game.")
#time.sleep(3)
import random #importing random module for code to choose any random number.
word_list=["TIGER","ELEPHANT","LION","CAT","DOG","HORSE"] #you can add n numbers of words.
chosen_word = random.choice(word_list) #giving variable to chosen random word.
length = len(chosen_word) #variable to find length of chosen word.
display=[] #creating an empty list.
in_game = True #for while loop to run continously
lives = 6 #user get 6 lives.
display=[]
duplicate=[] #creating an empty list to store duplicate values.
for _ in range (length):
display += "_"
#here looping for guess and game
while in_game:
guess = input("\nCome On Guess a word letter by letter : ").upper()
#make a list called duplicate
#add guess letter to duplicate list
#check if the entered letter is already present in that list
#if present then show msg stating already used word
#else follow the normal process
#duplicate=[]
if guess in display:
print("\nYou guessed",guess)
for position in range(length): #for getting length of number to be guessed
letter = chosen_word[position]
if letter == guess:
print("\nYou guessed",guess,"which is right aplhabet!!")
display[position] = letter
print(" ".join(display)) #joiningdisplay
if guess in duplicate:
lives -= 1 #this condition for taking life if duplicate entry.
print(f"\n{user} Do not repeat same alphabet entry. A LIFE LOST due to continues same
alphabet entry.") #here condition gets true and then goes to another if statment there also it gets true and code takes 2 life.
if lives == 0:
in_game = False
print(f"\n{user} You lost all your life, YOU LOSE.")
duplicate.append(guess)
#here 2 conditions are getting true so code is taking 2 lives please help
if guess not in chosen_word:
print("\nYou guessed", guess, "which is not the alphabet, life lost.")
lives -= 1
if lives == 0:
in_game = False
print(f"\n Try next
time {user}, You lost all your life, YOU LOSE.")
if not "_" in display:
in_game = False
print(f"\n Congrats {user} You WIN.")
from hangman_art import stages
print(stages[lives])
There are 2 if conditions that are true, so each will minus 1 live. You should use if and elif to ensure only 1 true condition is allowed. The code can be improved with 3 changes, see below:
<truncated>
while in_game:
guess = input("\nCome On Guess a word letter by letter : ").upper()
<truncated>
if guess in duplicate:
lives -= 1
print(f"\n{user} Do not repeat same alphabet entry. A LIFE LOST due to continues same alphabet entry.")
if lives == 0:
in_game = False
print(f"\n{user} You lost all your life, YOU LOSE.")
# duplicate.append(guess) #1. remove line from here
elif guess not in chosen_word: #2. change if to elif
print("\nYou guessed", guess, "which is not the alphabet, life lost.")
lives -= 1
if lives == 0:
in_game = False
print(f"\n Try next time {user}, You lost all your life, YOU LOSE.")
duplicate.append(guess) #3. add this line here instead
if not "_" in display:
in_game = False
print(f"\n Congrats {user} You WIN.")
Here's another way to do it, with MAX_WRONG = 6 means user gets 6 lives.
import random
WORDS = ['apple', 'banana', 'kiwi', 'orange', 'helicopter']
MAX_WRONG = 6
def game_play():
word = random.choice(WORDS).upper()
current_guess = '-' * len(word) #hidden answer
wrong_guesses = 0
used_letters = []
while wrong_guesses < MAX_WRONG and current_guess != word:
print ('\nRemaining tries:', MAX_WRONG - wrong_guesses)
print ('So far, the word is: ', current_guess)
print ('You have used the following letters: ', used_letters)
guess = input('Enter your letter guess:').upper()
if guess == word:
current_guess = word
break #exit the while-loop
while guess in used_letters: #check for duplicate input
print ('You have guessed "' + guess + '" already!')
guess = input ('Enter your letter guess: ').upper()
used_letters.append(guess) #append guess to used_letters
if guess in word:
print ('You have guessed correctly!')
new_current_guess = ''
for idx in range(len(word)): #update hidden answer
if guess == word[idx]:
new_current_guess += guess
else:
new_current_guess += current_guess[idx]
current_guess = new_current_guess
else:
print ('Sorry that was incorrect')
wrong_guesses += 1
if wrong_guesses == MAX_WRONG:
print ('\nYou have been hanged!')
print ('The correct word is', word)
elif current_guess == word:
print ('\nYou have won!! The word is:', word)
game_play()
Output:
Remaining tries: 6
So far, the word is: ----------
You have used the following letters: []
Enter your letter guess: helicopter
You have won!! The word is: HELICOPTER
Im trying to make my for loop return a string of the whole word with a dash or each letter depending on guess_letters instead of print out each letter one by one for my hangman game.
Ive tried to print letter as a string, return letter then set a variable to that function then print the variable.
import random
words = ['apple','python','parent']
def randomword(words):
return random.choice(words)
chosenword = randomword(words)
tries = 10
guess_letters = []
def dashshow(guess_letters):
for letter in chosenword:
if letter in guess_letters:
return str(letter)
string_letter = dashshow(guess_letters)
print(string_Letter)
else:
return '-'
dash_letter = dashshow(guess_letters)
print(dash_letter)
def playgame(tries):
while tries != 0 and "_" in chosenword:
print(f"You have {tries} tries left")
guess = str(input("Guess a letter of the word")).lower()
guess_letters.append(guess)
if guess in chosenword:
print("You got a letter correct!")
turns -= 1
else:
print("That letter is not in the word")
turns -= 1
playgame(tries)
I thought it would print out the string with dashes or letters depending on the guessed_letters list but it doesn't print anything.
here is way you can. just modify as you need.Also, You can compare your code with this one. to find mistake.
import random
words = ['apple','python','parent']
def randomword(words):
return random.choice(words)
chosenword = randomword(words)
print (chosenword) #this is random word you can delete this line.
tries = 10
guess_letters = []
def dashshow(guess_letter):
guess_letters.append(guess_letter)
print(guess_letters) # just to debug you can remove.
if len(guess_letters) == len(chosenword):
print("You Won Dear!")
exit()
def playgame(tries):
while tries != 0 :
print(f"You have {tries} tries left")
guess = str(input("Guess a letter of the word:> ")).lower()
if any(guess in s for s in chosenword):
print("You got a letter correct!")
dashshow(guess)
tries -= 1
else:
print("That letter is not in the word")
tries -= 1
playgame(tries)
I've am having trouble with the last two specifications of this program.
1) Guesser initially gets 6 misses (7th strike and they are out). If they win that game, they play again, but with only 5 misses, etc. The game ends when they fail to guess the word in the specified number of guesses or until they win a game in which they have 0 misses.
- I've tried but I don't know how to have all of my numbers from the other functions reflect the new change. I would like to keep the option to replay so they can quit at anytime.
2) Before each guess display a list of letters that have not yet been guessed.
- I know this one is simpler and I should know it but I think I've fried my brain.
I've still have documentation to do so I apologize for any errors. Any cleanup is always appreciated. Thanks in advance.
import random
import string
word_list = ["no", "hi", "bee", "car", "seat", "bear", "see", "chip"]
available_letters = string.ascii_lowercase # pop guessed letter from here
used_letters = [] # Add it to here, and display avaiable_letters each time a letter is guessed.
missed_letters = ""
correct_letters = ""
secret_word = random.choice(word_list).lower()
def get_random(word_list):
secret_word = random.choice(word_list).lower()
return secret_word
def display_board(missed_letters, correct_letters, secret_word):
print("Current Score:")
for letter in missed_letters:
print(letter)
print()
blanks = '-' * len(secret_word)
for i in range(len(secret_word)):
if secret_word[i] in correct_letters:
blanks = blanks[:i] + secret_word[i] + blanks[i+1:]
for letter in blanks:
print(letter)
print()
def get_player_guess(guessed):
while True:
guess = input("Enter a letter: ") # try guess = input(blah blah).lower()
guess = guess.lower()
if len(guess) != 1:
print("1 Letter at a time!")
elif guess in guessed:
print("Whoops, you already guessed that one!")
elif guess not in "abcdefghijklomnopqrstuvwxyz":
print("Letters only please!")
else:
return guess
def replay_game():
replay = input("Do you want to play again? y or n ")
if replay == "y":
play_game(missed_letters, correct_letters, secret_word)
else:
print("Bye!")
def play_game(missed_letters, correct_letters, secret_word):
count = 0
chance = 7
game_over = False
print("Welcome To Hangman.")
while True:
display_board(missed_letters, correct_letters, secret_word)
guess = get_player_guess(missed_letters + correct_letters)
if guess in secret_word:
correct_letters = correct_letters + guess
done = True
for i in range(len(secret_word)):
if secret_word[i] not in correct_letters:
done = False
break
if done:
print("You win!")
game_over = True
else:
missed_letters = missed_letters + guess
count += 1
chance -= 1
if count == 1:
print("You've got " + str(count) + " Strike. You have " + str(chance) + " Chances left")
elif count > 1 and count < 6:
print("You've got " + str(count) + " Strikes. You have " + str(chance) + " Chances left")
elif count == 6 and chance == 1:
print("You've got " + str(count) + " Strikes. You have " + str(chance) + " Chance left")
if len(missed_letters) == 7:
display_board(missed_letters, correct_letters, secret_word)
print("Sorry! You've run out of guesses! The right word was " + secret_word + "!")
game_over = True
if game_over:
if replay_game():
missed_letters = ""
correct_letters = ""
secret_word = get_random(word_list)
else:
break
play_game(missed_letters, correct_letters, secret_word)
At the moment, you aren't changing the word when replay_game is called because the text after if replay_game at the end is never being called.
For the first problem, I would record the total number of chances for the game as an input variable into play_game and change replay_game to just return true or false and move the other code into play_game
def replay_game():
replay = input("Do you want to play again? y or n ")
# Changed to just return true or false depending on input.
if replay == "y":
return True
else:
print("Bye!")
return False
Then change the start of play_game to
def play_game(missed_letters, correct_letters, secret_word, total_chances=7):
count = 0
# chance is now variable
chance = total_chances
game_over = False
and at the end of play_game, replace:
if len(missed_letters) == 7:
with
if chance == 0:
and change the call to if game_over to
if game_over:
if replay_game():
missed_letters = ""
correct_letters = ""
secret_word = get_random(word_list)
play_game(missed_letters, correct_letters, secret_word, total_chances - 1)
else:
break
This will mean your code which was resetting the letters will get called now, and each restarted game starts with one less chance than the previous.
You'll have to add some handling for the case where they win with no misses allowed.
For the second problem, just add the following to display board:
print("Available letters:")
print(','.join(sorted(set(available_letters) - set(missed_letters) - set(correct_letters))))
This makes a set of each of the three groups of letters, and then takes away those already guessed, before displaying them in one line, alphabetically sorted and comma separated.
Regarding the function display_board I would clean the code a bit to substitute the '_' in blanks with the correct letter when it was correctly guessed:
for i in range(len(secret_word)):
if secret_word[i] in correct_letters:
blanks[i] = secret_word[i]
It looks cleaner and does less reassignments of elements in blanks.
I've been working on hangman project recently, I have used enumerate to get the locations of a letter that's been guessed so i can put it into a list, but when i try and put it into "guess" list, it comes up with:
Edit: I do understand that you cannot simply change an entire list into a series of ints by doing int(list), it's simply a place holder
Here is my code
import random
lines = []
with open('words.txt', 'r') as f:
for line in f:
line = line.strip()
lines.append(line)
choice = random.choice(lines)
#print("it says", choice)
guessed = False
print("Your word is", len(choice), "letters long!")
answer = ["_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"]
wrong = 0
= 1
print(choice)
while not guessed:
guess = input("Guess a letter!")
#location = choice.find(guess)
location = [i for i, a in enumerate(choice) if a == guess]
print(location)
if wrong == 6:
print("Sorry, you have killed yourself.")
guessed = True
elif not location:
wrong += 1
print("Sorry, that was not part of the word!")
print("You have", (6 - wrong), "guesses left")
elif right == len(choice):
answer[int(location)] = guess
print(answer[0:len(choice)])
print("Congratulations! You have won!")
guessed = True
else:
right += 1
answer[location] = guess
print(answer[0:len(choice)])
Your code has other issues beyond this but as your question at hand, it is here:
elif right == len(choice):
answer[int(location)] = guess
print(answer[0:len(choice)])
print("Congratulations! You have won!")
guessed = True
else:
right += 1
answer[location] = guess
print(answer[0:len(choice)])
Your two statements answer[int(location)] = guess and answer[location] = guess if you print location it is a list, for a 4 letter word example vash, location is a list of range [0,3] you are attempting to pass the entire list as an index which will not work regardless if you convert it to int or not.
Please try this modification, this is not a full solution, I do not want to take away from your journey on this project but this will get your moving:
import random
lines = ['hey', 'this', 'that']
choice = random.choice(lines)
#print("it says", choice)
guessed = False
print("Your word is", len(choice), "letters long!")
answer = ["_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"]
wrong = 0
right = 0
print(choice)
while not guessed:
guess = input("Guess a letter!")
#location = choice.find(guess)
if wrong == 6:
print("Sorry, you have killed yourself.")
guessed = True
elif guess not in choice:
wrong += 1
print("Sorry, that was not part of the word!")
print("You have", (6 - wrong), "guesses left")
elif right == len(choice):
print(answer)
print("Congratulations! You have won!")
guessed = True
else:
right += 1
answer[choice.index(guess)] = guess
print(answer[0:len(choice)])
I am creating a "guess the word" game in python for my intro to programming class. The word is shown with dashes (-) in place of the vowels. The user is supposed to guess the word based off of a provided hint (the words/hints go together as parallel tuples). The user gets 5 guesses and if the word is guessed correctly, a certain amount of points are awarded. The user can then either choose to keep playing & accumulate points, or quit. The code was working until I added the coding to ask the user if he/she would like to keep playing. What is it that I need to fix in order for it to work?
#Clear Screen
print("\n"*50)
import random
#Variables
keep_playing = "y"
round_score = 0
overall_score = 0
new_words = ""
vowels = "AaEeIiOoUuYy"
#Parallel tuples
while keep_playing.lower() == "y":
guesswords = ("Japan","France","Mexico","Italy","Australia")
guesshints = ("Sushi comes from here","Croissants come from here","Tacos come from here","Pizza comes from here","Vegemite comes from here")
#Random
index = random.randrange(len(guesswords))
guesses = 5
#Replacing vowels
for letter in guesswords[index]:
if letter not in vowels:
new_words += letter
else:
new_words += "-"
#Output
print(new_words.center(80, " "))
print("Hint:",guesshints[index])
while guesses > 0:
input_string = "\nGuess the word! You have " + str(guesses) + " guesses remaining: "
user_guess = input(input_string)
if user_guess.upper() == guesswords[index].upper():
print("YOU WIN")
round_score = (guesses * 2)
overall_score += round_score
print("Your score for this round is ",round_score)
break
guesses -= 1
print("Your overall score is ",overall_score)
keep_playing = input("Would you like to keep playing? (y/n)")
print("GAME OVER")