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])
        PlayerBallSounds.hitPaddle.play
      }
  }

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

  // 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
    g.setColor(Color.white)
    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.

Advertisements