I'm working on a game which I'm writing in Javascript and then porting to iOS/Android via phonegap/cordova.

For the most part, I understand how to code and how to get what I want to happen, BUT I have a major struggling point in using proper techniques and avoiding redundancy and over-complexity.

For example, one of my first forays into game dev, I had tried to answer a question on how to simplify a set of actions or functions that are related (you can check out my bad answer here How can I design lots of different attack types that can be combined? )

Now, I'm sort of at a similar pass at my game, I have different 'enemy types' that are supposed to trigger a different action when they touch the player. I have a if/else structure right now to change between these different circumstances.

Sean Middleditch did a good job of answering why 'data-driven' design works better than 'procedural' design, but for the life of me I can't figure out HOW to employ this. It seems to me that no matter how I want to structure my objects in my game, and which properties I give them, at some point I will need an if/else or switch statement, can anyone help me work past this?

if(enemyType == 'black'){  // enemyType is a color
            done(index);   // done is a function that removes the enemy after it touches the player
            updateScore(score); // black is score point so it updates score
}else if(enemyType == 'red'){  // red is a death so gameOver
    if(!gameVars.invincible && gameVars.lives == 1){ // but the player might be invincible or have extra lives
    }else if (!gameVars.invincible){ // in that case we manage the lives or ignore the hit completely
}else if(enemyType == 'blue'){ // the rest are power ups of types
}else if(enemyType == 'grey'){
}else if (enemyType == 'green') {
    gameVars.teir_reducer += 2;
}else if (enemyType == 'yellow') {
    gameVars.speed_reducer += 10;
}else if (enemyType == 'orange') {
}else if (enemyType == 'purple') {
}else if (enemyType == 'violet') {
}else if (enemyType == 'gainsboro') {

In Javascript, a property can also be a function. Don't make enemyType a string. Make it an object which has multiple methods for different interactions.

violetThing = {
     name: "violet",
     sprite: "violetThing.png",
     onTouchFunction: setMagnetic,
     color: '#ffdd22'

yellowThing = {
     name: "yellow",
     sprite: "yellowThing.png",
     onTouchFunction: function() { gameVars.speed_reducer += 10; },
     color = '#00ddff'


In the long function you posted above you would simply do:

done(index); // whatever that's supposed to do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.