forked from FairPlay137/outrun
/
drawBattleRival.go
64 lines (61 loc) · 2.05 KB
/
drawBattleRival.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package battle
import (
"log"
"math/rand"
"time"
"github.com/fluofoxxo/outrun/consts"
"github.com/fluofoxxo/outrun/db"
"github.com/fluofoxxo/outrun/db/dbaccess"
"github.com/fluofoxxo/outrun/netobj"
)
func DrawBattleRival(player netobj.Player, limit int) netobj.BattleState {
if !player.BattleState.MatchedUpWithRival { // are we not matched up yet?
playerIDs := []string{}
dbaccess.ForEachKey(consts.DBBucketPlayers, func(k, v []byte) error {
playerIDs = append(playerIDs, string(k))
return nil
})
currentTime := time.Now().UTC().Unix()
rivalID := ""
iterations := 0
for len(playerIDs) > 0 {
index := rand.Intn(len(playerIDs))
potentialRival, err := db.GetPlayer(playerIDs[index])
if err != nil {
log.Printf("[WARN] (battle.DrawBattleRival) Unable to get player '%s': %s", playerIDs[index], err.Error())
} else {
if player.ID != playerIDs[index] && potentialRival.BattleState.ScoreRecordedToday && !potentialRival.BattleState.MatchedUpWithRival && currentTime < potentialRival.BattleState.BattleEndsAt {
rivalID = playerIDs[index]
break
}
}
playerIDs[index] = playerIDs[len(playerIDs)-1]
playerIDs = playerIDs[:len(playerIDs)-1]
iterations++
if iterations >= limit && limit > 0 {
break
}
}
if len(rivalID) > 0 {
rival, err := db.GetPlayer(rivalID)
if err != nil {
log.Printf("[WARN] (battle.DrawBattleRival) Unable to get player '%s': %s", rivalID, err.Error())
} else {
rival.BattleState.RivalID = player.ID
rival.BattleState.MatchedUpWithRival = true
err = db.SavePlayer(rival)
if err != nil {
log.Printf("[WARN] (battle.DrawBattleRival) Unable to save rival data: %s", err.Error())
} else {
player.BattleState.RivalID = rivalID
player.BattleState.MatchedUpWithRival = true
}
}
}
}
if player.ID == player.BattleState.RivalID && player.BattleState.MatchedUpWithRival {
log.Printf("[WARN] (battle.DrawBattleRival) Somehow matched up with self! Removing match...")
player.BattleState.MatchedUpWithRival = false
}
return player.BattleState
}