refactor: extract shared player.ID type and GenerateID to player package

Both game and snake packages had identical PlayerID types and the snake
package imported game.GenerateID. Now both use player.ID and
player.GenerateID from the shared player package.
This commit is contained in:
Ryan Hamamura
2026-03-02 19:09:01 -10:00
parent f47eb4cdf3
commit 063b03ce25
9 changed files with 61 additions and 45 deletions

View File

@@ -4,6 +4,7 @@ import (
"context"
"github.com/ryanhamamura/c4/db/repository"
"github.com/ryanhamamura/c4/player"
"github.com/rs/zerolog/log"
)
@@ -122,19 +123,19 @@ func snakeGameFromRow(row *repository.Game) (*SnakeGame, error) {
func snakePlayersFromRows(rows []*repository.GamePlayer) []*Player {
players := make([]*Player, 0, len(rows))
for _, row := range rows {
player := &Player{
p := &Player{
Nickname: row.Nickname,
Slot: int(row.Slot),
}
if row.UserID != nil {
player.UserID = row.UserID
player.ID = PlayerID(*row.UserID)
p.UserID = row.UserID
p.ID = player.ID(*row.UserID)
} else if row.GuestPlayerID != nil {
player.ID = PlayerID(*row.GuestPlayerID)
p.ID = player.ID(*row.GuestPlayerID)
}
players = append(players, player)
players = append(players, p)
}
return players
}

View File

@@ -5,7 +5,7 @@ import (
"sync"
"github.com/ryanhamamura/c4/db/repository"
"github.com/ryanhamamura/c4/game"
"github.com/ryanhamamura/c4/player"
)
type SnakeStore struct {
@@ -38,7 +38,7 @@ func (ss *SnakeStore) Create(width, height int, mode GameMode, speed int) *Snake
if speed <= 0 {
speed = DefaultSpeed
}
id := game.GenerateID(4)
id := player.GenerateID(4)
sg := &SnakeGame{
ID: id,
State: &GameState{
@@ -172,7 +172,7 @@ func (si *SnakeGameInstance) GetGame() *SnakeGame {
return si.game.snapshot()
}
func (si *SnakeGameInstance) GetPlayerSlot(pid PlayerID) int {
func (si *SnakeGameInstance) GetPlayerSlot(pid player.ID) int {
si.gameMu.RLock()
defer si.gameMu.RUnlock()
for i, p := range si.game.Players {

View File

@@ -3,6 +3,8 @@ package snake
import (
"encoding/json"
"time"
"github.com/ryanhamamura/c4/player"
)
type Direction int
@@ -78,10 +80,8 @@ const (
StatusFinished
)
type PlayerID string
type Player struct {
ID PlayerID
ID player.ID
UserID *string
Nickname string
Slot int // 0-7