Basic resource handling

master
Sven Slootweg 12 years ago
parent c9d9d410b0
commit f2b3efb87f

@ -29,6 +29,11 @@ Function.prototype.inheritsFrom = function(parentObject)
this.message = message;
}
var /*Exception*/ Warning = this.Warning = function(message)
{
this.message = message;
}
var /*Exception*/ ResourceException = this.ResourceException = function(message, resource, action)
{
this.resource = resource;
@ -37,23 +42,104 @@ Function.prototype.inheritsFrom = function(parentObject)
}
ResourceException.inheritsFrom(Exception);
var /*Exception*/ ResourceWarning = this.ResourceWarning = function(message, resource, action)
{
this.resource = resource;
this.message = message;
this.action = action;
}
ResourceWarning.inheritsFrom(Warning);
var /*Class*/ Player = this.Player = function()
{
this.credits = 0; /* Integer */
this.health = 1; /* Fraction */
this.resources = {}; /* Associative array -> Integer */
this.resources = {}; /* Associative array -> Resource */
this.InitializeResource = function(resource, negative_allowed, min, max)
{
var resource_object = new Resource();
resource_object.name = resource;
if(negative_allowed !== undefined)
{
resource_object.negative_allowed = negative_allowed;
}
if(min !== undefined)
{
resource_object.minimum = min;
}
if(min !== undefined)
{
resource_object.maximum = max;
}
if(min != null && min > 0)
{
/* Set current amount of units to minimum boundary. */
resource_object.value = min;
}
this.resources[resource] = resource_object;
}
this.TakeResource = function(resource, amount)
{
if(this.resources[resource])
{
this.resources[resource] -= amount;
resource_object = this.resources[resource];
if(resource_object.value - amount < 0 && resource_object.negative_allowed == false)
{
throw new ResourceException("There are not enough units of this resource available.", resource, "take");
}
else if(resource_object.minimum != null && resource_object.value - amount < resource_object.minimum)
{
throw new ResourceException("Taking away this many units will violate the lower resource boundary.", resource, "take");
}
else
{
resource_object.value -= amount;
}
}
else
{
throw new ResourceException("This resource does not exist.", resource, "take");
}
}
this.GiveResource = function(resource, amount)
{
if(this.resources[resource])
{
resource_object = this.resources[resource];
if(resource_object.maximum != null && resource_object.value + amount > resource_object.maximum)
{
resource_object.value = resource_object.maximum;
throw new ResourceWarning("The upper boundary of the resource was reached.", resource, "give");
}
else
{
resource_object.value += amount;
}
}
else
{
throw new ResourceException("This resource does not exist.", resource, "give");
}
}
}
var /*Class*/ Resource = this.Resource = function()
{
this.name = "Unnamed resource";
this.negative_allowed = false;
this.minimum = null;
this.maximum = null;
this.value = 0;
}
var point_distance = this.point_distance = function(x1, y1, x2, y2)

Loading…
Cancel
Save