I keep getting an EOF error when I try to run the code. I was wondering how I can fix this? Thanks in advance.When I try to remove if_name_ the program does not have any syntax errors but it does not run.
Here is a link that shows the error: codepad.org/d5p1Mgbb
def get_secret_word():
while True:
secret_word = input('Please enter a word to be guessed\nthat does not contain ? or whitespace:')
if not ('?' in secret_word or ' ' in secret_word or secret_word == '' ):
return secret_word
def is_game_over(wrong_guess,secret_word,output,chars_guessed):
if wrong_guess == 7:
print('You failed to guess the secret word:',secret_word)
return True
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '?'
if not('?' in output):
print('You correctly guessed the secret word:',secret_word)
return True
else:
return False
def display_hangman(wrong_guess):
if wrong_guess == 1:
print('\n |')
elif wrong_guess == 2:
print('\n |','\n 0')
elif wrong_guess == 3:
print('\n |','\n 0','\n |')
elif wrong_guess == 4:
print('\n |','\n 0','\n/|')
elif wrong_guess == 5:
print('\n |','\n 0','\n/|\\')
elif wrong_guess == 6:
print('\n |','\n 0', '\n/|\\','\n/')
elif wrong_guess == 7:
print('\n |','\n 0','\n/|\\','\n/','\\')
def display_guess(secret_word,chars_guessed):
print("")
output = ''
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '?'
if '?' in output:
output += '\nSo far you have guessed: '
for guess in chars_guessed:
output += guess + ","
print(output.strip(","))
def get_guess(secret_word,chars_guessed):
while True:
guess_letter = input('Please enter your next guess: ')
if guess_letter == '':
print('You must enter a guess.')
continue
elif len(guess_letter) > 1:
print('You can only guess a single character.')
elif guess_letter in chars_guessed:
print('You already guessed the character:',guess_letter)
else:
return guess_letter
def main():
wrong_guess = 0
chars_guessed = []
secret_word = get_secret_word()
output=''
while not(is_game_over(wrong_guess,secret_word,output,chars_guessed)):
display_hangman(wrong_guess)
display_guess(secret_word, chars_guessed)
guess_character = get_guess(secret_word, chars_guessed)
chars_guessed.join(guess_letter)
chars_guessed.sort()
if not guess_letter in secret_word:
wrong_guess += 1
return wrong_guess
pass
if __name__ == '__main__':
main()
A few things I found...
guess_character and guess_letter appear to be the same variable, but guess_letter is used before defined.
input allows for the entry of variable names or any block of python code. In order to use input as strings you must force input to string or (much easier) use raw_input
You were attemption to do a join operation on a list. This isn't possible. You can add an item to a list with append though.
So, here's the code with a few fixes. You'll have to fix the print loops but it should be better and get you past the earlier errors.
def get_secret_word():
while True:
secret_word = raw_input('Please enter a word to be guessed\nthat does not contain ? or whitespace:')
if not ('?' in secret_word or ' ' in secret_word or secret_word == '' ):
return secret_word
def is_game_over(wrong_guess,secret_word,output,chars_guessed):
if wrong_guess == 7:
print('You failed to guess the secret word:',secret_word)
return True
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '?'
if not('?' in output):
print('You correctly guessed the secret word:',secret_word)
return True
else:
return False
def display_hangman(wrong_guess):
if wrong_guess == 1:
print('\n |')
elif wrong_guess == 2:
print('\n |','\n 0')
elif wrong_guess == 3:
print('\n |','\n 0','\n |')
elif wrong_guess == 4:
print('\n |','\n 0','\n/|')
elif wrong_guess == 5:
print('\n |','\n 0','\n/|\\')
elif wrong_guess == 6:
print('\n |','\n 0', '\n/|\\','\n/')
elif wrong_guess == 7:
print('\n |','\n 0','\n/|\\','\n/','\\')
def display_guess(secret_word,chars_guessed):
print("")
output = ''
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '?'
if '?' in output:
output += '\nSo far you have guessed: '
for guess in chars_guessed:
output += guess + ","
print(output.strip(","))
def get_guess(secret_word,chars_guessed):
while True:
guess_letter = raw_input('Please enter your next guess: ')
if guess_letter == '':
print('You must enter a guess.')
continue
elif len(guess_letter) > 1:
print('You can only guess a single character.')
elif guess_letter in chars_guessed:
print('You already guessed the character:',guess_letter)
else:
return guess_letter
def main():
wrong_guess = 0
chars_guessed = []
secret_word = get_secret_word()
output=''
while not(is_game_over(wrong_guess,secret_word,output,chars_guessed)):
display_hangman(wrong_guess)
display_guess(secret_word, chars_guessed)
guess_character = get_guess(secret_word, chars_guessed)
chars_guessed.append(guess_character)
chars_guessed.sort()
if not guess_character in secret_word:
wrong_guess += 1
return wrong_guess
pass
if __name__ == '__main__':
main()
Related
My code keeps crashing after I put in the 1st guess I make. I've looked at syntax and dont think that's a problem how do I make it so it goes past the 1st guess and executes it. When I put the guess in it just puts in all the prompts at once, and how do I call the function properly at the end? Any help would be appreciated.
Import time,os,random
def get_int(message):
while True:
user_input = input(message)
try:
user_input = int(user_input)
print('Thats an integer!')
break
except:
print('That does not work we need an integer!')
return user_input
def game_loop():
fin = False
while not fin:
a = get_int('give me a lower bound:')
b = get_int('give me a upper bound:')
if a < 0:
print("that doesn't work")
if a > b:
a, b = b, a
print(a,b)
os.system('clear')
print("The number you guess has to be between " + str(a) + "and " + str(b) + '.')
num_guesses = 0
target = random.randint(a,b)
time_in = time.time()
while True:
print('You have guessed ' + str(num_guesses) + " times.")
print()
guess_input = get_int('guess a number')
if guess_input == target:
print("Congrats! You guessed the number!")
time_uin = time.time()
break
elif guess_input < a or guess_input > b:
print("guess was out of range... + 1 guess")
elif guess_input < target:
print("Your guess was too low")
else:
print("Your guess was to high")
num_guesses = num_guesses + 1
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
while True:
play_again = input ('Type y to play again or n to stop')
print()
if play_again == 'n':
fin = True
print('Thank God')
time.sleep(2)
os.system('clear')
break
elif play_again == 'y':
print('here we go again')
time.sleep(2)
os.system('clear')
break
else:
print('WRONG CHOCICE')
break
game_loop()
If guess_input != target on the first iteration of the loop, time_uin is referenced before assignment. Hence the error:
UnboundLocalError: local variable 'time_uin' referenced before assignment
Solution is to run the following only if guess_input == target.
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
Please follow coppereyecat's link to learn how to debug a basic Python program.
I am trying to make a small texted based game in which the player has to guess a word. If the secret word is water and the player guesses barge, the game should display -Ar-e, because those are the letters that are in common and since a is also in the correct place, it is shown as a capital letter.
from random import randint
def lingo():
fp = open("wordsEn.txt","r")
words = []
while True:
buffer = fp.readline()
if buffer == "":
break
else:
words.append(buffer[:-1])
secret_word = list(words[randint(0,len(words)-1)])
display_word = []
rand_num = randint(0,len(secret_word)-1)
compare_word = []
for i in range(len(secret_word)):
if i == rand_num:
display_word.append(secret_word[i])
compare_word.append(secret_word[i])
else:
display_word.append("-")
compare_word.append("-")
print(secret_word)
for i in range(5):
print(display_word)
print(compare_word)
if compare_word == secret_word:
break
else:
while True:
guess = input("guess: ")
if guess.isalpha() == False:
print("Only letters")
elif len(guess) > len(secret_word):
print("Too long")
elif len(guess) < len(secret_word):
print("Too short")
else:
break
for j in range(len(guess)):
print(guess[j])
print(guess[j] in secret_word)
if guess[j] in secret_word:
print("I am in")
if guess[j] == secret_word[j]:
display_word[j] == guess[j].upper()
compare_word[j] == guess[j]
else:
display_word[j] == guess[j]
else:
print("I am out")
continue
lingo()
I'm starting my studies in Python and I was assigned the Task to write code for a guessing game in which I have to control the total tries the player will have. I've described the functions, they're working (I believe...haha) but I can't make to "reset" the game when a wrong guess is input...
I wrote this:
guess_count = []
count_control = 1
def check_guess(letter,guess):
if guess.isalpha() == False:
print("Invalid!")
return False
elif guess.lower() < letter:
print("Low")
return False
elif guess.lower() > letter:
print("High")
return False
elif guess.lower() == letter:
print("Correct!")
return True
else:
print("anything")
def letter_guess(guess):
check_guess ('a',guess)
while len(guess_count) <= 3:
if check_guess == True:
return True
elif check_guess == False:
guess_count.append(count_control)
guess = input("Try again \n")
letter_guess(input("test: "))
UPDATE: I rewrote the code after some insights from other users and readings and came up with this:
class Game:
number_of_attempts = 3
no_more_attempts = "Game Over"
def attempt_down(self): #This will work as the counter of remaining lives.
self.number_of_attempts -= 1
print('Remaining Lives:',self.number_of_attempts)
def check_guess(self,letter):
"""
Requires
letter - a letter that has to be guessed
guess - a input from the user with the guessed letter
"""
while self.number_of_attempts > 0:
guess = input ("Guess the letter: ")
if guess.isalpha() == False:
print("Invalid!")
elif guess.lower() < letter:
self.attempt_down()
print("Low")
print("Try Again!")
elif guess.lower() > letter:
self.attempt_down()
print("High")
print("Try Again!")
elif guess.lower() == letter:
print("Correct!")
return True
print (self.no_more_attempts)
return False
game = Game()
"""
This is used to run the game.
Just insert the letter that
has to be guessed.
"""
teste1 = game.check_guess('g')
teste2 = game.check_guess('r')
The rub is in that you have a state of a game that you are tracking as global variables guess_count and count_control
This is an example of why python and other languages provide classes and objects:
class Game:
def __init__(self):
self.guess_count = []
self.count_control = 1
#staticmethod
def check_guess(letter, guess):
if guess.isalpha() == False:
print("Invalid!")
return False
elif guess.lower() < letter:
print("Low")
return False
elif guess.lower() > letter:
print("High")
return False
elif guess.lower() == letter:
print("Correct!")
return True
else:
print("anything")
def letter_guess(self, guess):
self.check_guess('a', guess)
while len(self.guess_count) <= 3:
if self.check_guess('a', guess) == True:
return True
elif self.check_guess('a', guess) == False:
self.guess_count.append(self.count_control)
guess = input("Try again \n")
game = Game()
game.letter_guess(input("test: "))
game = Game()
game.letter_guess(input("test: "))
I have to write a code in Python where it is about playing the game hangman. Currently my code cannot replace the "_" with the guessed letters properly, where it only replaces one and doesn't show all of the guessed letters.
My code is below:
import random
word = random.choice(["bread", "clouds", "plane"])
guess = 0
correct_guess = 0
play_again = True
print(word)
name = input("Hello, what's your name? ")
print('Hello', name)
status = input('Do you wish to play hangman? Yes/No ')
hyphens = print('_ ' * (len(word)))
if status == 'No' 'no' 'N' 'n':
exit()
while play_again is True:
letter = input('Guess a letter: ')
if letter in word:
guess = guess + 1
correct_guess = correct_guess + 1
print('You guessed a letter correctly!')
position = word.find(letter)
print("The letter is in position", position + 1, "out of", len(word), "in the word. Guess Count:", guess)
if position == 0:
print(letter, "_ _ _ _")
if position == 1:
print("_", letter, "_ _ _ ")
if position == 2:
print("_ _", letter, "_ _ ")
if position == 3:
print("_ _ _", letter, "_ ")
if position == 4:
print("_ _ _ _", letter)
else:
guess = guess + 1
print("That letter isn't in the word. Guess Count:", guess)
if guess == 10:
print('Bad luck. You lost.')
play = input('Do you want to play again? ')
if play == 'No' 'no' 'N' 'n':
exit()
if correct_guess == 5:
print('Congratulations! You have guessed the word! The word was', word + '.')
play = input('Do you want to play again? ')
if play == 'No' 'no' 'N' 'n':
exit()
Your help is very much appreciated. Also, I don't know a lot about programming and I am fairly new to it.
James
you can't write expression like :
if status == 'No' 'no' 'N' 'n':
the correct way is:
if play == 'No' or play == 'no' or play == 'N' or play == 'n':
or:
if play in ['No' ,'no', 'N' ,'n']
one solution:
import random
word = random.choice(["bread", "clouds", "plane"])
print(word)
name = input("Hello, what's your name? ")
print('Hello', name)
status = input('Do you wish to play hangman? Yes/No ')
def play():
if status == 'No' or status == 'no' or status == 'N' or status == 'n':
print ("Goodbye")
return # exit
else:
print('_ ' * (len(word))) # _ _ _ _ _
guess = 0
correct_guess = 0
play_again = True
pos_list = ['_' for x in range(len(word))] # define list where you will put your guessed letters ['_', '_', '_', '_', '_']
while play_again is True:
letter = input('Guess a letter: ')
if letter in word:
guess = guess + 1
correct_guess = correct_guess + 1
print('You guessed a letter correctly!')
position = word.find(letter)
print("The letter is in position", position + 1, "out of", len(word), "in the word. Guess Count:", guess)
pos_list[position] = letter # save letter at position # ['_', '_', '_', 'a', '_']
print (' '.join(pos_list)) # _ _ _ a _
else:
guess = guess + 1
print("That letter isn't in the word. Guess Count:", guess)
if guess == 10:
print('Bad luck. You lost.')
play = input('Do you want to play again? ')
if play == 'No' or play == 'no' or play == 'N' or play == 'n':
print("Goodbye")
return
else:
print('_ ' * (len(word)))
if correct_guess == len(word):
print('Congratulations! You have guessed the word! The word was', word + '.')
play = input('Do you want to play again? ')
if play == 'No' or play == 'no' or play == 'N' or play == 'n':
print("Goodbye")
return
else:
print('_ ' * (len(word)))
play()
Cleaned it up a bit, removing duplicated code. Also that problematic condition:
if status == 'No' 'no' 'N' 'n':
Changed it to:
if status.lower().startswith("n"):
Also important to lower the letter input by the user. Here a full working code.
import random
import re
def start():
status = input('Do you wish to play hangman? Yes/No ')
if status.lower().startswith("n"):
return True
# Computer chooses word
word = random.choice(["bread", "clouds", "plane"])
# Setup game vars
guess = []
game_status = ["_"] * len(word)
while True:
print(" ".join(game_status))
letter = input('Guess a letter: ').lower()
if letter in guess:
print("You already tried that one.")
continue
guess.append(letter)
if letter in word:
print('You guessed a letter correctly!')
positions = [m.start() for m in re.finditer(letter, word)]
for pos in positions:
game_status[pos] = letter
else:
print("That letter isn't in the word.")
if len(guess) == 10:
print(f'Bad luck {name}. You lost. The word was: {word}.')
return
if "_" not in game_status:
print(f'Congratulations {name}! You have guessed the word! The word was {word}.')
return
# Welcome
name = input("Hello, what's your name? ")
print('Hello', name)
while True:
stop = start()
if stop:
break
print("Goodbye!")
When I try to run the code it keeps repeating,"So far you have guessed" when I only want it to repeat once. The output for the name when a guess is made should be like : secret_word = hello , then after every word it should be h???o or h?ll?
def get_secret_word():
while True:
secret_word = input('Please enter a word to be guessed\nthat does not contain ? or whitespace:')
if not ('?' in secret_word or ' ' in secret_word or secret_word == ''):
return secret_word
def is_game_over(wrong_guess, secret_word, output, chars_guessed):
if wrong_guess == 7:
print('You failed to guess the secret word:', secret_word)
return True
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '?'
if not ('?' in output):
print('You correctly guessed the secret word:', secret_word)
return True
else:
return False
def display_hangman(wrong_guess):
if wrong_guess == 1:
print('\n |')
elif wrong_guess == 2:
print('\n |', '\n O')
elif wrong_guess == 3:
print('\n |', '\n O', '\n |')
elif wrong_guess == 4:
print('\n |', '\n O', '\n/|')
elif wrong_guess == 5:
print('\n |', '\n O', '\n/|\\')
elif wrong_guess == 6:
print('\n |', '\n O', '\n/|\\', '\n/')
elif wrong_guess == 7:
print('\n |', '\n O', '\n/|\\', '\n/', '\\')
def display_guess(secret_word, chars_guessed):
output = ''
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '\nSo far you have guessed: '
for guess in chars_guessed:
output += guess + ","
print(output.strip(","))
def get_guess(secret_word, chars_guessed):
while True:
guess_character = input('Please enter your next guess: ')
if guess_character == '':
print('You must enter a guess.')
continue
elif len(guess_character) > 1:
print('You can only guess a single character.')
elif guess_character in chars_guessed:
print('You already guessed the character:', guess_character)
else:
return guess_character
def main():
wrong_guess = 0
chars_guessed = []
secret_word = get_secret_word()
output = ''
while not is_game_over(wrong_guess, secret_word, output, chars_guessed):
display_hangman(wrong_guess)
display_guess(secret_word, chars_guessed)
guess_character = get_guess(secret_word, chars_guessed)
chars_guessed.append(guess_character)
chars_guessed.sort()
if not guess_character in secret_word:
wrong_guess += 1
return wrong_guess
pass
if __name__ == '__main__':
main()
so issues that I can see are:
indentation issues(as pointed out by some of the other posters already):
- get_secret_word() function with the if statement
- display_hangman() function with all the elif's
also with the below bit of code from the main function
if not guess_character in secret_word:
wrong_guess += 1
return wrong_guess
pass
this exits out of the app for me and as far as I can see the return and pass lines are not needed. The return exits from the main function when an incorrect guess is made and so pass is never reached and since the wrong_guess is a "global" variable in the main function the new count is available to everything in that function for the length of time that the function is active.
as for the repeated looping with displaying the users guesses it is the way in how you are looping in the display_guess() function. in the case that the character being guessed is not in the secret word it loops over everything twice, once for the outer for loop and then again for the inner loop.
I think you should change the display_guess() to something like the below. this way a user will always see what they have previously guessed
def display_guess():
output = "\nSo far you have guessed: "
count = 0
if len(chars_guessed) > 0:
for guess in chars_guessed:
if count < len(chars_guessed) and count != 0:
output += ','
output += guess
count +=1
print output
as for displaying the secret word with the guessed characters and the rest as ?'s, it doesn't seem that you are printing the value of the output variable from the is_game_over() function anywhere. i haven't tested it but adding a print just after that for loop should sort that out.
on a side note you might wish to add validation on user input as it excepts numbers and special characters