// player.js (function() { window.game = {}; window.game.player = { hp: 10, resist: .3, poisoned: false, damage: function(amount) { if (Math.random() < this.resist) { amount = Math.round(amount / 2); } this.hp -= amount; document.getElementById("hp").innerHTML = this.hp; if (this.hp <= 0) { this.die(); } }, die: function() { document.getElementById("controls").innerHTML = "Game Over"; }, setPoisoned: function(val) { this.poisoned = val; document.getElementById("poisoned").innerHTML = val; } }; }()); // enemy.js (function() { window.game.enemy = { damagePlayer: function() { window.game.player.damage(3); } }; }()); // poisonEnemy.js (function() { window.game.poisonEnemy = { damagePlayer: function() { window.game.enemy.damagePlayer(); window.game.player.setPoisoned(true); } }; }()); // set up the ui to test the code in jsfiddle $("#hp").text(window.game.player.hp); $("#poisoned").text(window.game.player.poisoned); $("#attack").on("click", window.game.enemy.damagePlayer); $("#poisonAttack").on("click", window.game.poisonEnemy.damagePlayer);
HP: <span id="hp"></span> <br> Poisoned: <span id="poisoned"></span> <div id="controls"> <button id="attack">attack from normal enemy</button> <br> <button id="poisonAttack">attack from poisonous enemy</button> </div>