aboutsummaryrefslogtreecommitdiffstatshomepage
diff options
context:
space:
mode:
author简律纯 <i@jyunko.cn>2024-06-28 18:25:40 +0800
committer简律纯 <i@jyunko.cn>2024-06-28 18:25:40 +0800
commit6dfe2f4a87362a27fe2e97a154daac2f11883284 (patch)
treebd4f28514482042735182d86d2c89dec8d655674
parent1b0d67664557e6f0b4a421e1183cee1b0dbca2d3 (diff)
downloadHydroRollCore-6dfe2f4a87362a27fe2e97a154daac2f11883284.tar.gz
HydroRollCore-6dfe2f4a87362a27fe2e97a154daac2f11883284.zip
style: ruff format code
-rw-r--r--docs/source/conf.py3
-rw-r--r--examples/COC7/Character.py94
-rw-r--r--examples/COC7/Wiki.py7
-rw-r--r--examples/COC7/__init__.py37
-rw-r--r--examples/brp_character.py4
-rw-r--r--hrc/__init__.py24
-rw-r--r--hrc/config.py3
-rw-r--r--hrc/core.py51
-rw-r--r--hrc/event.py3
-rw-r--r--hrc/log.py2
-rw-r--r--hrc/rule/BaseRule/CharacterCard.py13
-rw-r--r--hrc/rule/BaseRule/__init__.py6
-rw-r--r--hrc/rule/__init__.py15
-rw-r--r--hrc/typing.py2
-rw-r--r--hrc/utils.py2
-rw-r--r--tests/test_BaseRule.py5
16 files changed, 134 insertions, 137 deletions
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 7b02611..424ed3c 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -3,7 +3,8 @@
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
-import os, sys
+import os
+import sys
if sys.version_info >= (3, 11):
import tomllib
diff --git a/examples/COC7/Character.py b/examples/COC7/Character.py
index b5f07c5..70b934b 100644
--- a/examples/COC7/Character.py
+++ b/examples/COC7/Character.py
@@ -10,87 +10,101 @@ from hrc.rule.BaseRule import CharacterCard
@dataclass
class Attributes(CharacterCard.Attribute):
-
@property
- @aliases(['luck', '运气'], ignore_case=True)
+ @aliases(["luck", "运气"], ignore_case=True)
def LUK(self) -> Union[str, int, None]: ...
@property
- @aliases(['伤害加值', 'DamageBonus'], ignore_case=True)
+ @aliases(["伤害加值", "DamageBonus"], ignore_case=True)
def DB(self) -> Union[str, int, None]:
sum = self.STR + self.SIZ
return (
- str(math.ceil((sum - 164) / 80)) + "D6" if sum > 164 else
- "1D4" if sum > 124 else
- "0" if sum > 84 else
- "-1" if sum > 64 else
- "-2" if sum > 0 else
- None
+ str(math.ceil((sum - 164) / 80)) + "D6"
+ if sum > 164
+ else "1D4"
+ if sum > 124
+ else "0"
+ if sum > 84
+ else "-1"
+ if sum > 64
+ else "-2"
+ if sum > 0
+ else None
)
@property
- @aliases(['年龄', 'age'], ignore_case=True)
+ @aliases(["年龄", "age"], ignore_case=True)
def AGE(self) -> Union[str, int, None]: ...
@property
- @aliases(['HitPoints', '生命值', '生命'], ignore_case=True)
+ @aliases(["HitPoints", "生命值", "生命"], ignore_case=True)
def HP(self) -> Union[str, int, None]:
return self.MAX_HP
@property
- @aliases(['最大生命值', 'HitPointTotal', '总生命值'], ignore_case=True)
+ @aliases(["最大生命值", "HitPointTotal", "总生命值"], ignore_case=True)
def MAX_HP(self) -> Union[str, int, None]:
- if hasattr(self, 'CON') and hasattr(self, 'SIZ'):
+ if hasattr(self, "CON") and hasattr(self, "SIZ"):
return (self.CON + self.SIZ) // 10
else:
return None
@property
- @aliases(['理智', 'Sanity', 'SanityPoint', '理智值', 'san值'], ignore_case=True)
+ @aliases(["理智", "Sanity", "SanityPoint", "理智值", "san值"], ignore_case=True)
def SAN(self) -> Union[str, int, None]:
return self.POW
@property
- @aliases(['最大理智值', 'MaximumSanity'], ignore_case=True)
+ @aliases(["最大理智值", "MaximumSanity"], ignore_case=True)
def MAX_SAN(self) -> Union[str, int, None]:
return 99 - self.player_card.CM
@property
- @aliases(['魔法', '魔法值', 'MagicPoints'], ignore_case=True)
+ @aliases(["魔法", "魔法值", "MagicPoints"], ignore_case=True)
def MP(self) -> Union[str, int, None]:
- if hasattr(self, 'POW'):
+ if hasattr(self, "POW"):
return math.floor(self.POW / 5)
else:
return None
@property
- @aliases(['伤害加值', 'DamageBonus'], ignore_case=True)
- def DB(self) -> Union[int, str, None]:
+ @aliases(["伤害加值", "DamageBonus"], ignore_case=True)
+ def DB(self) -> Union[int, str, None]: # noqa: F811
sum = self.STR + self.SIZ
return (
- str(math.ceil((sum - 164) / 80)) + "D6" if sum > 164 else
- "1D4" if sum > 124 else
- "0" if sum > 84 else
- "-1" if sum > 64 else
- "-2" if sum > 0 else
- None
+ str(math.ceil((sum - 164) / 80)) + "D6"
+ if sum > 164
+ else "1D4"
+ if sum > 124
+ else "0"
+ if sum > 84
+ else "-1"
+ if sum > 64
+ else "-2"
+ if sum > 0
+ else None
)
@property
- @aliases(['体格', 'build'], ignore_case=True)
+ @aliases(["体格", "build"], ignore_case=True)
def BUILD(self) -> Union[str, int, None]:
sum = self.STR + self.SIZ
return (
- math.ceil((sum - 84) / 80) if sum > 164 else
- 1 if sum > 124 else
- 0 if sum > 84 else
- -1 if sum > 64 else
- -2 if sum > 0 else
- None
+ math.ceil((sum - 84) / 80)
+ if sum > 164
+ else 1
+ if sum > 124
+ else 0
+ if sum > 84
+ else -1
+ if sum > 64
+ else -2
+ if sum > 0
+ else None
)
@property
- @aliases(['移动速度'], ignore_case=True)
+ @aliases(["移动速度"], ignore_case=True)
def MOV(self) -> Union[str, int, None]:
mov = 8
siz = self.player_card.SIZ
@@ -109,23 +123,23 @@ class Attributes(CharacterCard.Attribute):
return mov
@property
- @aliases(['兴趣技能点', 'PersonalInterests'], ignore_case=True)
+ @aliases(["兴趣技能点", "PersonalInterests"], ignore_case=True)
def PI(self) -> Union[str, int, None]:
- return self.player_card.INT*2
+ return self.player_card.INT * 2
@property
- @aliases(['闪避', 'Dodge'], ignore_case=True)
+ @aliases(["闪避", "Dodge"], ignore_case=True)
def DODGE(self) -> Union[str, int, None]:
- if hasattr(self.player_card, 'DEX'):
- return math.floor(self.player_card.DEX/2)
+ if hasattr(self.player_card, "DEX"):
+ return math.floor(self.player_card.DEX / 2)
return None
@property
- @aliases(['锁匠', '开锁', '撬锁', 'Locksmith'], ignore_case=True)
+ @aliases(["锁匠", "开锁", "撬锁", "Locksmith"], ignore_case=True)
def LOCKSMITH(self) -> Union[str, int, None]:
return 1
@property
- @aliases(['动物驯养', '驯兽', 'AnimalHandling'], ignore_case=True)
+ @aliases(["动物驯养", "驯兽", "AnimalHandling"], ignore_case=True)
def ANIMAL_HANDLING(self) -> Union[str, int, None]:
return 1
diff --git a/examples/COC7/Wiki.py b/examples/COC7/Wiki.py
index 2c786e7..62b66ab 100644
--- a/examples/COC7/Wiki.py
+++ b/examples/COC7/Wiki.py
@@ -1,9 +1,2 @@
# MyRule
-import math
-import dataclasses
-from dataclasses import dataclass
-from typing import Literal, Optional, Union
-from pydantic import Field, BaseModel
-from hrc.rule import aliases, BaseRule
-from hrc.rule.BaseRule import CharacterCard \ No newline at end of file
diff --git a/examples/COC7/__init__.py b/examples/COC7/__init__.py
index ecd2091..01efe57 100644
--- a/examples/COC7/__init__.py
+++ b/examples/COC7/__init__.py
@@ -6,19 +6,36 @@ core = Core()
@core.event_post_processor_hook
-async def auto_card(_event='T_Event'):
+async def auto_card(_event="T_Event"):
g = core.session
pc = player_card
if g and core.session.gid and g.ac:
- if hasattr(pc.trans, '生命') or hasattr(pc.trans, '理智'):
- core.session.call("set_group_card", pc.gid, f"card#{pc.uid}", await overview_card(pc.char))
+ if hasattr(pc.trans, "生命") or hasattr(pc.trans, "理智"):
+ core.session.call(
+ "set_group_card", pc.gid, f"card#{pc.uid}", await overview_card(pc.char)
+ )
async def overview_card(pc: player_card):
- max_hp = math.floor((pc.get('CON', 0) + pc.get('SIZ', 0) / 10))
- max_san = math.floor(99 - pc.get('CM', 0))
- mp = pc.get('MP', 0)
- mp_show = " mp" + str(mp) + "/" + str(
- math.floor(pc.get('POW', 0) / 5)
- ) if mp and mp != math.floor(pc.get('POW', 0) / 5) else ""
- return pc.get('__Name', "") + " hp" + str(pc.get('HP', max_hp)) + "/" + str(max_hp) + " san" + str(pc.get('SAN', "?")) + "/" + str(max_san) + mp_show + " DEX" + str(pc.get('DEX', "?"))
+ max_hp = math.floor((pc.get("CON", 0) + pc.get("SIZ", 0) / 10))
+ max_san = math.floor(99 - pc.get("CM", 0))
+ mp = pc.get("MP", 0)
+ mp_show = (
+ " mp" + str(mp) + "/" + str(math.floor(pc.get("POW", 0) / 5))
+ if mp and mp != math.floor(pc.get("POW", 0) / 5)
+ else ""
+ )
+ return (
+ pc.get("__Name", "")
+ + " hp"
+ + str(pc.get("HP", max_hp))
+ + "/"
+ + str(max_hp)
+ + " san"
+ + str(pc.get("SAN", "?"))
+ + "/"
+ + str(max_san)
+ + mp_show
+ + " DEX"
+ + str(pc.get("DEX", "?"))
+ )
diff --git a/examples/brp_character.py b/examples/brp_character.py
index 9b52aa3..cc3bfcd 100644
--- a/examples/brp_character.py
+++ b/examples/brp_character.py
@@ -1,6 +1,6 @@
import inspect
-from hydro_roll_core.development import Character
-from typing import Literal, List, Tuple, Union, Dict, Generic, Optional, TYPE_CHECKING
+from hrc.development import Character
+from typing import Literal, Union, Optional
class Identity:
diff --git a/hrc/__init__.py b/hrc/__init__.py
index 4258192..ba4efed 100644
--- a/hrc/__init__.py
+++ b/hrc/__init__.py
@@ -1,13 +1,13 @@
-from .LibCore import *
+from .LibCore import * # noqa: F403
-from . import rule
-from . import core
-from . import log
-from . import exceptions
-from . import config
-from . import dependencies
-from . import event
-from . import performance
-from . import feature
-from . import document
-from . import development \ No newline at end of file
+from . import rule # noqa: F401
+from . import core # noqa: F401
+from . import log # noqa: F401
+from . import exceptions # noqa: F401
+from . import config # noqa: F401
+from . import dependencies # noqa: F401
+from . import event # noqa: F401
+from . import performance # noqa: F401
+from . import feature # noqa: F401
+from . import document # noqa: F401
+from . import development # noqa: F401
diff --git a/hrc/config.py b/hrc/config.py
index 7db4efe..b6458b2 100644
--- a/hrc/config.py
+++ b/hrc/config.py
@@ -2,6 +2,7 @@ from typing import Set, Union
from pydantic import BaseModel, ConfigDict, DirectoryPath, Field
+
class ConfigModel(BaseModel):
model_config = ConfigDict(extra="allow")
@@ -25,4 +26,4 @@ class RuleConfig(ConfigModel):
class MainConfig(ConfigModel):
core: CoreConfig = CoreConfig()
- rule: RuleConfig = RuleConfig() \ No newline at end of file
+ rule: RuleConfig = RuleConfig()
diff --git a/hrc/core.py b/hrc/core.py
index 8e69c21..94b9205 100644
--- a/hrc/core.py
+++ b/hrc/core.py
@@ -38,12 +38,7 @@ from .utils import (
samefile,
wrap_get_func,
)
-from .exceptions import (
- StopException,
- SkipException,
- GetEventTimeout,
- LoadModuleError
-)
+from .exceptions import StopException, SkipException, GetEventTimeout, LoadModuleError
if sys.version_info >= (3, 11): # pragma: no cover
@@ -58,11 +53,10 @@ HANDLED_SIGNALS = (
class Core:
-
should_exit: asyncio.Event
rules_priority_dict: Dict[int, List[Type[Rule[Any, Any, Any]]]]
- _condition: (asyncio.Condition)
+ _condition: asyncio.Condition
_current_event: Optional[Event[Any]]
_restart_flag: bool
_module_path_finder: ModulePathFinder
@@ -159,7 +153,7 @@ class Core:
hot_reload_task = None
if self._hot_reload: # pragma: no cover
- hot_reload_task = asyncio.create_task(self._run_hot_reload())
+ hot_reload_task = asyncio.create_task(self._run_hot_reload()) # noqa: F841
for core_run_hook_func in self._core_run_hooks:
await core_run_hook_func(self)
@@ -184,8 +178,7 @@ class Core:
for rule_ in _removed_rules:
rules.remove(rule_)
logger.info(
- "Succeeded to remove rule "
- f'"{rule_.__name__}" from file "{file}"'
+ "Succeeded to remove rule " f'"{rule_.__name__}" from file "{file}"'
)
return removed_rules
@@ -284,8 +277,7 @@ class Core:
config_class,
default_value,
)
- config_model = create_model(
- name, **config_update_dict, __base__=base)
+ config_model = create_model(name, **config_update_dict, __base__=base)
return config_model, config_model()
self.config = create_model(
@@ -352,25 +344,20 @@ class Core:
show_log: bool = True,
) -> None:
if show_log:
- logger.info(
- f"Rule {current_event.rule.name} received: {current_event!r}"
- )
+ logger.info(f"Rule {current_event.rule.name} received: {current_event!r}")
if handle_get:
_handle_event_task = asyncio.create_task(self._handle_event())
self._handle_event_tasks.add(_handle_event_task)
- _handle_event_task.add_done_callback(
- self._handle_event_tasks.discard)
+ _handle_event_task.add_done_callback(self._handle_event_tasks.discard)
await asyncio.sleep(0)
async with self._condition:
self._current_event = current_event
self._condition.notify_all()
else:
- _handle_event_task = asyncio.create_task(
- self._handle_event(current_event))
+ _handle_event_task = asyncio.create_task(self._handle_event(current_event))
self._handle_event_tasks.add(_handle_event_task)
- _handle_event_task.add_done_callback(
- self._handle_event_tasks.discard)
+ _handle_event_task.add_done_callback(self._handle_event_tasks.discard)
async def _handle_event(self, current_event: Optional[Event[Any]] = None) -> None:
if current_event is None:
@@ -385,9 +372,7 @@ class Core:
await _hook_func(current_event)
for rule_priority in sorted(self.rules_priority_dict.keys()):
- logger.debug(
- f"Checking for matching rules with priority {rule_priority!r}"
- )
+ logger.debug(f"Checking for matching rules with priority {rule_priority!r}")
stop = False
for rule in self.rules_priority_dict[rule_priority]:
try:
@@ -427,8 +412,7 @@ class Core:
@overload
async def get(
self,
- func: Optional[Callable[[Event[Any]],
- Union[bool, Awaitable[bool]]]] = None,
+ func: Optional[Callable[[Event[Any]], Union[bool, Awaitable[bool]]]] = None,
*,
event_type: None = None,
max_try_times: Optional[int] = None,
@@ -438,8 +422,7 @@ class Core:
@overload
async def get(
self,
- func: Optional[Callable[[EventT],
- Union[bool, Awaitable[bool]]]] = None,
+ func: Optional[Callable[[EventT], Union[bool, Awaitable[bool]]]] = None,
*,
event_type: None = None,
max_try_times: Optional[int] = None,
@@ -449,8 +432,7 @@ class Core:
@overload
async def get(
self,
- func: Optional[Callable[[EventT],
- Union[bool, Awaitable[bool]]]] = None,
+ func: Optional[Callable[[EventT], Union[bool, Awaitable[bool]]]] = None,
*,
event_type: Type[EventT],
max_try_times: Optional[int] = None,
@@ -564,8 +546,7 @@ class Core:
module_name, Rule, reload=reload
)
except ImportError as e:
- self.error_or_exception(
- f'Import module "{module_name}" failed:', e)
+ self.error_or_exception(f'Import module "{module_name}" failed:', e)
else:
for rule_class, module in rule_classes:
self._load_rule_class(
@@ -638,9 +619,7 @@ class Core:
except Exception as e:
self.error_or_exception(f'Load rule "{rule_}" failed:', e)
- def load_rules(
- self, *rules: Union[Type[Rule[Any, Any, Any]], str, Path]
- ) -> None:
+ def load_rules(self, *rules: Union[Type[Rule[Any, Any, Any]], str, Path]) -> None:
self._extend_plugins.extend(rules)
return self._load_plugins(*rules)
diff --git a/hrc/event.py b/hrc/event.py
index 7f6fb6d..afdb00c 100644
--- a/hrc/event.py
+++ b/hrc/event.py
@@ -5,6 +5,7 @@ from typing_extensions import Self
from pydantic import BaseModel, ConfigDict
from .typing import RuleT
+
class Event(ABC, BaseModel, Generic[RuleT]):
model_config = ConfigDict(extra="allow")
@@ -104,4 +105,4 @@ class MessageEvent(Event[RuleT], Generic[RuleT]):
"""
await self.reply(message)
- return await self.get(max_try_times=max_try_times, timeout=timeout) \ No newline at end of file
+ return await self.get(max_try_times=max_try_times, timeout=timeout)
diff --git a/hrc/log.py b/hrc/log.py
index 3a84bba..dfa126c 100644
--- a/hrc/log.py
+++ b/hrc/log.py
@@ -22,4 +22,4 @@ def error_or_exception(message: str, exception: Exception, verbose: bool):
if verbose:
logger.exception(message)
else:
- logger.critical(f"{message} {exception!r}") \ No newline at end of file
+ logger.critical(f"{message} {exception!r}")
diff --git a/hrc/rule/BaseRule/CharacterCard.py b/hrc/rule/BaseRule/CharacterCard.py
index 6d09e5a..2baea48 100644
--- a/hrc/rule/BaseRule/CharacterCard.py
+++ b/hrc/rule/BaseRule/CharacterCard.py
@@ -1,22 +1,17 @@
-import dataclasses
from dataclasses import dataclass
-from typing import Literal, Optional, Union
@dataclass
class Custom(object):
"""Docstring for Custom."""
- property: type
+ property: type
-class Attribute(Custom):
- ...
+class Attribute(Custom): ...
-class Skill(Custom):
- ...
+class Skill(Custom): ...
-class Information(Custom):
- ...
+class Information(Custom): ...
diff --git a/hrc/rule/BaseRule/__init__.py b/hrc/rule/BaseRule/__init__.py
index fbb8df2..fdde86c 100644
--- a/hrc/rule/BaseRule/__init__.py
+++ b/hrc/rule/BaseRule/__init__.py
@@ -1,3 +1,3 @@
-from . import CharacterCard
-from . import CustomRule
-from . import Wiki \ No newline at end of file
+from . import CharacterCard # noqa: F401
+from . import CustomRule # noqa: F401
+from . import Wiki # noqa: F401
diff --git a/hrc/rule/__init__.py b/hrc/rule/__init__.py
index 5382c27..f04dbba 100644
--- a/hrc/rule/__init__.py
+++ b/hrc/rule/__init__.py
@@ -1,29 +1,27 @@
-import functools
+import functools # noqa: F401
from typing import Generic, Any, Type
from abc import ABC
-from . import BaseRule
-from ..typing import RuleT
+from . import BaseRule # noqa: F401
+from ..typing import RuleT # noqa: F401
import inspect
-from abc import ABC, abstractmethod
+from abc import abstractmethod
from enum import Enum
from typing import (
TYPE_CHECKING,
- Any,
ClassVar,
- Generic,
NoReturn,
Optional,
Tuple,
- Type,
cast,
final,
)
from typing_extensions import Annotated, get_args, get_origin
from ..config import ConfigModel
+
# from ..dependencies import Depends
from ..event import Event
from ..exceptions import SkipException, StopException
@@ -56,7 +54,7 @@ class Rule(ABC, Generic[EventT, StateT, ConfigT]):
if TYPE_CHECKING:
event: EventT
else:
- event = Depends(Event)
+ event = Depends(Event) # noqa: F821
def __init_state__(self) -> Optional[StateT]:
"""Initialize rule state."""
@@ -163,4 +161,5 @@ def aliases(names, ignore_case=False):
func._aliases = names
func._ignore_case = ignore_case
return func
+
return decorator
diff --git a/hrc/typing.py b/hrc/typing.py
index 934fc98..a873194 100644
--- a/hrc/typing.py
+++ b/hrc/typing.py
@@ -16,4 +16,4 @@ RuleT = TypeVar("RuleT", bound="Rule[Any, Any, Any]")
ConfigT = TypeVar("ConfigT", bound=Optional["ConfigModel"])
CoreHook = Callable[["Core"], Awaitable[None]]
-EventHook = Callable[["Event[Any]"], Awaitable[None]] \ No newline at end of file
+EventHook = Callable[["Event[Any]"], Awaitable[None]]
diff --git a/hrc/utils.py b/hrc/utils.py
index d053d4d..480b105 100644
--- a/hrc/utils.py
+++ b/hrc/utils.py
@@ -296,4 +296,4 @@ else: # pragma: no cover
if not ann:
return {}
- return dict(ann) \ No newline at end of file
+ return dict(ann)
diff --git a/tests/test_BaseRule.py b/tests/test_BaseRule.py
index 4f7c188..58c8c24 100644
--- a/tests/test_BaseRule.py
+++ b/tests/test_BaseRule.py
@@ -1,4 +1 @@
-from hrc.rule import BaseRule
-from hrc.rule.BaseRule import CharacterCard, CustomRule, Wiki
-
-# print(BaseRule, CharacterCard, CustomRule, Wiki) \ No newline at end of file
+# print(BaseRule, CharacterCard, CustomRule, Wiki)