Reputation: 33
I'm trying to make a word guessing game in Python, but the final part is a bit confusing to me.
Here is my code uptil now:
word_tuple = ("c", "o", "d", "e", "c")
word = ""
word = input("Give a word of " + str(len(word_tuple)) + " characters: ")
while len(word) != len(word_tuple):
if len(word) != len(word_tuple):
print("Wrong!")
word = input("Give a word of " + str(len(word_tuple)) + " characters: ")
for i in range(len(word_tuple)):
print(word_tuple[i], end="")
Basically, the loop checks if you insert a 5 character word, and if you do, it compares the word with the characters of the tuple. If 1 or more characters are correct, it will print the correct characters, and the ones which haven't been guessed are masked with a symbol, for example '*'.
The confusing part is where I have to check if the entered word has characters that match the tuple and then print out the correct characters.
So for example:
Give a word of 5 characters: Python
Wrong!
Give a word of 5 characters: Candy
Almost there! The word is "C*d*c"
Give a word of 5 characters: Denim
Almost there! The word is "C*dec"
Give a word of 5 characters: Codec
You found the word!
Any help would be greatly appreciated.
Upvotes: 1
Views: 1114
Reputation: 6169
Your problem is you do not print your word correctly, and your print is outside of the while, here is an answer you can try
word_tuple = ("c", "o", "d", "e", "c")
# We use this list to keep in memory the letters found
found = [False] * len(word_tuple)
word = ""
# The `all` method return True only if the list contains only True values
# Which means, while all letters are not found
while not all(found):
# the `lower` method allows you to not take in account the uppercases
word = input("Give a word of " + str(len(word_tuple)) + " characters: ").lower()
if len(word) == len(word_tuple):
for charac in word_tuple:
if charac in word:
found = [b or word_tuple[index] in word for index, b in enumerate(found)]
# The `any` method return True only if the list contains at least one True value
# Which means we print Wrong only if there is no letter found
if not any(found):
print('Wrong!')
else:
print('Almost there! The word is "', end='')
for i in range(len(word_tuple)):
if found[i]:
print(word_tuple[i], end="")
else:
print('*', end='')
print('"')
else:
print('Wrong!')
# The method `join` allows you to join every string of an iterable
# Which means it joins every character of your tuple to a printable string
while word != ''.join(word_tuple):
print('Close, try again')
word = input("Give a word of " + str(len(word_tuple)) + " characters: ").lower()
print('You found the word!')
An exercise can be to refactor this code in different methods
Upvotes: 2