teeworlds_network/lib/snap_items/game_data.rb

84 lines
1.8 KiB
Ruby
Raw Normal View History

2022-11-18 08:25:08 +00:00
# frozen_string_literal: true
require_relative '../packer'
class NetObj
class GameData
attr_accessor :game_start_tick, :game_state_flags, :game_state_end_tick
def initialize(hash_or_raw)
@field_names = %i[
game_start_tick
game_state_flags
game_state_end_tick
]
@fields = @field_names.map do |_|
0
end
@size = @fields.count
@name = self.class.name
2022-11-18 08:25:08 +00:00
if hash_or_raw.instance_of?(Hash)
init_hash(hash_or_raw)
elsif hash_or_raw.instance_of?(Unpacker)
init_unpacker(hash_or_raw)
2022-11-18 08:25:08 +00:00
else
init_raw(hash_or_raw)
end
end
def self.match_type?(type)
2022-11-18 08:25:08 +00:00
type == NETOBJTYPE_GAMEDATA
end
def validate
@fields.select(&:nil?).empty?
end
def init_unpacker(u)
@fields.map! do |_|
# TODO: as of right now it can get nil values here
# the fix would be "u.get_int || 0"
# but fixing it would probably make it harder
# to debug invalid data
#
# but do rethink this in a later point please :)
# for now call .validate() everywhere
u.get_int
end
2022-11-18 08:25:08 +00:00
end
def init_raw(data)
u = Unpacker.new(data)
init_unpacker(u)
end
2022-11-18 08:25:08 +00:00
def init_hash(attr)
@fields_names.each do |name|
instance_variable_set("@#{name}", attr[name] || 0)
end
2022-11-18 08:25:08 +00:00
end
def to_h
hash = {}
@field_names.each_with_index do |name, index|
hash[name] = @fields[index]
end
hash
2022-11-18 08:25:08 +00:00
end
# basically to_network
# int array the server sends to the client
def to_a
arr = []
@fields.each do |value|
arr += Packer.pack_int(value)
end
arr
2022-11-18 08:25:08 +00:00
end
def to_s
to_h
end
end
end