server

package
v0.0.0-...-2592523 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Shield Fuel Thresholds
	// These control when bots will activate shields based on available fuel
	FuelCritical = 400  // Emergency threshold - only shield for immediate threats
	FuelLow      = 600  // Low fuel - shield for close threats
	FuelModerate = 1400 // Moderate fuel - shield for medium-range threats
	FuelGood     = 2000 // Good fuel reserves - shield more liberally

	// Threat Assessment Constants
	ThreatLevelImmediate = 6 // Threat level that triggers immediate shielding
	ThreatLevelHigh      = 4 // High threat level
	ThreatLevelMedium    = 3 // Medium threat level

	// Distance Thresholds for Threat Detection
	TorpedoVeryClose = 2000.0 // Torpedoes within this range are always dangerous
	TorpedoClose     = 3000.0 // Range for torpedo threat assessment
	EnemyVeryClose   = 1800.0 // Enemies within this range are immediate threats
	EnemyClose       = 2500.0 // Range for enemy threat assessment
	PlasmaClose      = 2000.0 // Range for plasma threat assessment
	PlasmaFar        = 4000.0 // Extended range for plasma detection

	// Shield Decision Weights
	// These control how threat levels translate to shield decisions
	ImmediateThreatBonus = 6 // Additional threat level for immediate threats
	TorpedoThreatBonus   = 4 // Bonus threat level for threatening torpedoes
	CloseEnemyBonus      = 3 // Bonus for very close enemies
	PlasmaThreatBonus    = 5 // Bonus for plasma threats

	// Special Situation Thresholds
	ArmyCarryingRange  = 3500.0 // Shield range when carrying armies
	DefenseShieldRange = 3000.0 // Shield range during planet defense
	PhaserRangeFactor  = 0.8    // Shield when within 80% of enemy phaser range
)
View Source
const (
	// OrbitDistance is the distance required to orbit a planet
	OrbitDistance = 2000.0

	// Planet defense constants
	PlanetDefenseDetectRadius    = 15000.0 // Range for bot to detect threats to friendly planets
	PlanetDefenseInterceptBuffer = 3000.0  // Additional range beyond bomb range to intercept threats
	PlanetBombRange              = 2000.0  // Range at which enemies can bomb planets effectively
)

Bot AI constants

View Source
const (
	MsgTypeLogin      = "login"
	MsgTypeMove       = "move"
	MsgTypeFire       = "fire"
	MsgTypePhaser     = "phaser"
	MsgTypeShields    = "shields"
	MsgTypeOrbit      = "orbit"
	MsgTypeRepair     = "repair"
	MsgTypeLock       = "lock"
	MsgTypeBeam       = "beam"
	MsgTypeBomb       = "bomb"
	MsgTypeCloak      = "cloak"
	MsgTypeTractor    = "tractor"
	MsgTypePressor    = "pressor"
	MsgTypePlasma     = "plasma"
	MsgTypeDetonate   = "detonate"
	MsgTypeMessage    = "message"
	MsgTypeTeamMsg    = "teammsg"
	MsgTypePrivMsg    = "privmsg"
	MsgTypeQuit       = "quit"
	MsgTypeUpdate     = "update"
	MsgTypeError      = "error"
	MsgTypeTeamUpdate = "team_update"
)

Message types

Variables

View Source
var BotNames = []string{
	"HAL-9000", "R2-D2", "C-3PO", "Data", "Bishop", "T-800",
	"Johnny-5", "WALL-E", "EVE", "Optimus", "Bender", "K-2SO",
	"BB-8", "IG-88", "HK-47", "GLaDOS", "SHODAN", "Cortana",
	"Friday", "Jarvis", "Vision", "Ultron", "Skynet", "Agent-Smith",
}

BotNames for generating random bot names

Functions

func AngleDifference

func AngleDifference(a1, a2 float64) float64

AngleDifference calculates the smallest angle difference between two angles

func InterceptDirectionSimple

func InterceptDirectionSimple(shooterPos, targetPos Point2D, targetVel Vector2D, projSpeed float64) (float64, bool)

InterceptDirectionSimple is a simplified version that only returns direction and success This is the interface that the existing bot code will use

func NormalizeAngle

func NormalizeAngle(angle float64) float64

NormalizeAngle normalizes an angle to the range [-π, π]

Types

type BeamData

type BeamData struct {
	Up bool `json:"up"` // true = beam up, false = beam down
}

BeamData represents army beam request

type Client

type Client struct {
	ID       int
	PlayerID int
	// contains filtered or unexported fields
}

Client represents a connected player

type ClientMessage

type ClientMessage struct {
	Type string          `json:"type"`
	Data json.RawMessage `json:"data"`
}

ClientMessage represents a message from client to server

type CombatManeuver

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

CombatManeuver represents a tactical movement decision

type CombatThreat

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

CombatThreat tracks various combat threats

type FireData

type FireData struct {
	Dir float64 `json:"dir"` // Direction to fire
}

FireData represents torpedo fire command

type InterceptSolution

type InterceptSolution struct {
	Direction       float64 // Direction to fire in radians
	TimeToIntercept float64 // Time until projectile reaches target
	InterceptPoint  Point2D // Where the intercept will occur
}

InterceptSolution contains the result of an intercept calculation

func InterceptDirection

func InterceptDirection(shooterPos, targetPos Point2D, targetVel Vector2D, projSpeed float64) (*InterceptSolution, bool)

InterceptDirection calculates the direction to fire a projectile to intercept a moving target. This is a pure mathematical function using the standard 2D intercept formula.

Parameters:

shooterPos: Position of the shooter (world units)
targetPos: Position of the target (world units)
targetVel: Velocity of target (world units per tick)
projSpeed: Speed of projectile (world units per tick)

Returns:

solution: The intercept solution, or nil if no solution exists
ok: true if a valid intercept solution was found

type LoginData

type LoginData struct {
	Name string        `json:"name"`
	Team int           `json:"team"`
	Ship game.ShipType `json:"ship"`
}

LoginData represents login request data

type MessageData

type MessageData struct {
	Text   string `json:"text"`
	Target int    `json:"target,omitempty"` // For private messages
}

MessageData represents a chat message

type MoveData

type MoveData struct {
	Dir   float64 `json:"dir"`   // Direction in radians
	Speed float64 `json:"speed"` // Desired speed
}

MoveData represents movement commands

type PhaserData

type PhaserData struct {
	Target int     `json:"target"` // Target player ID (-1 for direction)
	Dir    float64 `json:"dir"`    // Direction if no target
}

PhaserData represents phaser fire command

type PlanetDefenderInfo

type PlanetDefenderInfo struct {
	Defenders         []*game.Player // All enemy players within detection radius
	DefenderCount     int            // Count of enemy ships
	ClosestDefender   *game.Player   // The closest enemy ship
	MinDefenderDist   float64        // Distance to the closest defender
	HasCarrierDefense bool           // Whether any defender is carrying armies
	DefenseScore      float64        // Calculated threat score (higher = more dangerous)
}

PlanetDefenderInfo contains information about defenders around a planet

type PlasmaData

type PlasmaData struct {
	Dir float64 `json:"dir"` // Direction to fire
}

PlasmaData represents plasma fire command

type Point2D

type Point2D struct {
	X, Y float64
}

Point2D represents a 2D position

type SeparationVector

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

SeparationVector represents the direction and magnitude to separate from allies

type Server

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

Server manages the game and client connections

func NewServer

func NewServer() *Server

NewServer creates a new game server

func (*Server) AddBot

func (s *Server) AddBot(team, ship int)

AddBot adds a new bot player to the game

func (*Server) AutoBalanceBots

func (s *Server) AutoBalanceBots()

AutoBalanceBots adds or removes bots to balance teams Players and bots count equally as team members for balancing

func (*Server) CalculateEnhancedInterceptCourse

func (s *Server) CalculateEnhancedInterceptCourse(shooter, target *game.Player) float64

CalculateEnhancedInterceptCourse exposes the private calculateEnhancedInterceptCourse method for testing

func (*Server) CalculateInterceptCourse

func (s *Server) CalculateInterceptCourse(shooter, target *game.Player) float64

CalculateInterceptCourse exposes the private calculateInterceptCourse method for testing

func (*Server) FireBotTorpedo

func (s *Server) FireBotTorpedo(shooter, target *game.Player)

FireBotTorpedo exposes the private fireBotTorpedo method for testing

func (*Server) FireBotTorpedoWithLead

func (s *Server) FireBotTorpedoWithLead(shooter, target *game.Player)

FireBotTorpedoWithLead exposes the private fireBotTorpedoWithLead method for testing

func (*Server) FireEnhancedTorpedo

func (s *Server) FireEnhancedTorpedo(shooter, target *game.Player)

FireEnhancedTorpedo exposes the private fireEnhancedTorpedo method for testing

func (*Server) GetGameState

func (s *Server) GetGameState() *game.GameState

GetGameState allows tests to get the current game state

func (*Server) HandleTeamStats

func (s *Server) HandleTeamStats(w http.ResponseWriter, r *http.Request)

HandleTeamStats returns current team populations

func (*Server) HandleWebSocket

func (s *Server) HandleWebSocket(w http.ResponseWriter, r *http.Request)

HandleWebSocket handles WebSocket connections

func (*Server) OrbitalVelocity

func (s *Server) OrbitalVelocity(p *game.Player) (vx, vy float64, ok bool)

OrbitalVelocity returns the instantaneous tangential velocity of a ship that is currently orbiting a planet. If the ship is not orbiting, ok will be false.

The velocity is returned in world units per tick, which is the same unit that InterceptDirectionSimple expects for target velocity calculations.

func (*Server) RemoveBot

func (s *Server) RemoveBot(botID int)

RemoveBot removes a bot player from the game

func (*Server) Run

func (s *Server) Run()

Run starts the server main loop

func (*Server) SetGameState

func (s *Server) SetGameState(gs *game.GameState)

SetGameState allows tests to set the game state directly

func (*Server) UpdateBots

func (s *Server) UpdateBots()

UpdateBots updates all bot players' AI

type ServerMessage

type ServerMessage struct {
	Type string      `json:"type"`
	Data interface{} `json:"data"`
}

ServerMessage represents a message from server to client

type Vector2D

type Vector2D struct {
	X, Y float64
}

Vector2D represents a 2D velocity vector

Jump to

Keyboard shortcuts

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