UBS-Server / routes /wordle.py
m-abdur2024's picture
Update routes/wordle.py
0f1c32c verified
raw
history blame contribute delete
No virus
2.65 kB
import json
import logging
from collections import defaultdict
from flask import Flask, request, jsonify
import nltk
from nltk.corpus import words
import random
from routes import app
# Initialize NLTK word list
try:
nltk.data.find('corpora/words')
except LookupError:
nltk.download('words')
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def load_word_list():
word_list = [word.lower() for word in words.words() if len(word) == 5 and word.isalpha()]
return word_list
WORD_LIST = load_word_list()
def filter_words(guess, feedback, guess_list):
for word in guess_list[:]: # Create a copy of the list to avoid modifying it during iteration
for i in range(5):
if feedback[i] == "w" and guess[i] in word and guess.count(guess[i]) == 1:
guess_list.remove(word)
break
elif feedback[i] == "g" and guess[i] != word[i]:
guess_list.remove(word)
break
elif feedback[i] == "y" and guess[i] not in word:
guess_list.remove(word)
break
elif feedback[i] == "y" and guess[i] == word[i]:
guess_list.remove(word)
break
return guess_list
def suggest_best_guess(guess_history, evaluation_history, word_list):
# Start with the full word list
guess_list = word_list.copy()
for guess, feedback in zip(guess_history, evaluation_history):
guess_list = filter_words(guess, feedback, guess_list)
# Return the best guess (first valid word in the filtered list)
return guess_list[0] if guess_list else None # Return None if no valid words are left
@app.route('/wordle-game', methods=['POST'])
def wordle_game():
# Parse JSON input
data = request.get_json()
logger.info("Data received for evaluation: %s", data)
guess_history = data.get("guessHistory", [])
evaluation_history = data.get("evaluationHistory", [])
start_word = ["crate", "raise", "least", "salet"]
n = random.randint(-1,2)
# If first word, use "CRATE" as the first guess
if not guess_history:
next_guess = start_word[n]
logger.info("First guess: %s", next_guess)
return jsonify({"guess": next_guess})
# Suggest the next guess
next_guess = suggest_best_guess(guess_history, evaluation_history, WORD_LIST)
logger.info("Suggested next guess: %s", next_guess)
# If evaluation history is 6 or more, the game is over
if len(evaluation_history) >= 6:
return jsonify({})
# Return the response
return jsonify({"guess": next_guess})