Files
space_game_server/lib/game/planet.rb
T

75 lines
1.6 KiB
Ruby

# Nathan Hinton 22 Dec 2025
# Planet file
require 'securerandom'
# A planet object for the Game module
class Planet
attr_reader :owner, :planet_id
# Creates a new planet.
#
# @param width [Integer] The width of the game
# @param height [Integer] The height of the game
# @param depth [Integer] The depth of the game
def initialize(width, height, depth)
@owner = nil
@buildings = []
@position = [rand(width), rand(height), rand(depth)]
@planet_id = SecureRandom.hex
end
# Returns if the planet can be claimed. Currently requires that there be no
# buildings on the planet.
def claimable?
if @owner.nil?
return true
elsif @buildings == []
return true
end
return false
end
# Function that allows a player to claim the planet and to become the owner.
def claim(player)
@owner = player
end
# Function called to update the planet.
def update(delta_time)
end
# Function to return info to the client about a planet
def info_update
return {
'id' => @planet_id,
'position' => @position
}
end
##########################
##### UTIL FUNCTIONS #####
##########################
# Save a player to a file
def save_to_file
File.open("game_data/#{self.planet_id}_planet_.save", 'wb') do |fi|
# Load resources for the player:
fi.write(Marshal.dump(self))
end
return self.planet_id
end
# Load a player from a file
def self.load_from_save(fname)
File.open("game_data/#{fname}_planet_.save", 'rb') do |fi|
# Load resources for the player:
Marshal.load(fi.read)
end
end
end