# Nathan Hinton 19 Dec 2025 # Runs the server for the game require 'sinatra' require 'sinatra/cross_origin' require 'json' require './game' require './player' 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 test = Game.new(width: 10, height: 10, planets: 20, name: 'TEST') test.add_player(Player.new(name: 'hi')) games = {'TEST' => test} # Get the server status # # @return [String] UP 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 # # @param None # @return [Array] list of game names get '/list_games' do return games.keys.to_json end # old: # Returns true if the given player is part of the game # old: # # old: # @params game [String] Goes in the splat # old: # @params player_name [String] The name of the player to validate # old: # @return [Boolean] # old: get '/game/*/players' do # old: game = validate_game(params['splat'][0]) # old: if game # old: {"status" => game.find_player(params['player_name'])}.to_json # old: end # old: return {"status" => false}.to_json # old: end # Returns a player id for a given game # # @params game [String] Goes in the splat # @params player_name [String] The name of the player to add # @return [String] The ID for that player get '/game/*/player_id' do game = validate_game(params['splat'][0]) if game player = game.find_player(params['player_name']) if player return {"status" => player.get_id}.to_json end end return {"status" => false}.to_json end # Returns data about how the game is set up # Returns the planets owned by a player # # @params game [String] Goes in the splat # @params id [String] URL argument for player id. get '/game/*/get_captured_planets' do game = validate_game(params['splat'][0]) if game begin return {'planets' => game.get_captured_planets(params['id'])}.to_json end end return {"status" => false}.to_json end # Validates that a game exists: # # @param key [String] The name of the game to check for # @return [Game] The game the key belongs to. (Or nil if not found) def validate_game(name) return games[name] end