I'm new to programming. I was doing a classic hangman game, but I wanted it to be guessing some character's names from a show (name and surname).
My problem: the dashes print the space between name and surname instead of ignoring it, example:
Secret word: Rupert Giles
How it prints when all the letters are guessed: Rupert_ Giles
(yes, it has a space after the dash)
I've tried:
split()
writing character instead of letter (as space doesn't count
as character in lines 41,42 and 43)
separating the name as ["Name""Surname,
"Name2""Surname1"]
and ['Name'' ''Surname','Name1'' ''Surname1']
What I think it's the problem: the secret "word" is stored in main, and main is in charge of putting dashes instead of the letters, the code of that part goes like this
main = main + "_" + " "
So maybe there's something that should be changed in there so it ignores the spaces
My code:
import random, sys, time, os
def typingPrint(text):
for character in text:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
def typingInput(text):
for character in text:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
value = input()
return value
def clearScreen():
if os.name == 'posix':
_ = os.system('clear')
else:
_ = os.system('cls')
def hangman():
word = random.choice(
["Spike", "Rupert Giles", "Tara Maclay", "Willow Rosenberg", "Buffy Summers", "Xander Harris",
"Wesley Wyndam Price", "Faith Lehane", "Angel", "Darla", "Cordelia Chase", "Dawn Summers",
"Anya Jenkins", "Riley Finn", "Drusilla", "Oz Osbourne", "Kendra Young", "Joyce Summers", "Master",
"Harmony Kendall",
"Jenny Calendar", "Robin Wood", "Jonathan Levinson",
"Ethan Rayne", "Principal Snyder", "Kennedy", "Veruca", "Hank Summers", "Halfrek", "DHoffryn", "Mr Tick"])
validLetters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
turns = 10
guessmade = ''
while len(word) > 0:
main = ""
missed = 0
for character in word:
if character in guessmade.lower() or character in guessmade.upper():
main = main + character
else:
main = main + "_" + " "
if main == word:
print(main)
typingPrint("Congratulations! You win... for now.\nLet's try again")
typingPrint("\nin 3...2...1")
clearScreen()
break
print("\nGuess the word:", main)
guess = input()
if guess in validLetters:
guessmade = guessmade + guess
else:
typingPrint("Enter a valid character: ")
guess = input()
if guess.lower() not in word and guess.upper() not in word:
turns = turns - 1
if turns == 9:
typingPrint("You have 9 turns left")
print("\n -------- this is a ceiling, don't laugh at it")
if turns == 8:
typingPrint("You have 8 turns left")
print("\n -------- ")
print(" O ")
if turns == 7:
typingPrint("You have 7 turns left")
print("\n -------- ")
print(" O ")
print(" | ")
if turns == 6:
typingPrint("You have 6 turns left")
print("\n -------- ")
print(" O ")
print(" | ")
print(" / ")
if turns == 5:
typingPrint("You have 5 turns left")
print("\n -------- ")
print(" O ")
print(" | ")
print(" / \ ")
if turns == 4:
typingPrint("You have 4 turns left")
typingPrint("\nYou are walking on thin ice")
print("\n -------- ")
print(" \ O ")
print(" | ")
print(" / \ ")
if turns == 3:
typingPrint("You have 3 turns left")
typingPrint("\n No pressure")
print("\n -------- ")
print(" \ O / ")
print(" | ")
print(" / \ ")
if turns == 2:
typingPrint("You have 2 turns left")
typingPrint("\nYou call yourself a Buffy fan?")
print("\n -------- ")
print(" \ O / | ")
print(" | O ")
print(" / \ ")
if turns == 1:
typingPrint("You have 1 turn left")
typingPrint("\nYou should re-watch all seasons")
print("\n -------- ")
print(" \ O_|/ ")
print(" | ")
print(" / \ ")
if turns == 0:
typingPrint("You lose, ")
typingPrint(name)
typingPrint("\nThe name was...")
typingPrint(word)
print("\n -------- ")
print(" O_| ")
print(" /|\ ")
print(" / \ ")
typingPrint("Good night")
typingPrint("\nin 3...2...1")
clearScreen()
break
while 1:
name = typingInput("Enter your name: ")
typingPrint("Welcome, ")
typingPrint(name)
typingPrint(". You have been fooled\n")
typingPrint("Now you are my prisioner, my dear ")
typingPrint(name)
typingPrint("\nMwahahaha")
print("\n-------------------------------------")
typingPrint("Try to guess the name of this Buffy's character in less than 10 attempts")
typingPrint("\nIf you can't, you will be hanged")
typingPrint("\nNo pressure, ")
typingPrint(name)
typingPrint("\nOh... and one little, itty bitty thing...")
typingPrint("\nThe names are from Season 1 to 7")
typingPrint("\nGood luck, break a neck... I mean, a leg")
hangman()
print()
You can make this adjustment. Replace
if character in guessmade.lower() or character in guessmade.upper():
main = main + character
With
if character in guessmade.lower() or character in guessmade.upper() or character == " ":
main = main + character
As it stands, you are expecting your users to guess a space character. This new if statement removes that requirement.
Nice. I'd print out guessed letters as well. Think this is what you're going for. You don't have to keep caps in validLetters that way.
for character in word:
if character .lower() in guessmade .lower():
main = main + character
elif character == ' ':
main = main + ' '
else:
main = main + '_' + ' '
main is a terrible variable name, so I'll be using word_as_shown instead. Also, I'll replace guessmade with guessed_letters. If you replace
if guess in validLetters:
guessmade = guessmade + guess
with
if guess in validLetters:
guessed_letters += guess.lower()
and define
def char_as_shown(char):
if char == ' ':
return ' '
if char.lower() in guessed_letters:
return char
return "_"
then you can do
word_as_shown = [char_as_shown(char) for char in word]
Related
I've written a hangman program in python. The program is finished, but I have a problem with my main function. If I set a win or loss, it no longer execute my print statements from before. This means that if I have to guess a word, for example, it doesn't fill in the last letter in the placeholder, it just breaks out the loop without filling in the last letter. The same goes with my hangman. If I don't have any more attempts left, it won't finish drawing my hangman (just leave out the last part). Who knows why that is? Please help
Here is my code:
##### HANGMAN IN PYTHON #####
count_attempts = 0
guess_word = []
def guidance():
print('Welcome to Hangman in Python!')
print('''The point here is to guess a word by trying out letter combinations and
defining them with ENTER.''')
print('''For each word, you have 10 tries! If you can not solve the word,
the game is over.''')
print('You have 9 attempts to guess the word.')
print('Have fun!')
print('')
def user_word():
userinput = str(input("Type in the word you want to be guessed: "))
for character in userinput:
if character.isdigit():
print('There is a number in your word!')
userinput = str(input('Please try again: '))
return userinput.upper()
def change(userinput):
global guess_word
list_WordToBeGuessed = list(userinput)
for characters in list_WordToBeGuessed:
guess_word.append(' _')
def play_game(userinput):
global count_attempts
length_word = len(userinput)
user_guessed = []
print('Word to guess: ', *guess_word)
print("")
list_WordToBeGuessed = list(userinput)
guess = str(input('Guess a letter: ')).upper()
for number in guess:
if number.isdigit():
guess = str(input('Input not valid. Guess a letter: ')).upper()
if guess in user_guessed:
print('You have already given this letter. ')
elif guess in list_WordToBeGuessed:
user_guessed.append(guess)
print("You've guessed a letter correctly!")
for i in range(0, length_word):
if list_WordToBeGuessed[i] == guess:
guess_word[i] = guess
else:
count_attempts += 1
user_guessed.append(guess)
print('Sry your given letter is not in the word!')
print("You have failed", count_attempts, "of 5 attempts")
def draw_hangman(count_attempts):
print('-------' )
print(' | ' + ('|' if count_attempts > 0 else ''))
print(' | ' + ('O' if count_attempts > 1 else ''))
print(' | ' + ('/ \\' if count_attempts > 2 else ''))
print(' | ' + ('|' if count_attempts > 3 else ''))
print('--- ' + ('/ \\' if count_attempts > 4 else ''))
print("")
def main():
guidance()
userinput = user_word()
change(userinput)
while True:
draw_hangman(count_attempts)
play_game(userinput)
if count_attempts >= 5:
print("You haven't any attempts left. Bad luck")
break
elif ' _' not in guess_word:
print("")
print('You won, congratulation!')
break
main()
you are breaking out of a loop before it can draw the hangman and word.
in the endgame conditions, you can simply call draw_hangman(count_atttempts) before each print statement and change(userinput) as well.
Edit:
You will have to redraw the word as well. Since this is built into your play_game() function it is difficult, but you can use
for i in guess_word:
guess = guess + i + " "
print(guess)
before the print statements along with the draw_hangman(count_attempts) change you made before. Please note you will need to create a new variable called guess in your main() function prior to adding this code.
Since you have a "break" in your endgame condition, the loop stops and last "draw_hangman(count_attempts)" is not called. You can simply add "draw_hangman(count_attempts)" before "print("You haven't any attempts left. Bad luck")"
My problem is that when I run the program and get all the letters correct, it does not move on from there and I'm in an infinite loop. I expect it to say "Good Job!" and end the program when the player gets the word right. I am very new to coding, and would greatly appreciate any help.
import random
import time
name = input("What is your name? ")
print(name + ", ay?")
time.sleep(1)
start = input("Up for a game of Hangman?(y/n) ")
lis = random.choice(["yet"])
dash = []
while len(dash) != len(lis):
dash.append("_")
guess = []
guesscomb = "".join(guess)
wrongcount=int(0)
alphabet = "abcdefghijklmnopqrstuvwxyz"
if start == "y":
print("One game of Hangman comin' right up,",name)
letter = input("Alright then, Guess a letter: ")
thing = ''.join(dash)
while guesscomb != thing:
if letter == "" or letter == " " or len(letter) != 1:
print("I don't understand. Please only use singular letters.")
letter = input("Guess a letter: ")
elif letter in lis and letter in alphabet:
print("Nice!")
location = lis.find(letter)
dash[location] = letter
guess.append(letter)
alphabet.replace(letter," ")
guesscomb = "".join(guess)
letter = input("Guess a letter: ")
else:
print("Wrong.")
wrongcount = wrongcount + 1
print("Total Mistakes:",wrongcount)
letter = input("Guess a letter: ")
elif start == "n":
input("Shame.")
quit()
print("Good Job!")
time.sleep(10)
The thing variable is equal to ___ while lis is always equal to "yet".
guesscomb cannot be equal to thing as you validate a letter when the guess is equal to a letter in lis
You can use print with the parameter end="" so that the cursor don't go new line.
You can use the method isalpha on string to check if it is all characters instead of comparing it with the alphabets.
And as Ben said, thing is always ___
Modify this part of your code, and it will work
if start == "y":
print("One game of Hangman comin' right up,", name)
print("Alright then, ", end="")
# letter = input("Alright then, Guess a letter: ")
thing = ''.join(dash)
while guesscomb != thing:
letter = input("Guess a letter: ")
if letter == "" or letter == " " or len(letter) != 1:
print("I don't understand. Please only use singular letters.")
elif letter in lis and letter in alphabet:
print("Nice!")
location = lis.find(letter)
dash[location] = letter
guess.append(letter)
alphabet.replace(letter, " ")
guesscomb = "".join(guess)
else:
print("Wrong.")
wrongcount = wrongcount + 1
print("Total Mistakes:", wrongcount)
thing = ''.join(dash)
Imagine the user has input(ed) the letter 'f'. Then the error below pops up.
wrdsplit = list('ferret')
guess = input('> ')
# user inputs `f`
print(wrdsplit.index(guess))
But this results in ValueError: 'f' is not in list.
OMG....... Thank you guys so much for your help. I finally fixed it. Here... have fun playing my Hangman Game:
import random
import time
import collections
def pics():
if count == 0:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /|\ ")
print ("| / \ ")
print ("| ")
print ("| ")
elif count == 1:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /|\ ")
print ("| / ")
print ("| ")
print ("| ")
elif count == 2:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /|\ ")
print ("| ")
print ("| ")
print ("| ")
elif count == 3:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /| ")
print ("| ")
print ("| ")
print ("| ")
elif count == 4:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| | ")
print ("| ")
print ("| ")
print ("| ")
elif count == 5:
print (" _________ ")
print ("| | ")
print ("| GAME OVER ")
print ("| YOU LOSE ")
print ("| ")
print ("| ")
print ("| (**)--- ")
print("Welcome to HANGMAN \nHave Fun =)")
print("You can only get 5 wrong. You will lose your :\n1. Right Leg\n2.Left Leg\n3.Right Arm\n4.Left Arm\n5.YOUR HEAD... YOUR DEAD")
print("")
time.sleep(2)
words = "ferret".split()
word = random.choice(words)
w = 0
g = 0
count = 0
correct = []
wrong = []
for i in range(len(word)):
correct.append('#')
wrdsplit = [char for char in "ferret"]
while count < 5 :
pics()
print("")
print("CORRECT LETTERS : ",''.join(correct))
print("WRONG LETTERS : ",wrong)
print("")
print("Please input a letter")
guess = input("> ")
loop = wrdsplit.count(guess)
if guess in wrdsplit:
for count in range(loop):
x = wrdsplit.index(guess)
correct[x] = guess
wrdsplit[x] = '&'
g = g + 1
if "".join(correct) == word:
print("Well done... You guessed the word in", g ,"guesses and you got", w , "wrong")
print("YOU LIVED")
break
elif guess not in wrdsplit:
wrong.append(guess)
w = w + 1
g = g + 1
count = count +1
pics()
print("The correct word was : ",word)
Try this code to see if it works and does what you want
# Get this from a real place and not hardcoded
wrdsplit = list("ferret")
correct = ["-"]*len(wrdsplit) # We fill a string with "-" chars
# Ask the user for a letter
guess = input('> ')
if guess in wrdsplit:
for i, char in enumerate(wrdsplit):
if char == guess:
correct[i-1] = guess
# Calculate the number of guesses
if "-" in correct:
g = len(set(correct)) - 1
else:
g = len(set(correct))
# Print the right word
print("".join(correct))
The set generates an array without duplicates to count how many guesses he has done, if a "-" is found, one is substracted as that character is not a guess.
The only error I am seeing in here (based on your earlier code) is:
if guess in wrdsplit:
for count in range(len(wrdsplit)):
x = wrdsplit.index(guess)
wrdsplit[x] = '&'
correct[x] = guess
g = g + 1
wrdsplit[x] = '&' # x is out of scope
if "".join(correct) == word:
print("Well done... You guessed the word in", g ,"guesses and you got", w , "wrong")
print("YOU LIVED")
break
Now if you were to continue to retry things in here looking for f, it won't work because you've changed 'f' to '&' so you will get an error for f not in list. You just got caught in a nasty little bug cycle.
You should consider using dictionaries for this instead.
this is my hangman program. it returns a "NameError: name 'a' is not defined." please help me in fixing this. thank you very much.
import random
invalid= [" ","'",".",",","'", '"', "/", "\ ", '"',";","[","]", "=", "-", "~", "`", "§","±","!","#","#","$","%","^","&","*","(",")","_","+","{","}","|",":","?",">","<","0","1","2","3","4","5","6","7","8","9"]
choice = 0
print("Welcome to HANGMAN!")
def Menu():
print("[1] Play Hangman")
print("[2] Instructions ")
print("[3] Highscores")
print("[4] Exit")
choice = int(input("Please choose from the Menu: "))
if(not(choice <=4)):
print("Choose again.")
return Menu()
return choice
while True:
choice = Menu()
if choice == 1:
print("Categories: ")
print("[1] Movies")
print("[2] Animals")
print("[3] Something Blue")
choice_category = int(input("Please Choose a Category: "))
print("-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-")
print("Difficulties:")
print("[1] Easy")
print("[2] Average")
print("[3] Difficult")
choice_difficulty = int(input("Please Choose a Difficulty: "))
superword = a(choice_category, choice_difficulty)
legitgame(superword)
elif choice == 2:
print("Let yourself be hanged by mistaking the letters.")
elif choice == 3:
readHandle = open("Scores.txt","r")
names = []
for line in readHandle:
name = line[:-1]
names.append(name)
readHandle.close()
print()
Menu()
elif choice == 4:
print("Thank you for playing.")
Menu()
hangman =[" =========="
" | |"
" O |"
" |"
" |"
" | ",
" =========="
" | |"
" O |"
" | |"
" |"
" | ",
" ========== "
" | |"
" O |"
" /| |"
" |"
" | ",
" =========="
" | |"
" O |"
" /|\ |"
" |"
" | ",
" =========="
" | |"
" O |"
" /|\ |"
" / |"
" | ",
" =========="
" | |"
" O |"
" /|\ |"
" / \ |"
" | "]
#definition function for different options in a specific category and difficulty
def a(choice_category, choice_difficulties):
if choice_category == 1:
readHandle = open("movies.txt", 'r')
lines = readHandle.readlines()
elif choice_category == 2:
readHandle = open("animals.txt", 'r')
lines = readHandle.readlines()
elif choice_category == 3:
readHandle = open("something blue.txt", 'r')
lines = readHandle.readlines()
else:
print("Please choose again.")
if choice_difficulty == 1:
word = (lines[0])
elif choice_difficulty == 2:
word = (lines[1])
elif choice_difficulty == 3:
word = (lines[2])
else:
print("Please enter valid characters.")
legitword = word[:-1].split(".")
return (random.choice(legitword))
def legitgame (meh):
length = "__" * len(meh)
characters = []
mistake = 0
while mistake < 6 and length != meh:
print(hangman[mistake])
print(length)
print("Number of wrong guesses: ", mistake)
guess = (input("Guess:")).upper()
while len(guess) != 1:
print("You have inputted multiple letters. Please input a single letter.")
guess = input("Guess: ").upper()
while guess in invalid:
print("You have inputted an invalid character. Please try again.")
guess = input ("Guess: ").upper()
while guess in characters:
print("You have already inputted this letter. Please try again.")
guess= input("Guess: ").upper()
if guess in meh:
print()
print("Fantastic! You have entered a correct letter.")
characters.append(guess)
correct = ""
for x in range (0,len(meh)):
if guess == meh[x]:
correct += guess
else:
correct += length[x]
length = correct
else:
character.append(guess)
print("Sorry. You have inputted an incorrect letter. Please try again.")
mistake += 1
if mistake >= 6:
print(hangman[6])
print("The correct word is: ", meh)
print("Sorry. You killed the guy. Your conscience is chasing you.")
print("Game over")
elif correct == meh:
print("Congratulations! You saved the puny man.")
print("You have guessed ", word, "correctly!")
win()
Menu()
def win():
readHandle = open("Scores.txt", "a")
name = input("Enter your name: ")
readHandle.write(name + "\n")
readHandle.close
menu()
I can't tell for sure with the entire code, but from the given code I assume the error is that you call a(choice_category, choice_difficulty) before you have defined it. Put the def a(... before superword = a(choice_category, choice_difficulty), and you should be good to go (if this is indeed the problem)
"a" is apparently a function in your program as you have :
def a(choice_category, choice_difficulty)
This line defines 'a' as a function that requires 2 arguments (choice_category and choice_difficulty)
You need to define the function before you can use it
You program is calling/using the function with this line
superword = a(choice_category, choice_difficulty)
I have a dictionary object;
secret = {"word" : secretWord}
secretWord being an argument for a string with a single word inside. I also have a string generating an asterisk (*) for every character in the secretWord. In my code I have input from the user which gives a letter.
What I wish to accomplish is to check within the dictionary object secretWord, and if so, replace any asterisk with the input where relevant. However I am not sure how to then save this as a new argument, and then use the next input on the new argument.
Sorry if my question/problem isn't clear, as I am struggling how to word it.
What I want to happen:
for example the secretWord could be 'PRECEDENCE'
>>>
WORD : **********
Guess a letter: e
**E*E*E**E
Guess a letter: p
P*E*E*E**E
etc
What happens:
>>>
WORD : **********
Guess a letter: e
**E*E*E**E
Guess a letter: p
P*********
etc
My current Code:
import random
import sys
def diction(secretWord, lives):
global guess
global secret
secret = {"word" : secretWord, "lives" : lives}
guess = len(secret["word"]) * "*"
print (secret["word"])
print ("WORD: ", guess)
fileName = input("Please insert file name: ")
def wordGuessed(guess, secret):
if guess == secret["word"]:
print ("word is guessed")
if guess != secret["word"]:
print ("word is not guessed")
def livesLeft(inpu):
if inpu not in secret["word"]:
secret["lives"] = secret["lives"] - 1
print("Lives left: ", secret["lives"])
if inpu in secret["word"]:
print("Correct guess")
print(secret["lives"])
def guessCheck(inpu):
for char in secret["word"].lstrip():
if char == inpu:
print (char, end= "")
elif char != secret["word"]:
print ("*", end="")
try:
f = open(fileName)
content = f.readlines()
except IOError as e :
f = None
print("Failed to open", fileName, "- program aborted")
sys.exit()
Run = True
while Run == True:
levelIn = input("Enter difficulty (easy, intermediate or hard): ").lower()
if levelIn == ("easy"):
lives = 10
elif levelIn == ("intermediate"):
lives = 8
elif levelIn == ("hard"):
lives = 5
else:
print("Please input a valid difficulty.")
break
secretWord = (random.choice(content))
secretWord = secretWord.replace("\n", "")
diction(secretWord, lives)
wordGuessed(guess, secret)
while secret["lives"] > 0:
inpu = input("Guess a letter: ").upper()
livesLeft(inpu)
guessCheck(inpu)
if secret["lives"] == 0:
print ("You have no lives left – you have been hung!")
print ("The word was,", secret["word"])
You need to track the guesses made so far, and use those to display the word. Use a set to track what the player already guessed at:
guessed = set()
So that you can do:
if inpu in guessed:
print('You already tried that letter!')
else:
guessed.add(inpu)
whenever a user makes a guess.
You can then use that set to display the word revealed so far:
for char in secret["word"].lstrip():
if char in guessed:
print (char, end="")
else:
print ("*", end="")