From 3ce49872ff66a660fd534a0d13cbc8e9456c2298 Mon Sep 17 00:00:00 2001 From: Major- Date: Sun, 29 Jun 2014 03:05:04 +0100 Subject: [PATCH] Add attributes system. --- data/plugins/entity/attributes/attributes.rb | 67 ++++++++++++++++++++ data/plugins/entity/attributes/plugin.xml | 14 ++++ 2 files changed, 81 insertions(+) create mode 100644 data/plugins/entity/attributes/attributes.rb create mode 100644 data/plugins/entity/attributes/plugin.xml diff --git a/data/plugins/entity/attributes/attributes.rb b/data/plugins/entity/attributes/attributes.rb new file mode 100644 index 00000000..662ac2b2 --- /dev/null +++ b/data/plugins/entity/attributes/attributes.rb @@ -0,0 +1,67 @@ +require 'java' + +java_import 'org.apollo.game.model.Entity' + +# Maps attribute names (i.e. symbols) to attribute definitions. +ATTRIBUTE_DEFINITIONS = {} + +class Entity + + # The map of strings to attributes. + def attributes + @attributes ||= {} + end + + # Overridies method_missing + def method_missing(symbol, *args) + name = symbol.to_s.strip + + if name[-1] == "=" + raise "Error - expected argument count of 1, received #{args.length}" unless args.length == 1 + + name = name[0...-1].strip # Drop the equals and preceeding whitespace + attributes[name] = args[0] + elsif ATTRIBUTE_DEFINITIONS[name] == nil + super(symbol, *args) + else + return attributes[name] || ATTRIBUTE_DEFINITIONS[name].default + end + end + + def to_s + return value.to_s + end + +end + +# An attribute belonging to an entity. +class AttributeDefinition + attr_reader :default, :persistence + + def initialize(default, persistence=:transient) + @default = default + @type = get_type + @persistence = persistence + end + + def to_s + return "[AttributeDefinition - default=#{default}, type=#{type}, persistence=#{persistence}]." + end + + private # Gets the type of an attribute from its default value. + def get_type + case @default + when Fixnum, Integer then type = :number + when String then type = :string + when Symbol then type = :symbol + when TrueClass, FalseClass then type = :boolean + else raise "Error - #{value} has an unrecognised attribute type of #{value.class}." + end + end + +end + +# Declares an attribute which can then be assigned. +def declare_attribute(name, default, persistence=:transient) + ATTRIBUTE_DEFINITIONS[name.to_s] = AttributeDefinition.new(default, persistence) +end \ No newline at end of file diff --git a/data/plugins/entity/attributes/plugin.xml b/data/plugins/entity/attributes/plugin.xml new file mode 100644 index 00000000..ea11bba4 --- /dev/null +++ b/data/plugins/entity/attributes/plugin.xml @@ -0,0 +1,14 @@ + + + attributes + 0.9 + Attributes + Adds an attribute system for entites. + + Major + + + + + + \ No newline at end of file