Jason Chun
Jason Chun

Reputation: 1

How to get only one letter to change color

This is my code for a wordle game. when my code runs and say the target_word is a word with no double letters like Bread. But if the person enters a word with double letters like Breed then then I want the code to only make one 'e' yellow and the other leave as white. How can I do this?

import random
import nltk
nltk.download('words')

Turns = 0

from nltk.corpus import words

word_list = words.words()

word_list = [word for word in word_list if len(word)==5]

target_word = random.choice(word_list)
target_word = target_word.upper()
print(target_word)

# HEADER = '\033[95m'
# OKBLUE = '\033[94m'
# OKCYAN = '\033[96m'
# OKGREEN = '\033[92m' 
# WARNING = '\033[93m'
# FAIL = '\033[91m'
# ENDC = '\033[0m'
# BOLD = '\033[1m'
# UNDERLINE = '\033[4m'

print('You have 6 turns')

while Turns  < 6:
  print(f"\nThis is turn {Turns + 1}")
  
  response = input("Please enter a five letter word: ")
  
  if len(response) != 5:
    print(f"\nThis word is not five letters")
    continue
    
  if response not in word_list:
    print(f"\nThis is not a word")
    continue
    
  response = response.upper()
  
  result = ""
  
  target_word_tmp = list(target_word)
  
  for i in range(len(target_word_tmp)):
    if target_word_tmp[i] == response[i]:
      result += (f'\033[92m{response[i]}\033[0m')
      target_word_tmp[i] = ' '
    elif response[i] in target_word:
      result += (f'\033[93m{response[i]}\033[0m')
    else:
      result += (f'{response[i]}')
      
  print(f"\n{result}")
  
  Turns += 1

  if response == target_word:
    print("You win")
    break

if Turns == 6 and response != target_word:
  print(f'You lose. The word was {target_word}')

Upvotes: 0

Views: 463

Answers (1)

Mohammed
Mohammed

Reputation: 1

The code below gives you a list containing the index and the color for repeated letters. Notice that the list will be empty if the word has no repeated letters:

import re

rx = re.compile(r'(.)\1{1,}')
string = "Breed"

repeated_letters = []

for i in re.finditer(rx , string):
    
    repeated_letters.append({i.span()[0]:"yellow"})
    
    if (i.span()[1] - i.span()[0]) == 2: # this means there is only two repeated letters.
        
         repeated_letters.append({i.span()[1]-1:"white"})
            
    else: # in this case there are more than two repeated letters.
        
        for j in range(i.span()[0]+1 , i.span()[1]):
            repeated_letters.append({j:"white"})
            
if len(repeated_letters) == 0:
    print("there is no repeated letters") 

Upvotes: 0

Related Questions