Skip to content

Commit

Permalink
opt code
Browse files Browse the repository at this point in the history
  • Loading branch information
buffge committed Feb 24, 2022
1 parent f22934a commit de8eeba
Show file tree
Hide file tree
Showing 5 changed files with 337 additions and 3 deletions.
48 changes: 48 additions & 0 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -504,3 +504,51 @@ func listMemberHurt(gameSummary *lcu.GameSummary, memberParticipantIDList []int)
}
return res
}
func getAllUsersFromSession(selfID int64, session *lcu.GameFlowSession) (selfTeamUsers []int64,
enemyTeamUsers []int64) {
selfTeamUsers = make([]int64, 0, 5)
enemyTeamUsers = make([]int64, 0, 5)
selfTeamID := models.TeamIDNone
for _, teamUser := range session.GameData.TeamOne {
summonerID := int64(teamUser.SummonerId)
if selfID == summonerID {
selfTeamID = models.TeamIDBlue
break
}
}
if selfTeamID == models.TeamIDNone {
for _, teamUser := range session.GameData.TeamTwo {
summonerID := int64(teamUser.SummonerId)
if selfID == summonerID {
selfTeamID = models.TeamIDRed
break
}
}
}
if selfTeamID == models.TeamIDNone {
return
}
for _, user := range session.GameData.TeamOne {
userID := int64(user.SummonerId)
if userID <= 0 {
return
}
if models.TeamIDBlue == selfTeamID {
selfTeamUsers = append(selfTeamUsers, userID)
} else {
enemyTeamUsers = append(enemyTeamUsers, userID)
}
}
for _, user := range session.GameData.TeamTwo {
userID := int64(user.SummonerId)
if userID <= 0 {
return
}
if models.TeamIDRed == selfTeamID {
selfTeamUsers = append(selfTeamUsers, userID)
} else {
enemyTeamUsers = append(enemyTeamUsers, userID)
}
}
return
}
1 change: 0 additions & 1 deletion cmd/lcu-agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ func main() {
}
proxyURL = updateProxyURL
log.Println("update lcu:", proxyURL)

}
}()
log.Printf("listen on :%d, lcu api:%s\n", port, proxyURL)
Expand Down
76 changes: 76 additions & 0 deletions prophet.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,9 @@ func (p *Prophet) onGameFlowUpdate(gameFlow string) {
go p.ChampionSelectStart()
case string(models.GameFlowNone):
p.updateGameState(GameStateNone)
case string(models.GameFlowInProgress):
p.updateGameState(GameStateInGame)
go p.CalcEnemyTeamScore()
case string(models.GameFlowReadyCheck):
p.updateGameState(GameStateReadyCheck)
clientCfg := global.GetClientConf()
Expand Down Expand Up @@ -435,6 +438,79 @@ func (p Prophet) ChampionSelectStart() {
func (p Prophet) AcceptGame() {
_ = lcu.AcceptGame()
}
func (p Prophet) CalcEnemyTeamScore() {
// 获取当前游戏进程
session, err := lcu.QueryGameFlowSession()
if err != nil {
return
}
if session.Phase != models.GameFlowInProgress {
return
}
if p.currSummoner == nil {
return
}
selfID := p.currSummoner.SummonerId
selfTeamUsers, enemyTeamUsers := getAllUsersFromSession(selfID, session)
_ = selfTeamUsers
summonerIDList := enemyTeamUsers
logger.Debug("敌方队伍人员列表:", zap.Any("summonerIDList", summonerIDList))
if len(enemyTeamUsers) == 0 {
return
}
// 查询所有用户的信息并计算得分
g := errgroup.Group{}
summonerIDMapScore := map[int64]lcu.UserScore{}
mu := sync.Mutex{}
for _, summonerID := range summonerIDList {
summonerID := summonerID
g.Go(func() error {
actScore, err := GetUserScore(summonerID)
if err != nil {
logger.Error("计算用户得分失败", zap.Error(err), zap.Int64("summonerID", summonerID))
return nil
}
mu.Lock()
summonerIDMapScore[summonerID] = *actScore
mu.Unlock()
return nil
})
}
_ = g.Wait()
// 根据所有用户的分数判断小代上等马中等马下等马
for _, score := range summonerIDMapScore {
log.Printf("用户:%s,得分:%.2f\n", score.SummonerName, score.Score)
}
clientCfg := global.GetClientConf()
scoreCfg := global.GetScoreConf()
allMsg := ""
// 发送到选人界面
for _, scoreInfo := range summonerIDMapScore {
time.Sleep(time.Second / 2)
var horse string
// horseIdx := 0
for i, v := range scoreCfg.Horse {
if scoreInfo.Score >= v.Score {
horse = clientCfg.HorseNameConf[i]
// horseIdx = i
break
}
}
currKDASb := strings.Builder{}
for i := 0; i < 5 && i < len(scoreInfo.CurrKDA); i++ {
currKDASb.WriteString(fmt.Sprintf("%d/%d/%d ", scoreInfo.CurrKDA[i][0], scoreInfo.CurrKDA[i][1],
scoreInfo.CurrKDA[i][2]))
}
currKDAMsg := currKDASb.String()
if len(currKDAMsg) > 0 {
currKDAMsg = currKDAMsg[:len(currKDAMsg)-1]
}
msg := fmt.Sprintf("%s(%d): %s %s -- %s", horse, int(scoreInfo.Score), scoreInfo.SummonerName,
currKDAMsg, global.AdaptChatWebsiteTitle)
allMsg += msg + "\n"
}
_ = clipboard.WriteAll(allMsg)
}

func (p Prophet) onChampSelectSessionUpdate(sessionInfo *lcu.ChampSelectSessionInfo) error {
isSelfPick := false
Expand Down
205 changes: 205 additions & 0 deletions services/lcu/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,193 @@ type (
// } `json:"timer"`
// Trades []interface{} `json:"trades"`
}
GameFolwSessionTeamUser struct {
AccountId float64 `json:"accountId,omitempty"`
AdjustmentFlags float64 `json:"adjustmentFlags,omitempty"`
BotDifficulty string `json:"botDifficulty"`
ClientInSynch bool `json:"clientInSynch,omitempty"`
GameCustomization struct {
Regalia string `json:"Regalia,omitempty"`
Perks string `json:"perks,omitempty"`
SummonerEmotes string `json:"summonerEmotes,omitempty"`
} `json:"gameCustomization"`
Index float64 `json:"index,omitempty"`
LastSelectedSkinIndex float64 `json:"lastSelectedSkinIndex"`
Locale interface{} `json:"locale"`
Minor bool `json:"minor,omitempty"`
OriginalAccountNumber float64 `json:"originalAccountNumber,omitempty"`
OriginalPlatformId string `json:"originalPlatformId,omitempty"`
PartnerId string `json:"partnerId,omitempty"`
PickMode float64 `json:"pickMode"`
PickTurn float64 `json:"pickTurn"`
ProfileIconId float64 `json:"profileIconId,omitempty"`
Puuid string `json:"puuid,omitempty"`
QueueRating float64 `json:"queueRating,omitempty"`
RankedTeamGuest bool `json:"rankedTeamGuest,omitempty"`
SelectedPosition interface{} `json:"selectedPosition"`
SelectedRole interface{} `json:"selectedRole"`
SummonerId float64 `json:"summonerId,omitempty"`
SummonerInternalName string `json:"summonerInternalName"`
SummonerName string `json:"summonerName"`
TeamOwner bool `json:"teamOwner,omitempty"`
TeamParticipantId interface{} `json:"teamParticipantId"`
TeamRating float64 `json:"teamRating,omitempty"`
TimeAddedToQueue interface{} `json:"timeAddedToQueue"`
TimeChampionSelectStart float64 `json:"timeChampionSelectStart,omitempty"`
TimeGameCreated float64 `json:"timeGameCreated,omitempty"`
TimeMatchmakingStart float64 `json:"timeMatchmakingStart,omitempty"`
VoterRating float64 `json:"voterRating,omitempty"`
BotSkillLevel float64 `json:"botSkillLevel,omitempty"`
ChampionId interface{} `json:"championId"`
Role interface{} `json:"role"`
Spell1Id interface{} `json:"spell1Id"`
Spell2Id interface{} `json:"spell2Id"`
TeamId models.TeamIDStr `json:"teamId,omitempty"`
}
GameFlowSession struct {
CommonResp
// GameClient struct {
// ObserverServerIp string `json:"observerServerIp"`
// ObserverServerPort int `json:"observerServerPort"`
// Running bool `json:"running"`
// ServerIp string `json:"serverIp"`
// ServerPort int `json:"serverPort"`
// Visible bool `json:"visible"`
// } `json:"gameClient"`
GameData struct {
// GameId int64 `json:"gameId"`
// GameName string `json:"gameName"`
// IsCustomGame bool `json:"isCustomGame"`
// Password string `json:"password"`
// PlayerChampionSelections []struct {
// ChampionId float64 `json:"championId"`
// SelectedSkinIndex float64 `json:"selectedSkinIndex"`
// Spell1Id float64 `json:"spell1Id"`
// Spell2Id float64 `json:"spell2Id"`
// SummonerInternalName string `json:"summonerInternalName"`
// } `json:"playerChampionSelections"`
// Queue struct {
// AllowablePremadeSizes []interface{} `json:"allowablePremadeSizes"`
// AreFreeChampionsAllowed bool `json:"areFreeChampionsAllowed"`
// AssetMutator string `json:"assetMutator"`
// Category string `json:"category"`
// ChampionsRequiredToPlay int `json:"championsRequiredToPlay"`
// Description string `json:"description"`
// DetailedDescription string `json:"detailedDescription"`
// GameMode string `json:"gameMode"`
// GameTypeConfig struct {
// AdvancedLearningQuests bool `json:"advancedLearningQuests"`
// AllowTrades bool `json:"allowTrades"`
// BanMode string `json:"banMode"`
// BanTimerDuration int `json:"banTimerDuration"`
// BattleBoost bool `json:"battleBoost"`
// CrossTeamChampionPool bool `json:"crossTeamChampionPool"`
// DeathMatch bool `json:"deathMatch"`
// DoNotRemove bool `json:"doNotRemove"`
// DuplicatePick bool `json:"duplicatePick"`
// ExclusivePick bool `json:"exclusivePick"`
// Id int `json:"id"`
// LearningQuests bool `json:"learningQuests"`
// MainPickTimerDuration int `json:"mainPickTimerDuration"`
// MaxAllowableBans int `json:"maxAllowableBans"`
// Name string `json:"name"`
// OnboardCoopBeginner bool `json:"onboardCoopBeginner"`
// PickMode string `json:"pickMode"`
// PostPickTimerDuration int `json:"postPickTimerDuration"`
// Reroll bool `json:"reroll"`
// TeamChampionPool bool `json:"teamChampionPool"`
// } `json:"gameTypeConfig"`
// Id int `json:"id"`
// IsRanked bool `json:"isRanked"`
// IsTeamBuilderManaged bool `json:"isTeamBuilderManaged"`
// IsTeamOnly bool `json:"isTeamOnly"`
// LastToggledOffTime int `json:"lastToggledOffTime"`
// LastToggledOnTime int `json:"lastToggledOnTime"`
// MapId int `json:"mapId"`
// MaxLevel int `json:"maxLevel"`
// MaxSummonerLevelForFirstWinOfTheDay int `json:"maxSummonerLevelForFirstWinOfTheDay"`
// MaximumParticipantListSize int `json:"maximumParticipantListSize"`
// MinLevel int `json:"minLevel"`
// MinimumParticipantListSize int `json:"minimumParticipantListSize"`
// Name string `json:"name"`
// NumPlayersPerTeam int `json:"numPlayersPerTeam"`
// QueueAvailability string `json:"queueAvailability"`
// QueueRewards struct {
// IsChampionPointsEnabled bool `json:"isChampionPointsEnabled"`
// IsIpEnabled bool `json:"isIpEnabled"`
// IsXpEnabled bool `json:"isXpEnabled"`
// PartySizeIpRewards []interface{} `json:"partySizeIpRewards"`
// } `json:"queueRewards"`
// RemovalFromGameAllowed bool `json:"removalFromGameAllowed"`
// RemovalFromGameDelayMinutes int `json:"removalFromGameDelayMinutes"`
// ShortName string `json:"shortName"`
// ShowPositionSelector bool `json:"showPositionSelector"`
// SpectatorEnabled bool `json:"spectatorEnabled"`
// Type string `json:"type"`
// } `json:"queue"`
SpectatorsAllowed bool `json:"spectatorsAllowed"`
TeamOne []GameFolwSessionTeamUser `json:"teamOne"`
TeamTwo []GameFolwSessionTeamUser `json:"teamTwo"`
} `json:"gameData"`
GameDodge struct {
DodgeIds []interface{} `json:"dodgeIds"`
Phase string `json:"phase"`
State string `json:"state"`
} `json:"gameDodge"`
Map struct {
Assets struct {
ChampSelectBackgroundSound string `json:"champ-select-background-sound"`
ChampSelectFlyoutBackground string `json:"champ-select-flyout-background"`
ChampSelectPlanningIntro string `json:"champ-select-planning-intro"`
GameSelectIconActive string `json:"game-select-icon-active"`
GameSelectIconActiveVideo string `json:"game-select-icon-active-video"`
GameSelectIconDefault string `json:"game-select-icon-default"`
GameSelectIconDisabled string `json:"game-select-icon-disabled"`
GameSelectIconHover string `json:"game-select-icon-hover"`
GameSelectIconIntroVideo string `json:"game-select-icon-intro-video"`
GameflowBackground string `json:"gameflow-background"`
GameselectButtonHoverSound string `json:"gameselect-button-hover-sound"`
IconDefeat string `json:"icon-defeat"`
IconDefeatVideo string `json:"icon-defeat-video"`
IconEmpty string `json:"icon-empty"`
IconHover string `json:"icon-hover"`
IconLeaver string `json:"icon-leaver"`
IconVictory string `json:"icon-victory"`
IconVictoryVideo string `json:"icon-victory-video"`
MapNorth string `json:"map-north"`
MapSouth string `json:"map-south"`
MusicInqueueLoopSound string `json:"music-inqueue-loop-sound"`
PartiesBackground string `json:"parties-background"`
PostgameAmbienceLoopSound string `json:"postgame-ambience-loop-sound"`
ReadyCheckBackground string `json:"ready-check-background"`
ReadyCheckBackgroundSound string `json:"ready-check-background-sound"`
SfxAmbiencePregameLoopSound string `json:"sfx-ambience-pregame-loop-sound"`
SocialIconLeaver string `json:"social-icon-leaver"`
SocialIconVictory string `json:"social-icon-victory"`
} `json:"assets"`
CategorizedContentBundles struct {
} `json:"categorizedContentBundles"`
Description string `json:"description"`
GameMode string `json:"gameMode"`
GameModeName string `json:"gameModeName"`
GameModeShortName string `json:"gameModeShortName"`
GameMutator string `json:"gameMutator"`
Id int `json:"id"`
IsRGM bool `json:"isRGM"`
MapStringId string `json:"mapStringId"`
Name string `json:"name"`
PerPositionDisallowedSummonerSpells struct {
} `json:"perPositionDisallowedSummonerSpells"`
PerPositionRequiredSummonerSpells struct {
} `json:"perPositionRequiredSummonerSpells"`
PlatformId string `json:"platformId"`
PlatformName string `json:"platformName"`
Properties struct {
SuppressRunesMasteriesPerks bool `json:"suppressRunesMasteriesPerks"`
} `json:"properties"`
} `json:"map"`
Phase models.GameFlow `json:"phase"`
}
)

const (
Expand Down Expand Up @@ -796,3 +983,21 @@ func PickChampion(championID, actionID int) error {
func BanChampion(championID, actionID int) error {
return ChampSelectPatchAction(championID, actionID, ChampSelectPatchTypeBan, true)
}

// 查询游戏会话
func QueryGameFlowSession() (*GameFlowSession, error) {
bts, err := cli.httpGet("/lol-gameflow/v1/session")
if err != nil {
return nil, err
}
data := &GameFlowSession{}
err = json.Unmarshal(bts, data)
if err != nil {
logger.Info("查询游戏会话失败", zap.Error(err))
return nil, err
}
if data.CommonResp.ErrorCode != "" {
return nil, errors.New(fmt.Sprintf("查询游戏会话失败 :%s", data.CommonResp.Message))
}
return data, nil
}
10 changes: 8 additions & 2 deletions services/lcu/models/lol.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type (
GameFlow string // 游戏状态
MapID int // 地图id
TeamID int // 队伍id
TeamIDStr string // 队伍id
)

const (
Expand Down Expand Up @@ -45,6 +46,7 @@ const (
GameStatusHostBOT GameStatus = "hosting_BOT" // 人机组队中-队长
GameFlowChampionSelect GameFlow = "ChampSelect" // 英雄选择中
GameFlowReadyCheck GameFlow = "ReadyCheck" // 等待接受对局
GameFlowInProgress GameFlow = "InProgress" // 进行中
GameFlowNone GameFlow = "None" // 无
// 排位等级
RankTierIron RankTier = "IRON" // 黑铁
Expand Down Expand Up @@ -74,8 +76,12 @@ const (
MapIDClassic MapID = 11 // 经典模式召唤师峡谷
MapIDARAM MapID = 12 // 极地大乱斗
// 队伍id
TeamIDBlue TeamID = 100 // 蓝色方
TeamIDRed TeamID = 200 // 红色方
TeamIDNone TeamID = 0 // 未知
TeamIDBlue TeamID = 100 // 蓝色方
TeamIDRed TeamID = 200 // 红色方
TeamIDStrNone TeamIDStr = "" // 未知
TeamIDStrBlue TeamIDStr = "100" // 蓝色方
TeamIDStrRed TeamIDStr = "200" // 红色方
// 大区id
PlatformIDDX1 = "HN1" // 艾欧尼亚
PlatformIDDX2 = "HN2" // 祖安
Expand Down

0 comments on commit de8eeba

Please sign in to comment.