pushing befor major changes

This commit is contained in:
2025-12-20 15:07:58 -07:00
parent 057164122a
commit f4c5ba1f14
31 changed files with 438 additions and 1502 deletions
+169 -49
View File
@@ -1,55 +1,175 @@
# Nathan Hinton 19 Dec 2025
# Runs the server for the game
# Nathan Hinton 20 Dec 2025
# The main game server. This will handle the clients and the game in one go
require 'sinatra'
require 'sinatra/cross_origin'
require 'async'
require 'async/websocket'
require 'json'
require 'yaml'
require './game'
configure do
enable :cross_origin
end
# CORS headers for all routes
before do
headers 'Access-Control-Allow-Origin' => '*', # Allow all domains (you can change '*' to a specific domain for security)
'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS', # Allow only specific methods
'Access-Control-Allow-Headers' => 'Content-Type, Authorization'
end
games = {}
# Get the server status
get '/status' do
return 'UP'
end
# Creates a new game
#
# @param name [String] Required. The name of the game
# @param width [Integer] The width of the game space
# @param height [Integer] The height of the game space
# @param planets [Integer] The number of planets to have in the game
get '/create_game' do
puts "Creating game named #{params['name']}"
name = params['name']
width = params['width'] || 10
width = width.to_i
height = params['height'] || 10
height = height.to_i
planets = params['planets'] || 20
planets = planets.to_i
games.update({name => Game.new(width: width, height: height, planets: planets, name: name)})
return 'OK'
end
# Gets games available
#
# @return [Array] list of game names
get '/list_games' do
return games.keys.to_json
class GameServer
def initialize(conf_path)
@clients = {}
File.open(conf_path, 'r') do |fi|
world_config = YAML.safe_load(fi.read)
end
puts world_config
@world = World.new(
width: world_config['width'],
height: world_config['height'],
planets: world_config['planets'],
game_id: world_config['game_id'],
name: world_config['name']
)
end
def start(endpoint)
Async do |task|
Async::WebSocket::Server.open(endpoint) do |connection|
task.async do
handle_connection(connection)
end
end
task.async {simulation_loop}
end
end
def handle_connection(ws)
player = nil
while message == ws.read
data = JSON.parse(message)
response = nil
case data['type']
when 'hello'
player = handle_hello(ws, data)
when 'querey'
response = handle_query(ws, data)
when 'command'
response = handle_command(ws, data)
else
response = send_error('UNKNOWN_TYPE', 'Unknown message type')
end
ws.write(JSON.dump(response)) if response
end
rescue => e
puts "Connection error: #{e.message}"
ensure
disconnect(player)
end
def handle_hello(ws, data)
token = data.dig("payload", "auth_token")
player = authenticate(token)
@clients[player.id] = ws
ws.write(
JSON.dump(
{
type: "update",
domain: "all",
payload: {
player_id: player_id,
server_time: @world.time,
game_speed: @world.game_speed
player: player.snapshot
}
}
)
)
return player
end
def handle_query(player, data)
domain = data["domain"]
payload =
case domain
when "player"
player.snapshot
when "ship"
ship_id = data.dig("payload", "ship_id")
@world.ship(ship_id)&.snapshot
else
return error("UNKNOWN_DOMAIN", "Unknown query domain")
end
{
type: "update",
domain: domain,
payload: payload
}
end
def handle_command(player, data)
domain = data["domain"]
payload = data["payload"]
case domain
when "ship"
validate_and_queue_ship_command(player, payload)
else
return error("UNKNOWN_DOMAIN", "Unknown command domain")
end
{
type: "update",
domain: "command",
payload: { status: "accepted" }
}
rescue ValidationError => e
error("INVALID_COMMAND", e.message)
end
def validate_and_queue_ship_command(player, payload)
ship = @world.ship(payload["ship_id"])
raise ValidationError, "Ship not found" unless ship
raise ValidationError, "Not your ship" unless ship.owner == player
ship.set_target(payload["target"])
end
def broadcast_event(type, domain, payload)
message = JSON.dump({
type: type,
domain: domain,
payload: payload
})
@clients.values.each do |ws|
ws.write(message)
end
end
def simulation_loop
last = Time.now
loop do
now = Time.now
delta_real = now - last
delta_sim = delta_real * @world.game_speed
@world.advance(delta_sim)
last = now
sleep 0.05 # 20 tps
end
end
def error(code, message)
{
type: "error",
domain: "system",
payload: {
code: code,
message: message
}
}
end
end