From fc185faf08ab0a71e8440d0d4ce9b27af3541c3d Mon Sep 17 00:00:00 2001 From: CornWorld Date: Mon, 5 Feb 2024 23:45:04 +0800 Subject: [PATCH] [Change] Reorganize the package structure --- .../server/api/internal/command/message.go | 30 +++--- .../server/api/internal/command/pauser.go | 16 ++-- .../server/api/internal/receiver/context.go | 7 +- packages/server/api/internal/receiver/file.go | 59 ++++++------ packages/server/api/provider.go | 2 +- .../block/base_block.go} | 6 +- .../block/base_building.go} | 16 +++- .../block/block_blank.go} | 6 +- .../block/block_castle.go} | 6 +- .../block/block_king.go} | 6 +- .../block/block_mountain.go} | 6 +- .../block/block_soldier.go} | 21 +++-- .../block_manager/base_block.go} | 8 +- .../block_manager}/register.go | 6 +- .../{utils/pkg/game => game_logic}/game.go | 9 +- .../map/type => game_logic/game_def}/block.go | 2 +- .../game_def/game_mode.go} | 2 +- .../game_def}/instruction.go | 2 +- .../pkg/game => game_logic/game_def}/user.go | 2 +- .../{utils/pkg => game_logic}/map/map.go | 57 ++++++----- .../{utils/pkg => game_logic}/map/map_test.go | 30 +++--- .../internal/judge/judge.go | 69 +++++++------- .../server/{judgepool => judge_pool}/pool.go | 19 ++-- packages/server/main.go | 16 ++-- packages/server/main_test.go | 21 +++-- .../B__4b098g.gioreplay.processed | 0 .../test/replay/test1.gioreplay.processed | 7 ++ .../local/local.go | 94 +++++++++---------- .../local/local_test.go | 65 +++++++------ .../{datasource => data_source}/persistent.go | 6 +- .../pkg/{datasource => data_source}/pg/pg.go | 57 ++++++----- packages/server/utils/pkg/data_source/temp.go | 28 ++++++ packages/server/utils/pkg/datasource/temp.go | 28 ------ .../{gametemppool => game_temp_pool}/pool.go | 12 +-- 34 files changed, 380 insertions(+), 341 deletions(-) rename packages/server/{utils/pkg/map/blockManager/block/baseBlock.go => game_logic/block/base_block.go} (87%) rename packages/server/{utils/pkg/map/blockManager/block/baseBuilding.go => game_logic/block/base_building.go} (73%) rename packages/server/{utils/pkg/map/blockManager/block/blockBlank.go => game_logic/block/block_blank.go} (82%) rename packages/server/{utils/pkg/map/blockManager/block/blockCastle.go => game_logic/block/block_castle.go} (82%) rename packages/server/{utils/pkg/map/blockManager/block/blockKing.go => game_logic/block/block_king.go} (87%) rename packages/server/{utils/pkg/map/blockManager/block/blockMountain.go => game_logic/block/block_mountain.go} (81%) rename packages/server/{utils/pkg/map/blockManager/block/blockSoldier.go => game_logic/block/block_soldier.go} (73%) rename packages/server/{utils/pkg/map/blockManager/baseBlock.go => game_logic/block_manager/base_block.go} (85%) rename packages/server/{utils/pkg/map/blockManager => game_logic/block_manager}/register.go (85%) rename packages/server/{utils/pkg/game => game_logic}/game.go (67%) rename packages/server/{utils/pkg/map/type => game_logic/game_def}/block.go (94%) rename packages/server/{utils/pkg/game/mode.go => game_logic/game_def/game_mode.go} (93%) rename packages/server/{utils/pkg/instruction => game_logic/game_def}/instruction.go (95%) rename packages/server/{utils/pkg/game => game_logic/game_def}/user.go (94%) rename packages/server/{utils/pkg => game_logic}/map/map.go (83%) rename packages/server/{utils/pkg => game_logic}/map/map_test.go (69%) rename packages/server/{judgepool => judge_pool}/internal/judge/judge.go (73%) rename packages/server/{judgepool => judge_pool}/pool.go (75%) rename packages/server/test/{replay => }/B__4b098g.gioreplay.processed (100%) create mode 100644 packages/server/test/replay/test1.gioreplay.processed rename packages/server/utils/pkg/{datasource => data_source}/local/local.go (65%) rename packages/server/utils/pkg/{datasource => data_source}/local/local_test.go (76%) rename packages/server/utils/pkg/{datasource => data_source}/persistent.go (59%) rename packages/server/utils/pkg/{datasource => data_source}/pg/pg.go (68%) create mode 100644 packages/server/utils/pkg/data_source/temp.go delete mode 100644 packages/server/utils/pkg/datasource/temp.go rename packages/server/utils/pkg/{gametemppool => game_temp_pool}/pool.go (59%) diff --git a/packages/server/api/internal/command/message.go b/packages/server/api/internal/command/message.go index 030149c..5bf61e9 100644 --- a/packages/server/api/internal/command/message.go +++ b/packages/server/api/internal/command/message.go @@ -2,22 +2,22 @@ package command import ( "encoding/json" - "server/utils/pkg/datasource" - "server/utils/pkg/game" - game_temp_pool "server/utils/pkg/gametemppool" - "server/utils/pkg/map" - "server/utils/pkg/map/type" + "server/game_logic" + gameDef "server/game_logic/game_def" + "server/game_logic/map" + "server/utils/pkg/data_source" + game_temp_pool "server/utils/pkg/game_temp_pool" ) -var data datasource.TempDataSource +var data data_source.TempDataSource func ApplyDataSource(source any) { - data = source.(datasource.TempDataSource) + data = source.(data_source.TempDataSource) } type visibilityArr [][]bool -func getVisibility(id game.Id, userId uint16) *visibilityArr { +func getVisibility(id game_logic.Id, userId uint16) *visibilityArr { m := data.GetCurrentMap(id) ul := data.GetCurrentUserList(id) @@ -62,7 +62,7 @@ func getVisibility(id game.Id, userId uint16) *visibilityArr { for rowNum := uint8(0); rowNum <= m.Size().H-1; rowNum++ { for colNum := uint8(0); colNum <= m.Size().W-1; colNum++ { - o := m.GetBlock(_type.Position{X: colNum + 1, Y: rowNum + 1}).OwnerId() + o := m.GetBlock(gameDef.Position{X: colNum + 1, Y: rowNum + 1}).OwnerId() if o == 0 { continue } @@ -79,7 +79,7 @@ func getVisibility(id game.Id, userId uint16) *visibilityArr { type processedMap [][][]uint16 -func getProcessedMap(id game.Id, userId uint16, m *_map.Map) *processedMap { +func getProcessedMap(id game_logic.Id, userId uint16, m *_map.Map) *processedMap { vis := getVisibility(id, userId) var ret *processedMap if r, ok := game_temp_pool.Get(id, "processedMap"); ok { @@ -93,7 +93,7 @@ func getProcessedMap(id game.Id, userId uint16, m *_map.Map) *processedMap { for rowNum := uint8(0); rowNum <= m.Size().H-1; rowNum++ { (*ret)[rowNum] = make([][]uint16, m.Size().W) for colNum := uint8(0); colNum <= m.Size().W-1; colNum++ { - b := m.GetBlock(_type.Position{X: colNum + 1, Y: rowNum + 1}) + b := m.GetBlock(gameDef.Position{X: colNum + 1, Y: rowNum + 1}) if (*vis)[rowNum][colNum] { (*ret)[rowNum][colNum] = []uint16{uint16(b.Meta().BlockId), b.OwnerId(), b.Number()} } else { @@ -113,12 +113,12 @@ type playerInfo struct { Status string `json:"status"` } -func getUserList(id game.Id) []playerInfo { +func getUserList(id game_logic.Id) []playerInfo { l := data.GetCurrentUserList(id) ret := make([]playerInfo, len(l)) var status string for i, u := range l { - if u.Status == game.UserStatusConnected { + if u.Status == gameDef.UserStatusConnected { status = "connected" } else { status = "disconnect" @@ -134,7 +134,7 @@ func getUserList(id game.Id) []playerInfo { return ret } -func GenerateMessage(_type string, id game.Id, userId uint16) string { +func GenerateMessage(_type string, id game_logic.Id, userId uint16) string { switch _type { case "start": { @@ -172,7 +172,7 @@ func GenerateMessage(_type string, id game.Id, userId uint16) string { res := struct { Action string `json:"action"` Players []playerInfo `json:"players"` - Mode game.Mode `json:"mode"` + Mode gameDef.Mode `json:"mode"` }{"info", getUserList(id), g.Mode} ret, _ := json.Marshal(res) return string(ret) diff --git a/packages/server/api/internal/command/pauser.go b/packages/server/api/internal/command/pauser.go index 6d31d52..dd4fe8e 100644 --- a/packages/server/api/internal/command/pauser.go +++ b/packages/server/api/internal/command/pauser.go @@ -3,14 +3,14 @@ package command import ( "fmt" "github.com/go-playground/validator/v10" - "server/utils/pkg/instruction" + "server/game_logic/game_def" "strconv" "strings" ) -func PauseCommandStr(userId uint16, str string) (instruction.Instruction, error) { +func PauseCommandStr(userId uint16, str string) (_type.Instruction, error) { var err error = nil - ret := instruction.Instruction(nil) + ret := _type.Instruction(nil) args := strings.Split(str, " ") v := validator.New() switch args[0] { @@ -28,9 +28,9 @@ func PauseCommandStr(userId uint16, str string) (instruction.Instruction, error) n, _ := strconv.Atoi(c.Number) x, _ := strconv.Atoi(c.X) y, _ := strconv.Atoi(c.Y) - ret = instruction.Move{ - Position: instruction.BlockPosition{X: uint8(x), Y: uint8(y)}, - Towards: instruction.MoveTowardsType(c.Towards), + ret = _type.Move{ + Position: _type.BlockPosition{X: uint8(x), Y: uint8(y)}, + Towards: _type.MoveTowardsType(c.Towards), Number: uint16(n), } } else { @@ -51,7 +51,7 @@ func PauseCommandStr(userId uint16, str string) (instruction.Instruction, error) if c.Status == "true" { s = true } - ret = instruction.ForceStart{ + ret = _type.ForceStart{ UserId: userId, Status: s, } @@ -66,7 +66,7 @@ func PauseCommandStr(userId uint16, str string) (instruction.Instruction, error) case "Surrender": { if len(args)-1 == 0 { - ret = instruction.Surrender{UserId: userId} + ret = _type.Surrender{UserId: userId} } else { err = fmt.Errorf("argument number not right") } diff --git a/packages/server/api/internal/receiver/context.go b/packages/server/api/internal/receiver/context.go index 3918ebc..e74b7f7 100644 --- a/packages/server/api/internal/receiver/context.go +++ b/packages/server/api/internal/receiver/context.go @@ -2,13 +2,14 @@ package receiver import ( "context" - "server/utils/pkg/game" + "server/game_logic" + "server/game_logic/game_def" ) type Context struct { context.Context - Game *game.Game - User game.User + Game *game_logic.Game + User _type.User Command chan string Message chan string } diff --git a/packages/server/api/internal/receiver/file.go b/packages/server/api/internal/receiver/file.go index 6fa92d1..2cec69f 100644 --- a/packages/server/api/internal/receiver/file.go +++ b/packages/server/api/internal/receiver/file.go @@ -5,10 +5,11 @@ import ( "github.com/sirupsen/logrus" "os" _command "server/api/internal/command" - judge_pool "server/judgepool" - "server/utils/pkg/datasource" - "server/utils/pkg/game" - "server/utils/pkg/map" + "server/game_logic" + "server/game_logic/game_def" + "server/game_logic/map" + judge_pool "server/judge_pool" + "server/utils/pkg/data_source" "strconv" "strings" "time" @@ -17,11 +18,11 @@ import ( // NOTE: DEBUG ONLY // Use to receive instructions from local file, in order to test the game functions -var data datasource.TempDataSource +var data data_source.TempDataSource var fileDir = "./test/replay" func ApplyDataSource(source any) { - data = source.(datasource.TempDataSource) + data = source.(data_source.TempDataSource) } func NewFileReceiver(pool *judge_pool.Pool) { @@ -30,13 +31,13 @@ func NewFileReceiver(pool *judge_pool.Pool) { for index, r := range f { time.Sleep(time.Millisecond * 200) logrus.Infof("start game by reply file #%d", r.Id) - g := &game.Game{ + g := &game_logic.Game{ Map: r.Map, - Mode: game.Mode1v1, - Id: game.Id(index + 1e3), - UserList: []game.User{}, + Mode: _type.Mode1v1, + Id: game_logic.Id(index + 1e3), + UserList: []_type.User{}, CreateTime: time.Now().UnixMicro(), - Status: game.StatusWaiting, + Status: game_logic.StatusWaiting, RoundNum: 0, } pool.DebugNewGame(g) @@ -57,12 +58,12 @@ func NewFileReceiver(pool *judge_pool.Pool) { } type command struct { - User game.User + User _type.User Ins []string } type reply struct { - Id game.Id + Id game_logic.Id UserPack []command Map *_map.Map } @@ -87,7 +88,7 @@ func LoadFile() []reply { id, _ := strconv.Atoi(s[0]) r := reply{ - Id: game.Id(id), + Id: game_logic.Id(id), UserPack: []command{}, } @@ -111,10 +112,10 @@ func LoadFile() []reply { cmdStr := strings.Split(t[1], "\n") cmd := command{ - User: game.User{ + User: _type.User{ Name: name, UserId: uint16(userId), - Status: game.UserStatusConnected, + Status: _type.UserStatusConnected, TeamId: uint8(userId) - 1, ForceStartStatus: false, }, @@ -142,13 +143,16 @@ func fakePlayer(ctx *Context, c []string) { case <-ticker.C: { g := data.GetGameInfo(ctx.Game.Id) - if g.Status == game.StatusEnd { + if g.Status == game_logic.StatusEnd { return } if currentRound >= uint16(len(c)) { playerLogger.Infof("Command(tot: %d) runs out, quit", len(c)) ticker.Stop() + player := ctx.User + player.Status = _type.UserStatusDisconnected + data.SetUserStatus(ctx.Game.Id, player) } if ctx.Game.RoundNum > currentRound { playerLogger.Printf("Discover new round %d", g.RoundNum) @@ -175,8 +179,8 @@ func fakePlayer(ctx *Context, c []string) { } func receiver(ctx *Context) { - ctx.User.Name = strconv.Itoa(int(ctx.User.UserId)) // DEBUG ONLY, avoiding strange username from `gioreply` file - ctx.User.Status = game.UserStatusConnected + //ctx.User.Name = strconv.Itoa(int(ctx.User.UserId)) // DEBUG ONLY, avoiding strange username from `gioreply` file + ctx.User.Status = _type.UserStatusConnected data.SetUserStatus(ctx.Game.Id, ctx.User) receiverLogger := logrus.WithFields(logrus.Fields{ @@ -185,7 +189,7 @@ func receiver(ctx *Context) { receiverLogger.Infof("user join") defer func() { - ctx.User.Status = game.UserStatusDisconnected + ctx.User.Status = _type.UserStatusDisconnected data.SetUserStatus(ctx.Game.Id, ctx.User) receiverLogger.Infof("user quit") }() @@ -202,18 +206,19 @@ func receiver(ctx *Context) { } case cmd := <-ctx.Command: { - if cmd == "" { + + if strings.TrimSpace(cmd) == "" { continue } ins, err := _command.PauseCommandStr(ctx.User.UserId, cmd) if err != nil { - receiverLogger.Panicf("cannot parse command: %s", cmd) + receiverLogger.Panicf("cannot parse command: |%s|", cmd) } data.UpdateInstruction(ctx.Game.Id, ctx.User, ins) } case <-ticker.C: { - done := func(g *game.Game, d string) { + done := func(g *game_logic.Game, d string) { res := _command.GenerateMessage(d, ctx.Game.Id, ctx.User.UserId) ctx.Message <- res ctx.Game = g @@ -222,11 +227,11 @@ func receiver(ctx *Context) { // Check game status g := data.GetGameInfo(ctx.Game.Id) if g.Status != ctx.Game.Status { - if ctx.Game.Status == game.StatusWaiting && g.Status == game.StatusRunning { + if ctx.Game.Status == game_logic.StatusWaiting && g.Status == game_logic.StatusRunning { done(g, "info") done(g, "start") continue - } else if g.Status == game.StatusEnd { + } else if g.Status == game_logic.StatusEnd { done(g, "end") ticker.Stop() flag = false @@ -235,12 +240,12 @@ func receiver(ctx *Context) { } else { if i%20 == 0 { done(g, "info") - if ctx.Game.Status == game.StatusWaiting { + if ctx.Game.Status == game_logic.StatusWaiting { done(g, "wait") } } - if ctx.Game.Status == game.StatusRunning && ctx.Game.RoundNum != g.RoundNum { + if ctx.Game.Status == game_logic.StatusRunning && ctx.Game.RoundNum != g.RoundNum { done(g, "newTurn") continue } diff --git a/packages/server/api/provider.go b/packages/server/api/provider.go index 4879720..ab12284 100644 --- a/packages/server/api/provider.go +++ b/packages/server/api/provider.go @@ -3,7 +3,7 @@ package api import ( "server/api/internal/command" "server/api/internal/receiver" - judge_pool "server/judgepool" + judge_pool "server/judge_pool" "time" ) diff --git a/packages/server/utils/pkg/map/blockManager/block/baseBlock.go b/packages/server/game_logic/block/base_block.go similarity index 87% rename from packages/server/utils/pkg/map/blockManager/block/baseBlock.go rename to packages/server/game_logic/block/base_block.go index ab1ea18..ad63098 100644 --- a/packages/server/utils/pkg/map/blockManager/block/baseBlock.go +++ b/packages/server/game_logic/block/base_block.go @@ -2,7 +2,7 @@ package block import ( "github.com/sirupsen/logrus" - "server/utils/pkg/map/type" + "server/game_logic/game_def" ) var _ _type.Block = (*BaseBlock)(nil) @@ -33,7 +33,9 @@ func (*BaseBlock) GetMoveStatus() _type.MoveStatus { return _type.MoveStatus{} } -func (*BaseBlock) MoveFrom(_ uint16) {} +func (*BaseBlock) MoveFrom(_ uint16) uint16 { + return 0 +} func (*BaseBlock) MoveTo(_type.BlockVal) _type.Block { return nil diff --git a/packages/server/utils/pkg/map/blockManager/block/baseBuilding.go b/packages/server/game_logic/block/base_building.go similarity index 73% rename from packages/server/utils/pkg/map/blockManager/block/baseBuilding.go rename to packages/server/game_logic/block/base_building.go index 5ca1350..5a3b328 100644 --- a/packages/server/utils/pkg/map/blockManager/block/baseBuilding.go +++ b/packages/server/game_logic/block/base_building.go @@ -1,6 +1,8 @@ package block -import "server/utils/pkg/map/type" +import ( + "server/game_logic/game_def" +) var _ _type.Block = (*BaseBuilding)(nil) @@ -22,8 +24,16 @@ func (*BaseBuilding) GetMoveStatus() _type.MoveStatus { return _type.MoveStatus{AllowMoveFrom: true, AllowMoveTo: true} } -func (block *BaseBuilding) MoveFrom(number uint16) { - block.number -= number +func (block *BaseBuilding) MoveFrom(number uint16) uint16 { + var ret uint16 + if block.number <= number { + ret = block.number - 1 + block.number = 1 + } else { + ret = number + block.number -= number + } + return ret } func (block *BaseBuilding) MoveTo(info _type.BlockVal) _type.Block { diff --git a/packages/server/utils/pkg/map/blockManager/block/blockBlank.go b/packages/server/game_logic/block/block_blank.go similarity index 82% rename from packages/server/utils/pkg/map/blockManager/block/blockBlank.go rename to packages/server/game_logic/block/block_blank.go index 5ac4896..6bb7a3b 100644 --- a/packages/server/utils/pkg/map/blockManager/block/blockBlank.go +++ b/packages/server/game_logic/block/block_blank.go @@ -1,8 +1,8 @@ package block import ( - "server/utils/pkg/map/blockManager" - "server/utils/pkg/map/type" + "server/game_logic/block_manager" + "server/game_logic/game_def" ) var _ _type.Block = (*Blank)(nil) @@ -19,7 +19,7 @@ var BlankMeta = _type.Meta{ } func init() { - blockManager.Register(BlankMeta, toBlockBlank) + block_manager.Register(BlankMeta, toBlockBlank) } func (*Blank) Meta() _type.Meta { diff --git a/packages/server/utils/pkg/map/blockManager/block/blockCastle.go b/packages/server/game_logic/block/block_castle.go similarity index 82% rename from packages/server/utils/pkg/map/blockManager/block/blockCastle.go rename to packages/server/game_logic/block/block_castle.go index ddd0bea..be73585 100644 --- a/packages/server/utils/pkg/map/blockManager/block/blockCastle.go +++ b/packages/server/game_logic/block/block_castle.go @@ -2,8 +2,8 @@ package block import ( "math/rand" - "server/utils/pkg/map/blockManager" - "server/utils/pkg/map/type" + "server/game_logic/block_manager" + "server/game_logic/game_def" ) var _ _type.Block = (*Castle)(nil) @@ -20,7 +20,7 @@ var CastleMeta = _type.Meta{ } func init() { - blockManager.Register(CastleMeta, toBlockCastle) + block_manager.Register(CastleMeta, toBlockCastle) } func toBlockCastle(b _type.Block) _type.Block { diff --git a/packages/server/utils/pkg/map/blockManager/block/blockKing.go b/packages/server/game_logic/block/block_king.go similarity index 87% rename from packages/server/utils/pkg/map/blockManager/block/blockKing.go rename to packages/server/game_logic/block/block_king.go index ab68990..75d0c24 100644 --- a/packages/server/utils/pkg/map/blockManager/block/blockKing.go +++ b/packages/server/game_logic/block/block_king.go @@ -1,8 +1,8 @@ package block import ( - "server/utils/pkg/map/blockManager" - "server/utils/pkg/map/type" + "server/game_logic/block_manager" + "server/game_logic/game_def" ) var _ _type.Block = (*King)(nil) @@ -20,7 +20,7 @@ var KingMeta = _type.Meta{ } func init() { - blockManager.Register(KingMeta, toBlockKing) + block_manager.Register(KingMeta, toBlockKing) } func toBlockKing(b _type.Block) _type.Block { diff --git a/packages/server/utils/pkg/map/blockManager/block/blockMountain.go b/packages/server/game_logic/block/block_mountain.go similarity index 81% rename from packages/server/utils/pkg/map/blockManager/block/blockMountain.go rename to packages/server/game_logic/block/block_mountain.go index 60973e9..9572f42 100644 --- a/packages/server/utils/pkg/map/blockManager/block/blockMountain.go +++ b/packages/server/game_logic/block/block_mountain.go @@ -1,8 +1,8 @@ package block import ( - "server/utils/pkg/map/blockManager" - "server/utils/pkg/map/type" + "server/game_logic/block_manager" + "server/game_logic/game_def" ) type Mountain struct { @@ -17,7 +17,7 @@ var MountainMeta = _type.Meta{ } func init() { - blockManager.Register(MountainMeta, toBlockMountain) + block_manager.Register(MountainMeta, toBlockMountain) } func toBlockMountain(_type.Block) _type.Block { diff --git a/packages/server/utils/pkg/map/blockManager/block/blockSoldier.go b/packages/server/game_logic/block/block_soldier.go similarity index 73% rename from packages/server/utils/pkg/map/blockManager/block/blockSoldier.go rename to packages/server/game_logic/block/block_soldier.go index 3abab48..b504c54 100644 --- a/packages/server/utils/pkg/map/blockManager/block/blockSoldier.go +++ b/packages/server/game_logic/block/block_soldier.go @@ -1,10 +1,12 @@ package block import ( - "server/utils/pkg/map/blockManager" - "server/utils/pkg/map/type" + "server/game_logic/block_manager" + "server/game_logic/game_def" ) +var _ _type.Block = (*Soldier)(nil) + type Soldier struct { BaseBlock } @@ -17,7 +19,7 @@ var SoldierMeta = _type.Meta{ } func init() { - blockManager.Register(SoldierMeta, toBlockSoldier) + block_manager.Register(SoldierMeta, toBlockSoldier) } func toBlockSoldier(b _type.Block) _type.Block { @@ -45,12 +47,19 @@ func (*Soldier) GetMoveStatus() _type.MoveStatus { return _type.MoveStatus{true, true} } -func (block *Soldier) MoveFrom(number uint16) { - block.number -= number +func (block *Soldier) MoveFrom(number uint16) uint16 { + var ret uint16 + if block.number <= number { + ret = block.number - 1 + block.number = 1 + } else { + ret = number + block.number -= number + } + return ret } func (block *Soldier) MoveTo(info _type.BlockVal) _type.Block { - if block.ownerId != info.OwnerId { if block.number < info.Number { block.ownerId = info.OwnerId diff --git a/packages/server/utils/pkg/map/blockManager/baseBlock.go b/packages/server/game_logic/block_manager/base_block.go similarity index 85% rename from packages/server/utils/pkg/map/blockManager/baseBlock.go rename to packages/server/game_logic/block_manager/base_block.go index 36e91d1..2dc6908 100644 --- a/packages/server/utils/pkg/map/blockManager/baseBlock.go +++ b/packages/server/game_logic/block_manager/base_block.go @@ -2,11 +2,11 @@ Create block only */ -package blockManager +package block_manager import ( "github.com/sirupsen/logrus" - _type "server/utils/pkg/map/type" + "server/game_logic/game_def" ) var _ _type.Block = (*BaseBlock)(nil) @@ -37,7 +37,9 @@ func (*BaseBlock) GetMoveStatus() _type.MoveStatus { return _type.MoveStatus{} } -func (*BaseBlock) MoveFrom(_ uint16) {} +func (*BaseBlock) MoveFrom(_ uint16) uint16 { + return 0 +} func (*BaseBlock) MoveTo(_type.BlockVal) _type.Block { return nil diff --git a/packages/server/utils/pkg/map/blockManager/register.go b/packages/server/game_logic/block_manager/register.go similarity index 85% rename from packages/server/utils/pkg/map/blockManager/register.go rename to packages/server/game_logic/block_manager/register.go index 4c800a8..78b69eb 100644 --- a/packages/server/utils/pkg/map/blockManager/register.go +++ b/packages/server/game_logic/block_manager/register.go @@ -1,8 +1,8 @@ -package blockManager +package block_manager import ( "github.com/sirupsen/logrus" - "server/utils/pkg/map/type" + "server/game_logic/game_def" ) type tranFunc func(_type.Block) _type.Block @@ -25,7 +25,7 @@ func Register(meta _type.Meta, transFunc tranFunc) { GetBlockIdByName[meta.Name] = meta.BlockId GetMetaById[meta.BlockId] = meta transBlockTypeFunc[meta.BlockId] = transFunc - logrus.Println("Registered a block type", "id:", meta.BlockId, " name:", meta.Name, " description:", meta.Description) + logrus.Println("Registered a block game_def", "id:", meta.BlockId, " name:", meta.Name, " description:", meta.Description) } func ToBlockByTypeId(typeId uint8, block _type.Block) _type.Block { diff --git a/packages/server/utils/pkg/game/game.go b/packages/server/game_logic/game.go similarity index 67% rename from packages/server/utils/pkg/game/game.go rename to packages/server/game_logic/game.go index edd680d..9a67d39 100644 --- a/packages/server/utils/pkg/game/game.go +++ b/packages/server/game_logic/game.go @@ -1,7 +1,8 @@ -package game +package game_logic import ( - "server/utils/pkg/map" + "server/game_logic/game_def" + "server/game_logic/map" ) type Status uint8 @@ -15,9 +16,9 @@ const ( type Game struct { Map *_map.Map - Mode Mode + Mode _type.Mode Id Id - UserList []User + UserList []_type.User CreateTime int64 Status Status RoundNum uint16 diff --git a/packages/server/utils/pkg/map/type/block.go b/packages/server/game_logic/game_def/block.go similarity index 94% rename from packages/server/utils/pkg/map/type/block.go rename to packages/server/game_logic/game_def/block.go index 0b2ad93..d3eb265 100644 --- a/packages/server/utils/pkg/map/type/block.go +++ b/packages/server/game_logic/game_def/block.go @@ -23,7 +23,7 @@ type Block interface { RoundEnd(roundNumber uint16) GetMoveStatus() MoveStatus - MoveFrom(number uint16) + MoveFrom(number uint16) uint16 // MoveTo Ret: a new block to replace this place MoveTo(BlockVal) Block diff --git a/packages/server/utils/pkg/game/mode.go b/packages/server/game_logic/game_def/game_mode.go similarity index 93% rename from packages/server/utils/pkg/game/mode.go rename to packages/server/game_logic/game_def/game_mode.go index 2a9e7e9..3e38e36 100644 --- a/packages/server/utils/pkg/game/mode.go +++ b/packages/server/game_logic/game_def/game_mode.go @@ -1,4 +1,4 @@ -package game +package _type type Mode struct { MaxUserNum uint8 diff --git a/packages/server/utils/pkg/instruction/instruction.go b/packages/server/game_logic/game_def/instruction.go similarity index 95% rename from packages/server/utils/pkg/instruction/instruction.go rename to packages/server/game_logic/game_def/instruction.go index b3eaeab..0218142 100644 --- a/packages/server/utils/pkg/instruction/instruction.go +++ b/packages/server/game_logic/game_def/instruction.go @@ -1,4 +1,4 @@ -package instruction +package _type type Instruction interface{} diff --git a/packages/server/utils/pkg/game/user.go b/packages/server/game_logic/game_def/user.go similarity index 94% rename from packages/server/utils/pkg/game/user.go rename to packages/server/game_logic/game_def/user.go index bdbb1b0..13c8595 100644 --- a/packages/server/utils/pkg/game/user.go +++ b/packages/server/game_logic/game_def/user.go @@ -1,4 +1,4 @@ -package game +package _type type UserStatus uint8 diff --git a/packages/server/utils/pkg/map/map.go b/packages/server/game_logic/map/map.go similarity index 83% rename from packages/server/utils/pkg/map/map.go rename to packages/server/game_logic/map/map.go index f3904f1..d77253b 100644 --- a/packages/server/utils/pkg/map/map.go +++ b/packages/server/game_logic/map/map.go @@ -4,9 +4,8 @@ import ( "encoding/json" "fmt" "github.com/sirupsen/logrus" - "server/utils/pkg/instruction" - "server/utils/pkg/map/blockManager" - "server/utils/pkg/map/type" + "server/game_logic/block_manager" + "server/game_logic/game_def" "strconv" "strings" ) @@ -19,7 +18,7 @@ type mapInfo struct { } type Map struct { - blocks [][]_type.Block + Blocks [][]_type.Block mapInfo } @@ -32,15 +31,15 @@ func (p *Map) Id() uint32 { } func (p *Map) GetBlock(position _type.Position) _type.Block { - return p.blocks[position.Y-1][position.X-1] + return p.Blocks[position.Y-1][position.X-1] } func (p *Map) SetBlock(position _type.Position, block _type.Block) { - p.blocks[position.Y-1][position.X-1] = block + p.Blocks[position.Y-1][position.X-1] = block } func (p *Map) HasBlocks() bool { - if p.blocks == nil { + if p.Blocks == nil { return false } else { return true @@ -48,7 +47,7 @@ func (p *Map) HasBlocks() bool { } func (p *Map) RoundStart(roundNum uint16) { - for _, col := range p.blocks { + for _, col := range p.Blocks { for _, b := range col { b.RoundStart(roundNum) } @@ -56,7 +55,7 @@ func (p *Map) RoundStart(roundNum uint16) { } func (p *Map) RoundEnd(roundNum uint16) { - for _, col := range p.blocks { + for _, col := range p.Blocks { for _, b := range col { b.RoundEnd(roundNum) } @@ -65,7 +64,7 @@ func (p *Map) RoundEnd(roundNum uint16) { func CreateMapWithInfo(mapId uint32, size MapSize) *Map { return &Map{ - blocks: nil, + Blocks: nil, mapInfo: mapInfo{ size: size, id: mapId, @@ -88,8 +87,8 @@ func DebugOutput(p *Map, f func(_type.Block) uint16) { // Only for debugging tmp += ex(i) + " " } tmp += "\n" - for rowNum, row := range p.blocks { - tmp += ex(uint16(rowNum)) + ": " + for rowNum, row := range p.Blocks { + tmp += ex(uint16(rowNum+1)) + ": " for _, b := range row { tmp += ex(f(b)) + " " } @@ -102,25 +101,25 @@ func isPositionLegal(position _type.Position, size MapSize) bool { return 1 <= position.X && position.X <= size.W && 1 <= position.Y && position.Y <= size.H } -func (p *Map) Move(ins instruction.Move) bool { +func (p *Map) Move(ins _type.Move) bool { var offsetX, offsetY int switch ins.Towards { - case instruction.MoveTowardsDown: + case _type.MoveTowardsDown: { offsetX = 0 offsetY = 1 } - case instruction.MoveTowardsUp: + case _type.MoveTowardsUp: { offsetX = 0 offsetY = -1 } - case instruction.MoveTowardsLeft: + case _type.MoveTowardsLeft: { offsetX = -1 offsetY = 0 } - case instruction.MoveTowardsRight: + case _type.MoveTowardsRight: { offsetX = 1 offsetY = 0 @@ -161,8 +160,8 @@ func (p *Map) Move(ins instruction.Move) bool { } var toBlockNew _type.Block - thisBlock.MoveFrom(ins.Number) - toBlockNew = toBlock.MoveTo(_type.BlockVal{Number: thisBlock.OwnerId(), OwnerId: ins.Number}) + hasMovedNum := thisBlock.MoveFrom(ins.Number) + toBlockNew = toBlock.MoveTo(_type.BlockVal{Number: hasMovedNum, OwnerId: thisBlock.OwnerId()}) if toBlockNew != nil { p.SetBlock(newPosition, toBlockNew) } @@ -181,7 +180,7 @@ func Str2GameMap(mapId uint32, originalMapStr string) *Map { for rowNum, row := range result { ret[rowNum] = make([]_type.Block, size.W) for colNum, typeId := range row { - ret[rowNum][colNum] = blockManager.NewBlock(typeId, 0, 0) + ret[rowNum][colNum] = block_manager.NewBlock(typeId, 0, 0) } } return &Map{ @@ -205,7 +204,7 @@ func FullStr2GameMap(mapId uint32, originalMapStr string) *Map { ownerId := blockInfo[1] number := blockInfo[2] - newBlock := blockManager.NewBlock(uint8(blockId), number, ownerId) + newBlock := block_manager.NewBlock(uint8(blockId), number, ownerId) ret[rowNum][colNum] = newBlock } @@ -234,7 +233,7 @@ type mapJsonStruct struct { Block []string `json:"block"` Owner []uint16 `json:"owner,omitempty"` } `json:"mappings"` - Type []uint8Array `json:"type"` + Type []uint8Array `json:"game_def"` Owner []uint8Array `json:"owner,omitempty"` Number [][]uint16 `json:"number,omitempty"` } @@ -249,7 +248,7 @@ func JsonStrToMap(jsonStr string) *Map { // process original mapping blockMapping := make(map[uint8]uint8) for i, v := range res.Mappings.Block { - blockMapping[uint8(i)] = blockManager.GetBlockIdByName[v] + blockMapping[uint8(i)] = block_manager.GetBlockIdByName[v] } if res.Mappings.Owner == nil || res.Owner == nil { @@ -262,13 +261,13 @@ func JsonStrToMap(jsonStr string) *Map { var blocks [][]_type.Block if (res.Number != nil && len(res.Type) != len(res.Number)) || (res.Owner != nil && len(res.Type) != len(res.Owner)) { - logrus.Panic("original block type, number, owner id must have the same size") + logrus.Panic("original block game_def, number, owner id must have the same size") } blocks = make([][]_type.Block, len(res.Type)) for i, v := range res.Type { if (res.Number != nil && len(v) != len(res.Number[i])) || (res.Owner != nil && len(v) != len(res.Owner[i])) { - logrus.Panic("original block type, number, owner id must have the same size") + logrus.Panic("original block game_def, number, owner id must have the same size") } blocks[i] = make([]_type.Block, len(v)) @@ -287,10 +286,10 @@ func JsonStrToMap(jsonStr string) *Map { } if typeId >= uint8(len(blockMapping)) { - logrus.Panic("original block type must be less than block type mapping size") + logrus.Panic("original block game_def must be less than block game_def mapping size") } - blocks[i][j] = blockManager.NewBlock(blockMapping[typeId], n, o) + blocks[i][j] = block_manager.NewBlock(blockMapping[typeId], n, o) } } return &Map{ @@ -309,7 +308,7 @@ func MapToJsonStr(m *Map) string { ret.Owner = make([]uint8Array, m.size.H) ret.Number = make([][]uint16, m.size.H) - for i, row := range m.blocks { + for i, row := range m.Blocks { ret.Type[i] = make(uint8Array, m.size.W) ret.Owner[i] = make(uint8Array, m.size.W) ret.Number[i] = make([]uint16, m.size.W) @@ -329,7 +328,7 @@ func MapToJsonStr(m *Map) string { } for k := range typeMapping { - ret.Mappings.Block = append(ret.Mappings.Block, blockManager.GetMetaById[k].Name) + ret.Mappings.Block = append(ret.Mappings.Block, block_manager.GetMetaById[k].Name) } for k := range ownerMapping { ret.Mappings.Owner = append(ret.Mappings.Owner, k) diff --git a/packages/server/utils/pkg/map/map_test.go b/packages/server/game_logic/map/map_test.go similarity index 69% rename from packages/server/utils/pkg/map/map_test.go rename to packages/server/game_logic/map/map_test.go index 8fb7494..7c2c85f 100644 --- a/packages/server/utils/pkg/map/map_test.go +++ b/packages/server/game_logic/map/map_test.go @@ -2,10 +2,10 @@ package _map import ( "reflect" - "server/utils/pkg/map/blockManager" - "server/utils/pkg/map/blockManager/block" - _ "server/utils/pkg/map/blockManager/block" - "server/utils/pkg/map/type" + "server/game_logic/block" + _ "server/game_logic/block" + "server/game_logic/block_manager" + "server/game_logic/game_def" "testing" ) @@ -21,7 +21,7 @@ func TestConvJsonStrMap(t *testing.T) { { name: "basic map string", args: args{ - jsonStr: `{"mappings":{"block":["blank"]},"type":[[0,0,0]]}`, + jsonStr: `{"mappings":{"block":["blank"]},"game_def":[[0,0,0]]}`, }, want: &Map{ [][]_type.Block{ @@ -40,7 +40,7 @@ func TestConvJsonStrMap(t *testing.T) { { name: "with not expected owner field 1", args: args{ - jsonStr: `{"mappings":{"block":["blank"],"owner":[1,2]},"type":[[0,0,0]]}`, + jsonStr: `{"mappings":{"block":["blank"],"owner":[1,2]},"game_def":[[0,0,0]]}`, }, want: &Map{ [][]_type.Block{ @@ -59,7 +59,7 @@ func TestConvJsonStrMap(t *testing.T) { { name: "with not expected owner field 2", args: args{ - jsonStr: `{"mappings":{"block":["blank"]},"type":[[0,0,0]],"owner":[[1,1,1]]}`, + jsonStr: `{"mappings":{"block":["blank"]},"game_def":[[0,0,0]],"owner":[[1,1,1]]}`, }, want: &Map{ [][]_type.Block{ @@ -78,14 +78,14 @@ func TestConvJsonStrMap(t *testing.T) { { name: "with owner field", args: args{ - jsonStr: `{"mappings":{"block":["soldier"],"owner":[1]},"type":[[0,0,0]],"owner":[[1,1,1]]}`, + jsonStr: `{"mappings":{"block":["soldier"],"owner":[1]},"game_def":[[0,0,0]],"owner":[[1,1,1]]}`, }, want: &Map{ [][]_type.Block{ { - blockManager.NewBlock(1, 0, 1), - blockManager.NewBlock(1, 0, 1), - blockManager.NewBlock(1, 0, 1), + block_manager.NewBlock(1, 0, 1), + block_manager.NewBlock(1, 0, 1), + block_manager.NewBlock(1, 0, 1), }, }, mapInfo{ @@ -97,14 +97,14 @@ func TestConvJsonStrMap(t *testing.T) { { name: "with owner field and number field", args: args{ - jsonStr: `{"mappings":{"block":["soldier"],"owner":[1]},"type":[[0,0,0]],"owner":[[1,1,1]],"number":[[1,2,255]]}`, + jsonStr: `{"mappings":{"block":["soldier"],"owner":[1]},"game_def":[[0,0,0]],"owner":[[1,1,1]],"number":[[1,2,255]]}`, }, want: &Map{ [][]_type.Block{ { - blockManager.NewBlock(1, 1, 1), - blockManager.NewBlock(1, 2, 1), - blockManager.NewBlock(1, 255, 1), + block_manager.NewBlock(1, 1, 1), + block_manager.NewBlock(1, 2, 1), + block_manager.NewBlock(1, 255, 1), }, }, mapInfo{ diff --git a/packages/server/judgepool/internal/judge/judge.go b/packages/server/judge_pool/internal/judge/judge.go similarity index 73% rename from packages/server/judgepool/internal/judge/judge.go rename to packages/server/judge_pool/internal/judge/judge.go index ef9f98d..270ae2b 100644 --- a/packages/server/judgepool/internal/judge/judge.go +++ b/packages/server/judge_pool/internal/judge/judge.go @@ -2,14 +2,13 @@ package judge import ( "github.com/sirupsen/logrus" - data_source "server/utils/pkg/datasource" - "server/utils/pkg/game" - game_temp_pool "server/utils/pkg/gametemppool" - "server/utils/pkg/instruction" - "server/utils/pkg/map" - "server/utils/pkg/map/blockManager" - "server/utils/pkg/map/blockManager/block" - "server/utils/pkg/map/type" + "server/game_logic" + "server/game_logic/block" + "server/game_logic/block_manager" + "server/game_logic/game_def" + "server/game_logic/map" + data_source "server/utils/pkg/data_source" + game_temp_pool "server/utils/pkg/game_temp_pool" "time" ) @@ -26,7 +25,7 @@ const ( ) type GameJudge struct { - gameId game.Id + gameId game_logic.Id status Status c chan Status } @@ -36,7 +35,7 @@ func ApplyDataSource(source interface{}) { pData = source.(data_source.PersistentDataSource) } -func NewGameJudge(id game.Id) *GameJudge { +func NewGameJudge(id game_logic.Id) *GameJudge { j := &GameJudge{ gameId: id, status: StatusWaiting, @@ -67,7 +66,7 @@ func judgeWorking(j *GameJudge) { if !g.Map.HasBlocks() { g.Map = pData.GetOriginalMap(g.Map.Id()) } - data.SetGameStatus(j.gameId, game.StatusRunning) + data.SetGameStatus(j.gameId, game_logic.StatusRunning) g.UserList = data.GetCurrentUserList(j.gameId) kingPos := getKingPos(g) @@ -85,19 +84,22 @@ func judgeWorking(j *GameJudge) { //Round End if g.RoundNum != 0 { roundLogger.Infof("Round end") + if g.RoundNum == 1 { + logrus.Info("debug") + } data.NewInstructionTemp(j.gameId, g.RoundNum) instructionList := data.GetInstructions(j.gameId, g.RoundNum) - for _, ins := range instructionList { - if !executeInstruction(j.gameId, ins) { + for userId, ins := range instructionList { + if !executeInstruction(j.gameId, userId, ins) { roundLogger.Infof("Instruction %#v failed to execute", ins) } } g.UserList = data.GetCurrentUserList(g.Id) g.Map.RoundEnd(g.RoundNum) - if judgeGame(g, kingPos) != game.StatusRunning { + if judgeGame(g, kingPos) != game_logic.StatusRunning { // Game Over - data.SetGameStatus(g.Id, game.StatusEnd) + data.SetGameStatus(g.Id, game_logic.StatusEnd) data.SetWinner(g.Id, g.Winner) j.status = StatusWaiting game_temp_pool.Delete(g.Id) @@ -126,7 +128,7 @@ func judgeWorking(j *GameJudge) { } } -func getKingPos(g *game.Game) []_type.Position { +func getKingPos(g *game_logic.Game) []_type.Position { var kingPos []_type.Position for y := uint8(1); y <= g.Map.Size().H; y++ { for x := uint8(1); x <= g.Map.Size().W; x++ { @@ -140,30 +142,30 @@ func getKingPos(g *game.Game) []_type.Position { } // judgeGame TODO: Add unit test -func judgeGame(g *game.Game, kingPos []_type.Position) game.Status { +func judgeGame(g *game_logic.Game, kingPos []_type.Position) game_logic.Status { // Check online player number onlinePlayerNum := uint8(0) for _, u := range g.UserList { - if u.Status == game.UserStatusConnected { + if u.Status == _type.UserStatusConnected { onlinePlayerNum++ } } if onlinePlayerNum <= 0 { - return game.StatusEnd + return game_logic.StatusEnd } if onlinePlayerNum == 1 { // TODO: Announce game-over for _, u := range g.UserList { - if u.Status == game.UserStatusConnected { + if u.Status == _type.UserStatusConnected { g.Winner = u.TeamId break } } - return game.StatusEnd + return game_logic.StatusEnd } // Check king status - if g.Mode == game.Mode1v1 { + if g.Mode == _type.Mode1v1 { flag := true for _, k := range kingPos { if g.Map.GetBlock(k).Meta().BlockId != block.KingMeta.BlockId { @@ -186,14 +188,14 @@ func judgeGame(g *game.Game, kingPos []_type.Position) game.Status { } } g.Winner = wt - return game.StatusEnd + return game_logic.StatusEnd } } - return game.StatusRunning + return game_logic.StatusRunning } -func allocateKing(g *game.Game, kingPos []_type.Position) { +func allocateKing(g *game_logic.Game, kingPos []_type.Position) { allocatableKingNum := 0 for _, k := range kingPos { if g.Map.GetBlock(k).OwnerId() == 0 { @@ -207,13 +209,13 @@ func allocateKing(g *game.Game, kingPos []_type.Position) { break } g.Map.SetBlock(kingPos[i], - blockManager.NewBlock(block.KingMeta.BlockId, g.Map.GetBlock(kingPos[i]).Number(), u.UserId)) + block_manager.NewBlock(block.KingMeta.BlockId, g.Map.GetBlock(kingPos[i]).Number(), u.UserId)) allocatableKingNum-- } } -func allocateTeam(g *game.Game) { - if g.Mode == game.Mode1v1 { +func allocateTeam(g *game_logic.Game) { + if g.Mode == _type.Mode1v1 { for i := range g.UserList { g.UserList[i].TeamId = uint8(i) + 1 } @@ -222,15 +224,18 @@ func allocateTeam(g *game.Game) { } } -func executeInstruction(id game.Id, ins instruction.Instruction) bool { +func executeInstruction(id game_logic.Id, userId uint16, ins _type.Instruction) bool { var ret bool var m *_map.Map switch ins.(type) { - case instruction.Move: + case _type.Move: { + i := ins.(_type.Move) m = data.GetCurrentMap(id) - ret = m.Move(ins.(instruction.Move)) - + if m.GetBlock(_type.Position(i.Position)).OwnerId() != userId { + return false + } + ret = m.Move(i) } } return ret diff --git a/packages/server/judgepool/pool.go b/packages/server/judge_pool/pool.go similarity index 75% rename from packages/server/judgepool/pool.go rename to packages/server/judge_pool/pool.go index b56d228..55d1413 100644 --- a/packages/server/judgepool/pool.go +++ b/packages/server/judge_pool/pool.go @@ -2,16 +2,17 @@ package judgePool import ( "github.com/sirupsen/logrus" - "server/judgepool/internal/judge" - data_source "server/utils/pkg/datasource" - "server/utils/pkg/game" + "server/game_logic" + "server/game_logic/game_def" + "server/judge_pool/internal/judge" + data_source "server/utils/pkg/data_source" "sync" "time" ) type Pool struct { judges sync.Map - AllowGameMode []game.Mode + AllowGameMode []_type.Mode } var data data_source.TempDataSource @@ -21,7 +22,7 @@ func ApplyDataSource(source interface{}) { judge.ApplyDataSource(source) } -func (p *Pool) NewGame(mode game.Mode) { +func (p *Pool) NewGame(mode _type.Mode) { id := data.CreateGame(mode) if id == 0 { logrus.Panic("cannot create game") @@ -29,7 +30,7 @@ func (p *Pool) NewGame(mode game.Mode) { p.judges.Store(id, judge.NewGameJudge(id)) } -func (p *Pool) DebugNewGame(g *game.Game) { +func (p *Pool) DebugNewGame(g *game_logic.Game) { if ok := data.DebugCreateGame(g); !ok { logrus.Panic("cannot create game in debug mode") } @@ -39,7 +40,7 @@ func (p *Pool) DebugNewGame(g *game.Game) { p.judges.Store(g.Id, judge.NewGameJudge(g.Id)) } -func CreatePool(allowGameMode []game.Mode) *Pool { +func CreatePool(allowGameMode []_type.Mode) *Pool { p := &Pool{AllowGameMode: allowGameMode} go poolWorking(p) return p @@ -52,7 +53,7 @@ func poolWorking(p *Pool) { } for _ = range t.C { // Ensure there is a game always in waiting status - tryStartGame := func(game game.Game) { + tryStartGame := func(game game_logic.Game) { if uint8(len(data.GetCurrentUserList(game.Id))) == game.Mode.MaxUserNum { jAny, _ := p.judges.Load(game.Id) @@ -65,7 +66,7 @@ func poolWorking(p *Pool) { for _, mode := range p.AllowGameMode { list := data.GetGameList(mode) for _, g := range list { - if g.Status == game.StatusWaiting { + if g.Status == game_logic.StatusWaiting { tryStartGame(g) break } diff --git a/packages/server/main.go b/packages/server/main.go index 029bec7..3ac9ad5 100644 --- a/packages/server/main.go +++ b/packages/server/main.go @@ -7,11 +7,11 @@ import ( "github.com/gookit/ini/v2" "github.com/sirupsen/logrus" "server/api" - judge_pool "server/judgepool" - "server/utils/pkg/datasource/local" - "server/utils/pkg/game" - "server/utils/pkg/instruction" - _ "server/utils/pkg/map/blockManager/block" + "server/game_logic" + _ "server/game_logic/block" + "server/game_logic/game_def" + judge_pool "server/judge_pool" + "server/utils/pkg/data_source/local" db "server/utils/pkg/pg" "time" ) @@ -53,14 +53,14 @@ func main() { defer exit() data := local.Local{ - GamePool: make(map[game.Id]*game.Game), + GamePool: make(map[game_logic.Id]*game_logic.Game), OriginalMapStrPool: make(map[uint32]string), - InstructionLog: make(map[game.Id]map[uint16]map[uint16]instruction.Instruction), + InstructionLog: make(map[game_logic.Id]map[uint16]map[uint16]_type.Instruction), } data.OriginalMapStrPool[0] = "[\n[0,0,0,0,2],\n[0,2,0,0,0],\n[0,0,0,0,0],\n[0,3,3,0,3],\n[0,3,0,2,0]\n]" judge_pool.ApplyDataSource(&data) - p := judge_pool.CreatePool([]game.Mode{game.Mode1v1}) + p := judge_pool.CreatePool([]_type.Mode{_type.Mode1v1}) time.Sleep(200 * time.Millisecond) diff --git a/packages/server/main_test.go b/packages/server/main_test.go index 71fec35..ca76faf 100644 --- a/packages/server/main_test.go +++ b/packages/server/main_test.go @@ -4,10 +4,11 @@ import ( nested "github.com/antonfisher/nested-logrus-formatter" "github.com/sirupsen/logrus" "server/api" - judge_pool "server/judgepool" - "server/utils/pkg/datasource/local" - "server/utils/pkg/game" - "server/utils/pkg/instruction" + "server/game_logic" + _ "server/game_logic/block" + "server/game_logic/game_def" + judge_pool "server/judge_pool" + "server/utils/pkg/data_source/local" "testing" "time" ) @@ -19,28 +20,28 @@ func TestServer_main(t *testing.T) { }) data := local.Local{ - GamePool: make(map[game.Id]*game.Game), + GamePool: make(map[game_logic.Id]*game_logic.Game), OriginalMapStrPool: make(map[uint32]string), - InstructionLog: make(map[game.Id]map[uint16]map[uint16]instruction.Instruction), + InstructionLog: make(map[game_logic.Id]map[uint16]map[uint16]_type.Instruction), } data.OriginalMapStrPool[0] = "[\n[0,0,0,0,2],\n[0,2,0,0,0],\n[0,0,0,0,0],\n[0,3,3,0,3],\n[0,3,0,2,0]\n]" judge_pool.ApplyDataSource(&data) - p := judge_pool.CreatePool([]game.Mode{game.Mode1v1}) + p := judge_pool.CreatePool([]_type.Mode{_type.Mode1v1}) time.Sleep(200 * time.Millisecond) api.ApplyDataSource(&data) api.DebugStartFileReceiver(p) - id := game.Id(1000) + id := game_logic.Id(1000) ticker := time.NewTicker(1 * time.Second) for i := 1; true; i++ { <-ticker.C if i >= 20 { t.Fatalf("game running timeout(20s)") } - if data.GetGameInfo(id).Status == game.StatusEnd { + if data.GetGameInfo(id).Status == game_logic.StatusEnd { ticker.Stop() break } @@ -52,7 +53,7 @@ func TestServer_main(t *testing.T) { userList = append(userList, u.Name) } } - if userList[0] != "2" { + if userList[0] != "test2" { t.Fatalf("game result is unexpected: expected [\"2\"], got %v (team %d)", userList, data.GamePool[id].Winner) } } diff --git a/packages/server/test/replay/B__4b098g.gioreplay.processed b/packages/server/test/B__4b098g.gioreplay.processed similarity index 100% rename from packages/server/test/replay/B__4b098g.gioreplay.processed rename to packages/server/test/B__4b098g.gioreplay.processed diff --git a/packages/server/test/replay/test1.gioreplay.processed b/packages/server/test/replay/test1.gioreplay.processed new file mode 100644 index 0000000..1e7dfa6 --- /dev/null +++ b/packages/server/test/replay/test1.gioreplay.processed @@ -0,0 +1,7 @@ +[[[2, 1, 50]],[[1, 2, 100]],[[2, 2, 1]]] +|test1:Move 1 1 down 0 +Move 1 2 down 0 + +|test2: + +Move 1 2 up 0 \ No newline at end of file diff --git a/packages/server/utils/pkg/datasource/local/local.go b/packages/server/utils/pkg/data_source/local/local.go similarity index 65% rename from packages/server/utils/pkg/datasource/local/local.go rename to packages/server/utils/pkg/data_source/local/local.go index c98fe8c..1def222 100644 --- a/packages/server/utils/pkg/datasource/local/local.go +++ b/packages/server/utils/pkg/data_source/local/local.go @@ -3,23 +3,23 @@ package local import ( "github.com/sirupsen/logrus" "math/rand" - "server/utils/pkg/datasource" - "server/utils/pkg/game" - "server/utils/pkg/instruction" - "server/utils/pkg/map" + "server/game_logic" + "server/game_logic/game_def" + "server/game_logic/map" + "server/utils/pkg/data_source" "sort" "sync" "time" ) -var _ datasource.PersistentDataSource = (*Local)(nil) -var _ datasource.TempDataSource = (*Local)(nil) +var _ data_source.PersistentDataSource = (*Local)(nil) +var _ data_source.TempDataSource = (*Local)(nil) type Local struct { m sync.Mutex - GamePool map[game.Id]*game.Game + GamePool map[game_logic.Id]*game_logic.Game OriginalMapStrPool map[uint32]string - InstructionLog map[game.Id]map[uint16]map[uint16]instruction.Instruction + InstructionLog map[game_logic.Id]map[uint16]map[uint16]_type.Instruction } func (l *Local) lock() bool { @@ -45,7 +45,7 @@ func (l *Local) unlock() { l.m.Unlock() } -func (l *Local) SetWinner(id game.Id, teamId uint8) (ok bool) { +func (l *Local) SetWinner(id game_logic.Id, teamId uint8) (ok bool) { if l.lock() { defer l.unlock() l.GamePool[id].Winner = teamId @@ -53,12 +53,12 @@ func (l *Local) SetWinner(id game.Id, teamId uint8) (ok bool) { return false } -func (l *Local) GetGameList(mode game.Mode) []game.Game { +func (l *Local) GetGameList(mode _type.Mode) []game_logic.Game { if l.lock() { defer l.unlock() - var ret []game.Game + var ret []game_logic.Game for _, p := range l.GamePool { - if p.Status == game.StatusEnd { + if p.Status == game_logic.StatusEnd { continue } g := *p @@ -75,12 +75,12 @@ func (l *Local) GetGameList(mode game.Mode) []game.Game { } // CancelGame 1. Set game status 2. Quit existing users -func (l *Local) CancelGame(id game.Id) (ok bool) { +func (l *Local) CancelGame(id game_logic.Id) (ok bool) { if l.lock() { defer l.unlock() g := l.GamePool[id] - if g.Status == game.StatusWaiting || g.Status == game.StatusRunning { - g.Status = game.StatusEnd + if g.Status == game_logic.StatusWaiting || g.Status == game_logic.StatusRunning { + g.Status = game_logic.StatusEnd g.UserList = nil // TODO return true } else { @@ -91,7 +91,7 @@ func (l *Local) CancelGame(id game.Id) (ok bool) { } } -func (l *Local) GetGameInfo(id game.Id) *game.Game { +func (l *Local) GetGameInfo(id game_logic.Id) *game_logic.Game { if l.lock() { defer l.unlock() g := *l.GamePool[id] @@ -103,7 +103,7 @@ func (l *Local) GetGameInfo(id game.Id) *game.Game { } } -func (l *Local) GetCurrentUserList(id game.Id) []game.User { +func (l *Local) GetCurrentUserList(id game_logic.Id) []_type.User { if l.lock() { defer l.unlock() return l.GamePool[id].UserList @@ -112,32 +112,28 @@ func (l *Local) GetCurrentUserList(id game.Id) []game.User { } } -func (l *Local) GetInstructions(id game.Id, tempId uint16) []instruction.Instruction { +func (l *Local) GetInstructions(id game_logic.Id, tempId uint16) map[uint16]_type.Instruction { if l.lock() { defer l.unlock() - var list []instruction.Instruction - for _, v := range l.InstructionLog[id][tempId] { - list = append(list, v) - } - return list + return l.InstructionLog[id][tempId] } else { return nil } //return ExampleInstruction } -func (l *Local) NewInstructionTemp(id game.Id, _ uint16) (ok bool) { +func (l *Local) NewInstructionTemp(id game_logic.Id, _ uint16) (ok bool) { if l.lock() { defer l.unlock() l.GamePool[id].RoundNum++ - l.InstructionLog[id][l.GamePool[id].RoundNum] = make(map[uint16]instruction.Instruction) + l.InstructionLog[id][l.GamePool[id].RoundNum] = make(map[uint16]_type.Instruction) return true } else { return false } } -func (l *Local) SetGameStatus(id game.Id, status game.Status) (ok bool) { +func (l *Local) SetGameStatus(id game_logic.Id, status game_logic.Status) (ok bool) { if l.lock() { defer l.unlock() l.GamePool[id].Status = status @@ -147,7 +143,7 @@ func (l *Local) SetGameStatus(id game.Id, status game.Status) (ok bool) { } } -func (l *Local) SetGameMap(id game.Id, m *_map.Map) (ok bool) { +func (l *Local) SetGameMap(id game_logic.Id, m *_map.Map) (ok bool) { if l.lock() { defer l.unlock() l.GamePool[id].Map = &(*m) @@ -157,19 +153,19 @@ func (l *Local) SetGameMap(id game.Id, m *_map.Map) (ok bool) { } } -func (l *Local) SetUserStatus(id game.Id, user game.User) (ok bool) { +func (l *Local) SetUserStatus(id game_logic.Id, user _type.User) (ok bool) { if l.lock() { defer l.unlock() g := l.GamePool[id] - if g.Status == game.StatusEnd { + if g.Status == game_logic.StatusEnd { return false } - if g.Status == game.StatusWaiting { + if g.Status == game_logic.StatusWaiting { // Try to find for i, u := range g.UserList { if u.UserId == user.UserId { - if user.Status == game.UserStatusDisconnected { + if user.Status == _type.UserStatusDisconnected { // Remove the user from the list if they are disconnected g.UserList = append(g.UserList[:i], g.UserList[i+1:]...) } else { @@ -186,13 +182,13 @@ func (l *Local) SetUserStatus(id game.Id, user game.User) (ok bool) { logrus.Panic("game mode is illegal") } // If the user is not in the list, try to add him/her if the game is not full - if user.Status == game.UserStatusConnected && uint8(len(g.UserList)) < g.Mode.MaxUserNum { + if user.Status == _type.UserStatusConnected && uint8(len(g.UserList)) < g.Mode.MaxUserNum { user.TeamId = 0 g.UserList = append(g.UserList, user) return true } } - if g.Status == game.StatusRunning { + if g.Status == game_logic.StatusRunning { for i, u := range g.UserList { if u.UserId == user.UserId { g.UserList[i].Status = user.Status @@ -204,7 +200,7 @@ func (l *Local) SetUserStatus(id game.Id, user game.User) (ok bool) { return false } -func (l *Local) UpdateInstruction(id game.Id, user game.User, instruction instruction.Instruction) (ok bool) { +func (l *Local) UpdateInstruction(id game_logic.Id, user _type.User, instruction _type.Instruction) (ok bool) { if l.lock() { defer l.unlock() l.InstructionLog[id][l.GamePool[id].RoundNum][user.UserId] = instruction @@ -214,7 +210,7 @@ func (l *Local) UpdateInstruction(id game.Id, user game.User, instruction instru } } -func (l *Local) GetCurrentMap(id game.Id) *_map.Map { +func (l *Local) GetCurrentMap(id game_logic.Id) *_map.Map { if l.lock() { defer l.unlock() m := *l.GamePool[id].Map @@ -233,7 +229,7 @@ func (l *Local) GetOriginalMap(mapId uint32) *_map.Map { } } -func (l *Local) GetCurrentGame(id game.Id) *game.Game { +func (l *Local) GetCurrentGame(id game_logic.Id) *game_logic.Game { if l.lock() { defer l.unlock() return l.GamePool[id] @@ -241,37 +237,37 @@ func (l *Local) GetCurrentGame(id game.Id) *game.Game { return nil } -func (l *Local) CreateGame(mode game.Mode) game.Id { +func (l *Local) CreateGame(mode _type.Mode) game_logic.Id { //m := l.GetOriginalMap(rand.Uint32()) m := l.GetOriginalMap(0) // TODO DEBUG ONLY if l.lock() { defer l.unlock() - var gameId game.Id + var gameId game_logic.Id for { - gameId = game.Id(rand.Uint32()) + gameId = game_logic.Id(rand.Uint32()) if _, ok := l.GamePool[gameId]; !ok && gameId >= 100 { // gameId 1-99 is for debugging usage break } } - g := &game.Game{ + g := &game_logic.Game{ Map: m, Mode: mode, Id: gameId, CreateTime: time.Now().UnixMicro(), - Status: game.StatusWaiting, + Status: game_logic.StatusWaiting, RoundNum: 0, - UserList: []game.User{}, + UserList: []_type.User{}, } l.GamePool[g.Id] = g - l.InstructionLog[g.Id] = make(map[uint16]map[uint16]instruction.Instruction) + l.InstructionLog[g.Id] = make(map[uint16]map[uint16]_type.Instruction) return g.Id } else { return 0 } } -func (l *Local) DebugCreateGame(g *game.Game) (ok bool) { +func (l *Local) DebugCreateGame(g *game_logic.Game) (ok bool) { if !g.Map.HasBlocks() { g.Map = l.GetOriginalMap(g.Map.Id()) } @@ -282,24 +278,24 @@ func (l *Local) DebugCreateGame(g *game.Game) (ok bool) { return false } - var gameId game.Id + var gameId game_logic.Id for { - gameId = game.Id(rand.Uint32()) + gameId = game_logic.Id(rand.Uint32()) if _, ok := l.GamePool[gameId]; !ok { break } } - ng := &game.Game{ + ng := &game_logic.Game{ Map: g.Map, Mode: g.Mode, Id: g.Id, UserList: g.UserList, CreateTime: time.Now().UnixMicro(), - Status: game.StatusWaiting, + Status: game_logic.StatusWaiting, RoundNum: 0, } l.GamePool[g.Id] = ng - l.InstructionLog[g.Id] = make(map[uint16]map[uint16]instruction.Instruction) + l.InstructionLog[g.Id] = make(map[uint16]map[uint16]_type.Instruction) return true } else { return false diff --git a/packages/server/utils/pkg/datasource/local/local_test.go b/packages/server/utils/pkg/data_source/local/local_test.go similarity index 76% rename from packages/server/utils/pkg/datasource/local/local_test.go rename to packages/server/utils/pkg/data_source/local/local_test.go index 830401c..a94f422 100644 --- a/packages/server/utils/pkg/datasource/local/local_test.go +++ b/packages/server/utils/pkg/data_source/local/local_test.go @@ -1,11 +1,10 @@ package local import ( - "server/utils/pkg/game" - "server/utils/pkg/instruction" - "server/utils/pkg/map" - _ "server/utils/pkg/map/blockManager/block" - "server/utils/pkg/map/type" + "server/game_logic" + _ "server/game_logic/block" + "server/game_logic/game_def" + "server/game_logic/map" "strconv" "testing" ) @@ -16,19 +15,19 @@ func init() { func create() *Local { return &Local{ - GamePool: make(map[game.Id]*game.Game), + GamePool: make(map[game_logic.Id]*game_logic.Game), OriginalMapStrPool: make(map[uint32]string), - InstructionLog: make(map[game.Id]map[uint16]map[uint16]instruction.Instruction), + InstructionLog: make(map[game_logic.Id]map[uint16]map[uint16]_type.Instruction), } } var userCount = uint16(1) -func getUser() game.User { - return game.User{ +func getUser() _type.User { + return _type.User{ Name: strconv.Itoa(int(userCount)), UserId: userCount, - Status: game.UserStatusDisconnected, + Status: _type.UserStatusDisconnected, TeamId: uint8(userCount), ForceStartStatus: false, } @@ -52,23 +51,23 @@ func TestLocal_lock(t *testing.T) { func TestLocal_Game(t *testing.T) { l := create() - id := game.Id(1) + id := game_logic.Id(1) // This function must be correct - l.DebugCreateGame(&game.Game{ + l.DebugCreateGame(&game_logic.Game{ Map: _map.FullStr2GameMap(1, "[[[0,0,0]]]"), // Wait - Mode: game.Mode1v1, + Mode: _type.Mode1v1, Id: id, - UserList: []game.User{getUser()}, + UserList: []_type.User{getUser()}, CreateTime: 0, - Status: game.StatusWaiting, + Status: game_logic.StatusWaiting, RoundNum: 0, Winner: 0, }) t.Run("set game status", func(t *testing.T) { - l.SetGameStatus(id, game.StatusRunning) - if l.GamePool[id].Status != game.StatusRunning { + l.SetGameStatus(id, game_logic.StatusRunning) + if l.GamePool[id].Status != game_logic.StatusRunning { t.Fatalf("the status has unchanged") } }) @@ -79,7 +78,7 @@ func TestLocal_Game(t *testing.T) { } }) t.Run("get game list", func(t *testing.T) { - gl := l.GetGameList(game.Mode1v1) + gl := l.GetGameList(_type.Mode1v1) if len(gl) != 1 { t.Fatalf("game count is incorrect") } @@ -96,8 +95,8 @@ func TestLocal_Game(t *testing.T) { }) t.Run("update instruction", func(t *testing.T) { u := l.GamePool[id].UserList[0] - ins := instruction.Move{ - Position: instruction.BlockPosition{1, 1}, + ins := _type.Move{ + Position: _type.BlockPosition{1, 1}, Towards: "down", Number: 1, } @@ -109,7 +108,7 @@ func TestLocal_Game(t *testing.T) { t.Run("cancel game", func(t *testing.T) { l.CancelGame(id) - if l.GamePool[id].Status != game.StatusEnd { + if l.GamePool[id].Status != game_logic.StatusEnd { t.Fatalf("the status has unchanged") } if l.GamePool[id].UserList != nil { @@ -120,14 +119,14 @@ func TestLocal_Game(t *testing.T) { func TestLocal_User(t *testing.T) { l := create() - id := game.Id(2) - l.DebugCreateGame(&game.Game{ + id := game_logic.Id(2) + l.DebugCreateGame(&game_logic.Game{ Map: _map.FullStr2GameMap(1, "[[[0,0,0]]]"), - Mode: game.Mode1v1, + Mode: _type.Mode1v1, Id: id, - UserList: []game.User{}, + UserList: []_type.User{}, CreateTime: 0, - Status: game.StatusWaiting, + Status: game_logic.StatusWaiting, RoundNum: 0, Winner: 0, }) @@ -138,14 +137,14 @@ func TestLocal_User(t *testing.T) { t.Fatalf("user has been added unexpectedly") } - u.Status = game.UserStatusConnected + u.Status = _type.UserStatusConnected l.SetUserStatus(id, u) if len(l.GamePool[id].UserList) != 1 || l.GamePool[id].UserList[0].UserId != u.UserId { t.Fatalf("user has not been added") } - u.Status = game.UserStatusDisconnected + u.Status = _type.UserStatusDisconnected l.SetUserStatus(id, u) @@ -157,14 +156,14 @@ func TestLocal_User(t *testing.T) { func TestLocal_Map(t *testing.T) { l := create() - id := game.Id(3) - l.DebugCreateGame(&game.Game{ + id := game_logic.Id(3) + l.DebugCreateGame(&game_logic.Game{ Map: _map.FullStr2GameMap(1, "[[[0,0,0]]]"), - Mode: game.Mode1v1, + Mode: _type.Mode1v1, Id: id, - UserList: []game.User{}, + UserList: []_type.User{}, CreateTime: 0, - Status: game.StatusWaiting, + Status: game_logic.StatusWaiting, RoundNum: 0, Winner: 0, }) diff --git a/packages/server/utils/pkg/datasource/persistent.go b/packages/server/utils/pkg/data_source/persistent.go similarity index 59% rename from packages/server/utils/pkg/datasource/persistent.go rename to packages/server/utils/pkg/data_source/persistent.go index e026d7a..40cddfb 100644 --- a/packages/server/utils/pkg/datasource/persistent.go +++ b/packages/server/utils/pkg/data_source/persistent.go @@ -1,6 +1,8 @@ -package datasource +package data_source -import "server/utils/pkg/map" +import ( + "server/game_logic/map" +) type PersistentDataSource interface { GetOriginalMap(mapId uint32) *_map.Map diff --git a/packages/server/utils/pkg/datasource/pg/pg.go b/packages/server/utils/pkg/data_source/pg/pg.go similarity index 68% rename from packages/server/utils/pkg/datasource/pg/pg.go rename to packages/server/utils/pkg/data_source/pg/pg.go index 1b95b9b..9a89311 100644 --- a/packages/server/utils/pkg/datasource/pg/pg.go +++ b/packages/server/utils/pkg/data_source/pg/pg.go @@ -4,11 +4,10 @@ import ( "encoding/json" "github.com/sirupsen/logrus" "math/rand" - data_source "server/utils/pkg/datasource" - "server/utils/pkg/game" - "server/utils/pkg/instruction" - _map "server/utils/pkg/map" - "server/utils/pkg/map/type" + "server/game_logic" + "server/game_logic/game_def" + "server/game_logic/map" + data_source "server/utils/pkg/data_source" db "server/utils/pkg/pg" ) @@ -22,7 +21,7 @@ const sqlCreateGame = "INSERT INTO game(game_id,mode,status,round_num,create_tim func generatorMapJson(m *_map.Map) string { type b struct { - TypeId uint8 `json:"type"` + TypeId uint8 `json:"game_def"` OwnerId uint16 `json:"owner"` Number uint16 `json:"num"` } @@ -63,15 +62,15 @@ func generatorMapJson(m *_map.Map) string { var sqlQueryGame = "SELECT * FROM game WHERE game_id=$1" -func (p *Pg) CreateGame(mode game.Mode) game.Id { - var gameId game.Id +func (p *Pg) CreateGame(mode _type.Mode) game_logic.Id { + var gameId game_logic.Id for { - gameId = game.Id(rand.Uint32()) + gameId = game_logic.Id(rand.Uint32()) if ok := db.SqlQueryExist(sqlQueryGame, gameId); !ok && gameId >= 100 { // gameId 1-99 is for debugging usage break } } - g := game.Game{ + g := game_logic.Game{ Mode: mode, Id: gameId, RoundNum: 0, @@ -80,8 +79,8 @@ func (p *Pg) CreateGame(mode game.Mode) game.Id { return gameId } -func (p *Pg) DebugCreateGame(g *game.Game) (ok bool) { - r := db.SqlExec(sqlCreateGame, g.Id, g.Mode.NameStr, game.StatusWaiting, g.RoundNum, generatorMapJson(g.Map), "[]") +func (p *Pg) DebugCreateGame(g *game_logic.Game) (ok bool) { + r := db.SqlExec(sqlCreateGame, g.Id, g.Mode.NameStr, game_logic.StatusWaiting, g.RoundNum, generatorMapJson(g.Map), "[]") if row, err := r.RowsAffected(); err != nil || row != 1 { logrus.Warn("create game filed: ", err) return false @@ -92,46 +91,46 @@ func (p *Pg) DebugCreateGame(g *game.Game) (ok bool) { var sqlQueryGameList = "SELECT game_id FROM game WHERE mode=$1 AND (status=1 OR status=2)" -func (p *Pg) GetGameList(mode game.Mode) []game.Game { +func (p *Pg) GetGameList(mode _type.Mode) []game_logic.Game { r := db.SqlQuery(sqlQueryGameList, mode) - var list []game.Id + var list []game_logic.Id for { - var id game.Id + var id game_logic.Id r.Next() if err := r.Scan(&id); err != nil { break } list = append(list, id) } - ret := make([]game.Game, len(list)) + ret := make([]game_logic.Game, len(list)) for i, id := range list { ret[i] = *p.GetGameInfo(id) } return ret } -func (p *Pg) CancelGame(id game.Id) (ok bool) { +func (p *Pg) CancelGame(id game_logic.Id) (ok bool) { //TODO implement me panic("implement me") } -func (p *Pg) GetCurrentUserList(id game.Id) []game.User { +func (p *Pg) GetCurrentUserList(id game_logic.Id) []_type.User { //TODO implement me panic("implement me") } -func (p *Pg) GetInstructions(id game.Id, tempId uint16) []instruction.Instruction { +func (p *Pg) GetInstructions(id game_logic.Id, tempId uint16) map[uint16]_type.Instruction { //TODO implement me panic("implement me") } var sqlQueryGameInfo = "SELECT mode,status,round_num,create_time FROM game WHERE game_id=$1" -func (p *Pg) GetGameInfo(id game.Id) *game.Game { +func (p *Pg) GetGameInfo(id game_logic.Id) *game_logic.Game { r := db.SqlQuery(sqlQueryGameInfo, id) defer func() { _ = r.Close() }() - g := &game.Game{ + g := &game_logic.Game{ Id: id, } @@ -142,7 +141,7 @@ func (p *Pg) GetGameInfo(id game.Id) *game.Game { logrus.Warn("cannot get game info") return nil } - if mode, ok := game.ModeMap[modeStr]; !ok { + if mode, ok := _type.ModeMap[modeStr]; !ok { logrus.Warn("get unknown mode ", modeStr, " when get game info") } else { g.Mode = mode @@ -150,37 +149,37 @@ func (p *Pg) GetGameInfo(id game.Id) *game.Game { return g } -func (p *Pg) NewInstructionTemp(id game.Id, tempId uint16) (ok bool) { +func (p *Pg) NewInstructionTemp(id game_logic.Id, tempId uint16) (ok bool) { //TODO implement me panic("implement me") } -func (p *Pg) SetGameStatus(id game.Id, status game.Status) (ok bool) { +func (p *Pg) SetGameStatus(id game_logic.Id, status game_logic.Status) (ok bool) { //TODO implement me panic("implement me") } -func (p *Pg) SetGameMap(id game.Id, m *_map.Map) (ok bool) { +func (p *Pg) SetGameMap(id game_logic.Id, m *_map.Map) (ok bool) { //TODO implement me panic("implement me") } -func (p *Pg) SetUserStatus(id game.Id, user game.User) (ok bool) { +func (p *Pg) SetUserStatus(id game_logic.Id, user _type.User) (ok bool) { //TODO implement me panic("implement me") } -func (p *Pg) SetWinner(id game.Id, teamId uint8) (ok bool) { +func (p *Pg) SetWinner(id game_logic.Id, teamId uint8) (ok bool) { //TODO implement me panic("implement me") } -func (p *Pg) UpdateInstruction(id game.Id, user game.User, instruction instruction.Instruction) (ok bool) { +func (p *Pg) UpdateInstruction(id game_logic.Id, user _type.User, instruction _type.Instruction) (ok bool) { //TODO implement me panic("implement me") } -func (p *Pg) GetCurrentMap(id game.Id) *_map.Map { +func (p *Pg) GetCurrentMap(id game_logic.Id) *_map.Map { //TODO implement me panic("implement me") } diff --git a/packages/server/utils/pkg/data_source/temp.go b/packages/server/utils/pkg/data_source/temp.go new file mode 100644 index 0000000..4a51f34 --- /dev/null +++ b/packages/server/utils/pkg/data_source/temp.go @@ -0,0 +1,28 @@ +package data_source + +import ( + "server/game_logic" + "server/game_logic/game_def" + "server/game_logic/map" +) + +type TempDataSource interface { + CreateGame(mode _type.Mode) game_logic.Id + GetGameList(mode _type.Mode) []game_logic.Game // Returns `Game` structs with only basic info of not end game + CancelGame(id game_logic.Id) (ok bool) + + GetCurrentUserList(id game_logic.Id) []_type.User + GetInstructions(id game_logic.Id, tempId uint16) map[uint16]_type.Instruction + GetGameInfo(id game_logic.Id) *game_logic.Game // Returns a `Game` struct with only basic info + NewInstructionTemp(id game_logic.Id, tempId uint16) (ok bool) + SetGameStatus(id game_logic.Id, status game_logic.Status) (ok bool) + SetGameMap(id game_logic.Id, m *_map.Map) (ok bool) + + SetUserStatus(id game_logic.Id, user _type.User) (ok bool) + SetWinner(id game_logic.Id, teamId uint8) (ok bool) + UpdateInstruction(id game_logic.Id, user _type.User, instruction _type.Instruction) (ok bool) + GetCurrentMap(id game_logic.Id) *_map.Map + + // Functions only for debug + DebugCreateGame(game *game_logic.Game) (ok bool) +} diff --git a/packages/server/utils/pkg/datasource/temp.go b/packages/server/utils/pkg/datasource/temp.go deleted file mode 100644 index d980f0e..0000000 --- a/packages/server/utils/pkg/datasource/temp.go +++ /dev/null @@ -1,28 +0,0 @@ -package datasource - -import ( - "server/utils/pkg/game" - "server/utils/pkg/instruction" - "server/utils/pkg/map" -) - -type TempDataSource interface { - CreateGame(mode game.Mode) game.Id - GetGameList(mode game.Mode) []game.Game // Returns `Game` structs with only basic info of not end game - CancelGame(id game.Id) (ok bool) - - GetCurrentUserList(id game.Id) []game.User - GetInstructions(id game.Id, tempId uint16) []instruction.Instruction - GetGameInfo(id game.Id) *game.Game // Returns a `Game` struct with only basic info - NewInstructionTemp(id game.Id, tempId uint16) (ok bool) - SetGameStatus(id game.Id, status game.Status) (ok bool) - SetGameMap(id game.Id, m *_map.Map) (ok bool) - - SetUserStatus(id game.Id, user game.User) (ok bool) - SetWinner(id game.Id, teamId uint8) (ok bool) - UpdateInstruction(id game.Id, user game.User, instruction instruction.Instruction) (ok bool) - GetCurrentMap(id game.Id) *_map.Map - - // Functions only for debug - DebugCreateGame(game *game.Game) (ok bool) -} diff --git a/packages/server/utils/pkg/gametemppool/pool.go b/packages/server/utils/pkg/game_temp_pool/pool.go similarity index 59% rename from packages/server/utils/pkg/gametemppool/pool.go rename to packages/server/utils/pkg/game_temp_pool/pool.go index 5730f79..313e911 100644 --- a/packages/server/utils/pkg/gametemppool/pool.go +++ b/packages/server/utils/pkg/game_temp_pool/pool.go @@ -1,7 +1,7 @@ -package gametemppool +package game_temp_pool import ( - "server/utils/pkg/game" + "server/game_logic" "sync" ) @@ -9,22 +9,22 @@ import ( var pool = &sync.Map{} -func Create(id game.Id) { +func Create(id game_logic.Id) { if _, ok := pool.Load(id); !ok { pool.Store(id, &sync.Map{}) } } -func Delete(id game.Id) { +func Delete(id game_logic.Id) { pool.Delete(id) } -func Get(id game.Id, key string) (any, bool) { +func Get(id game_logic.Id, key string) (any, bool) { v, _ := pool.Load(id) return v.(*sync.Map).Load(key) } -func Put(id game.Id, key string, value any) { +func Put(id game_logic.Id, key string, value any) { v, _ := pool.Load(id) v.(*sync.Map).Store(key, value) }