I am writing a simple word guessing game in python, instead of using a list, I have all the words for the game in a txt file called as the parameter of a function. the list itself is fine.
the game requires the user to enter a letter. once the letter is entered, if it matched one of the words that is randomly selected by the random function, it gives points accordingly.
the problem is that when the function runs, the entered letter by the user iterates through all the words in the list. How do I fix this issue.
def guess_game(data):
word = random.choice(data)
print("alright, guess the first letter:")
ans = input("Enter a letter to guess: ")
print(ans)
counter = 0
tries = 15 #how many tries a user is allowed to make
for match in word:
if ans in match:
counter = 10
tries -= 1
print("That's right, 10 points added")
print(f"You have {tries} tries left. ")
elif ans not in match:
counter -= 10
tries -= 1
print("That's wrong, 10 points deducted")
print(f"You have {tries} tries left. ")
```
CodePudding user response:
Not sure if I understand this completely, but if word is just a word like "apple" or "cat", then your function shouldn't be iterating through your entire list (your list being data). This function iterates through each letter of the randomized word (like "apple") and checks if the inputted letter is equal to any of the letters in that word.
CodePudding user response:
few ideas:
- make a loop over your "tries" - the player can play until that is 0
- the player has to provide the letter inside this loop
- check for the letter provided by the player using
if ans in word
Here is my suggestion:
import random
print('Hi, welcome to the guessing game, wanna play?')
answer = input('Enter yes or no: ')
#just added a list to test
data = ['hello', 'coffee', 'tea']
word = random.choice(data)
if answer == "yes".lower():
print("OK, let's play")
print("alright, guess the first letter:")
counter = 0
tries = 15 # how many tries a user is allowed to make
while tries > 0:
ans = input("Enter a letter to guess: ")
print(ans)
if ans in word:
counter = 10
tries -= 1
print("That's right, 10 points added")
print(f"You have {tries} tries left. ")
elif ans not in word:
counter -= 10
tries -= 1
print("That's wrong, 10 points deducted")
print(f"You have {tries} tries left. ")
elif answer == "no".lower():
print("OK, have a good day")
else:
print('Please enter yes or no')
You could also make a list of letter that were already guessed so you can give the player feedback as soon as they found all the needed letters.
CodePudding user response:
The 'in' keyword itself checks only the first occurrence of a variable in a collection.
However if you want to be more specific, assign your entered word to a variable and then use break keyword after it matches under the if statement while iterating through the list.