Skip to content

Commit

Permalink
0.3.0
Browse files Browse the repository at this point in the history
  • Loading branch information
MeetWq committed Jun 27, 2023
1 parent 35a60a9 commit ab342ef
Show file tree
Hide file tree
Showing 5 changed files with 660 additions and 669 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/update_poetry_lock.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
python-version: "3.10"

- name: Setup Poetry
uses: Gr1N/setup-poetry@v7
uses: Gr1N/setup-poetry@v8

- name: Update poetry.lock
run: poetry update --lock
Expand Down
130 changes: 55 additions & 75 deletions nonebot_plugin_cchess/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,7 @@
from typing import Dict, Iterable, List, NoReturn, Union

from nonebot import on_command, on_message, on_shell_command, require
from nonebot.adapters.onebot.v11 import Bot as V11Bot
from nonebot.adapters.onebot.v11 import GroupMessageEvent as V11GMEvent
from nonebot.adapters.onebot.v11 import Message as V11Msg
from nonebot.adapters.onebot.v11 import MessageEvent as V11MEvent
from nonebot.adapters.onebot.v11 import MessageSegment as V11MsgSeg
from nonebot.adapters.onebot.v11 import PrivateMessageEvent as V11PMEvent
from nonebot.adapters.onebot.v12 import Bot as V12Bot
from nonebot.adapters.onebot.v12 import ChannelMessageEvent as V12CMEvent
from nonebot.adapters.onebot.v12 import GroupMessageEvent as V12GMEvent
from nonebot.adapters.onebot.v12 import Message as V12Msg
from nonebot.adapters.onebot.v12 import MessageEvent as V12MEvent
from nonebot.adapters.onebot.v12 import MessageSegment as V12MsgSeg
from nonebot.adapters.onebot.v12 import PrivateMessageEvent as V12PMEvent
from nonebot.adapters import Bot, Event, Message
from nonebot.exception import ParserExit
from nonebot.matcher import Matcher
from nonebot.params import (
Expand All @@ -33,8 +21,28 @@
from nonebot.rule import ArgumentParser, Rule
from nonebot.typing import T_State

require("nonebot_plugin_saa")
require("nonebot_plugin_session")
require("nonebot_plugin_userinfo")
require("nonebot_plugin_datastore")

from nonebot_plugin_saa import Image, MessageFactory
from nonebot_plugin_saa import __plugin_meta__ as saa_plugin_meta
from nonebot_plugin_session import SessionIdType, SessionLevel
from nonebot_plugin_session import __plugin_meta__ as session_plugin_meta
from nonebot_plugin_session import extract_session
from nonebot_plugin_userinfo import __plugin_meta__ as userinfo_plugin_meta
from nonebot_plugin_userinfo import get_user_info

assert saa_plugin_meta.supported_adapters
assert session_plugin_meta.supported_adapters
assert userinfo_plugin_meta.supported_adapters
supported_adapters = (
saa_plugin_meta.supported_adapters
& session_plugin_meta.supported_adapters
& userinfo_plugin_meta.supported_adapters
)

from .board import MoveResult
from .config import Config
from .engine import EngineError
Expand All @@ -50,7 +58,10 @@
"发送 中文纵线格式如“炮二平五” 或 起始坐标格式如“h2e2”下棋;\n"
"发送“结束下棋”结束当前棋局;发送“显示棋盘”显示当前棋局"
),
type="application",
homepage="https://github.com/noneplugin/nonebot-plugin-cchess",
config=Config,
supported_adapters=supported_adapters,
extra={
"unique_name": "cchess",
"example": "@小Q 象棋人机lv5\n炮二平五\n结束下棋",
Expand Down Expand Up @@ -93,50 +104,31 @@ class Options:

@cchess.handle()
async def _(
bot: Union[V11Bot, V12Bot],
bot: Bot,
matcher: Matcher,
event: Union[V11MEvent, V12MEvent],
event: Event,
argv: List[str] = ShellCommandArgv(),
):
await handle_cchess(bot, matcher, event, argv)


def get_cid(bot: Union[V11Bot, V12Bot], event: Union[V11MEvent, V12MEvent]):
if isinstance(event, V11MEvent):
cid = f"{bot.self_id}_{event.sub_type}_"
else:
cid = f"{bot.self_id}_{event.detail_type}_"

if isinstance(event, V11GMEvent) or isinstance(event, V12GMEvent):
cid += str(event.group_id)
elif isinstance(event, V12CMEvent):
cid += f"{event.guild_id}_{event.channel_id}"
else:
cid += str(event.user_id)

return cid
def get_cid(bot: Bot, event: Event):
return extract_session(bot, event).get_id(SessionIdType.GROUP)


def shortcut(cmd: str, argv: List[str] = [], **kwargs):
command = on_command(cmd, **kwargs, block=True, priority=13)

@command.handle()
async def _(
bot: Union[V11Bot, V12Bot],
matcher: Matcher,
event: Union[V11MEvent, V12MEvent],
msg: Union[V11Msg, V12Msg] = CommandArg(),
):
async def _(bot: Bot, matcher: Matcher, event: Event, msg: Message = CommandArg()):
try:
args = shlex.split(msg.extract_plain_text().strip())
except:
args = []
await handle_cchess(bot, matcher, event, argv + args)


def game_running(
bot: Union[V11Bot, V12Bot], event: Union[V11MEvent, V12MEvent]
) -> bool:
def game_running(bot: Bot, event: Event) -> bool:
cid = get_cid(bot, event)
return bool(games.get(cid, None))

Expand All @@ -146,8 +138,11 @@ def smart_to_me(command_start: str = CommandStart(), to_me: bool = EventToMe())
return bool(command_start) or to_me


def not_private(event: Union[V11MEvent, V12MEvent]) -> bool:
return not (isinstance(event, V11PMEvent) or isinstance(event, V12PMEvent))
def not_private(bot: Bot, event: Event) -> bool:
return extract_session(bot, event).level not in (
SessionLevel.LEVEL0,
SessionLevel.LEVEL1,
)


shortcut("象棋对战", ["--battle"], aliases={"象棋双人"}, rule=Rule(smart_to_me) & not_private)
Expand Down Expand Up @@ -182,9 +177,9 @@ def get_move_input(state: T_State, msg: str = EventPlainText()) -> bool:

@pos_matcher.handle()
async def _(
bot: Union[V11Bot, V12Bot],
bot: Bot,
matcher: Matcher,
event: Union[V11MEvent, V12MEvent],
event: Event,
state: T_State,
):
move: str = state["move"]
Expand Down Expand Up @@ -216,20 +211,16 @@ def set_timeout(matcher: Matcher, cid: str, timeout: float = 600):


async def handle_cchess(
bot: Union[V11Bot, V12Bot],
bot: Bot,
matcher: Matcher,
event: Union[V11MEvent, V12MEvent],
event: Event,
argv: List[str],
):
async def new_player(event: Union[V11MEvent, V12MEvent]) -> Player:
async def new_player(event: Event) -> Player:
user_id = event.get_user_id()
user_name = ""
if isinstance(event, V11MEvent):
user_name = event.sender.card or event.sender.nickname or ""
else:
assert isinstance(bot, V12Bot)
resp = await bot.get_user_info(user_id=user_id)
user_name = resp["user_displayname"] or resp["user_name"]
if user_info := await get_user_info(bot, event, user_id=user_id):
user_name = user_info.user_name
return Player(user_id, user_name)

async def send(msgs: Union[str, Iterable[Union[str, BytesIO]]] = "") -> NoReturn:
Expand All @@ -238,25 +229,14 @@ async def send(msgs: Union[str, Iterable[Union[str, BytesIO]]] = "") -> NoReturn
if isinstance(msgs, str):
await matcher.finish(msgs)

if isinstance(bot, V11Bot):
message = V11Msg()
for msg in msgs:
if isinstance(msg, BytesIO):
message.append(V11MsgSeg.image(msg))
else:
message.append(msg)
else:
message = V12Msg()
for msg in msgs:
if isinstance(msg, BytesIO):
resp = await bot.upload_file(
type="data", name="cchess", data=msg.getvalue()
)
file_id = resp["file_id"]
message.append(V12MsgSeg.image(file_id))
else:
message.append(msg)
await matcher.finish(message)
msg_builder = MessageFactory([])
for msg in msgs:
if isinstance(msg, BytesIO):
msg_builder.append(Image(msg))
else:
msg_builder.append(msg)
await msg_builder.send()
await matcher.finish()

try:
args = parser.parse_args(argv)
Expand Down Expand Up @@ -328,7 +308,7 @@ async def send(msgs: Union[str, Iterable[Union[str, BytesIO]]] = "") -> NoReturn
games[cid] = game
set_timeout(matcher, cid)
await game.save_record(cid)
await send((msg, game.draw()))
await send((msg + "\n", game.draw()))

game = games[cid]
set_timeout(matcher, cid)
Expand Down Expand Up @@ -366,7 +346,7 @@ async def send(msgs: Union[str, Iterable[Union[str, BytesIO]]] = "") -> NoReturn
game.pop()
game.pop()
await game.save_record(cid)
await send((f"{player} 进行了悔棋", game.draw()))
await send((f"{player} 进行了悔棋\n", game.draw()))

if (game.player_next and game.player_next != player) or (
game.player_last and game.player_last == player
Expand Down Expand Up @@ -426,7 +406,7 @@ async def send(msgs: Union[str, Iterable[Union[str, BytesIO]]] = "") -> NoReturn
if game.player_next and game.is_battle:
msg += f",下一手轮到 {game.player_next}"

msgs.append(msg)
msgs.append(msg + "\n")

if game.is_battle:
msgs.append(game.draw())
Expand All @@ -439,7 +419,7 @@ async def send(msgs: Union[str, Iterable[Union[str, BytesIO]]] = "") -> NoReturn
move_chi = move.chinese(game)
result = game.push(move)

msg = f"{ai_player} 下出 {move_chi}"
msg = f"\n{ai_player} 下出 {move_chi}"
if result == MoveResult.ILLEAGAL:
game.pop()
await send("象棋引擎出错,请结束游戏或稍后再试")
Expand All @@ -453,7 +433,7 @@ async def send(msgs: Union[str, Iterable[Union[str, BytesIO]]] = "") -> NoReturn
msg += ",恭喜你赢了!" if player == game.player_black else ",很遗憾你输了!"
elif result == MoveResult.DRAW:
msg += f",本局游戏平局"
msgs.append(msg)
msgs.append(msg + "\n")
msgs.append(game.draw())

await game.save_record(cid)
Expand Down
1 change: 0 additions & 1 deletion nonebot_plugin_cchess/drawer.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ def draw_board(board: "Board", sameside: bool = True) -> BytesIO:

for i, line in enumerate(pieces):
for j, piece in enumerate(line):

if side:
x = 200 + 300 * j
y = 3150 - 300 * i
Expand Down
Loading

0 comments on commit ab342ef

Please sign in to comment.