Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

重构自动bp #520

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions app/lol/phase.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import asyncio
from abc import abstractmethod, ABC

from app.lol.tools import autoBan, autoPick, autoTrade, autoSwap


class Selection:
def __init__(self):
self._phase = Planning()

def _change_phase(self, phase):
if isinstance(phase, Phase):
self._phase = phase

async def act(self, data: dict):
print(data)
localPlayerCellId = data['localPlayerCellId']
actions = data['actions']
actionsInProgress = None
for action_group in actions:
for action in action_group:
if action['isInProgress']:
actionsInProgress = action_group
break

if asyncio.iscoroutinefunction(self._phase.conduct):
self._change_phase(
await self._phase.conduct(
data,
local_player_cell_id=localPlayerCellId,
actions_in_progress=actionsInProgress)
)
else:
self._change_phase(
self._phase.conduct(
data,
local_player_cell_id=localPlayerCellId,
actions_in_progress=actionsInProgress)
)


class Phase(ABC):
@abstractmethod
def conduct(self, data: dict, *args, **kwargs):
pass


class Planning(Phase):
async def conduct(self, data: dict, *args, **kwargs):
if data.get('pickOrderSwaps'):
await autoSwap(data)
return

actions = kwargs.get('actions_in_progress')
if actions:
for action in actions:
if (action['actorCellId'] == kwargs['local_player_cell_id']
and action['type'] == 'ban'):
await autoBan(data)
return Picking()


class Banning(Phase):
async def conduct(self, data: dict, *args, **kwargs):
actions = kwargs.get('actions_in_progress')
if actions:
for action in actions:
if (action['actorCellId'] == kwargs['local_player_cell_id']
and action['type'] == 'ban'):
await autoBan(data)
return Picking()


class Picking(Phase):
async def conduct(self, data: dict, *args, **kwargs):
if data.get('pickOrderSwaps'):
await autoSwap(data)
return

if kwargs.get('action'):
if kwargs['action']['type'] == 'ban':
await autoBan(data)
return Picking()
elif kwargs['action']['type'] == 'pick':
await autoPick(data)
return Waiting()


class Waiting(Phase):
async def conduct(self, data: dict, *args, **kwargs):
if data.get('trades'):
await autoTrade(data)
return


class GameStart(Phase):
def conduct(self, data: dict, *args, **kwargs):
pass
19 changes: 6 additions & 13 deletions app/lol/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1386,7 +1386,7 @@ def reset(self):
self.__init__()


async def autoSwap(data, selection: ChampionSelection):
async def autoSwap(data):
"""
选用顺序交换请求发生时,自动接受
"""
Expand All @@ -1397,11 +1397,9 @@ async def autoSwap(data, selection: ChampionSelection):
for pickOrderSwap in data['pickOrderSwaps']:
if 'RECEIVED' == pickOrderSwap['state']:
await connector.acceptTrade(pickOrderSwap['id'])
selection.isChampionPickedCompleted = False
return True


async def autoTrade(data, selection):
async def autoTrade(data):
"""
英雄交换请求发生时,自动接受
"""
Expand Down Expand Up @@ -1471,11 +1469,11 @@ async def showOpggBuild(data, selection: ChampionSelection):
return True


async def autoPick(data, selection: ChampionSelection):
async def autoPick(data):
"""
自动选用英雄
"""
if not cfg.get(cfg.enableAutoSelectChampion) or selection.isChampionPicked:
if not cfg.get(cfg.enableAutoSelectChampion):
return

localPlayerCellId = data['localPlayerCellId']
Expand Down Expand Up @@ -1517,7 +1515,6 @@ async def autoPick(data, selection: ChampionSelection):
candidates = [x for x in candidates if x not in bans]

if not candidates:
selection.isChampionPicked = True
return

championId = candidates[0]
Expand All @@ -1528,8 +1525,6 @@ async def autoPick(data, selection: ChampionSelection):
and action['type'] == "pick"):

await connector.selectChampion(action['id'], championId)

selection.isChampionPicked = True
return True


Expand Down Expand Up @@ -1557,16 +1552,14 @@ async def autoComplete(data, selection: ChampionSelection):
return True


async def autoBan(data, selection: ChampionSelection):
async def autoBan(data):
"""
自动禁用英雄
"""
isAutoBan = cfg.get(cfg.enableAutoBanChampion)
if not isAutoBan or selection.isChampionBanned:
if not isAutoBan:
return

selection.isChampionBanned = True

localPlayerCellId = data['localPlayerCellId']
for actionGroup in data['actions']:
for action in actionGroup:
Expand Down
75 changes: 32 additions & 43 deletions app/view/main_window.py
Original file line number Diff line number Diff line change
@@ -1,55 +1,52 @@
import asyncio
import copy
import os
import sys
import traceback
import threading
import time
import copy
import win32api
import traceback
from pathlib import Path

import pyperclip

import asyncio
from aiohttp.client_exceptions import ClientConnectorError
from qasync import asyncClose, asyncSlot
import win32api
from PyQt5.QtCore import Qt, pyqtSignal, QSize
from PyQt5.QtGui import QIcon, QImage
from PyQt5.QtWidgets import QApplication, QSystemTrayIcon
from aiohttp.client_exceptions import ClientConnectorError
from qasync import asyncClose, asyncSlot

from app.common.config import cfg, VERSION, BETA
from app.common.icons import Icon
from app.common.logger import logger
from app.common.qfluentwidgets import (NavigationItemPosition, InfoBar, InfoBarPosition, Action,
FluentWindow, SplashScreen, MessageBox, SmoothScrollArea,
ToolTipFilter, FluentIcon, ToolTipPosition, FluentWindowBase)

from app.view.start_interface import StartInterface
from app.view.setting_interface import SettingInterface
from app.view.career_interface import CareerInterface
from app.view.search_interface import SearchInterface
from app.view.game_info_interface import GameInfoInterface
from app.view.auxiliary_interface import AuxiliaryInterface
from app.view.opgg_window import OpggWindow
ToolTipFilter, FluentIcon, ToolTipPosition)
from app.common.signals import signalBus
from app.common.util import (github, getLolClientPid, getTasklistPath,
getLolClientPidSlowly, getLoLPathByRegistry)
from app.components.avatar_widget import NavigationAvatarWidget
from app.components.temp_system_tray_menu import TmpSystemTrayMenu
from app.common.icons import Icon
from app.common.config import cfg, VERSION, BETA
from app.common.logger import logger
from app.common.signals import signalBus
from app.components.message_box import (UpdateMessageBox, NoticeMessageBox,
WaitingForLolMessageBox, ExceptionMessageBox,
ChangeDpiMessageBox)
from app.components.temp_system_tray_menu import TmpSystemTrayMenu
from app.lol.aram import AramBuff
from app.lol.champions import ChampionAlias
from app.lol.connector import connector
from app.lol.exceptions import (SummonerGamesNotFound, RetryMaximumAttempts,
SummonerNotFound, SummonerNotInGame, SummonerRankInfoNotFound)
from app.lol.listener import (LolProcessExistenceListener, StoppableThread)
from app.lol.connector import connector
from app.lol.tools import (parseAllyGameInfo, parseGameInfoByGameflowSession,
getAllyOrderByGameRole, getTeamColor, autoBan, autoPick,
autoComplete, autoSwap, autoTrade, ChampionSelection,
SERVERS_NAME, SERVERS_SUBSET, showOpggBuild)
from app.lol.aram import AramBuff
from app.lol.champions import ChampionAlias
from app.lol.opgg import opgg

import threading
from app.lol.phase import Planning, Selection
from app.lol.tools import (parseAllyGameInfo, parseGameInfoByGameflowSession,
getAllyOrderByGameRole, getTeamColor, ChampionSelection,
SERVERS_NAME, SERVERS_SUBSET)
from app.view.auxiliary_interface import AuxiliaryInterface
from app.view.career_interface import CareerInterface
from app.view.game_info_interface import GameInfoInterface
from app.view.opgg_window import OpggWindow
from app.view.search_interface import SearchInterface
from app.view.setting_interface import SettingInterface
from app.view.start_interface import StartInterface

TAG = "MainWindow"

Expand Down Expand Up @@ -447,7 +444,7 @@ def quit():
def show(self):
self.activateWindow()
self.setWindowState(self.windowState() & ~
Qt.WindowMinimized | Qt.WindowActive)
Qt.WindowMinimized | Qt.WindowActive)
self.showNormal()

def __initListener(self):
Expand Down Expand Up @@ -849,8 +846,10 @@ async def reconnect():

# 进入英雄选择界面时触发
async def __onChampionSelectBegin(self):
self.selection = Selection()
self.championSelection.reset()
session = await connector.getChampSelectSession()
await self.selection.act(session)

if cfg.get(cfg.autoShowOpgg):
self.opggWindow.show()
Expand All @@ -865,17 +864,7 @@ async def __onChampionSelectBegin(self):
@asyncSlot(dict)
async def __onChampSelectChanged(self, data):
data = data['data']

phase = {
'PLANNING': [autoPick],
'BAN_PICK': [autoBan, autoPick, autoComplete, autoSwap, showOpggBuild],
'FINALIZATION': [autoTrade, showOpggBuild],
# 'GAME_STARTING': []
}

for func in phase.get(data['timer']['phase'], []):
if await func(data, self.championSelection):
break
await self.selection.act(data)

# 更新头像
await self.gameInfoInterface.updateAllyIcon(data['myTeam'])
Expand Down Expand Up @@ -1023,7 +1012,7 @@ def exceptHook(self, ty, value, tb):
logger.error(str(self.auxiliaryFuncInterface), "Crash")
logger.error(str(self.settingInterface), "Crash")

content = f"Seraphine ver.{BETA or VERSION}\n{'-'*5}\n{content}"
content = f"Seraphine ver.{BETA or VERSION}\n{'-' * 5}\n{content}"

w = ExceptionMessageBox(title, content, self.window())

Expand Down