Update app/noi_tu.py
Browse files- app/noi_tu.py +46 -27
app/noi_tu.py
CHANGED
|
@@ -1,30 +1,49 @@
|
|
| 1 |
-
# Thêm vào đầu file main.py (sau các import hiện có)
|
| 2 |
import httpx
|
| 3 |
-
|
| 4 |
-
from
|
| 5 |
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
async def
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import httpx
|
| 2 |
+
import random
|
| 3 |
+
from typing import Optional
|
| 4 |
|
| 5 |
+
class NoiTuApp:
|
| 6 |
+
def __init__(self):
|
| 7 |
+
self.url = "https://github.com/NNBnh/noi-tu/raw/refs/heads/main/words/words.txt"
|
| 8 |
+
self.words = set()
|
| 9 |
|
| 10 |
+
async def start(self):
|
| 11 |
+
"""Tải dữ liệu từ vựng khi khởi động server"""
|
| 12 |
+
try:
|
| 13 |
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 14 |
+
response = await client.get(self.url)
|
| 15 |
+
if response.status_code == 200:
|
| 16 |
+
# Tách từ theo dòng, chuyển về chữ thường và strip khoảng trắng
|
| 17 |
+
self.words = {line.strip().lower() for line in response.text.splitlines() if line.strip()}
|
| 18 |
+
print(f"Loaded {len(self.words)} words for NoiTuApp")
|
| 19 |
+
else:
|
| 20 |
+
print(f"Failed to load words: {response.status_code}")
|
| 21 |
+
except Exception as e:
|
| 22 |
+
print(f"Error loading words: {e}")
|
| 23 |
+
|
| 24 |
+
async def stop(self):
|
| 25 |
+
self.words.clear()
|
| 26 |
+
|
| 27 |
+
def get_next_word(self, current_word: str) -> Optional[str]:
|
| 28 |
+
"""Tìm một từ bắt đầu bằng tiếng cuối của từ hiện tại"""
|
| 29 |
+
current_word = current_word.lower().strip()
|
| 30 |
+
parts = current_word.split()
|
| 31 |
+
|
| 32 |
+
# Lấy tiếng cuối cùng (ví dụ: "học sinh" -> "sinh")
|
| 33 |
+
last_syllable = parts[-1]
|
| 34 |
+
|
| 35 |
+
# Tìm các từ trong danh sách bắt đầu bằng last_syllable
|
| 36 |
+
# Và phải là từ có ít nhất 2 tiếng (để game tiếp tục được)
|
| 37 |
+
candidates = [
|
| 38 |
+
w for w in self.words
|
| 39 |
+
if w.startswith(last_syllable + " ") and w != current_word
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
if not candidates:
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
return random.choice(candidates)
|
| 46 |
+
|
| 47 |
+
def is_valid_word(self, word: str) -> bool:
|
| 48 |
+
"""Kiểm tra từ có trong từ điển không"""
|
| 49 |
+
return word.lower().strip() in self.words
|