player

package
v0.0.0-...-80cf271 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 18, 2025 License: AGPL-3.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ResourceIronOre = 1
	ResourceGoldOre = 2
	ResourceWood    = 3
	ResourceStone   = 4
)

Resource type constants

View Source
const (
	QualityPoor   = 0
	QualityNormal = 1
	QualityRich   = 2
)

Resource subtype constants

View Source
const MaxSessionsPerPlayer = 5

MaxSessionsPerPlayer defines the maximum number of active sessions per player

View Source
const SessionTimeout = 24

SessionTimeout defines how long a session remains valid (in hours)

Variables

This section is empty.

Functions

func AuthMiddleware

func AuthMiddleware(playerManager *Manager) func(http.Handler) http.Handler

AuthMiddleware creates a middleware that requires authentication

func CORSMiddleware

func CORSMiddleware() func(http.Handler) http.Handler

CORS middleware to handle cross-origin requests

func CreateSessionExpiry

func CreateSessionExpiry() time.Time

CreateSessionExpiry creates an expiry time for a session

func GetQualityName

func GetQualityName(quality int64) string

GetQualityName returns the human-readable name for a quality level

func GetResourceName

func GetResourceName(resourceType int64) string

GetResourceName returns the human-readable name for a resource type

func IsSessionExpired

func IsSessionExpired(expiresAt time.Time) bool

IsSessionExpired checks if a session has expired

func LoggingMiddleware

func LoggingMiddleware() func(http.Handler) http.Handler

LoggingMiddleware logs HTTP requests

func OptionalAuthMiddleware

func OptionalAuthMiddleware(playerManager *Manager) func(http.Handler) http.Handler

OptionalAuthMiddleware creates a middleware that optionally authenticates If authentication is provided and valid, the player is added to context If no authentication is provided, the request continues without player context

func ValidateEmail

func ValidateEmail(email string) error

ValidateEmail performs basic email validation

func ValidatePassword

func ValidatePassword(password string) error

ValidatePassword checks if a password meets requirements

func ValidateUsername

func ValidateUsername(username string) error

ValidateUsername checks if a username meets requirements

Types

type AuthError

type AuthError struct {
	Message string `json:"message"`
}

AuthError represents an authentication error

func (*AuthError) Error

func (e *AuthError) Error() string

type ContextKey

type ContextKey string

ContextKey represents the type used for context keys

const (
	PlayerContextKey ContextKey = "player"
)

Context keys for player data

type CreatePlayerRequest

type CreatePlayerRequest struct {
	Username string  `json:"username" validate:"required,min=3,max=32"`
	Password string  `json:"password" validate:"required,min=8"`
	Email    *string `json:"email,omitempty" validate:"omitempty,email"`
}

CreatePlayerRequest represents the request to create a new player

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Code    int    `json:"code,omitempty"`
	Message string `json:"message,omitempty"`
}

ErrorResponse represents an error response

type HarvestStatsUpdate

type HarvestStatsUpdate struct {
	ResourceType    int64
	AmountHarvested int64
	NodeID          int64
	IsNewNode       bool
}

HarvestStatsUpdate represents the data needed to update player stats after a harvest

type LoginRequest

type LoginRequest struct {
	Username string `json:"username" validate:"required"`
	Password string `json:"password" validate:"required"`
}

LoginRequest represents the request to log in

type LoginResponse

type LoginResponse struct {
	Success      bool      `json:"success"`
	SessionToken string    `json:"session_token"`
	Player       Player    `json:"player"`
	ExpiresAt    time.Time `json:"expires_at"`
}

LoginResponse represents the response after successful login

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager handles all player-related operations

func NewManager

func NewManager(database *sql.DB) *Manager

NewManager creates a new player manager

func (*Manager) AddEnergyCost

func (m *Manager) AddEnergyCost(ctx context.Context, playerID int64, energyCost int64) error

AddEnergyCost deducts energy from a player for an action

func (*Manager) AddItem

func (m *Manager) AddItem(ctx context.Context, playerID int64, itemID int64) error

AddItem adds an item to the player's inventory (alias for AddToInventory)

func (*Manager) AddToInventory

func (m *Manager) AddToInventory(ctx context.Context, playerID int64, resourceType, resourceSubtype, quantity int64) error

AddToInventory adds resources to a player's inventory

func (*Manager) AddXp

func (m *Manager) AddXp(ctx context.Context, playerID int64, xpAmount int64) error

AddXp adds experience points to a player

func (*Manager) AuthenticateSession

func (m *Manager) AuthenticateSession(ctx context.Context, sessionToken string) (*Player, error)

AuthenticateSession validates a session token and returns the player

func (*Manager) CleanupExpiredSessions

func (m *Manager) CleanupExpiredSessions(ctx context.Context) error

CleanupExpiredSessions removes expired sessions from the database

func (*Manager) CreatePlayer

func (m *Manager) CreatePlayer(ctx context.Context, req CreatePlayerRequest) (*Player, error)

CreatePlayer creates a new player account

func (*Manager) GetOnlinePlayers

func (m *Manager) GetOnlinePlayers(ctx context.Context) ([]Player, error)

GetOnlinePlayers returns all currently online players

func (*Manager) GetPlayerInventory

func (m *Manager) GetPlayerInventory(ctx context.Context, playerID int64) ([]PlayerInventory, error)

GetPlayerInventory returns a player's inventory

func (*Manager) GetPlayerStats

func (m *Manager) GetPlayerStats(ctx context.Context, playerID int64) (*PlayerStats, error)

GetPlayerStats returns a player's statistics

func (*Manager) Login

func (m *Manager) Login(ctx context.Context, req LoginRequest, ipAddress, userAgent string) (*LoginResponse, error)

Login authenticates a player and creates a session

func (*Manager) Logout

func (m *Manager) Logout(ctx context.Context, sessionToken string) error

Logout logs out a player and invalidates their session

func (*Manager) Save

func (m *Manager) Save(ctx context.Context) error

Save persists any pending player manager state to the database This method ensures all player-related data is properly persisted

func (*Manager) UpdateHarvestStats

func (m *Manager) UpdateHarvestStats(ctx context.Context, playerID int64, update chunk.HarvestStatsUpdate) error

UpdateHarvestStats updates a player's statistics after a harvest

func (*Manager) UpdatePlayerPosition

func (m *Manager) UpdatePlayerPosition(ctx context.Context, playerID int64, req UpdatePositionRequest) error

UpdatePlayerPosition updates a player's position in the world

type PasswordManager

type PasswordManager struct {
	// contains filtered or unexported fields
}

PasswordManager handles password hashing and verification

func NewPasswordManager

func NewPasswordManager() *PasswordManager

NewPasswordManager creates a new password manager with default settings

func (*PasswordManager) GenerateSalt

func (pm *PasswordManager) GenerateSalt() (string, error)

GenerateSalt creates a random salt

func (*PasswordManager) HashPassword

func (pm *PasswordManager) HashPassword(password, salt string) (string, error)

HashPassword creates a password hash with the given salt

func (*PasswordManager) VerifyPassword

func (pm *PasswordManager) VerifyPassword(password, storedHash, salt string) bool

VerifyPassword verifies if a password matches the stored hash

type Player

type Player struct {
	PlayerID      int64      `json:"player_id"`
	Username      string     `json:"username"`
	Email         *string    `json:"email,omitempty"`
	WorldX        float64    `json:"world_x"`
	WorldY        float64    `json:"world_y"`
	WorldZ        float64    `json:"world_z"`
	CurrentChunkX int64      `json:"current_chunk_x"`
	CurrentChunkZ int64      `json:"current_chunk_z"`
	IsOnline      bool       `json:"is_online"`
	LastLogin     *time.Time `json:"last_login,omitempty"`
	LastLogout    *time.Time `json:"last_logout,omitempty"`
	CreatedAt     time.Time  `json:"created_at"`
	UpdatedAt     time.Time  `json:"updated_at"`
}

Player represents a player in the game

func GetPlayerFromContext

func GetPlayerFromContext(ctx context.Context) (*Player, bool)

GetPlayerFromContext retrieves the authenticated player from the request context

func RequirePlayer

func RequirePlayer(ctx context.Context) (*Player, error)

RequirePlayer is a helper function to get the player from context or return an error

type PlayerHandlers

type PlayerHandlers struct {
	// contains filtered or unexported fields
}

PlayerHandlers contains all HTTP handlers for player operations

func NewPlayerHandlers

func NewPlayerHandlers(playerManager *Manager) *PlayerHandlers

NewPlayerHandlers creates a new player handlers instance

func (*PlayerHandlers) GetInventory

func (h *PlayerHandlers) GetInventory(w http.ResponseWriter, r *http.Request)

GetInventory returns the player's inventory

func (*PlayerHandlers) GetOnlinePlayers

func (h *PlayerHandlers) GetOnlinePlayers(w http.ResponseWriter, r *http.Request)

GetOnlinePlayers returns all currently online players

func (*PlayerHandlers) GetPlayerProfile

func (h *PlayerHandlers) GetPlayerProfile(w http.ResponseWriter, r *http.Request)

GetPlayerProfile returns a specific player's public profile

func (*PlayerHandlers) GetProfile

func (h *PlayerHandlers) GetProfile(w http.ResponseWriter, r *http.Request)

GetProfile returns the current player's profile

func (*PlayerHandlers) GetStats

func (h *PlayerHandlers) GetStats(w http.ResponseWriter, r *http.Request)

GetStats returns the player's statistics

func (*PlayerHandlers) Login

func (h *PlayerHandlers) Login(w http.ResponseWriter, r *http.Request)

Login handles player authentication

func (*PlayerHandlers) Logout

func (h *PlayerHandlers) Logout(w http.ResponseWriter, r *http.Request)

Logout handles player logout

func (*PlayerHandlers) Register

func (h *PlayerHandlers) Register(w http.ResponseWriter, r *http.Request)

Register handles player registration

func (*PlayerHandlers) RegisterRoutes

func (h *PlayerHandlers) RegisterRoutes(r chi.Router)

RegisterRoutes registers all player-related routes

func (*PlayerHandlers) UpdatePosition

func (h *PlayerHandlers) UpdatePosition(w http.ResponseWriter, r *http.Request)

UpdatePosition updates the player's position

type PlayerInventory

type PlayerInventory struct {
	InventoryID     int64     `json:"inventory_id"`
	PlayerID        int64     `json:"player_id"`
	ResourceType    int64     `json:"resource_type"`
	ResourceSubtype int64     `json:"resource_subtype"`
	Quantity        int64     `json:"quantity"`
	FirstObtained   time.Time `json:"first_obtained"`
	LastUpdated     time.Time `json:"last_updated"`
}

PlayerInventory represents a single inventory item

type PlayerProfile

type PlayerProfile struct {
	Username                string     `json:"username"`
	IsOnline                bool       `json:"is_online"`
	TotalResourcesHarvested int64      `json:"total_resources_harvested"`
	TotalHarvestSessions    int64      `json:"total_harvest_sessions"`
	SessionsCount           int64      `json:"sessions_count"`
	TotalPlaytimeMinutes    int64      `json:"total_playtime_minutes"`
	FirstHarvest            *time.Time `json:"first_harvest,omitempty"`
	LastHarvest             *time.Time `json:"last_harvest,omitempty"`
	CreatedAt               time.Time  `json:"created_at"`
}

PlayerProfile represents a player's public profile

type PlayerSession

type PlayerSession struct {
	SessionID    int64     `json:"session_id"`
	PlayerID     int64     `json:"player_id"`
	SessionToken string    `json:"session_token"`
	IPAddress    *string   `json:"ip_address,omitempty"`
	UserAgent    *string   `json:"user_agent,omitempty"`
	CreatedAt    time.Time `json:"created_at"`
	ExpiresAt    time.Time `json:"expires_at"`
	LastActivity time.Time `json:"last_activity"`
}

PlayerSession represents an active player session

type PlayerStats

type PlayerStats struct {
	StatID                  int64      `json:"stat_id"`
	PlayerID                int64      `json:"player_id"`
	TotalResourcesHarvested int64      `json:"total_resources_harvested"`
	TotalHarvestSessions    int64      `json:"total_harvest_sessions"`
	IronOreHarvested        int64      `json:"iron_ore_harvested"`
	GoldOreHarvested        int64      `json:"gold_ore_harvested"`
	WoodHarvested           int64      `json:"wood_harvested"`
	StoneHarvested          int64      `json:"stone_harvested"`
	UniqueNodesDiscovered   int64      `json:"unique_nodes_discovered"`
	TotalNodesHarvested     int64      `json:"total_nodes_harvested"`
	TotalPlaytimeMinutes    int64      `json:"total_playtime_minutes"`
	SessionsCount           int64      `json:"sessions_count"`
	FirstHarvest            *time.Time `json:"first_harvest,omitempty"`
	LastHarvest             *time.Time `json:"last_harvest,omitempty"`
	StatsUpdated            time.Time  `json:"stats_updated"`
}

PlayerStats represents player statistics

type TokenManager

type TokenManager struct {
	// contains filtered or unexported fields
}

TokenManager handles session token generation and validation

func NewTokenManager

func NewTokenManager() *TokenManager

NewTokenManager creates a new token manager

func (*TokenManager) GenerateToken

func (tm *TokenManager) GenerateToken() (string, error)

GenerateToken creates a random session token

func (*TokenManager) ValidateToken

func (tm *TokenManager) ValidateToken(token string) error

ValidateToken performs basic token validation

type UpdatePositionRequest

type UpdatePositionRequest struct {
	WorldX float64 `json:"world_x"`
	WorldY float64 `json:"world_y"`
	WorldZ float64 `json:"world_z"`
}

UpdatePositionRequest represents the request to update player position

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL