Bläddra i källkod

d02 Упрощение параметров

SVI 2 år sedan
förälder
incheckning
6bba94e7ea

BIN
pkg/components/count_time.zip


+ 6 - 10
pkg/components/lststring/lststring.go → pkg/components/lst_string/lst_string.go

@@ -1,4 +1,5 @@
-package lststring
+// package lst_string -- потокобезопасный компонент списка строк для анализа объектов
+package lst_string
 
 import (
 	"fmt"
@@ -6,18 +7,14 @@ import (
 	"sync"
 )
 
-/*
-	Потокобезопасный компонент списка строк для анализа объектов
-*/
-
 // LstString -- потокобезопасный список строк объекта
 type LstString struct {
 	val        []string
-	strControl string
+	strControl string // Контрольная строка в исходной строке для анализа
 	block      sync.RWMutex
 }
 
-// NewLstString -- возвращает новый *LstString
+// NewLstString -- возвращает новый потокобезопасный список строк
 func NewLstString(strControl string) (*LstString, error) {
 	if strControl == "" {
 		return nil, fmt.Errorf("NewLstString(): strControl is empty")
@@ -29,14 +26,14 @@ func NewLstString(strControl string) (*LstString, error) {
 	return sf, nil
 }
 
-// Get -- возвращает список строк
+// Get -- возвращает список строк для анализа
 func (sf *LstString) Get() []string {
 	sf.block.RLock()
 	defer sf.block.RUnlock()
 	return sf.val
 }
 
-// Set -- устанавливает список строк
+// Set -- устанавливает список строк для анализа
 func (sf *LstString) Set(lstString []string) error {
 	sf.block.Lock()
 	defer sf.block.Unlock()
@@ -62,5 +59,4 @@ func (sf *LstString) Set(lstString []string) error {
 		}
 	}
 	return fmt.Errorf("LstString.Set(): lstString не имеет правильный title(%q), фактически(%q)", sf.strControl, strOut)
-
 }

+ 10 - 11
pkg/components/counttime/counttime.go → pkg/components/section/count_time/count_time.go

@@ -1,4 +1,7 @@
-package counttime
+// package count_time -- счётчик обратного времени в мсек
+//
+//	Похоже, нигде не используется
+package count_time
 
 import (
 	"fmt"
@@ -12,17 +15,13 @@ import (
 	"wartank/pkg/types"
 )
 
-/*
-	Счётчик обратного временив мсек
-*/
-
 const (
 	iSleep = time.Millisecond * 100
 )
 
 // CountTime -- счётчик обратного времени
 type CountTime struct {
-	app    types.IServer
+	bot    types.IBot
 	val    *safeint.SafeInt
 	parser *parsetime.ParseTime
 
@@ -35,12 +34,12 @@ type CountTime struct {
 }
 
 // NewCountTime -- возвращает новый *CountTime
-func NewCountTime(app types.IServer) *CountTime {
-	if app == nil {
-		panic("NewCountTime(): app==nil")
+func NewCountTime(bot types.IBot) *CountTime {
+	if bot == nil {
+		panic("NewCountTime(): IBot == nil")
 	}
 	sf := &CountTime{
-		app:        app,
+		bot:        bot,
 		val:        safeint.NewSafeInt(),
 		chTick:     make(chan int, 3),
 		chCall:     make(chan int, 2),
@@ -67,7 +66,7 @@ func (sf *CountTime) makeTick() {
 	countSleep := time.Duration(0)
 	for {
 		select {
-		case <-sf.app.Done(): // Отмена контекста приложения
+		case <-sf.bot.Ctx().Done(): // Отмена контекста бота
 			// log._rintf("CountTime.makeTick(): глобальная отмена контекста\n")
 			return
 		default:

+ 8 - 6
pkg/components/counttime/counttime_test.go → pkg/components/section/count_time/count_time_test.go

@@ -1,10 +1,11 @@
-package counttime
+package count_time
 
 import (
 	"testing"
 	"time"
 	"wartank/pkg/components/safebool"
 	"wartank/pkg/mock/mockapp"
+	"wartank/pkg/types"
 )
 
 /*
@@ -15,6 +16,7 @@ import (
 type tester struct {
 	t      *testing.T
 	app    *mockapp.MockApp
+	bot    types.IBot
 	ct     *CountTime
 	err    error
 	isCall *safebool.SafeBool // Признак обратного вызова
@@ -42,7 +44,7 @@ func TestCountTime(t *testing.T) {
 // Оменяет работу таймера
 func (sf *tester) cancel() {
 	sf.t.Logf("=cancel=\n")
-	ct := NewCountTime(sf.app)
+	ct := NewCountTime(sf.bot)
 	for len(ct.chTick) > 0 {
 		<-ct.chTick
 	}
@@ -52,7 +54,7 @@ func (sf *tester) cancel() {
 
 // Проверяет обработчик тика
 func (sf *tester) checkTick() {
-	ct := NewCountTime(sf.app)
+	ct := NewCountTime(sf.bot)
 	{ // Секундный тик
 		ct.Parse("00:00:08")
 		time.Sleep(time.Second * 1)
@@ -107,7 +109,7 @@ func (sf *tester) setStrBad1(strBad string) {
 // Устанавливает строковое значение времени
 func (sf *tester) setStr() {
 	go sf.call()
-	ct := NewCountTime(sf.app)
+	ct := NewCountTime(sf.bot)
 	{ // BAD-1 пустая строка
 		if sf.err = ct.Parse(""); sf.err == nil {
 			sf.t.Errorf("setStr(): BAD-1 err==nil")
@@ -161,7 +163,7 @@ func (sf *tester) setStr() {
 // Устанавливает число секунд для отсчёта
 func (sf *tester) setInt() {
 	go sf.call()
-	ct := NewCountTime(sf.app)
+	ct := NewCountTime(sf.bot)
 	{ // Bad-1 Отрицательное число
 		if sf.err = ct.Set(-1); sf.err == nil {
 			sf.t.Errorf("setInt(): BAD-1 err==nil")
@@ -240,7 +242,7 @@ func (sf *tester) createGood1() {
 			sf.t.Errorf("createGood1(): panic=%v", _panic)
 		}
 	}()
-	ct := NewCountTime(sf.app)
+	ct := NewCountTime(sf.bot)
 	if ct == nil {
 		sf.t.Errorf("createGood1(): countTime==nil")
 	}

+ 10 - 10
pkg/components/section/section.go

@@ -5,9 +5,9 @@ import (
 	"fmt"
 	"log"
 
-	"wartank/pkg/components/counttime"
-	"wartank/pkg/components/lststring"
-	"wartank/pkg/components/section/sectionmode"
+	"wartank/pkg/components/lst_string"
+	"wartank/pkg/components/section/count_time"
+	"wartank/pkg/components/section/section_mode"
 	"wartank/pkg/types"
 )
 
@@ -18,20 +18,20 @@ import (
 
 // Section -- секция игры
 type Section struct {
-	countDown types.ICountTime     // Обратный отсчёт до окончания работы режима
-	mode      types.IMode          // Объект режима работы
-	lstString *lststring.LstString // Список строк из сети для анализа секции
+	countDown types.ICountTime      // Обратный отсчёт до окончания работы режима
+	mode      types.IMode           // Объект режима работы
+	lstString *lst_string.LstString // Список строк из сети для анализа секции
 }
 
 // NewSection -- возвращает новую секцию игры
-func NewSection(app types.IServer, strControl string) (*Section, error) {
+func NewSection(bot types.IBot, strControl string) (*Section, error) {
 	log.Printf("NewSection(): strControl=%q\n", strControl)
 	sf := &Section{
-		countDown: counttime.NewCountTime(app),
-		mode:      sectionmode.NewSectionMode(),
+		countDown: count_time.NewCountTime(bot),
+		mode:      section_mode.NewSectionMode(),
 	}
 	var err error
-	sf.lstString, err = lststring.NewLstString(strControl)
+	sf.lstString, err = lst_string.NewLstString(strControl)
 	if err != nil {
 		return nil, fmt.Errorf("NewSection(): in create *LstString, err=\n\t%w", err)
 	}

+ 2 - 6
pkg/components/section/sectionmode/sectionmode.go → pkg/components/section/section_mode/section_mode.go

@@ -1,16 +1,12 @@
-// package sectionmode -- типовой режим секция работы части игры
+// package section_mode -- типовой режим секция работы части игры
 //
 //	Имеет имя режима и имя текущей работы в режиме
-package sectionmode
+package section_mode
 
 import (
 	"sync"
 )
 
-/*
-	Режим работы секции
-*/
-
 // SectionMode -- режим работы секции
 type SectionMode struct {
 	name  string // Имя режима

+ 7 - 1
pkg/types/ibot.go

@@ -1,5 +1,7 @@
 package types
 
+import "context"
+
 // IBot -- серверный бот среальным состоянием
 type IBot interface {
 	// Name -- возвращает им бота
@@ -25,5 +27,9 @@ type IBot interface {
 	// Make -- создаёт компоненты бота
 	Make() error
 	// Server -- возвращает ссылку на объект сервера
-	Server()IServer
+	Server() IServer
+	// Ctx -- возвращает контекст бота
+	Ctx() context.Context
+	// CancelBot -- отменяет контекст бота
+	CancelBot()
 }