Skip to content

Commit

Permalink
wordle multiplayer (#1574)
Browse files Browse the repository at this point in the history
* u

* fix

* u

* locale

* fix
---------

Co-authored-by: 好耶! <[email protected]>
  • Loading branch information
DoroWolf and cloudw233 committed Feb 7, 2025
1 parent 007ac26 commit 3459a71
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 58 deletions.
4 changes: 2 additions & 2 deletions core/locales/en_us.json
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@
"error.prompt.timeout": "An error occurred while executing the command:\n${detail}\nThis error may be caused by the bot not processing messages in time. If the error occurs repeatedly, please report the following message to developers.",
"example": "Hello world!",
"game.help.stop": "Stop the current game.",
"game.message.running": "This game is currently in progress.",
"game.message.running": "This game is currently running.",
"game.message.stop": "Stopped.",
"game.message.stop.none": "This game is not in progress.",
"game.message.stop.none": "This game is not running.",
"help.option.legacy": "Force text mode.",
"i18n.unit.1": "k",
"i18n.unit.2": "M",
Expand Down
45 changes: 21 additions & 24 deletions core/utils/game.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from collections import defaultdict
from datetime import datetime
from typing import Any, Dict
from typing import Any, Dict, Optional

from core.builtins import MessageSession
from core.logger import Logger
Expand Down Expand Up @@ -81,26 +81,22 @@ def disable(self) -> None:
if self.target_id not in _ps_lst:
return
target_dict = _ps_lst[self.target_id]
if self.whole_target:
game_dict = target_dict.get(self.game)
if game_dict:
game_dict["_status"] = False
else:
sender_dict = target_dict.get(self.sender_id)
if sender_dict:
game_dict = sender_dict.get(self.game)
if game_dict:
game_dict["_status"] = False
if self.whole_target:
game_dict = target_dict.get(self.game)
if game_dict and game_dict.get("_status"):
game_dict["_status"] = False
Logger.info(
f"[{self.target_id}]: Disabled {self.game} by {self.sender_id}."
)
else:
Logger.info(
f"[{self.sender_id}]: Disabled {self.game} at {self.target_id}."
)
sender_dict = target_dict.get(self.sender_id)
if sender_dict:
game_dict = sender_dict.get(self.game)
if game_dict and game_dict.get("_status"):
game_dict["_status"] = False
Logger.info(
f"[{self.sender_id}]: Disabled {self.game} at {self.target_id}."
)

def update(self, **kwargs: Dict[str, Any]) -> None:
def update(self, **kwargs) -> None:
"""
更新游戏事件中需要的值。
Expand All @@ -119,24 +115,25 @@ def check(self) -> bool:
"""
检查游戏事件状态。
"""
if self.target_id not in _ps_lst:
status = self.get("_status", False, True)
if not (self.target_id in _ps_lst and status):
return False
status = self.get("_status", False)
return status
return True

def get(self, key: str, default: Any = None) -> Any:
def get(self, key: str, default: Any = None, whole_target: Optional[bool] = None) -> Any:
"""
获取游戏事件中需要的值。
:param key: 键名。
:param default: 默认值。
:param whole_target: 是否取全对话的值。(默认跟随类定义)
:return: 值。
:default: 默认值。
"""
print(str(_ps_lst))
whole_target = self.whole_target if whole_target is None else whole_target
if self.target_id not in _ps_lst:
return None
target_dict = _ps_lst[self.target_id]
if self.whole_target:
if whole_target:
return target_dict.get(self.game, {}).get(key, default)
sender_dict = target_dict.get(self.sender_id, {})
return sender_dict.get(self.game, {}).get(key, default)
4 changes: 1 addition & 3 deletions modules/core/modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,9 +383,7 @@ def module_reload(module, extra_modules, base_module=False):
await msg.finish(msglist)
else:
await msg.send_message(msglist)
if recommend_modules_help_doc_list and (
"-g" not in msg.parsed_msg or not msg.parsed_msg["-g"]
):
if recommend_modules_help_doc_list and not ("-g" in msg.parsed_msg and msg.parsed_msg["-g"]):
confirm = await msg.wait_confirm(
msg.locale.t(
"core.message.module.recommends",
Expand Down
58 changes: 35 additions & 23 deletions modules/wordle/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,27 @@
)


@wordle.command("{{wordle.help}}")
@wordle.command("hard {{wordle.help.hard}}")
@wordle.command()
@wordle.command("[--hard] [--trial] {{wordle.help}}",
options_desc={"--hard": "{wordle.help.option.hard}",
"--trial": "{wordle.help.option.trial}"})
async def _(msg: Bot.MessageSession):
play_state = PlayState("wordle", msg)
hard_mode = bool(msg.parsed_msg and msg.parsed_msg.get("--hard", False))
trial = bool(msg.parsed_msg and msg.parsed_msg.get("--trial", False))

play_state = PlayState("wordle", msg, whole_target=not trial)
if play_state.check():
await msg.finish(msg.locale.t("game.message.running"))
if PlayState("wordle", msg, whole_target=trial).check():
await msg.finish(msg.locale.t("wordle.message.occupied"))

qc = CoolDown("wordle", msg, 180)
qc = CoolDown("wordle", msg, 180, whole_target=not trial)
if not msg.target.client_name == "TEST" and not msg.check_super_user():
c = qc.check()
if c != 0:
await msg.finish(msg.locale.t("message.cooldown", time=int(c)))

board = WordleBoard.from_random_word()
hard_mode = bool(msg.parsed_msg and "hard" in msg.parsed_msg)
last_word = None
board_image = WordleBoardImage(
wordle_board=board, dark_theme=msg.data.options.get("wordle_dark_theme")
Expand All @@ -40,18 +46,21 @@ async def _(msg: Bot.MessageSession):
play_state.enable()
play_state.update(answer=board.word)
Logger.info(f"Answer: {board.word}")
if text_mode:
start_msg = msg.locale.t("wordle.message.start")
if hard_mode:
start_msg += "\n" + msg.locale.t("wordle.message.start.hard")
else:
start_msg = [BImage(board_image.image), I18NContext("wordle.message.start")]
if hard_mode:
start_msg.append(I18NContext("wordle.message.start.hard"))
start_msg = []
if not text_mode:
start_msg.append(BImage(board_image.image))
start_msg.append(I18NContext("wordle.message.start"))
if hard_mode:
start_msg.append(I18NContext("wordle.message.start.hard"))
if trial:
start_msg.append(I18NContext("wordle.message.start.trial"))
await msg.send_message(start_msg)

while board.get_trials() <= 6 and play_state.check() and not board.is_game_over():
wait = await msg.wait_next_message(timeout=GAME_EXPIRED)
if trial:
wait = await msg.wait_next_message(timeout=GAME_EXPIRED)
else:
wait = await msg.wait_anyone(timeout=GAME_EXPIRED)
word = wait.as_display(text_only=True).strip().lower()
if len(word) != 5 or not (word.isalpha() and word.isascii()):
continue
Expand All @@ -78,10 +87,11 @@ async def _(msg: Bot.MessageSession):
g_msg = msg.locale.t("wordle.message.finish", answer=board.word)
if board.board[-1] == board.word:
g_msg = msg.locale.t("wordle.message.finish.success", attempt=attempt)
petal = 2 if attempt <= 3 else 1
petal += 1 if hard_mode else 0
if reward := await gained_petal(msg, petal):
g_msg += "\n" + reward
if trial:
petal = 2 if attempt <= 3 else 1
petal += 1 if hard_mode else 0
if reward := await gained_petal(msg, petal):
g_msg += "\n" + reward
qc.reset()
if text_mode:
await msg.finish(board.format_board() + "\n" + g_msg, quote=False)
Expand All @@ -92,13 +102,15 @@ async def _(msg: Bot.MessageSession):
@wordle.command("stop {{game.help.stop}}")
async def _(msg: Bot.MessageSession):
play_state = PlayState("wordle", msg)
qc = CoolDown("wordle", msg, 180)
target_play_state = PlayState("wordle", msg, whole_target=True)
if play_state.check():
play_state.disable()
qc.reset()
await msg.finish(
msg.locale.t("wordle.message.stop", answer=play_state.get("answer"))
)
CoolDown("wordle", msg, 180).reset()
await msg.finish(msg.locale.t("wordle.message.stop", answer=play_state.get("answer")))
elif target_play_state.check():
target_play_state.disable()
CoolDown("wordle", msg, 180, whole_target=True).reset()
await msg.finish(msg.locale.t("wordle.message.stop", answer=target_play_state.get("answer")))
else:
await msg.finish(msg.locale.t("game.message.stop.none"))

Expand Down
7 changes: 5 additions & 2 deletions modules/wordle/locales/en_us.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@
"config.comments.wordle_disable_image": "Whether to disable images of wordle module.",
"wordle.help": "Start a new game.",
"wordle.help.desc": "Play Wordle.",
"wordle.help.hard": "Use hard mode.",
"wordle.help.option.hard": "Use hard mode.",
"wordle.help.option.trial": "Use trial mode.",
"wordle.help.theme": "Set whether to use dark theme.",
"wordle.message.finish": "Game over. The answer is ${answer}.\\nWord lookup: https://dictionary.cambridge.org/dictionary/english/${answer}",
"wordle.message.occupied": "There is the game running in this session.",
"wordle.message.finish": "Game over. The answer is ${answer}.\nWord lookup: https://dictionary.cambridge.org/dictionary/english/${answer}",
"wordle.message.finish.success": "Congratulations! You complete the game in ${attempt} turn(s).",
"wordle.message.hard.not_matched": "The word does not correspond.",
"wordle.message.not_a_word": "This is not a valid word.",
"wordle.message.start": "The game has started. You will guess a 5-letter word by testing up to 6 words.\nGreen indicates the letter is in the word and is in its place; yellow indicates the letter is in the word, but it is not at its current location; gray indicates the letter is not in the word.",
"wordle.message.start.hard": "The letters that were color-coded in the previous turn must appear in the following turn and must meet the corresponding requirements.",
"wordle.message.start.trial": "You are playing in trial mode. Successfully completing the game will earn you the petals.",
"wordle.message.stop": "Stopped. The answer is: ${answer}.\nWord lookup: https://dictionary.cambridge.org/dictionary/english/${answer}",
"wordle.message.theme.disable": "Dark theme disabled.",
"wordle.message.theme.enable": "Dark theme enabled."
Expand Down
7 changes: 5 additions & 2 deletions modules/wordle/locales/zh_cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@
"config.comments.wordle_disable_image": "wordle 模块是否禁用图片。",
"wordle.help": "开始新游戏。",
"wordle.help.desc": "玩 Wordle。",
"wordle.help.hard": "使用困难模式。",
"wordle.help.option.hard": "使用困难模式。",
"wordle.help.option.trial": "使用挑战模式。",
"wordle.help.theme": "设置是否使用深色主题。",
"wordle.message.finish": "游戏结束,答案为:${answer}。\n查询词典:https://dictionary.cambridge.org/dictionary/english-chinese-simplified/${answer}",
"wordle.message.occupied": "此会话内有游戏正在进行。",
"wordle.message.finish": "游戏结束,答案为:${answer}。\n查询词典:https://dictionary.cambridge.org/dictionary/english/${answer}",
"wordle.message.finish.success": "祝贺!你在 ${attempt} 回合内完成了游戏。",
"wordle.message.hard.not_matched": "输入的单词不符合要求。",
"wordle.message.not_a_word": "这不是一个有效的单词。",
"wordle.message.start": "游戏开始,你需要猜一个由 5 个字母组成的单词,你有 6 次机会。\n绿色表示字母和位置都正确,黄色代表字母正确但位置不正确,灰色代表单词中没有这个字母。",
"wordle.message.start.hard": "在上一回合中被颜色标记的字母在接下来的回合中必须出现,且必须符合对应的要求。",
"wordle.message.start.trial": "你正在进行挑战模式,成功完成游戏可获得花瓣。",
"wordle.message.stop": "已停止,答案为:${answer}。\n查询词典:https://dictionary.cambridge.org/dictionary/english/${answer}",
"wordle.message.theme.disable": "已关闭深色主题。",
"wordle.message.theme.enable": "已开启深色主题。"
Expand Down
7 changes: 5 additions & 2 deletions modules/wordle/locales/zh_tw.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@
"wordle.help": "開始新遊戲。",
"wordle.help.desc": "玩 Wordle。",
"wordle.help.hard": "使用困難模式。",
"wordle.help.option.trial": "使用挑戰模式。",
"wordle.help.theme": "設定是否使用深色主題。",
"wordle.message.finish": "遊戲結束,答案為:${answer}。\n查詢辭典:https://dictionary.cambridge.org/dictionary/english-chinese-traditional/${answer}",
"wordle.message.occupied": "此會話內有遊戲正在進行。",
"wordle.message.finish": "遊戲結束,答案為:${answer}。\n查詢辭典:https://dictionary.cambridge.org/dictionary/english/${answer}",
"wordle.message.finish.success": "祝賀!你在 ${attempt} 回合內完成了遊戲。",
"wordle.message.hard.not_matched": "輸入的單詞不符合要求。",
"wordle.message.not_a_word": "這不是一個有效的單詞。",
"wordle.message.start": "遊戲開始,你需要猜一個由 5 個字母組成的單詞,你有 6 次機會。\n綠色表示字母和位置都正確,黃色代表字母正確但位置不正確,灰色代表單詞中沒有這個字母。",
"wordle.message.start.hard": "在上一回合中被色彩標記的字母在接下來的回合中必須出現,且必須符合對應的要求。",
"wordle.message.start.trial": "你正在進行挑戰模式,成功完成遊戲可取得花瓣。",
"wordle.message.stop": "已停止,答案为:${answer}。\n查詢辭典:https://dictionary.cambridge.org/dictionary/english/${answer}",
"wordle.message.theme.disable": "已禁用深色主題。",
"wordle.message.theme.enable": "已啟用深色主題。"
}
}

0 comments on commit 3459a71

Please sign in to comment.