Python HangMan game using functions - python

So I'm trying to make a little hangman game in Python. I've managed it already, but I've seen lots of other people using functions to achieve this. Here's my code without using function:
from hangman_words import word_list
import random
def select_word():
return random.choice(word_list)
hidden_word = select_word()
char_lines = "_" * len(hidden_word)
guessed_letters = []
Lives = 8
game_start = input("Would you like to play HangMan? (Y/N)\n")
if game_start.upper() == "Y":
prompt_user = True
elif game_start.upper() == "N":
print("*Sad Python Noises*")
prompt_user = False
else:
print("You to say 'Yes'(Y) or 'No'(N)")
while (Lives > 0 and prompt_user == True):
user_input = input("Choose a letter!\n\n")
user_input = user_input.upper()
if user_input.upper() in guessed_letters:
print("\nYou have already guessed that letter. Choose something else!")
elif hidden_word.count(user_input) > 0:
for i, L in enumerate(hidden_word):
if L == user_input:
char_lines = char_lines[:i] + hidden_word[i] + char_lines[i+1:]
print("\nCorrect!")
print(char_lines)
else:
guessed_letters.append(user_input)
print("\nNope, that letter isn't in the word. Try again!")
Lives -= 1
if char_lines == hidden_word:
print("Well done! You won the game!")
print(f"You had {Lives} lives remaining and your incorrect guesses were:")
print(guessed_letters)
exit()
print(f"Lives remaining: {Lives}")
print(f"Incorrect guessed letters: {guessed_letters}")
print(char_lines)
if (Lives == 0 and prompt_user == True):
print("You have ran out of lives and lost the game!.....you suck")
if prompt_user == False:
print("Please play with me")
My current code for the version using functions is like this:
from hangman_words import word_list
import random
def select_word():
global blanks
selected_word = random.choice(word_list)
blanks = "_" * len(selected_word)
return selected_word, blanks
def game_setup():
global lives
global guessed_letters
global hidden_word
lives = 20
guessed_letters = []
hidden_word = select_word()
return lives, guessed_letters, hidden_word
def play_option():
game_start = (input("Would you like to play HangMan? (Y/N)\n")).upper()
if game_start == "Y":
global prompt_user
prompt_user = True
game_setup()
return prompt_user
elif game_start == "N":
print("*Sad Python Noises*")
exit()
else:
print("You need to say 'Yes'(Y) or 'No'(N)")
def user_input_check(user_input):
if type(user_input) != str: # [Want to check if unput is of tpye Str]
print("Please input letter values!")
elif user_input != 1:
print("Please only input single letters! (e.g. F)")
else:
pass
def game_board(user_input, hidden_word, guessed_letters, blanks, lives):
if user_input in guessed_letters:
print("You have already guessed that letter. Choose something else!")
elif hidden_word.count(user_input) > 0:
for i, L in enumerate(hidden_word):
if L == user_input:
blanks = blanks[:i] + hidden_word[i] + blanks[i+1:]
print("Correct!")
print(blanks)
else:
guessed_letters.append(user_input)
print("Nope, that letter isn't in the word. Try again!")
lives -= 1
print(f"Lives remaining: {lives}")
print(f"Incorrect guessed letters: {guessed_letters}")
print(blanks)
return
def win_check(blanks, hidden_word, lives, guessed_letters):
if blanks == hidden_word:
print("Well done! You won the game!")
print(f"You had {lives} lives remaining and your incorrect guesses were:")
print(guessed_letters)
exit()
def lives_check(lives, prompt_user):
if (lives == 0 and prompt_user == True):
print("You have ran out of lives and lost the game!.....you suck")
exit()
play_option()
while (lives > 0 and prompt_user == True):
user_input = (input("Choose a letter!\n\n")).upper()
user_input_check(user_input)
game_board(user_input, hidden_word, guessed_letters, blanks, lives)
win_check(blanks, hidden_word, lives, guessed_letters)
lives_check(lives, prompt_user)
I think I should be using classes instead of functions really, but I'd like to get it work with functions first, then try adapting it to work with classes. If I'm using functions, how does return actually work? Does returning variable names put those variables within the global name-space? Or does return only work when you assign the returned value to a global name-space variable? Like this:
def add_one(a):
return a + 1
b = add_one(3) # b = 4

You're correct, return works by setting the function to be equal to whatever you return it as.

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

I only can type 1 letter , how do I let the code know that 2 or more letters are also okay?

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)

Debugging a "guess the word " game

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

How to loop the program back to the beginning with user input

I'm setting up a basic hangman game and am trying to get the program to loop back to the beginning when the game is finished.
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
print("Play Again? (y/n)")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
print("Play again? (y/n)")
Wrap your game in a function and throw it in a while loop.
After the play game function, they'll be asked to play again. If they respond with anything but 'y', the loop breaks.
while True:
# play_game()
if input("Play again?") != 'y':
break
print("Thanks for playing!")
You can use an user input and a while loop
play_again = "Y"
while play_again == "Y" or play_again == "y":
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
print("Play Again? (y/n)")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
play_again = input("Play again? (Y/N)")
or in short just put in in a function:
play_again = "Y"
while play_again == "Y" or play_again == "y":
game()
play_again = input("Play again? (Y/N)")
You could put it all into a function and have it loop back like this:
def start():
replay = True
while (replay):
game_started()
inp = input("Play again? Y/n ")
if inp == 'n' or inp == 'N':
replay = False
def game_started():
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
break
start()
Edit:
Your check if a letter was guesses is also flawed:
If you guess "abcdefghijklmnopqrstuvwxyz", you always win.
I'd suggest checking the length of the input before appending it to guesses.
Also, to print it all into one line, you could use "print(char, end='')" (and "print('_', end='')", respectively). Just make sure to print a newline after the loop, to finish the line.
Hey friend here is what I came up with I hope it helps! Instead of using your turns to control the while loop you can use a "running" variable that is set to a boolean which you can use input statements for your replay feature to control when you want to exit (False) or continue through your loop (True).
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
running = True
while running:
failed = 0
for char in word:
if char in guesses:
print(char),
else:
print("_"),
failed += 1
if failed <= 0:
print("You won")
x = input("Play Again? (y/n) \n")
if x == "y":
turns = 10
else:
running = False
guess = input("Guess a character: \n")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
z = input("Play Again? (y/n) \n")
if z == "y":
turns = 10
else:
running = False

Instead of using global what to use for my situation in my hangman game (python)

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

Categories