I'm trying to get a function to put correct guesses in their blanks in a hangman program, but all it does is, whatever the guess and no matter whether it's right or wrong, it just gradually reveals the word. Where am I going wrong?
code:
while lettersrevealed!=word:
guess=getGuess(lettersrevealed)
for i in range(len(word)):
if guess in word:
blanks = blanks[:i] + word[i] + blanks[i+1:]
print(blanks)
ex:
(secret word is badger)
Guess a letter:
a
b*****
ba****
bad***
badg**
badge*
badger
Guess a letter:
OR:
Guess a letter:
h
b*****
ba****
bad***
badg**
badge*
badger
Guess a letter:
The issue is with the for loop
for i in range(len(word)): # This will run 6 times for "badger" | 0, 1, .., 5
if guess in word:
# blanks == ****** then gradually gets the next letter added replacing a *
blanks = blanks[:i] + word[i] + blanks[i+1:]
print(blanks)
You probably want something like this.
def convert_to_blanks(word, letters):
return ''.join(c if c in letters else '*' for c in word)
>>> word = 'badger'
>>> letters = set()
>>> convert_to_blanks(word, letters)
'******'
>>> letters.add('g')
>>> letters
{'g'}
>>> convert_to_blanks(word, letters)
'***g**'
And so you have a while loop prompting for letter something like this.
guessed = set()
word = 'badger'
while True:
guess = input("Guess a letter")
guessed.add(guess)
blanks = convert_to_blanks(word, guessed)
print(blanks)
if blanks == word:
break
Related
So I was following this tutorial on youtube however when it comes to running the program, nothing shows up on the terminal while my CPU doubles in usage. I am using VScode to run this program. PS. I am very new to this and I always have frequent trouble when it comes to coding in general so i decided to resort in asking questions.
import random
from words import words
import string
def get_valid_word(words):
word = random.choice(words) #randomly chooses something from the list
while '-' in word or '' in word: #helps pick words that have a dash or space in it
word = random.choice(words)
return word.upper() #returns in uppercase
def hangman():
word = get_valid_word(words)
word_letters = set(word) # saves all the letters in the word
alphabet = set(string.ascii_uppercase) #imports predetermined list from english dictionary
used_letters = set() #keeps track of what user guessed
#getting user input
while len(word_letters) > 0: #keep guessing till you have no letters to guess the word
#letters used
#'' .join (['a', 'b', 'cd']) --> 'a, b cd'
print('you have used these letters: ',' '.join(used_letters))
#what the current word is (ie W - R D)
word_list = [letter if letter in used_letters else '-' for letter in word]
print('current word: ',' '.join(word_list))
user_letter = input('Guess a letter: ')
if user_letter in alphabet - used_letters: #letters haven't used
used_letters.add(user_letter) #add the used letters
if user_letter in word_letters: #if the letter that you've just guessed is in the word then you remove that letter from word_letters. So everytime you've guessed correctly from the word letters which is keeping track of all the letters in the word decreases in size.
word_letters.remove(user_letter)
elif user_letter in used_letters:
print('You have used this')
else:
print('Invalid')
#gets here when len(word_letters) == 0
hangman()
I am creating a guess a letter game in python. the program chooses a random word from a file and the user has the amount of letters to guess the letters to the word. There is one part I am having trouble coding. I need to display the word as dashes and after every guess change the dashed word to include the correctly guessed letters in their corresponding position. So the output looks something like this.
Welcome to Guess a Letter!
Your word has 10 letters
You have 10 incorrect guesses.
Here is the word:
Enter a letter: e
Awe, shucks. You missed with that letter
Enter a letter: a
You got a hit! Here's what the word looks like now:
-------a-a
Enter a letter: o
Awe, shucks. You missed with that letter
Enter a letter: u
Awe, shucks. You missed with that letter
Enter a letter: i
You got a hit! Here's what the word looks like now:
---i---a-a
Enter a letter: y
You got a hit! Here's what the word looks like now:
-y-i---a-a
Enter a letter: t
You got a hit! Here's what the word looks like now:
-y-i-t-ata
Enter a letter: l
You got a hit! Here's what the word looks like now:
ly-i-t-ata
Enter a letter: s
You got a hit! Here's what the word looks like now:
lysist-ata
Enter a letter: r
You got a hit! Here's what the word looks like now:
lysistrata
You won!
Great job!
so here is what i have so far
import random
def pick_word_from_file():
'''Read a file of words and return one word at random'''
file = open("wordlist.txt", 'r')
words = file.readlines()
file.close()
global word #globalizes the variable "word"
word = random.choice(words).strip("\n")
global guesses
guesses = len(word) #number of guesses user has according to number of letters
print(word)
def dashed_word(): #this function turns the word into dashes
global hidden_word #globalizes the variable "hidden_word"
hidden_word = ""
for letter in word: #this for loop changes all the letters of the word to dashes
if letter != " ":
hidden_word = hidden_word + "-"
print(hidden_word)
list(hidden_word)
def game_intro(): #introduces word game rules
print("Welcome to Guess a Word!\n")
print("Your word has",len(word),"letters")
print("You have",len(word),"incorrect guesses.")
print("Only guess with lower case letters please!")
def game(): #this is the main games function
global guess
for letter in range(len(word)):
guess = input("Please enter a lowercase letter as your guess: ") #asks user for lowercase letter as their guess
new_hidden_word = ''
random_int = 0
int(random_int)
for i in range(len(word)):
if guess == word[i:i+1]:
print("Lucky guess!")
print(guess, "is in position", i+1)
hidden_word[i] = guess
hidden_word.join(' ')
print(hidden_word)
random_int = 1
if random_int == 0:
print("Unlucky")
def main(): #this runs all the functions in order
pick_word_from_file()
game_intro()
dashed_word()
game()
main()
Just need help with what is in the game() function
Since strings a immutable, I would use a list to keep track of the guesses and then transfer that to a string in order to print it out. Here is your code modified to reflect those changes :
import random
def pick_word_from_file():
'''Read a file of words and return one word at random'''
file = open("wordlist.txt", 'r')
words = file.readlines()
file.close()
global word #globalizes the variable "word"
word = random.choice(words).strip("\n")
global guesses
guesses = len(word) #number of guesses user has according to number of letters
print(word)
def dashed_word(): #this function turns the word into dashes
global hidden_word #globalizes the variable "hidden_word"
hidden_word = []
for letter in word: #this for loop changes all the letters of the word to dashes
if letter != " ":
hidden_word.append ("-")
print_out = ''
print(print_out.join (hidden_word))
def game_intro(): #introduces word game rules
print("Welcome to Guess a Word!\n")
print("Your word has",len(word),"letters")
print("You have",len(word),"incorrect guesses.")
print("Only guess with lower case letters please!")
def game(): #this is the main games function
global guess
for letter in range(len(word)):
guess = input("Please enter a lowercase letter as your guess: ") #asks user for lowercase letter as their guess
new_hidden_word = ''
random_int = 0
int(random_int)
for i in range(len(word)):
if guess == word[i:i+1]:
print("Lucky guess!")
print(guess, "is in position", i+1)
hidden_word[i] = guess
print_out = ''
print(print_out.join (hidden_word))
random_int = 1
if random_int == 0:
print("Unlucky")
def main(): #this runs all the functions in order
pick_word_from_file()
game_intro()
dashed_word()
game()
main()
I group all functions into one so we don't need to declare global variables. I also add something:
use .lower() to accept uppercase input
a statement telling user how many guesses left
win and lose condition
import random
def game():
# pick_word_from_file()
# using with to close the file automatically
with open("wordlist.txt") as f:
wordlist = f.readlines()
word = random.choice(wordlist).strip("\n")
# game_intro()
print("Welcome to Guess a Word!\n")
print("Your word has", len(word), "letters")
# why we need to say incorrect guesses from the start?
# print("You have", len(word), "incorrect guesses.")
# dashed_word()
# use a list to save letters because string is immutable
hidden_word = ["-" for w in word]
print("".join(hidden_word))
# number of guesses equal to length of word
for guesses in range(len(word)):
# tell user how many guesses left
print(f"You have {len(word) - guesses} guesses left.")
# use .lower() so user can also input uppercase letter
guess = input("Please enter a letter as your guess: ").lower()
change = False
for i in range(len(word)):
if word[i] == guess:
hidden_word[i] = guess
change = True
if change:
print("You got a hit! Here's what the word looks like now:")
print("".join(hidden_word))
else:
print("Awe, shucks. You missed with that letter.")
if "".join(hidden_word) == word:
print("You won! Great job!")
break
# you lose when you are out of guesses
else:
print("You lose.")
game()
Output:
"""
Welcome to Guess a Word!
Your word has 10 letters
----------
You have 10 guesses left.
Please enter a letter as your guess: E
Awe, shucks. You missed with that letter.
You have 9 guesses left.
Please enter a letter as your guess: A
You got a hit! Here's what the word looks like now:
-------a-a
You have 8 guesses left.
Please enter a letter as your guess: O
Awe, shucks. You missed with that letter.
You have 7 guesses left.
Please enter a letter as your guess: U
Awe, shucks. You missed with that letter.
You have 6 guesses left.
Please enter a letter as your guess: I
You got a hit! Here's what the word looks like now:
---i---a-a
You have 5 guesses left.
Please enter a letter as your guess: Y
You got a hit! Here's what the word looks like now:
-y-i---a-a
You have 4 guesses left.
Please enter a letter as your guess: T
You got a hit! Here's what the word looks like now:
-y-i-t-ata
You have 3 guesses left.
Please enter a letter as your guess: L
You got a hit! Here's what the word looks like now:
ly-i-t-ata
You have 2 guesses left.
Please enter a letter as your guess: S
You got a hit! Here's what the word looks like now:
lysist-ata
You have 1 guesses left.
Please enter a letter as your guess: R
You got a hit! Here's what the word looks like now:
lysistrata
You won! Great job!
"""
My task is to check the word list on doublings and output the result in a dictionary.
Firstly i was trying to execute this code:
for word in wordsList:
for letter in word:
if word[letter] == word[letter+1]:
But as long as i got a mistake, i've changed it a bit:
wordsList = ["creativity", "anna", "civic", "apology", "refer", "mistress", "rotor", "mindset"]
dictionary = {}
for word in wordsList:
for letter in range(len(word)-1):
if word[letter] == word[letter+1]:
dictionary[word] = ("This word has a doubling")
else:
dictionary[word] = ("This word has no doubling")
print(dictionary)
Now it works, but not properly. I really need suggestions! Thanks in advance
I expect the output
{creativity: 'This word has no doubling'}, {anna: 'This ward has a doubling'} etc.
wordsList = ["creativity", "anna", "civic", "apology", "refer", "mistress", "rotor", "mindset"]
dictionary = {}
for word in wordsList:
for index, char in enumerate(word[:-1]): # Take one less to prevent out of bounds
if word[index + 1] == char: # Check char with next char
dictionary[word] = True
break # The one you forgot, with the break you wouldnt override the state
else:
dictionary[word] = False
print(dictionary)
You forgot the break statement; The loop would continue and override your found conclusion.
I made my own implementation of your casus.
wordsList = ["creativity", "anna", "civic", "apology", "refer", "mistress", "rotor", "mindset"]
dictionaries = []
for word in wordsList: #for example:creativity
alphabets=[]
for x in word:
alphabets+=x #now alphabets==['c','r','e','a','t','i','v','i','t','y']
num=0
while True:
x=alphabets[0] #for example 'c'
alphabets.remove(x) #now alphabets==['r','e','a','t','i','v','i','t','y']
if x in alphabets: # if alphabets contain 'c'
doubling=True # it is doubling
break
else:
doubling=False #continue checking
if len(alphabets)==1: #if there is only one left
break #there is no doubling
if doubling:
dictionaries.append({word:"This word has a doubling"})
else:
dictionaries.append({word:"This word has no doubling"})
print(dictionaries)
import time, random
#WELSCR
print(WOF1)
print("\n")
print(WOF2)
print("\n"*2)
input("Hit enter to play")
print("\n"*45)
print(WOF1)
print("\n")
print(WOF2)
doublespace = print("\n\n")
singlespace = print("\n")
tripplespace = print("\n\n\n")
guessed = []
score = 1000
wrong = 0
puzzle , hint = random.choice(questions)
blank = puzzle
for round in range (1,10):
tries = 0
iscorrect = False
while (not iscorrect) and (tries < 6):
blank = puzzle
for letter in blank:
if letter in "abcdefghijklmnopqrstuvwxyz":
blank = blank.replace(letter, "-")
def print_puzzle():
print("\n"*45)
print(WOF1)
print("\n")
print(WOF2)
print("\n"*2)
print(blank.center(80))
print("The hint is:",hint.title())
print("You currently have $",score)
print_puzzle()
input("enter")
break
break
This is the beginning of my program that I just started, a wheel of fortune game for a class. I can get it to replace almost all of the letters with a dash, however, there are the occasional few letters that do not always get hidden by this code and I'm not sure why. I have a variable defined as question which is a nested tuple but I did not include it because it's long and contains about 150 different entries.
Nevermind, the problem was case sensitivity. I had proper nouns and capitalized them, but I did not include capital letters in my replace string.
Here is my function:
def evilSetup():
words = setUp()
result = {}
char = input('Please enter your one letter guess: ')
for word in words:
key = ' '.join(char if c == char else '-' for c in word)
if key not in result:
result[key] = []
result[key].append(word)
return max(result.items(), key=lambda keyValue: len(keyValue[1]))
from collections import defaultdict
import random
words= evilSetup()#list of words from which to choose
won, lost = 0,0 #accumulators for games won, and lost
while True:
wrongs=0 # accumulator for wrong guesses
secretWord = words
print(secretWord) #for testing purposes
guess= len(secretWord)*'_'
print('Secret Word:' + ' '.join(guess))
while wrongs < 8 and guess != secretWord:
wrongs, guess = playRound(wrongs, guess)
won, lost = endRound(wrongs,won,lost)
if askIfMore()== 'N':
break
printStats(won, lost)
The function will take a list of words, and sort them into a dictionary based on the position of the guessed letter. As of now, it returns the key,value pair that is the largest. What I would like it to ultimately return is a random word from the biggest dictionary entry. The values as of now are in the form of a list.
For example {- - -, ['aah', 'aal', 'aas']}
Ideally I would grab a random word from this list to return. Any help is appreciated. Thanks in advance.
If you have a list lst, then you can simply do:
random_word = random.choice(lst)
to get a random entry of the list. So here, you will want something like:
return random.choice(max(result.items(), key=lambda kv: len(kv[1]))[1])
# ^^^^^^^^^^^^^^ ^^^^