Home > OS >  Validate user input uses only specific characters (7 random letters) for a word game in Python 3.10
Validate user input uses only specific characters (7 random letters) for a word game in Python 3.10

Time:03-15

I'm very new to programming, but I'm getting my feet wet by creating a word game.

import random
HowManyVowels = random.randint(1,5)
vowels = ["A" , "E" , "I" , "O" , "U"]
RoundVowels = random.sample(vowels,HowManyVowels)
HowManyConsonants = 7 - HowManyVowels
Consonants = ["B" , "C" , "D" , "F" , "G" , "H" , "J" , "K" , "L" , "M" , "N" , "P" , "Q" ,"R" , "S" , "T" , "V" , "W" , "X" , "Y" , "Z"]
RoundConsonants = random.sample(Consonants,HowManyConsonants)
RoundLetters = RoundVowels   RoundConsonants 
print(RoundLetters)
import time
WordsGuessed = []

timeout = time.time()   60*1   # 1 minute from now
while True:
    test = 0
    if test == 1 or time.time() > timeout:
        break
    test = test - 1
    PlayerWord = input("What letters can you make from these letters?")
    WordsGuessed.append(PlayerWord)

print(WordsGuessed)

I have gotten to where it can randomly select the letters for a round and limit a round to a minute. The input validation is where I am getting hung up. So if I run the code and the letters [ A E M R T S V ] are selected, the user should only be allowed to use those letters. Repetition will be allowed, and it must be over 3 length (but these two rules will be easier to implement).

The question is how do I restrict user input to the characters chosen each round (both uppercase and lowercase).

CodePudding user response:

Here's an easy way to validate. Loop through the letters in the word they input and make sure they're in the allowed list of letters. It'll look something like this:

for letter in PlayerWord: # This will loop through the input word
  if letter not in RoundLetters:
    print('Letter not in allowed list')
    check = True
    break
if check:
  check = False
  continue
else:
  wordsGuessed.append(PlayerWord)

Also, just a side note, group together all your import statements at the top of your code.

CodePudding user response:

I'll give you some parts but not the whole answer:

  • use in to check if a character is contained in a string e.g. 'a' in 'aeiou' == True
  • a string is correctly chosen if each of its letters is correctly chosen. use a for c in PlayerWord: loop to iterate over each letter in the word and remember if you find one that is incorrect
  • repeat the player input with a while loop until you get a correct word
  • Related