Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can traits be used to build a game component system in Scala?

Tags:

scala

traits

I'm just wondering if it is semantically correct to use traits to build game objects. On one hand, I view this as a has a relationship (an object has components), but on the other hand I view components as composing an object.

For example. You have a GameObject. A GameObject does pretty much nothing on its own, but the things you mix into it give it additional properties. Components could be HealthComponent (has health), PhysicsComponent (simulates physics), ClickableComponent (can be clicked).

I like the idea of using traits because all of the properties and methods are added on the original object and I can do player.getHP instead of player.getHealthComponent.getHP. On the other hand, I find the naming and semantics of using traits weird. trait HealthComponent extends GameObject - this doesn't make sense. A HealthComponent belongs to a GameObject, it doesn't fulfill the is a relationship that's implied by extend. Am I correct in assuming that traits are normally treated as specialized versions of their parent class? If so, how would I name something like the above object?

like image 336
ryeguy Avatar asked Dec 28 '22 22:12

ryeguy


1 Answers

To supplement @Moritz's answer, it's also possible to stack related behaviors without inheriting implementation from the super type:

trait HasFoo { def foo: Unit }

class GameObject extends HasFoo {
   def foo = {}
}

trait Health extends HasFoo { 
   self: GameObject =>

   abstract override def foo = {
      println("health foo")
      super.foo
   }
}

trait Dog extends HasFoo { 
   self: GameObject =>

   abstract override def foo = {
      println("dog foo")
      super.foo
   }
}

scala> val g = new GameObject with Health with Dog
g: GameObject with Health with Dog = $anon$1@33b7b32c

scala> g.foo
dog foo
health foo
like image 195
Aaron Novstrup Avatar answered Jan 30 '23 07:01

Aaron Novstrup