airobot/lib/ai.go
2022-12-13 08:13:44 +08:00

98 lines
1.6 KiB
Go

package lib
import (
"bytes"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/sirupsen/logrus"
"legu.airobot/storage"
)
type myAI struct {
robots []*Robot
scenes []*scene
iscenes []IScene
tickets Tickets //票池
useCount uint32 //计数(压入的用户数)
lock sync.Mutex //
config *storage.Config //配置
}
func NewAI(aip AIParam) (*myAI, error) {
if err := aip.Check(); err != nil {
return nil, err
}
ai := &myAI{
scenes: make([]*scene, 0),
config: aip.Config,
iscenes: aip.Scenes,
}
if err := ai.init(); err != nil {
return nil, err
}
return ai, nil
}
func (m *myAI) init() error {
var buf bytes.Buffer
buf.WriteString("初始化AI")
uct := m.config.Global.UserCountTotal
tickets, err := NewTickets(uct)
if err != nil {
return err
}
m.tickets = tickets
buf.WriteString(fmt.Sprintf("完成 用户数量:%d", uct))
logrus.Debug(buf.String())
return nil
}
func (m *myAI) appendRobot(robot *Robot) {
defer m.lock.Unlock()
m.lock.Lock()
m.robots = append(m.robots, robot)
}
func (m *myAI) Start() bool {
if len(m.config.Scenes) == 0 {
logrus.Warn("还未设置场景")
return false
}
go func() {
for {
m.tickets.Take()
if m.useCount >= uint32(m.config.Global.UserCount) {
atomic.StoreUint32(&m.useCount, 0)
time.Sleep(time.Duration(m.config.Global.IntervalS) * time.Second)
}
go func() {
atomic.AddUint32(&m.useCount, 1)
robot := NewRobot(m.config)
robot.SetScenes(m.iscenes)
m.appendRobot(robot)
robot.Start()
}()
}
}()
return true
}
func (m *myAI) Stop() {
}
func (m *myAI) ShowResult() {
}