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..!
Related
the code is about a game like hangman. It has 3 input : guess_num, length, guess. It should terminate the whole program if in any of that input the word stop or exit is entered.my break statement only works for each part of the program. for example each input only terminates its part. how can i code this to terminate whole program if stop or exit is entered in any of that
while True: # For repeating the game if user wants to
print("Welcome to Guess-The-Letter game") # Start of the game
print("") # Just and indent line
# Asking for user to choose number of guess
while True:
num_guess = input("how many times do you want to guess [1-10]: ")
if num_guess.lower() == "stop" or num_guess.lower() == "exit":
print("Game Ends!")
break
try:
num_guess = int(num_guess)
except ValueError:
print("Not a number!")
continue # Checking for non number input
if num_guess < 1 or num_guess > 10:
print("Out of Range") # Checking for out of range input
else:
result1 = int(num_guess) # Storing the value
break # Anything else would be in range that we want and will store the value and break the loop
# Asking for user to choose length of word
while True:
length = input("please enter the length of the word [4-5]: ")
if length.lower() == "stop" or length.lower() == "exit":
print("Game Ends!")
break
try:
length = int(length)
except ValueError:
print("Not a number!")
continue # Checking for non number input
if length < 4 or length > 5:
print("Out of Range") # Checking for out of range input
else:
result2 = int(length) # Storing the value
break # Anything else would be in range that we want and will store the value and break the loop
# Choosing the words
if result2 == 4:
word = choice(word4)
elif result2 == 5:
word = choice(word5)
guess_list = [] # List of guess letters
sec_word = [] # the list for formatting the random word
for i in range(len(word)):
sec_word.append("*") # To format the random word into ****
guess = "" # Defining nothing in variable for the first time of iteration
print("Selecting the word...") # Just a Display
while result1 > 0: # Start of the guessing game on the condition that guess left is greater than 0
print("word is:", "".join(sec_word)) # Displaying the word
# Displaying the remaining guess number
print("Guess remaining:", result1)
# Showing the guess for the previous time
print("Previous guess:", guess)
guess = input("Please guess a letter: ") # Guessing the letter
if guess in guess_list:
# if user input a similar letter like previous letter
print(guess, "has been guessed before", end=" ")
guess_list.append(guess) # Add the guess letters to a list
if guess.lower() == "stop" or guess.lower() == "exit":
print("Game Ends!")
break # Letting user end the game at anytime
if guess in word: # For the input that is correct
if length == 4: # Displaying the word letter by checking for each index for 4 letters words
if guess == word[0]:
sec_word[0] = guess
if guess == word[1]:
sec_word[1] = guess
if guess == word[2]:
sec_word[2] = guess
if guess == word[3]:
sec_word[3] = guess
elif length == 5: # Displaying the word letter by checking for each index for 5 letters words
if guess == word[0]:
sec_word[0] = guess
if guess == word[1]:
sec_word[1] = guess
if guess == word[2]:
sec_word[2] = guess
if guess == word[3]:
sec_word[3] = guess
if guess == word[4]:
sec_word[4] = guess
print(guess, "is in the word!")
if guess not in word: # For the wrong inputs from user
print(guess, "is not in the word! Try agin")
print("") # Just a space after each question
if "".join(sec_word) == word:
print("You win!")
break # if user guess the right word before end of the guess number
result1 -= 1 # After each guess the remaining guess time drops 1 time
You can use sys.exit() to terminate the program.
import sys
if guess.lower() == "stop" or guess.lower() == "exit":
print("Game Ends!")
sys.exit()
I am creating a random number generator. I want to add up the guess tries I had for different trials and find the average. However, when I add up the list, it will only calculate how many guesses I had for the first trials divided by the number of trials. How could I fix this problem?
import random
import string
#get the instruction ready
def display_instruction():
filename = "guessing_game.txt"
filemode = "r"
file = open(filename, filemode)
contents = file.read()
file.close()
print(contents)
#bring the instruction
def main():
display_instruction()
main()
#set the random letter
alpha_list = ['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']
letter = random.choice(alpha_list)
print(letter)
guess = ''
dist = []
number_of_guess = []
number_of_game = 1
guess_number = 1
game = True
if guess_number < 5:
rank = 'expert'
elif guess_number >= 5 and guess_number < 10:
rank = 'intermidiate'
else:
rank = beginner
while game == True:
guess_number = int(guess_number)
guess_number += 1
#add the input of user
guess = input("I am thinking of a letter between a and z" + "\n" + "Take a guess ")
#what happens if it is not a letter?
if guess not in alpha_list:
print("Invalid input")
elif alpha_list.index(guess) > alpha_list.index(letter):
print("too high")
dist.append(alpha_list.index(guess) - alpha_list.index(letter))
number_of_guess.append(guess)
#what happens if the guess is less than the letter?
elif alpha_list.index(guess) < alpha_list.index(letter):
print("too low")
dist.append(alpha_list.index(letter) - alpha_list.index(guess))
number_of_guess.append(guess)
elif guess == letter:
print("Good job, you guessed the correct letter!")
guess_number = str(guess_number)
print("---MY STATS---" + "\n" + "Number of Guesses:", guess_number + "\n" + "Level", rank)
replay = input("Would you like to play again? Y/N")
if replay == 'y' or replay == 'Y':
number_of_game += 1
game = True
else:
game = False
print(number_of_guess)
print("---MY STATS---" + "\n" + "Lowest Number of Guesses:" + "\n" + "Lowest Number of Guesses:" + "\n" + "Average Number of Guesses:", str(len(number_of_guess)/number_of_game))
If you want to get the average guesses per game, why you divide the length of the guess list? Why it is even a list? You can save it as an int do:
... "Average Number of Guesses:", (number_of_guess / number_of_game))
Also, note the following:
You initialize number_of_guess with 1, means that you will always count one more guess for the first round.
You do not choose a new letter between each round!
I'm writing code with Python 2.7 that checks if a character is present in a input string but Python keeps skipping part of my if-statement.
Each time I run the code and enter a guess character value, the execution goes straight to the else statement and never executes the if(guess in PuzzleSetter) == True block at all.
What am I doing wrong?
PuzzleSetter = " "
List = []
def setPuzzle():
PuzzleSetter = raw_input("Puzzle setter set your word: ")
PuzzleSetter = PuzzleSetter.replace(" ", "")
print("Guessing player try guessing: "+PuzzleSetter.upper())
time.sleep(5)
print(chr(27) + "[2J")
List = [' __ ']*len(PuzzleSetter)
print("\n")
print(List)
while(True):
guess = raw_input("\nGuessing player make your guess: ")
if len(guess) != 1:
print("You are meant to enter a single letter")
continue
else:
guess = guess.upper()
print(guess)
if(guess in PuzzleSetter) == True:
finder = PuzzleSetter.find(guess)
print(PuzzleSetter+" contains "+str(PuzzleSetter.count(guess))+" "+guess+"'s")
for count in range(PuzzleSetter.count(guess)):
List[finder] = guess.upper()
finder = PuzzleSetter.find(guess, finder+1)
print(List)
if List.count("__") == 0:
print("Guessing player wins!")
break
else:
HangerMan()
enter += 1
if enter == 7:
print("Guessing player lost!")
print("\nPlayer two becomes the puzzle setter")
setPuzzle()
As I thought, you're leaving PuzzleSetter as input and not converting it to upper case like you are guess. If it contains any lower case letters they will never be found. Try this:
PuzzleSetter = raw_input("Puzzle setter set your word: ")
PuzzleSetter = PuzzleSetter.replace(" ", "")
PuzzleSetter = PuzzleSetter.upper()
print("Guessing player try guessing: "+PuzzleSetter)
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()
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()