Dimensions expressions example (Score)
The following example creates a custom dimension
called Score that represents
a score in a game. The score measures progress for each player in a point
value stored as a BigDecimal
value.
The following is the Score class:
package example
uses java.math.BigDecimal
final class Score implements IDimension<Score, BigDecimal> {
// Declare a Points property
var _points : BigDecimal as Points
/* REQUIRED BY IDimension */
construct( p : BigDecimal) {
_points = p
}
construct() {
_points = 0 // If used with a no argument constructor, just set points to 0
}
override function toNumber(): BigDecimal {
return _points
}
override function fromNumber(bigDecimal: BigDecimal): Score {
return new Score(bigDecimal)
}
override function numberType(): Class<BigDecimal> {
return BigDecimal
}
/* REQUIRED BY Comparable */
override function compareTo(o: Score): int {
return (_points.compareTo(o.Points))
}
/* Improve printing... */
public function toString() : String {
return "Score is " + _points + " points"
}
// ADDITIONAL conversions
function fromNumber(i: int): Score {
return new Score(i as BigDecimal)
}
function fromNumber(i: Integer): Score {
return new Score(i as BigDecimal)
}
/* ENABLE arithmetic for Dimensions */
function add( td: Score) : Score {
return new Score(td.Points + _points)
}
function subtract( td: Score) : Score {
return new Score(td.Points + _points)
}
function multiply( bd : BigDecimal) : Score {
return new Score(bd * _points)
}
function multiply( td : Score) : Score {
return new Score(td.Points * _points)
}
function divide( bd : BigDecimal) : Score {
return new Score(_points / bd)
}
function divide( td: Score) : Score {
return new Score(_points / td.Points)
}
}
Consider the following code that you can run in the Gosu Scratchpad:
uses example.Score
var x = new Score()
var y = new Score()
var addme = new Score(2)
print ("x = " + x + " ..... y = " + y)
x = x + addme
y = y + addme + addme
print ("x = " + x + " ..... y = " + y)
var z = x * y.Points
print ("z = " + z )
This example prints the following:
x = Score is 0 points ..... y = Score is 0 points
x = Score is 2 points ..... y = Score is 4 points
z = Score is 8 points
