My text file have words one per line like "CLASS", then to another line "PYTHON" and so on. Supposed my random word is "CLASS", instead of "*****" i get "******" with one more "*". I really don't know why ...
import random
import sys
choice = None
List = open("words_for_hangman.txt").readlines()
while choice != "0":
print('''
--------------------
Welcome to Hangman
--------------------
Please select a menu option:
0 - Exit
1 - Enter a new list of words
2 - Play Game
''')
choice= input("Enter you choice: ")
if choice == "0":
sys.exit("Exiting from Python")
elif choice =="1":
list = []
x = 0
while x != 5:
word = str(input("Enter a new word to put in the list: "))
list.append(word)
word = word.upper()
x += 1
elif choice == "2":
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.upper()
hidden_word = "*" * len(word)
lives = 10
guessed = []
elif level == "1":
word = random.choice(List)
#word = word.upper()
hidden_word = "*" * len(word)
lives = 7
guessed = []
elif level == "2":
word = random.choice(List)
#word = word.upper()
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: ")
You likely have a newline character trailing each word read from a text file, e.g.
'CLASS\n'
To remove this extra character you can use strip
word = word.strip()
Related
enter image description herei want to find out how
i can take in user’s inputs on the number of times user wishes to run/play, and execute accordingly. and also how can i provide user with an option on the game/run mode
allow the user to choose the complexity level of a game?
include a scoreboard that shows the top 5 players/scores.
[enter image description here](https://i.stack.enter image description hereimgur.com/CcJOM.png)
from IPython.display import clear_output
import random
NUMBER_OF_PICKS = 3
MINIMUM_SELECTION = 1
MAXIMUM_SELECTION = 36
#Input for the word by game master
user = input("Please enter your name:")
print("Hi " + user + " good luck ")
no_of_time = input("How many times do you want to play: ")
answer_word = list(str.lower(input("input enter your word: "))) #https://stackoverflow.com/questions/1228299/change-one-character-in-a-string
clear_output()
win = False
#defining function
def guesscheck(guess,answer,guess_no):
clear_output()
if len(guess)==1:
if guess in answer:
print("Correct, ",guess," is a right letter")
return True
else:
print("Incorrect, ",guess, " is a not a correct letter. That was your chance number ",guess_no)
return False
else:
print("Enter only one letter")
#Storing the number of characters in different variable
answer_display=[]
for each in answer_word:
answer_display += ["*"]
print(answer_display)
#initializing number of allowable guesses
guess_no = 1
while guess_no<5:
clear_output
#Player input for guess letter
guess_letter=str.lower(input('Enter your guess letter: '))
#Calling a sub function to check if correct letter was guessed
guess_check=guesscheck(guess_letter,answer_word,guess_no);
#Conditional: if incorrect letter
if guess_check == False:
guess_no +=1
print(answer_display)
#Conditional: if correct letter
elif guess_check == True:
num = [i for i, x in enumerate(answer_word) if x == guess_letter] #https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list
for all in num:
answer_display[all]=guess_letter
print(answer_display)
#Conditional: if no remaining unknown letter then win screen
if answer_display.count('*')==0:
win = True
break
if win:
print("You won!")
else:
print("The correct answer was: ", answer_word)
print("You lost!")
To install random_words package in jupyter notebook.
run this command in code shell.
!pip install random_word
import package. from random_word import RandomWords
generate.
r = RandomWords()
print(r.get_random_word())
Code snippet:
import random
from random_word import RandomWords
# Input for the word by game master
user = input("Please enter your name:")
print("Hi " + user + " good luck ")
while True:
try:
no_of_time = int(input("How many times do you want to play: "))
played_time = no_of_time
break
except ValueError:
print("Please enter a number. specify in number how many time you want to play.")
r=RandomWords()
scorecard = 0
# defining function
def guesscheck(guess, answer, guess_no):
if len(guess) == 1:
if guess in answer:
print("Correct, ", guess, " is a right letter")
return True
else:
print("Incorrect, ", guess, " is a not a correct letter. That was your chance number ", guess_no)
return False
else:
print("Enter only one letter")
while no_of_time:
while True:
try:
difficulty_level = int(input(
"Enter the difficulty you want to play: press [1] for easy, press [2] for medium, press [3] for hard, press [4] for manually word"))
if difficulty_level in [1, 2, 3, 4]:
break
else:
print("Enter number 1 or 2 or 3 or 4 not other than that!!")
continue
except ValueError:
print("Please enter difficulty level specific.")
answer_word = ""
if difficulty_level == 1:
while len(answer_word)!=5:
answer_word = r.get_random_word()
elif difficulty_level == 2:
while len(answer_word)!=6:
answer_word = r.get_random_word()
elif difficulty_level == 3:
while len(answer_word)!=10:
answer_word = r.get_random_word()
else:
answer_word=input("Enter manually what word you wanted to set..!")
win = False
# Storing the number of characters in different variable
answer_display = []
for each in answer_word:
answer_display += ["*"]
print(answer_display)
# initializing number of allowable guesses
guess_no = 1
while guess_no <= 5: # User chances given 5
# Player input for guess letter
guess_letter = str.lower(input('Enter your guess letter: '))
# Calling a sub function to check if correct letter was guessed
guess_check = guesscheck(guess_letter, answer_word, guess_no)
# Conditional: if incorrect letter
if guess_check == False:
guess_no += 1
print(answer_display)
# Conditional: if correct letter
elif guess_check == True:
num = [i for i, x in enumerate(answer_word) if
x == guess_letter] # https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list
for all in num:
answer_display[all] = guess_letter
print(answer_display)
# Conditional: if no remaining unknown letter then win screen
if answer_display.count('*') == 0:
win = True
break
if win:
print("You won!")
scorecard += 1
else:
print("The correct answer was: ", answer_word)
print("You lost!")
no_of_time -= 1
print("You played " + str(played_time) + ":")
print("Won: " + str(scorecard) + " Guessed correctly!!")
print("Lose: " + str(played_time - scorecard) + "not Guessed correctly!!")
don't know why specific length is not working in random_word hence included while statement.. this code snippet is working you can go through this..!
import random
from typing import List
words = [ 'apple', 'tree', 'python', 'bench', 'float' ]
word = random.choice(words)
guesses= []
letter_storage = []
f = "Do you want to play?"
a = ["yes","no"]
max_fails = []
def print_word_to_guess(letters: List):
print("{0}".format(" ".join(letters))) # need to display _ _ _ _ instead of ['_', '_', '_', '_', '_']
def input_choice(f:str,a:list[str])->str:
if f in a:
if f == "yes":
a = "yes"
elif f == "no":
print("ok no")
elif f not in a:
while f not in a:
f = input("Invalid answer. Try again")
if f in a:
if f == "yes":
a = "yes"
elif f == "no":
print("ok no")
def shape(word:str,guesses:str)->str:
for letter in word:
guesses.append("_ ")
def hangman(word:str,max_fails:int):
max_fails = int(input("Number of allowed mistakes: "))
while max_fails> 0:
guess = input("make a guess:")
if guess in letter_storage:
print("mistakes left:",max_fails,",you already guessed that letter!")
else:
letter_storage.append(guess)
if guess in word :
for x in range(0, len(word)):
if word[x] == guess:
guesses[x] = guess
print_word_to_guess(guesses)
if not '_ ' in guesses:
print("You won!","The word was:",word)
break
else:
max_fails -= 1
print(max_fails,"mistakes left")
if max_fails == 0:
print("You lost :( The word was",word)
input_choice(input("Do you want to play? [yes / no]"),("yes","no"))
shape(word,guesses)
hangman(word,max_fails)
Here is my little hangman game.
The code recognizes that the multiple letters are in the word but it doesnt add them to the spaces.
I would like that multiple letters are also accepted so when you already guessed app u can also add le
to finish the game. How can I implement this into my code ?
You can save the guess to a variable guess_str, then loop through all the letters of the guess with for guess in guess_str and run your code logic again:
def hangman(word: str, max_fails: int):
max_fails = int(input("Number of allowed mistakes: "))
while max_fails > 0:
guess_str = input("make a guess:")
for guess in guess_str:
if guess in letter_storage:
print("mistakes left:", max_fails, ",you already guessed that letter!")
else:
letter_storage.append(guess)
if guess in word:
for x in range(0, len(word)):
if word[x] == guess:
guesses[x] = guess
print_word_to_guess(guesses)
if not "_ " in guesses:
print("You won!", "The word was:", word)
break
else:
max_fails -= 1
print(max_fails, "mistakes left")
if max_fails == 0:
print("You lost :( The word was", word)
There is one small problem with my code , after I get all the letters correct, I had to enter another letter only it will show that I got it right. What is the problem?
import random
import string
import sys
def split(word):
return list(word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
list(alphabet)
words = ['hat','pop' ,'cut' , 'soup' , 'you' , 'me' , 'gay' , 'lol' ]
guess_word = []
wrong_letters_storage = []
secret_word = random.choice(words)
word_length = print("the length of the word is " + str(len(secret_word)))
correct_letters = split(secret_word)
def words():
for letter in secret_word:
guess_word.append("-")
return print("the words that you are guessing is " + str(guess_word))
def guessing():
while True:
c = 0
b = 7
while c <= 7:
print("")
hide = ""
print("you have " + str(b) + " guess left")
print("Wrong letters : " + str(wrong_letters_storage))
command = input("guess: ").lower()
if not '-' in guess_word:
print("you win!")
break
elif command == 'quit':
print("thank you for playing my game")
break
else:
if not command in alphabet :
print("pick an alphabet")
elif command in wrong_letters_storage:
print("you have picked this word")
else :
if command in secret_word :
print("right")
c += 1
b -= 1
for x in range(0, len(secret_word)):
if correct_letters[x] == command:
guess_word[x] = command
print(guess_word)
elif not command in secret_word :
print("wrong")
wrong_letters_storage.append(command)
c += 1
b -= 1
else :
print("error")
print("*"*20)
return print("Thank you for playing my game")
words()
guessing()
print("the words that you are guessing is " + secret_word )
Your code has several "problems":
you check if the current solution has no more '-' in it, after you ask for the next character input()
return print("whatever") returns None because the print function prints and returns None
you use variables with single_letter_names that make it hard to know what they are for
you use list's instead of set()'s for lookups (its fine here, but not optimal)
You can fix your problem by moving the test statement before the input() command:
# your code up to here
while True:
c = 0
b = 7
while c <= 7:
if not '-' in guess_word:
print("you win!")
break
print("")
hide = ""
print("you have " + str(b) + " guess left")
print("Wrong letters : " + str(wrong_letters_storage))
command = input("guess: ").lower()
if command == 'quit':
print("thank you for playing my game")
break
else:
# etc.
It would probably be better to do some more refaktoring:
import random
import string
import sys
def join_list(l):
return ''.join(l)
def guessing():
# no need to put all this in global scope
alphabet = frozenset(string.ascii_lowercase) # unchangeable set of allowed letters
words = ['hat', 'pop', 'cut', 'soup', 'you', 'me', 'beautiful', 'lol']
secret = random.choice(words) # your random word
secret_word = list(secret.lower()) # your random word as lowercase list
wrong = set() # set of wrongly guessed characters
right = set() # set of already correctly guessed characters
correct = frozenset(secret_word) # set of letters in your word, not changeable
guess_word = ['-' for k in correct] # your guessed letters in a list
guesses = 7
guessed = 0
print("The length of the word is ", len(secret))
# loop until breaked from (either by guessing correctly or having no more guesses)
while True:
print("")
print(f"you have {guesses-guessed} guess left")
if wrong: # only print if wrong letters guessed
print(f"Wrong letters : {wrong}")
# print whats know currently:
print(f"Guess so far: {join_list(guess_word)}")
command = input("guess: ").strip().lower()
try:
if command != "quit":
command = command[0]
except IndexError:
print("Input one letter")
continue
if command == 'quit':
print("thank you for playing my game")
break
else:
if command not in alphabet:
print("pick an alphabet")
continue
elif command in (wrong | right):
print("you already picked this letter")
continue
else :
guessed += 1
# always lookup in set of lowercase letters
if command in correct:
right.add(command)
for i,letter in enumerate(secret_word):
if command == letter:
# use the correct capitalisation from original word
guess_word[i] = secret[i]
else:
print("wrong")
wrong.add(command)
print("*"*20)
# break conditions for win or loose
if join_list(secret_word) == join_list(guess_word):
print("You won.")
break
elif guessed == guesses:
print(f"You lost. Word was: {join_list(secret_word)}")
break
guessing()
Currently this is my code, but i don't know how to integrate the lives concept into my hangman game. When it is Game Over (0 lives), i want the game to end even if they didn't figure out the word after 7 attempts.
master = input("Enter a word: ")
print("\n"* 50 )
word = list(master)
length = len(word)
right = list("_" * length)
finished = False
while finished == False:
guess = input("Guess a letter!")
if guess not in master:
print("This letter is not in the word.")
for letter in word:
if letter == guess:
index = word.index(guess)
right[index] = guess
word[index] = "_"
print(right)
if list(master) == right:
print("You win!")
again = input("Again? y/n ")
if again == "y" or "Y":
master = input("Enter a word: ")
print("\n" * 50)
word = list(master)
length = len(word)
right = list("_" * length)
else:
finished = True
You have to initialize a variable with the number of wrong tries allowed and decrement it by 1 every time a wrong entry has been made. Finally check if the number of tries have finished(ie. 0) before continuing the loop.
master = input("Enter a word: ")
print("\n"* 50 )
word = list(master)
length = len(word)
right = list("_" * length)
tries=7
finished = False
while finished == False:
guess = input("Guess a letter!")
if guess not in master:
print("This letter is not in the word.")
tries-=1
print(tries," tries left")
for letter in word:
if letter == guess:
index = word.index(guess)
right[index] = guess
word[index] = "_"
print(right)
if list(master) == right:
print("You win!")
again = input("Again? y/n ")
if again == "y" or "Y":
master = input("Enter a word: ")
print("\n" * 50)
word = list(master)
length = len(word)
right = list("_" * length)
else:
finished = True
elif tries == 0:
print("Game Over!")
finished = True
i am wondering whether there is other way to solve my situation(replace user input(guessword) into dashes string(words) in my Hangman Game than to use global. My previous posts for the game: How to replace the repeat word in python (Hangman Game)! and How do i detect the repeat input in my hangman game (Python)! and here is my code:
code from beginning:
def writeCustomwords():
f = open('custom.txt', 'w')
words = input("Enter a list of comma separated words:")
print("Custom words save into custom.txt")
f.write(words)
f.close()
def readFileWords():
if choose == "1":
txt = open('easy.txt', 'r')
txt.read()
txt.close()
elif choose == "2":
txt = open('intermediate.txt', 'r')
txt.read()
txt.close()
elif choose == "3":
txt = open('hard.txt', 'r')
txt.read()
txt.close()
elif choose == "4":
txt = open('custom.txt', 'r')
txt.read()
txt.close()
import random
def getRandomWord():
if choose == "1":
with open('easy.txt') as txt:
word = txt.read().splitlines()
random_word = random.choice(word)
print(random_word)
print("\nThere are", len(random_word),"letters in this word")
elif choose == "2":
with open('intermediate.txt') as txt:
word = txt.read().splitlines()
random_word = random.choice(word)
print("\nThere are", len(random_word),"letters in this word")
elif choose == "3":
with open('hard.txt') as txt:
word = txt.read().splitlines()
random_word = random.choice(word)
print("\nThere are", len(random_word),"letters in this word")
elif choose == "4":
with open('custom.txt') as txt:
word = txt.read().split(",")
random_word = random.choice(word)
print(random_word)
print("\nThere are", len(random_word)-random_word.count(" "),"letters in this word")
return random_word
def gethiddenWord():
import re
guess = getRandomWord().lower()
guessed = re.sub(r"\S", "-", guess)
print("\n\t\t\t-----------------------------------------------")
print("\t\t\tRULES")
print("\t\t\t-----------------------------------------------")
print("\n\t\t\tPlease Guess one letter(a-z) at a time!")
print("\n\t\t\tIf you want to guess the word, please enter '0'")
print("\n\nThe word is : ",guessed)
return guess,guessed
def checkValidGuess():
if len(guessword)==1 and guessword not in guesslist and guessword not in num:
return True
elif guessword in guesslist:
print("You have already guessed that letter")
elif guessword in num:
print("You can only input letter a-z")
print("Try again")
elif len(guessword) >1:
print("You can only guess one letter at a time!")
print("Try again")
def checkPlayerWord():
if guessall == word:
return True
else:
return False
return checkp
def checkLetterInWords():
if guessword.lower() in word:
return True
elif guessword.lower() not in word and guessword.lower() not in num:
return False
def gethiddenWord():
import re
guess = getRandomWord().lower()
guessed = re.sub(r"\S", "-", guess)
print("\n\t\t\t-----------------------------------------------")
print("\t\t\tRULES")
print("\t\t\t-----------------------------------------------")
print("\n\t\t\tPlease Guess one letter(a-z) at a time!")
print("\n\t\t\tIf you want to guess the word, please enter '0'")
print("\n\nThe word is : ",guessed)
return guess,guessed
my problem is here:
def getGuessedWord():
global words
for pos,l in enumerate(word):
if l==guessword.lower():
words= words[:pos] + guessword.lower() +words[pos+1:]
print(words)
return words
And outside the function
word,words = gethiddenWord()
my further code to access function:
choose = input("Enter your choice:")
readFileWords()
time =10
word,words = gethiddenWord()
count = len(word)-word.count(" ")
guesslist=[]
while time !=0 and word:
print("You have", time, "guesses left.")
guessword = input("Guess a letter or enter '0''to guess the word: ")
num = ["1","2","3","4","5","6","7","8","9"]
valid = checkValidGuess()
guesslist.append(guessword.lower())
if guessword =="0":
guessall = input("What is the word: ")
checkp = checkPlayerWord()
del guesslist[0]
if checkp == True:
print("Well done! You got the word correct!")
break
elif checkp == False:
print("Uh oh! That is not the word!")
time -=1
elif valid== True:
checkl= checkLetterInWords()
if checkl == True:
time -=1
print("Well done!",guessword,"is in my word")
count -= word.count(guessword)
getGuessedWord()
countfinish = checkFinish()
if countfinish == True:
break
else:
continue
elif checkl == False:
time -=1
print("Uh oh! That letter is not in my word!")
If without global, i cannot solve it. Please help! Thanks