When you work with several classes in a Javascript / NodeJS game, it’s hard for me to understand which class should emit events and which classes should listen. I follow this guide to creating event-driven games: http://pragprog.com/magazines/2011-08/decouple-your-apps-with-eventdriven-coffeescript
I am writing a small game and divided my classes into the following controllers:
world - creates a game world and develops through several "turns" to determine some simple logic of the game (i.e., the character must move, the tower must shoot).
tower - the tower sits on a 10x10 grid and has a range. When an object falls within range, it can shoot.
mobs (enemies) - the crowd appears on a 10x10 grid and moves every 3 seconds. At some point, he wanders within the tower.
I read about EventEmitters all day, but can't figure out how to properly build my events. Should mobs shoot an event when they move and the tower listens to the "move" event? Or should the world control all the events, and the tower / mobs are listening to the world?
See below for sample code.
Reference Information. I was working on a simple TowerD game for NodeJS and decided to implement the server first. I store all the objects in MongoDB and using geospatial analysis to determine if the objects are in range for shooting. I am currently using a rudimentary 3-second loop to “tick off” the game logic and progress, but I would like to move on to a truly event-driven model and am afraid.
:
exports.World = class World extends EventEmitter
constructor: ->
@gameTime = 3000
@game = setInterval ->
world.gameLoop()
, @gameTime
@maps = []
@maps.push new map 'hiddenvalley'
@mobs = []
@mobs.push new mob @maps[0].mobs[0]
@mobs.push new mob @maps[0].mobs[0]
(. world.coffee: https://github.com/bdickason/node-towerd/blob/master/controllers/world.coffee)
:
exports.Tower = class Tower
constructor: (name) ->
name = name.toLowerCase()
checkTargets: (callback) ->
mobModel.find { loc : { $near : @loc , $maxDistance : @range } }, (err, hits) ->
if err
console.log 'Error: ' + err
else
callback hits
(. towers.coffee: https://github.com/bdickason/node-towerd/blob/master/controllers/towers.coffee)
:
exports.Mob = class Mob extends EventEmitter
move: (X, Y, callback) ->
@loc = [@loc[0] + X, @loc[1] + Y]
newloc = @loc
mobModel.find { uid: @uid }, (err, mob) ->
if(err)
console.log 'Error finding mob: {@uid} ' + err
else
mob[0].loc = newloc
mob[0].save (err) ->
if (err)
console.log 'Error saving mob: {@uid} ' + err
console.log 'MOB ' + @uid + ' [' + @id + '] moved to (' + @loc[0] + ',' + @loc[1] + ')'
(. mobs.coffee: https://github.com/bdickason/node-towerd/blob/master/controllers/mobs.coffee)
: https://github.com/bdickason/node-towerd
. 15 nodejs github , : (