Modelling Game Entities Using Traits

For a while now I’ve thought that Scala would be a good language to write games in. Well, I’m putting those thoughts into practice: I resurrected a couple of old game ideas and am now working on a 2D game or two as hobby projects. I decided that it would be a good idea to try my hand on simpler games before I embark on a longer project (which will likely be a platformer), so the one I’m working on now is something of a mix between Breakout and Peggle.

As part of writing those games, I’m also designing a generic game entity system, which will be integrated with Slick2D (for graphics, sound, input and other stuff) and a Scala port of Box2D (for collision detection and physics) that I’m also working on. So far I am very pleased that I chose Scala for this project — the code is generally more concise than Java (requiring roughly 2 times less lines), but what I like most is that traits, pattern matching plus some other features make Scala a great language for building components.

With the entity system I’m trying to take full advantage of that, implementing the building blocks for entities as traits that deal with different concerns. Some of these traits only define an interface for some type of behavior, but some also implement it, reducing the amount of code needed in concrete entities. Here are some of the most basic traits I’ve got implemented so far and descriptions of what they do:

Entity – the base trait for all my game entities, which extends Updateable, making it able to act on updates (or “ticks”) from the game engine during each frame.

PhysicalEntity – can be mixed into an entity class to add a physical body to an Entity, which takes part in the physics simulation and collision detection.

GraphicalEntity – adds a render method, which the entity can implement to render itself.

WithStates – for more complex entities that behave differently depending on their current state. For example a camera in a sneaking game may have states “Off” and “On”. In the Off state, the camera might not do anything, but in the On state it might be listening to some game events to react to seeing the player. To do this, a specific state (which are implemented as internal classes of the Entities) could mix in the Updateable and/or EventListener traits to react to events differently when that state is active. Additionally, defining state transitions can limit how the entity moves from one state to the other and allows to run some code when the state changes.

EventListener – an entity (or one of its states) with this trait will receive notifications of events it is interested in. This can be used in other objects besides entities and states, but only the latter two are automatically registered as listeners in the event queue.

Environment – this is the container for entities, the physics world and the event queue.

This is not all, but these are the most basic building blocks. Here is the code for a simple entity that makes use of some of these:

class Paddle
    extends PhysicalEntity with GraphicalEntity
    with EventListener with GameStateAware[InGame] {

  // we define the physical body for the PhysicalEntity
  val bodyDef = new BodyDef
  bodyDef.pos = (0,-10)
  bodyDef.fixedRotation = true
  bodyDef.allowSleep = false

  // the radius at which the paddle moves around world center
  val radius = 10
  // keeps track of the number of balls shot from the paddle and currently in play.
  var ballsInPlay: Int = 0
  def noBallsInPlay = ballsInPlay == 0

  // we call a convenience method of the EventListener to listen to some specific kinds of events
  listenTo {
    case ce @ ContactResultEventBetween(body1, body2) =>
      val other = 
        if (body1 == body) body2
        else if (body2 == body) body1
        else null
      if (other != null) {
        gameState.scorer.hitPaddle(this, other.userData.asInstanceOf[PlayerBall])

  // we override the function that is called when a PhysicalEntity is inserted into the world
  override def enterWorld(w: World) {
    val shape =, 0.1f)
    shape.density = 0f

  // define the render method to render the paddle (currently just rendering the physical body as a placeholder)
  def render(g: Graphics) = {
    import org.newdawn.slick.Color
    rendering.RenderUtils.renderBody(g, body)

I am already pleased that I was able to separate the different basic concerns using Scala’s traits and making them easily composable as seen above, but I hope that the real benefits should become apparent in a larger game with lots of different entities. Mick West talks about creating game entities as components in his blog post “Evolve Your Hierarchy” – I think he is right and that Scala’s language support for this (especially in the form of traits) is better than in C++ or Java, where you could do something similar with inheritance, interfaces and object composition. Note: I’ve never been a professional game developer or even got to the point of releasing a hobby project to the wider audience so I’m not speaking from reliable personal experience exactly, but I’ve worked with a few entity systems and this just seems right to me.

I will post more about this in the future, hopefully after having released a simple game :) and I’m considering releasing the code for the entity system under an open source license.


8 thoughts on “Modelling Game Entities Using Traits

  1. I’m using Slick as-is, but I do plan to release the Box2D port once it’s completed. It’s actually a port of JBox2D ( ) to be more precise and you could use that as-is from Scala.
    My Scala version makes some changes to the API (mainly by preferring immutable classes where possible), is somewhat experimental and may end up being too difficult to maintain so I’m not sure what the status of that will be. I’ll be talking with Eric Jordan (JBox2D developer) about it.

  2. Scala (or other functional language, whatever) in games is something I’m also insterested, but I have a suggestion regarding your current game objects model:

    Why don’t you try this without using the inheritance model for game entities? Long time ago this was replaced in (good) game engines by the componentized architecture described in some articles since 2000 or so.

    (I personally recommend reading “Game Object Component System”, by Cris Stoy, in Game Programming Gems 6 for this matter; or using the Unity3D game engine)

    Instead of making each entity extend (or implement) different behaviors, make them agregate those. This makes a game object system more suitable for having even its structure data-driven.

    Going for an inheritance model is a failure from the very beginning. Sooner or later you’ll get stuck in problems with the current approach (regardless of the choosen language).

  3. (I am a working game designer – I program too, though that is not my official role)

    I agree with the above poster. The compositional model is the right one to use. An inherited Entity class will become a “God Class” as things crop up that require you to stuff data into “most” entities. With composition you can pick and choose and this is not only organizationally more sound, but it saves you memory, which is very valuable for console development.

    A system I have been working on in my spare time to improve further on compositional approaches is to incorporate application state as a system of modules: modules for various kinds of displays, collision methods, different types of AI, etc. Entities then become collections of referenced data from various modules, and data updates that need to access another module’s data(a collision changing an animation, for example) traverses explicitly through the entity(I implemented this with a hashtable). A player character might reference some graphics module, collision and character-specific movement dynamics, and a specialized input module.

    Modules contain a simple formalized finite state machine with transitions and updates: My current approach to using them is to have a central update controller that binds together all the modules and enforces state at the application-level.

    This means that if, for example, I want to go to a sub menu and pause the gameplay and then resume, I don’t have to worry too much about integrating the logic into the application: I just have to tell the modules for gameplay to pause, and if they are built correctly, they’ll wait until I tell them to start again. But if I want other elements of gameplay like a HUD to stay on-screen, the modules for those may continue to run and update normally.

    So far this system seems to be working pretty smoothly – haven’t finished a game with it yet – but it also takes way longer to architect than more simplistic approaches, because a lot more design and debugging surfaces itself as you build each module, rather than later on.

  4. Perhaps composition is indeed better in the end. But I think for relatively small games composing the traits into entity classes works well enough and is perhaps simpler. I guess I really should read some more of the related literature, though. Thanks for the pointers!

  5. Pingback: Ziggy Returns, Rewritten in Scala « Villane

  6. Pingback: My Head Asplode « Villane

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s