Debugging a "guess the word " game - python

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()

Related

Find out how i can improve my Hangman coding on jupyter notebook

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..!

Putting guessed letters instead of dashes / Hangman / Python

i made hangman and am using this code. everything works fine, i just want to replace dashes in the list [lenghtDashes] with the correctly guessed letter in the corresponding place. i could not find any information online or here as well. maybe someone knows.
im open to any improvement suggestions as well.
secWord = input("What is the word for others to guess?: ")
life = 10
#starting information
i = 1
while i < 10:
print(".")
i += 0.01
#dots so players can not see the word
print("you have 10 tries to guess the word")
print("you will have to choose between gessing a letter (l) or a word (w) in start of every turn")
print("however, if you guess the word incorrectly you will lose immediately")
ans = input("are you ready to begin?: ")
while ans != "yes":
ans = input("now? ")
#rules
i = 1
while i < 10:
print(".")
i += 0.01
#dots for taking players to start
lenghtDashes = []
for letter in range(len(secWord)):
lenghtDashes.append("_")
#making dashes list
print("let's begin")
print("the word has " + str(len(secWord)) + " letters.")
appended = "".join(lenghtDashes)
print(appended)
#info for players
usedLetters = []
guessedLetters = []
wordLis = []
while life > 0 and ans != secWord:
print("are you guessing letter or a word?")
guessThing = input("l / w : ")
#for guessing a word
if guessThing == "w":
ans = input("What is the secret word?: ")
if ans == secWord:
print("Congratulations, you have guessed the right word\nYou won!")
else:
print("You guessed the word incorrectly\n The word was " + secWord + " \n You lost!")
exit()
#=================================================================
#for guessing a letter
elif guessThing == "l":
letList = [letter for letter in secWord]
guLett = input("Guess the letter \n(single letter only): ")
usedLetters.append(guLett)
if guLett in letList:
guessedLetters.append(guLett)
letListPlus = [letter for letter, x in enumerate(letList) if x == guLett]
letListPlusPlus = [num + 1 for num in letListPlus]
print("///")
print("///")
print("///")
print("Letters that you have used : " + str(usedLetters))
print("Letter that are correct: " + str(guessedLetters))
print("The position of letter " + str(guLett) + " is " + str(letListPlusPlus))
else:
print("///")
print("///")
print("///")
print("incorrect guess, you have " + str(life - 1) + " guesses remaining")
life = life - 1
print("Letters that you have used are: " + str(usedLetters))
print("Letter that are correct: " + str(guessedLetters))
#=================================================================
Whenever you need your in-progress word to be displayed (like "o_e_f_ow"), call this function:
def wordWithDashes(guessedLetters, letList):
return [letter if letter in guessedLetters else "_" for letter in letList]
It creates a new list from letList with missing letters replaced with "_". You can use str on it if you want a string result.
You don't need to keep track of lenghtDashes. Just compute it from the guessed letters and the actual word whenever you need it, as the code I provided does.

how to fix this python hangman game?

I have coded this hangman game to test something, and it doesn't work properly.
Here is the code:
import random
from string import ascii_lowercase, ascii_uppercase
secret_words = ["screen", "secret", "game", "hangman"]
def lowerChar(c):
if 'A' <= c <= 'Z':
return ascii_lowercase[ascii_uppercase.index(c)]
else:
return c
def get_guess():
word = random.choice(secret_words)
length = len(word)
limit = 5
count = 0
display = "*" * length
print(display, " Is the word")
while count < 5:
letter = input("Please Enter Your guess letter")
for l in word:
if letter.lower() == lowerChar(l):
print("Right guess!")
index = word.find(l)
display = display[:index] + letter + display[index + 1: ]
print(display)
if not '*' in display:
print("You won!")
break
else:
count += 1
print("You got it incorrect, you have: ", limit - count , " Additional trials")
get_guess()
You are doing too much inside the block for l in word. You have to check, whether the character is contained in the word or not, outside this loop:
import random
secret_words = ["screen", "secret", "game", "hangman"]
def get_guess():
word = random.choice(secret_words)
count = 0
display = "*" * len(word)
print(display, " Is the word")
while count < 5:
letter = input("Please Enter Your guess letter")
if letter.lower() not in word:
count += 1
print("You got it incorrect, you have: ", limit - count , " Additional trials")
else:
print("Right guess!")
new_display = ''
for w, l in zip(word, display):
if letter.lower() == w:
new_display += letter.lower()
else:
new_display += l
display = new_display
print(display)
if not '*' in display:
print("You won!")
break
get_guess()
An alternative solution to Daniel's would be introducing a variable called goodGuess that allows you to check if the person has made a correct guess in the for loop, and then once you have exited the for loop, then checking if the player has made an incorrect guess, see below
import random
from string import ascii_lowercase, ascii_uppercase
secret_words = ["screen", "secret", "game", "hangman"]
def lowerChar(c):
if 'A' <= c <= 'Z':
return ascii_lowercase[ascii_uppercase.index(c)]
else:
return c
def get_guess():
word = random.choice(secret_words)
length = len(word)
limit = 5
count = 0
display = "*" * length
print(display, " Is the word")
while count < 5:
letter = input("Please Enter Your guess letter")
#as we do not yet know if this guess is good we set it to False until we do know
goodGuess = False
for l in word:
if letter.lower() == lowerChar(l):
#as the player has made a correct guess we set goodGuess to True
goodGuess = True
print("Right guess!")
index = word.find(l)
display = display[:index] + letter + display[index + 1: ]
print(display)
if not '*' in display:
print("You won!")
break
#checking if the player has made a correct guess
if not goodGuess:
count += 1
print("You got it incorrect, you have: ", limit - count , " Additional trials")
get_guess()
Hope this helps.

Question about dictionary items addition in Python (Guess the word game)

How can i add a letter multiple times in the different keys of a dictionary?
I made a guess the word game where the user enters the letter to complete the mysterious word.
Everything works fine with words where letters appears just one time (Ex. Dog) but I have problems when letters occur multiple times (Ex. Employee) because only the first one is filled.
I know this is probably not the most efficient way of doing this but I'm starting programming in python and was experimenting a bit with the concepts learned.
Here's the code, thanks for the help:
import os
word = input('choose the word to play with: ')
os.system('cls')
word_list = list(word)
word_dict = {}
for x in range(len(word_list)):
word_dict[str(x)] = word_list[x]
guess_dict = {}
for x in range(len(word_list)):
guess_dict[str(x)] = '_'
health = 10
victory = False
values = list(guess_dict.values())
print(values)
while victory == False:
letter = input('Choose the letter: ')
if letter in word_dict.values():
guess_dict[list(word_dict.keys())[list(word_dict.values()).index(letter)]] = letter
valori = list(guess_dict.values())
print(valori)
print()
if guess_dict == word_dict:
victory = True
print ('You won')
else:
health -= 1
print('ERROR!! ' + str(health) + ' lives remaining')
if health == 0:
print('You lose')
break
Your problem is exactly the dictionary. The dictionary has only one entry for each key. See here
In my opinion, you should use either a list, or a list of dictionaries.
import os
word = input('choose the word to play with: ')
os.system('cls')
word_list = list(word)
guess_list = [{'character': x, 'guessed': False} for x in word]
health = 10
victory = False
while True:
str = ''
for item in guess_list: #generate the string each iteration once
if False == item['guessed']:
str = str + "'_'"
else:
str = str + "'" + item['character'] + "'"
print(str)
if True == victory: #put the test here, so that the result is printed
print('You won!')
break
else:
letter = input('Choose the letter: ')
hit = False
missed_cnt = 0
for item in guess_list:
if item['character'] == letter: #if letter guessed, set flag
item['guessed'] = True
hit = True
if item['guessed'] == False: #count unguessed letters
missed_cnt +=1
if False == hit:
health -= 1
print('ERROR!! {0} lives remaining'.format(health))
if 0 == health:
print('You lose!')
break
if 0 == missed_cnt: #exit only after printing result
victory = True
Instead of a dictionary, you could use a set(). Since guessing a letter reveals all instances of that letter, removing it from the set corresponds to the same notion.
So you could do something like this:
word = input("hidden word:")
remainingLetters = set(word)
health = 10
while True:
print( "".join( "_" if letter in remainingLetters else letter for letter in word) )
letter = input("guess a letter:")
if letter in remainingLetters:
remainingLetters.remove(letter)
if remainingLetters: continue
print("you Win!")
break
health -= 1
if health == 0:
print("You lose")
break
print('ERROR!! {0} lives remaining'.format(health))
I would simply use a list of letters:
import os
from copy import deepcopy
word = list(input('choose the word to play with: '))
compare = deepcopy(word)
os.system('cls')
guess = []
for index, letter in enumerate(word):
guess.append('_')
health = 10
victory = False
while not victory:
letter = input('Choose the letter: ')
if letter in compare:
guess[compare.index(letter)] = letter
compare[compare.index(letter)] = ' '
print(guess)
print()
if guess == word:
victory = True
print ('You won')
else:
health -= 1
print('ERROR!! ' + str(health) + ' lives remaining')
if health == 0:
print('You lose')
break
The deepcopy in the beginning is because in Python if you do compare = word, compare would become a pointer to word. The variable compare by the way is to remove the already guessed characters from.
You could also check the input letter to make the code more robust:
while not victory:
letter = input('Choose the letter: ')
try:
value = float(letter)
print('Please enter a letter of type (str).')
continue
except ValueError:
pass
if len(letter) != 1:
print('Please enter only one letter!')
continue

How to reveal letters if correct to what is inputted

I am creating a hangman game , where a user will enter a word in which another user will have to guess.
I have got the word to print with dashes, however when I input a letter which is in the word, I cannot get it to remove the dashes.
#output a game of hangman
letters= ["A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"]
for i in range(1):
print("Welcome to Hangman")
word_guess = str(input("Please enter a word for user 2 to guess:"))
print("Word to be guessed:"+str(word_guess))
length_of_word=len(word_guess)
display=("-"*length_of_word)
print("Display:"+str(display))
for i in range(1):
print("Welcome to Hangman Player 2")
letter_guess=str(input("Please guess a letter:"))
if letter_guess in word_guess:
print("Yay you have a match")
display=display.rstrip(display)
print(display)
Hangman
Try this code, is not refinished, but it works. Maybe it can give you some ideas. To work, you got to be connected, otherwise put the file with words on the computer.
from urllib.request import urlopen
from random import choice
w0 = urlopen("https://raw.githubusercontent.com/Xethron/Hangman/master/words.txt")
w = [str(x).replace("b'", "").replace("\\n", "") for x in w0]
word = choice(w)
word = word.replace("'", "")
strips = list("_" * len(word))
chosen = []
def guess():
y = input("Guess a letter: ")
if y in chosen:
print("You have choose this letter yet, retry...")
guess()
chosen.append(y)
if y in word:
if "_" not in strips:
print("GREAT, YOU WIN!")
print()
print()
pass
print("Great the letter is in the word")
indexes = [x for x, y2 in enumerate(word) if y == y2]
for ind in indexes:
strips[ind] = y
for ch in strips:
print("[" + ch + "]", end='')
print("You`ve choosen: ", "".join(chosen))
print()
print()
guess()
else:
print("This letter is not in the word, try again")
print("".join(strips))
print("You`ve choosen: ", "".join(chosen))
def start():
for ch in range(len(word)):
guess()
print("Game over " * 5)
print("The word was " + word)
print("\n" * 5)
print("HANGMAN - Giovanni Gianni Gatto")
print("print start() to restart")
print()
start()
I had a hangman lying around which I adapted to your needs. What you need is to have a list with found items [] and when you print the word to display you show only letters which are in the found items else _.
print(' '.join(i if i in found else '_' for i in secretword))
Here is a full example of a game where it asks for one_guess (a function) until the length of found items is equal too the length of the set of the secretword (set removes duplicate letters). Try it:
def print_word():
print(' '.join(i if i in found else '_' for i in secretword))
def valid_input():
while True:
guess = input("Guess a letter: ({})".format(''.join(i for i in alpha)))
if guess in alpha:
alpha.remove(guess)
return guess
else:
print("Not valid input!")
def one_guess():
print_word()
guess = valid_input()
if guess in letters:
print("You found one!\n")
letters.remove(guess)
found.append(guess)
else:
print("You didn't find one!\n")
secretword = "animal"
alpha = list("abcdefghijklmnopqrstuvwxyz")
letters = list(set(secretword))
found = []
while True:
one_guess()
if len(set(secretword)) == len(found):
print("You won!")

Categories