-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbot_client.go
91 lines (78 loc) · 2.04 KB
/
bot_client.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"log"
"math/rand"
)
// BotClient represents a connection to the game for an AI player
type BotClient struct {
nickname string
id uint64
room *Room
incomingEvents chan []byte
outgoingActions chan *PlayerAction
}
func newBotClient(id uint64, room *Room) *BotClient {
botClient := &BotClient{
nickname: generateBotName(),
id: id,
room: room,
// We use buffered channel because a decision of one bot produces game events for this bot too
incomingEvents: make(chan []byte, MaxPlayersInRoom*MaxPlayersInRoom+1),
outgoingActions: make(chan *PlayerAction),
}
bot := newBot(botClient)
go botClient.sendingActionsToGame()
go bot.run()
return botClient
}
func (bl *BotClient) sendEvent(event interface{}) {
jsonEvent, _ := eventToJSON(event)
bl.sendMessage(jsonEvent)
}
func (bl *BotClient) sendMessage(message []byte) {
bl.incomingEvents <- message
}
// Nickname returns nickname of the bot
func (bl *BotClient) Nickname() string {
return bl.nickname
}
// Id returns id of the bot
func (bl *BotClient) Id() uint64 {
return bl.id
}
func (bl *BotClient) sendGameAction(playerActionName string, actionData interface{}) {
game := bl.room.game
if game.status != GameStatusPlaying {
log.Printf("BOT: Cannot send game action - wrong status of game = %s", game.status)
return
}
var player *Player
for _, gamePlayer := range game.players {
if gamePlayer.client.Id() == bl.Id() {
player = gamePlayer
break
}
}
if player == nil {
return
}
playerAction := &PlayerAction{Name: playerActionName, Data: actionData, player: player}
bl.outgoingActions <- playerAction
}
func (bl *BotClient) sendingActionsToGame() {
for {
select {
case playerAction := <-bl.outgoingActions:
bl.room.game.playerActions <- playerAction
}
}
}
func generateBotName() string {
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const botNameLength = 7
b := make([]byte, botNameLength)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return "bot-" + string(b)
}