Artikel mit Tag jade
Verwandte Tags
object orientation performance mixins adom scala java composition rpg optimization traits groovy fun c# niceSamstag, 7. Februar 2009
Toying around ... with Scala
After a long time here is a post about Scala again. I played around with composition of objects an classes from traits.
This post is also a reaction to Thomas Biskups post Toying around ..., where he played around with Qi4j to perhaps find a better architecture for his rogue like rpg “JADE”. We sometimes talking about this and I once mentioned Scalas traits.
So here is a little example of object and class composition with traits in Scala from the domain of role play games. I implemented some simple traits which I used to compose a class and a (singelton) object.
package de.myndian.scala.rpg
// Something that has a “name”
trait Named
{
def name : String
}
// Something that has “power”
trait Powered
{
def power : Int
}
// A namend thing that can be hitted
trait Hitable
{
this: Named =>
var hitpoints : Int
def hit(points : Int)
{
hitpoints -= points
print(name + “ was hitted with ” + points + “ points. ”)
if(hitpoints <= 0)
println(name + " is dead.")
else
println(name + " has " + hitpoints + " hitpoints remaining.")
}
}
// A named thing that can use its power to hit a hittable
trait Fighter
{
this : Named with Powered =>
val rnd = new Random(System.currentTimeMillis)
def hit(target : Named with Hitable)
{
println(name + “ hits ” + target.name)
target.hit(rnd.nextInt(power))
}
}
class Door(val name : String, var hitpoints : Int)
extends Named
with Hitable
// In this fight the dwarf “kills” a door
object DemoFight
extends Application
{
var aDoor = new Door(“a door”, 10)
object TheDwarf
extends Named
with Hitable
with Fighter
with Powered
{
val name = “the dwarf”
val power = 10
var hitpoints = 20
}
while(aDoor.hitpoints > 0)
TheDwarf.hit(aDoor)
}
Some sample output:
the dwarf hits a door a door was hitted with 3 points. a door has 7 hitpoints remaining. the dwarf hits a door a door was hitted with 7 points. a door is dead.
So Thomas, what about “SADE”? ;-)
Geschrieben von Jörg
in Softwaretechnik
um
15:41
| Kommentare (0)
| Trackbacks (0)
Artikel mit ähnlichen Themen:
(Seite 1 von 1, insgesamt 1 Einträge)


Jörg bei Twitter

