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()
Related
I am trying to make a game where the user inputs a word with only three guesses available, but instead it keeps allowing four guesses which I don't want.
When i input a word and my guess_count reaches 3, i am supposed to be sent this msg "You have no more guesses, you lose!" then ask if i want to retry but instead it lets me play one more time thereby exceeding the guess_limit
Here is my code
secret_word = "loading"
guess_word = ""
guess_count = 0
guess_limit = 3
end = False
print("Welcome to the guessing game\nYou have 3 guesses")
guess_word = input("Enter a word: ")
def end_msg(msg):
print(msg)
retry = input("Do you want to play again? ")
if (retry == "yes") :
global end, guess_word, guess_count
end = False
guess_word = ""
guess_count = 0
print("Welcome to the guessing game\\nYou have 3 guesses")
guess_word = input("Enter a word: ")
else:
end = True
while (not(end)) :
if (guess_word != secret_word and guess_count \< guess_limit):
guess_count += 1
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_word = input("Try again: ")
elif (guess_count == 3):
end_msg("You have no more guesses, you lose!")
else:
end_msg("Correct, you win")
I see your query already answered above, In case you want I have adapted your code to make it more organized and structured into two functions
playagain - which asks after winning/losing if the user wants to play the game again
play - the actual program to play the game
I removed some redundancies like end = False variable you used and could have also removed some other variables like guess_limiter (by just assigning the guess limit value in the actual program) but I wanted to retain your code as much as possible in case for your understanding, hope this helps
def playagain():
play_again = input("Do you want to play again? (y/n) ")
if play_again == 'y':
return play()
elif play_again == 'n':
print("Thank you for playing")
else:
print("incorrect input please try again")
playagain()
def play():
secret_word = "loading"
guess_word = ""
guess_count = 1
guess_limit = 3
print("Welcome to the guessing game\nYou have 3 guesses")
while (guess_count != guess_limit + 1):
guess_word = input("Enter a word: ")
if guess_word == secret_word:
print("Correct, you win")
playagain()
break
elif guess_count == guess_limit:
print("You have no more guesses, you lose!")
playagain()
break
else:
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_count += 1
play()
You are getting this bug because you wrote guess_limit = 3. You know Programs count from 0, so you need to enter 1 less from your desire try. It should be guess_limit = 2.
And also you wrote elif (guess_count == 3) :, thats mean if guess_count == 3 your will get "You have no more guesses, you lose!" even, user put the right answer. so it should be
elif (guess_word != secret_word and guess_count == 2):
so your final code should be:
secret_word = "loading"
guess_word = ""
guess_count = 0
guess_limit = 2
end = False
print("Welcome to the guessing game\nYou have 3 guesses")
guess_word = input("Enter a word: ")
def end_msg (msg) :
print(msg)
retry = input("Do you want to play again? ")
if (retry == "yes") :
global end, guess_word, guess_count
end = False
guess_word = ""
guess_count = 0
print("Welcome to the guessing game\\nYou have 3 guesses")
guess_word = input("Enter a word: ")
else:
end = True
while (not(end)) :
if (guess_word != secret_word and guess_count < guess_limit) :
guess_count += 1
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_word = input("Try again: ")
elif (guess_word != secret_word and guess_count == 2) :
end_msg("You have no more guesses, you lose!")
else:
end_msg("Correct, you win")
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 can't figure out why my while loop won't break to finish the hangman program. I've included the whole program to give you some context. It will print the game over message, but not the win message
import random
import os
import time
def playGame():
wordList = ["dog", "bird", "chair", "computer", "elephant", "school"]
letterList=[]
underscoreList=[]
guessesLeft = 6
word = random.choice(wordList)
#print(word)
for letter in word:
letterList.append(letter)
underscoreList.append("_")
#print(letterList)
#print(underscoreList)
while guessesLeft > 0:
#os.system('clear') #clears screen
print(underscoreList)
print("You Have" , guessesLeft, "Guesses Remaining")
userGuess = (input("Please enter a letter... \n>")).lower()
if len(userGuess) != 1 or not userGuess.isalpha():
print("Please Enter A Single Letter Only")
time.sleep(1)
elif userGuess in letterList:
print(userGuess, "is there")
time.sleep(1)
for position, letter in enumerate(letterList):
if letter == userGuess:
underscoreList[position] = userGuess
elif '_' not in underscoreList:
break
else:
print("Not In Word")
time.sleep(2)
guessesLeft -= 1
if guessesLeft > 0:
print("Congratulations you have guessed the word " , word)
else:
print("You Loser")
playGame()
Just have to move the elif to the beginning of the code. So now it checks before continuing the program.
import random
import os
import time
def playGame():
wordList = ["dog", "bird", "chair", "computer", "elephant", "school"]
letterList=[]
underscoreList=[]
guessesLeft = 6
word = random.choice(wordList)
#print(word)
for letter in word:
letterList.append(letter)
underscoreList.append("_")
#print(letterList)
#print(underscoreList)
while guessesLeft > 0:
#os.system('clear') #clears screen
if '_' not in underscoreList:
break
print(underscoreList)
print("You Have" , guessesLeft, "Guesses Remaining")
userGuess = (input("Please enter a letter... \n>")).lower()
if len(userGuess) != 1 or not userGuess.isalpha():
print("Please Enter A Single Letter Only")
time.sleep(1)
elif userGuess in letterList:
print(userGuess, "is there")
time.sleep(1)
for position, letter in enumerate(letterList):
if letter == userGuess:
underscoreList[position] = userGuess
else:
print("Not In Word")
time.sleep(2)
guessesLeft -= 1
if guessesLeft > 0:
print("Congratulations you have guessed the word " , word)
else:
print("You Loser")
playGame()
What I am trying to do is to read a text file from a user and then run the game with that particular file. I know that it will be more easier to have functions but I don't know how to modify the whole code with functions.
How can I run the game with that text file inputted by user?
import random
import sys
choice = None
while choice != "0":
print('''
--------------------
Welcome to Hangman
--------------------
Please select a menu option:
0 - Exit
1 - Enter a new text file to be read:
2 - Play Game
''')
choice= input("Enter you choice: ")
if choice == "0":
sys.exit("Exiting from Python")
elif choice =="1":
newIn = []
fileInput = input("Enter a new text file name: ")
newIn = open(fileInput).readlines()
newIn=List
elif choice == "2":
List = open("words_for_hangman.txt").readlines()
print('''
Now select your difficulty level:
0 - EASY
1 - INTERMEDIATE
2 - HARD
''')
level= input("Enter your choice: ")
if level == "0":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 10
guessed = []
elif level == "1":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 7
guessed = []
elif level == "2":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 5
guessed = []
while lives != 0 and hidden_word != word:
print("\n-------------------------------")
print("The word is")
print(hidden_word.replace("_"," _ "))
print("\nThere are", len(word), "letters in this word")
print("So far the letters you have guessed are: ")
print(' '.join(guessed))
print("\n You have", lives,"lives remaining")
guess = input("\n Guess a letter: \n")
guess = guess.upper()
if len(guess) > 1:
guess = input("\n You can only guess one letter at a time!\n Try again: ")
guess = guess.upper()
elif guess== " ":
guess = input("\n You need to input a letter, not a space!\n Come on let's try again: ")
guess = guess.upper()
while guess in guessed:
print("\n You have already guessed that letter!")
guess = input("\n Please take another guess: ")
guess = guess.upper()
guessed.append(guess)
if guess in word:
print('''-------------------------------
''')
print("Well done!", guess.upper(),"is in the word")
word_so_far = ""
for i in range (len(word)):
if guess == str(word[i]):
word_so_far += guess
else:
word_so_far += hidden_word[i]
hidden_word = word_so_far
else:
print('''-------------------------------
''')
print("Sorry, but", guess, "is not in the word")
lives -= 1
if lives == 0:
print("GAME OVER! You have no lives left")
else:
print("\n CONGRATULATIONS! You have guessed the word")
print("The word was", word)
print("\nThank you for playing Hangman")
else:
choice = print("\n That is not a valid option! Please try again!")
choice = input("Choice: ")
At first sight, there are two mistakes in the program
The lines
newIn = open(fileInput).readlines()
newIn=List
first read the file into the variable newIn and then remove the content of newIn by setting it to the content of List. I guess you wanted to do
List = open(fileInput).readlines()
as you did in the second part.
The second mistake is that the whole game is played only when the user presses 2. Try moving the whole block beginning with
while lives != 0 and hidden_word != word:
to the left, so that block is entered either when the user presses 1 or 2. Also, if you do this, the else at the end of the program should go right before the while lives != 0...
First keep all your files in a folder and run this file..
For choice 1: Give your new.txt file or try with same file of option two.(words_for_hangman.txt) but it will be easy for your if you keep all your files in same folder.
import random
import sys
choice = None
while choice != "0":
print('''
--------------------
Welcome to Hangman
--------------------
Please select a menu option:
0 - Exit
1 - Enter a new text file to be read:
2 - Play Game
''')
choice= input("Enter you choice: ")
if choice == "0":
sys.exit("Exiting from Python")
elif choice =="1":
newIn = []
fileInput = input("Enter a new text file name: ")
newIn = open(fileInput).readlines()
newIn=List
elif choice == "2":
List = open("words_for_hangman.txt").readlines()
print('''
Now select your difficulty level:
0 - EASY
1 - INTERMEDIATE
2 - HARD
''')
level= input("Enter your choice: ")
if level == "0":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 10
guessed = []
elif level == "1":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 7
guessed = []
elif level == "2":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 5
guessed = []
while lives != 0 and hidden_word != word:
print("\n-------------------------------")
print("The word is")
print(hidden_word.replace("_"," _ "))
print("\nThere are", len(word), "letters in this word")
print("So far the letters you have guessed are: ")
print(' '.join(guessed))
print("\n You have", lives,"lives remaining")
guess = input("\n Guess a letter: \n")
guess = guess.upper()
if len(guess) > 1:
guess = input("\n You can only guess one letter at a time!\n Try again: ")
guess = guess.upper()
elif guess== " ":
guess = input("\n You need to input a letter, not a space!\n Come on let's try again: ")
guess = guess.upper()
while guess in guessed:
print("\n You have already guessed that letter!")
guess = input("\n Please take another guess: ")
guess = guess.upper()
guessed.append(guess)
if guess in word:
print('''-------------------------------
''')
print("Well done!", guess.upper(),"is in the word")
word_so_far = ""
for i in range (len(word)):
if guess == str(word[i]):
word_so_far += guess
else:
word_so_far += hidden_word[i]
hidden_word = word_so_far
else:
print('''-------------------------------
''')
print("Sorry, but", guess, "is not in the word")
lives -= 1
if lives == 0:
print("GAME OVER! You have no lives left")
else:
print("\n CONGRATULATIONS! You have guessed the word")
print("The word was", word)
print("\nThank you for playing Hangman")
else:
choice = print("\n That is not a valid option! Please try again!")
choice = input("Choice: ")
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()