# frozen_string_literal: true require 'json' # Converts the current world-state into something we can send to a client. class Serialiser def initialize(cid) @cid = cid @last_snapshot = '' end # NOTE: "full" is a hint that we're OK to send stuff we might otherwise omit. def snapshot(world, full: false) actors = Hash[world.actors.map { |a| [a.object_id, actor_json(a, full)] }] result = { actors: actors }.to_json return nil if @last_snapshot == result @last_snapshot = result end private # TODO: A better idea would be to only include "full" details if they change. def actor_json(actor, full) json = actor.as_json # This includes EVERYTHING, which we dont always send. user = json.delete('user') position = json.delete('position') result = { x: position[0], y: position[1] } result.merge!(json) if full # <-- This is what the comment above refers to. user == @cid ? result.merge(yours: true) : result end end