Spelling Game using Python - python

I have provided a list of words that will randomly be picked for the game. What it does is to prompt the player to enter an alphabet of the selected word. If the letter provided by the users is found in the selected word, they if be asked if they want to attempt spelling the whole word. if they say yes, then they will be able to do so. Else, they will have to try entering another alphabet.how do I get the output/ results of each user input to be printed as (eg: Outcome: a------) And if the users ended up saying yes to spelling the whole word, how should they be prompt to enter the word?
eg: Do you want spell the word now? (y/n): y
Spell the complete word:
You are correct!
The correct word is albumen
Spell another word? (y/n): y
import random
wordList = ('apple', 'albumen', 'toothpaste', 'enthusiastic')
word = random.choice(wordList)
letter_guess = ""
word_guess = ""
store_letter = ""
count = 1
limit = 5
countLetters = len(word)
choice1 = ("Do you want to spell the word now? (y/n):")
choice2 = ("Spell another word? (y/n):")
choiceY = ("y")
choiceN = ("n")
startGame = print("The word ________ has {} letters. Spell it in 5 tries.".format(countLetters))
while count < limit:
letter_guess = input("Try {} - Current: ________. Your guess? ".format(count))
if letter_guess in word:
print ("yes")
print (input(choice1))
else :
print("no")
count += 1
if choice1 == choiceY:
print (input("Spell the complete word: "))
else:
print (letter_guess)
store_letter += letter_guess
count += 1
while count == limit:
spellFinal = input("Spell the complete word: ")
if spellFinal in word:
print ("You are correct!")
print ("Spell another word? (y/n):")
if choice == "y":
print (startGame)
else:
print('Remaining Words are: ', store_letter)
if spellFinal not in word:
print ("You are incorrect")
print ("The correct word is {}.".format(correct))

You are not collecting the information from your print (input(choice1)) line. You should be assigning it to a variable to be able to compare it later with your choiceY (or you could simply compare the new variable to "y" without having a choiceY variable defined, up to you).
For example:
user_choice = ""
complete_word = ""
if letter_guess in word:
print ("yes\n")
user_choice = input(choice1)
if user_choice.lower() is "y":
complete_word = input("Spell the complete word: ")
#here you compare complete_word with your word variable
else:
print (letter_guess)
store_letter += letter_guess
count += 1
else:
print("no\n")
count +=1
The same applies to the other sections of you code that have the print(input(...)).
Nested ifs can get messy. Perhaps you can consider having a verification function and call that instead.
Hope this helps!

Related

Printing the Guessed Letter

import random
title = ("Guess the Word Title")
print(title.center(80))
Tuple = ()
Tuple = ("Spring", "Summer", "Autumn", "Winter")
TupleItem = random.choice(Tuple)
Item_len = len(TupleItem)
ItemAsteriks = ("*" * Item_len)
print("\n\n\n", ItemAsteriks.center(80), "\n\n\n")
response = "n"
while response == "n":
response = input("Would you like to guess the word (y / n)? ")
if response == "y":
break
letter = input("\nEnter a letter: ")
if letter.upper() in TupleItem.upper():
print("The letter ", letter, "is in the word!\n")
new_message = ""
for i in range(len(TupleItem)):
if TupleItem[i].upper()==letter.upper():
new_message += TupleItem[i]
else:
new_message += ItemAsteriks[i]
ItemAskeriks = new_message
else:
print("The letter ", letter, "is not in the word!\n")
GuessedWord = input("\nGuess the word then: ")
if GuessedWord.upper() == TupleItem.upper():
print("You guessed the right word. Congratz!")
else:
print("You guessed the wrong word. The right word was:", TupleItem)
input("\n\nPress Enter to Exit. ")
This is what i've come up so far. If the word is "Summer" and user guessed letter "U", I want to show/update the asterisks like: *u****., and so on. I tried some print commands under the for loop but i couldnt figure it out.
Well, I think the problem is that it will always just show the most recent letter, but not the ones from before. I would initialise a list of strings, one for each letter in the word, starting with
guessed = ["*"] * len(TupleItem)
Then at each guess, iterate though the real word and replace * entries with the actual guessed letter.
for k, ch in enumerate(TupleItem.upper()):
if ch == letter.upper():
guessed[k] = ch
Then you can simply
print("".join(guessed))

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 check if a single letter (which has been input as a string variable) is equal to any character in another string?

I am trying to make a hangman game at the minute and this is the code so far:
word = raw_input("Please enter a word")
correctguesses = []
wrongguesses = []
guesscorrect = False
while guesscorrect == False:
guess = raw_input("Guess a letter")
if len(guess) != 1:
print "Your guess was more than one letter"
for i in word:
if guess == i in word:
print "correct"
correctguesses.append(guess)
print "here are your correct guesses so far" ,(''.join(correctguesses))
for i in word:
if guess != i in word:
print "incorrect"
wrongguesses.append(guess)
print "here are your wrong guesses so far:", (''.join(wrongguesses))
my output:
correct/
here are your correct guesses so far:/ e/
incorrect/
incorrect/
incorrect/
incorrect/
here are your wrong guesses so far:/ eeee/
It is doing that because it isn't the correct letter for the 4 other letters in hello (which was the word).
word = raw_input("Please enter a word")
correctguesses = []
wrongguesses = []
guesscorrect = False
while guesscorrect == False:
guess = raw_input("Guess a letter")
if len(guess) != 1:
print "Your guess was more than one letter"
continue #to prompt for input again
for i in word:
if guess == i: #i will be a letter in the word
print "correct"
correctguesses.append(guess)
print "here are your correct guesses so far" ,(''.join(correctguesses))
for i in word:
if guess != i: #put this case in the else block of the if in the previous loop and remove this loop
print "incorrect"
wrongguesses.append(guess)
print "here are your wrong guesses so far:", (''.join(wrongguesses))
I have commented some of the details.
This course might help with basics of python and programming.

How can I let the users of my python hangman game input their own words?

I have been stuck on this for a while now and I can't figure out what to do. I know that it will probably involve creating an empty list and then adding the words to the list but I haven't got a clue when it comes to retrieving the words as I have never done this before.
the code itself works, it's just adding this new function I'm having trouble with.
import random
import sys
#importing both random and time modules
print("Hello!")
playAgn = 'yes'
animalNames = ['wildebeest','wolverine','woodlouse','woodpecker','yak','zebra']
#this is the list of words that the user will have to guess if they play the game multiple times
while playAgn == 'yes':
secretWord = random.choice(animalNames)
#this line tells the computer to randomly select one of the words in the list "animalNames"
lives = 6
#Defining how many lives the user has
guessedletters = []
print("Okay!\n Lets play hangman!!")
while lives > 0:
inword = False
#user has not guessed word yet so the boolean value is automatically off (False)
print("you have",lives, "lives")
#tells the user how many lives they have left
guessedletter = input("Guess a letter: ")
if len(guessedletter) > 1:
print("Error! Please only enter 1 letter at a time")
#if the user tries to guess something longer than 1 character the computer displays a message asking to only enter 1 letter at a time
elif guessedletter in guessedletters:
print("Sorry, you have already guessed this letter. Try again")
#if the user tries to guess a letter that has already been guessed the computer displays a message telling the user to choose another letter as they have already chose this one
else:
guessedletters+=str(guessedletter)
#adds the guessed letter to guessedletters variable
print("You have guessed:")
for letter in guessedletters:
print(letter.upper(),"")
#prints the letters already guessed in uppercase
shownword = ""
for letter in secretWord:
if letter in guessedletters:
shownword +=str(letter)
#if the letter is in guessedletters then add the letter to shownword(word displayed to user)
if letter == guessedletter:
inword = True
#inword is true as the guessed letter is in the secret word
else:
shownword+=str("_")
#the computer is now adding the underscores too the word being displayed to the user
print(shownword)
#the computer prints the word with the letters that the user has guessed so far (word including underscores for not yet guessed characters)
if "_" not in shownword:
print("Congratulations, you won! The word was '", shownword,"'")
#if there are no underscores(meaning the word is completed) tell the user they have won the game
break
elif inword == False:
#the guessed word is not in the secret word so the boolean value is now off (False)
print("No luck," , guessedletter , "is not in my word")
lives -= 1
#deducts a life for the wrong letter being guessed and also displays a message telling the user that the letter just guessed isn't in the secret word
if lives == 0:
print("You have run out of lives. The word was '",secretWord,"'")
#if the user runs out of lives and still hasn't guessed the word, tell them they failed to beat the game and also tell them the word
while True:
playAgn = input("Would you like to play again? yes/no: ")
if playAgn == 'no':
print("okay\n Goodbye!")
break
elif playAgn == 'yes':
break
thanks a lot to anyone who can help figure this out :)
You could just swap this:
animalNames = ['wildebeest','wolverine','woodlouse','woodpecker','yak','zebra']
For this:
animalNames = getNames()
And define the function:
def getNames():
names = []
while True:
name = raw_input("Add a word to the list (or press enter to cancel): ")
if name == "":
break
else:
names.append(name)
return names
Look at this line:
animal_names.append(input("Enter Word To Word Pool:"))
like that?

While loop initiating when I dont want it to

I'm going over the formatting of the while loop and I remain unsure (I'm a beginner- forgive me) of how I can go about fixing this. Any assistance would be greatly appreciated! I do not want the 'Sorry that's not it' message to pop up when the user asks for a hint- and yet it persists in doing just that.
# Word Jumble
#
# The computer picks a random word and then "jumbles" it
# The player has to guess the original word
import random
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pick one word randomly from the sequence
word = random.choice(WORDS)
hint = ''
if word == 'python':
hint = 'snake'
if word == 'jumble':
hint = 'jumble'
if word == 'easy':
hint = 'opposite of hard'
if word == 'difficult':
hint = 'opposite of easy'
if word == 'answer':
hint = 'question'
if word == 'xylophone':
hint = 'dingding'
# create a variable to use later to see if the guess is correct
correct = word
# create a jumbled version of the word
jumble =""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
count = 0
# start the game
print(
"""
Welcome to Word Jumble!
Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
print("The jumble is:", jumble)
guess = input("\nYour guess: ")
while guess != correct and guess != "":
print("Sorry, that's not it.")
count += 1
hint_input = input('would you like a hint')
if hint_input == 'y':
print(hint)
else:
guess = input("Your guess: ")
if guess == correct:
print("That's it! You guessed it!\n")
print("Thanks for playing.")
input("\n\nPress the enter key to exit.")
Remove the else: since you always wish to get a new guess from the user, regardless of if they've received a hint.
if hint_input == 'y':
print(hint)
guess = input("Your guess: ")
Your code works fine - but you are expected to enter a string including the " or ' in the input field. So enter "jumble" and not just jumble or "y" and not just y.
(well, there is some strange logic in there, e.g. after giving a hint it asks once more whether you want a hint - jus remove the else to get rid of this behaviour) but at least it works...)
I've copied your code and ran it.
I changed input to raw_input, which makes input much nicer.
Removed else: after print(hint) , which should fix your problem.
Lastly, I've added extra space after "Would you like a hint? " - makes it a bit easier to read.
# Word Jumble
#
# The computer picks a random word and then "jumbles" it
# The player has to guess the original word
import random
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pick one word randomly from the sequence
word = random.choice(WORDS)
hint = ''
if word == 'python':
hint = 'snake'
if word == 'jumble':
hint = 'jumble'
if word == 'easy':
hint = 'opposite of hard'
if word == 'difficult':
hint = 'opposite of easy'
if word == 'answer':
hint = 'question'
if word == 'xylophone':
hint = 'dingding'
# create a variable to use later to see if the guess is correct
correct = word
# create a jumbled version of the word
jumble =""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
count = 0
# start the game
print(
"""
Welcome to Word Jumble!
Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
print("The jumble is:", jumble)
guess = raw_input("\nYour guess: ")
while guess != correct and guess != "":
print("Sorry, that's not it.")
count += 1
hint_input = raw_input('would you like a hint? ')
if hint_input == 'y':
print(hint)
guess = raw_input("Your guess: ")
if guess == correct:
print("That's it! You guessed it!\n")
print("Thanks for playing.")
raw_input("\n\nPress the enter key to exit.")

Categories