I am currently in school in my first programming class. This week we have an assignment to create a Wordle type of game. I have most of my code done so far. Thing that I am struggling with the most right now is how do I tell the computer to Recognize certain letters in their guess and make them lowercase if they are in the wrong spot?
word = 'PYTHON'
guess = 'PINCH'
result = ''
for i, letter in enumerate(guess):
if i < len(word):
if word[i] == letter:
result += letter
continue
if letter in word:
result += letter.lower()
else:
result += '_'
print(result)
Now let’s break it down:
for i, letter in enumerate(guess):
This will loop on letter and return the index and value
if i < len(word):
We don’t want an exception when checking to see if the letter is placed beyond the length of the word (this isn’t relevant for Wordle where you’re limited to 5 letters but I thought it would be worth showing as well).
if word[i] == letter:
result += letter
continue
If we have the same letter at the same index in both words - add it to the result and then continue to loop because we’ve finished processing that letter.
if letter in word:
result += letter.lower()
If the letter is in the word but not that spot add the lowercase version to the result (str.lower() gives the lowercase string.)
else:
result += '_'
The letter isn’t in the word so add a placeholder.
I hope this helps out somewhat. There is other functionality you probably want to add such as if the word is SNAKE and the guess is CANNY you don’t want to indicate that there are multiple Ns in the word.
I wrote a Wordle copy a while ago, and the thing that took me the longest to work out was needing to use two separate loops: checking if a letter is in the word and in the correct position, then checking again to see if a letter is in the word but in the wrong position.