├── Player.js ├── README.md ├── ROBOTRON.js ├── core ├── Sprite.js ├── globals.js ├── imagesPreload.js ├── keys.js ├── main.js ├── render.js ├── update.js └── userInput.js ├── entities ├── Brain.js ├── Bullet.js ├── CruiseMissile.js ├── Electrode.js ├── Enemy.js ├── Enforcer.js ├── Entity.js ├── Family.js ├── Grunt.js ├── Hulk.js ├── Powerup.js ├── Prog.js ├── Protagonist.js ├── Quark.js ├── ScoreImg.js ├── Shell.js ├── Spark.js ├── Spheroid.js └── Tank.js ├── index.php ├── jquery-1.11.0.min.js ├── managers ├── entityManager.js ├── handleMouse.js ├── highScores.js ├── levelManager.js ├── playlist.js └── spatialManager.js ├── particles ├── AfterImage.js └── Particle.js ├── phplogic ├── highscores.class.php └── savescore.php ├── utils ├── consts.js ├── urls.js └── util.js └── views ├── canvas.php ├── footer.php ├── header.php ├── main.php ├── navigation.php └── style.css /Player.js: -------------------------------------------------------------------------------- 1 | //====== 2 | //PLAYER 3 | //====== 4 | /* 5 | 6 | An object which contains all the important parameters of the player such as 7 | the score, remaining lives and the current level number. 8 | 9 | Well, that's what it started as. Now it also contains the power up methods 10 | and effects, and the score values as well as rendering the scorebar... 11 | 12 | */ 13 | 14 | "use strict"; 15 | 16 | /* jshint browser: true, devel: true, globalstrict: true */ 17 | 18 | /* 19 | 0 1 2 3 4 5 6 7 8 20 | 12345678901234567890123456789012345678901234567890123456789012345678901234567890 21 | */ 22 | 23 | function Player() { 24 | 25 | }; 26 | 27 | Player.prototype.setup = function (descr) { 28 | // Apply all setup properies from the (optional) descriptor 29 | for (var property in descr) { 30 | this[property] = descr[property]; 31 | } 32 | }; 33 | 34 | Player.prototype.level = 1; 35 | Player.prototype.lives = 5; 36 | Player.prototype.multiplier = 1; 37 | Player.prototype.score = 0; 38 | Player.prototype.saveCount = 0; 39 | Player.prototype.speed = 3; 40 | Player.prototype.speedTimer = 10 * SECS_TO_NOMINALS; 41 | Player.prototype.fireRate = 20; 42 | Player.prototype.ammo = 0; 43 | Player.prototype.hasShotgun = false; 44 | Player.prototype.hasMachineGun = false; 45 | Player.prototype.shieldTime = 0; 46 | Player.prototype.powerupTime = 1 * SECS_TO_NOMINALS; 47 | Player.prototype.powerupText = ""; 48 | Player.prototype.colorCounter = 0; 49 | Player.prototype.scoreValues = { 50 | Electrode: 5, 51 | Spark: 25, 52 | Shell: 50, 53 | CruiseMissile: 75, 54 | Prog: 100, 55 | Grunt: 100, 56 | Enforcer: 200, 57 | Tank : 300, 58 | Brain: 500, 59 | Spheroid: 1000, 60 | Quark: 1000, 61 | Family: 1000, 62 | Powerup: 300 63 | }; 64 | 65 | // ------------- 66 | // Basic Methods 67 | 68 | Player.prototype.resetAll = function() { 69 | this.resetLives(); 70 | this.resetLevel(); 71 | this.resetScore(); 72 | this.resetSpeed(); 73 | this.resetSpeedTimer(); 74 | this.resetMultiplier(); 75 | this.resetFireRate(); 76 | this.resetAmmo(); 77 | this.resetShield(); 78 | this.resetShieldTime(); 79 | }; 80 | 81 | Player.prototype.render = function(ctx) { 82 | ctx.save(); 83 | 84 | // Display score bar 85 | ctx.fillStyle = "black"; 86 | ctx.fillRect(0, 0, ctx.canvas.width, consts.wallTop); 87 | 88 | // Display the score 89 | ctx.lineWidth = 1.5; 90 | ctx.font = "20px Arial"; 91 | ctx.fillStyle = "red"; 92 | var scoretxt = "Score: " + this.score; 93 | ctx.fillText(scoretxt, 5, 20); 94 | 95 | //display the multiplier and the level 96 | var disp = "X" + this.multiplier + " Level: " + this.level; 97 | ctx.fillText(disp, g_canvas.width/2 - 140, 20); 98 | 99 | // Display ammo 100 | var text = "Ammo: " + this.ammo; 101 | ctx.fillText(text, g_canvas.width/2, 20); 102 | 103 | // Display shield 104 | var moretxt = "Shield: " + Math.ceil(this.shieldTime / SECS_TO_NOMINALS); 105 | ctx.fillText(moretxt, g_canvas.width/2 + 130, 20); 106 | 107 | // Display remaining lives 108 | for (var i = 1; i < this.lives; i++) { 109 | g_sprites.Extralife.drawCentredAt(ctx, 110 | g_canvas.width - i*20, 111 | 15, 112 | 0 113 | ); 114 | }; 115 | 116 | // Display border 117 | ctx.fillStyle = consts.colors[this.colorCounter%consts.colors.length]; 118 | ctx.fillRect(0, consts.wallTop, ctx.canvas.width, consts.wallThickness); 119 | ctx.fillRect(0, consts.wallTop, consts.wallLeft, g_canvas.height - consts.wallTop); 120 | ctx.fillRect(0, consts.wallBottom, g_canvas.width, consts.wallThickness); 121 | ctx.fillRect(consts.wallRight, consts.wallTop, consts.wallThickness, g_canvas.height - consts.wallTop); 122 | 123 | ctx.restore(); 124 | }; 125 | 126 | 127 | // --------------------------- 128 | // General attribute modifiers 129 | 130 | Player.prototype.addLevel = function () { 131 | this.level += 1; 132 | if (this.level > 255) this.level = 1; 133 | }; 134 | 135 | Player.prototype.subtractLevel = function () { 136 | this.level += -1; 137 | }; 138 | 139 | Player.prototype.resetLevel = function () { 140 | this.level = 1; 141 | }; 142 | 143 | Player.prototype.getLevel = function () { 144 | return this.level; 145 | }; 146 | 147 | Player.prototype.addScore = function (score) { 148 | this.score += score; 149 | }; 150 | 151 | Player.prototype.resetScore = function () { 152 | this.score = 0; 153 | }; 154 | 155 | Player.prototype.getScore = function () { 156 | return this.score; 157 | }; 158 | 159 | Player.prototype.addLives = function () { 160 | this.lives += 1; 161 | if (this.lives > 8) this.lives = 8; 162 | }; 163 | 164 | Player.prototype.subtractLives = function () { 165 | if(this.lives > 0) this.lives += -1; 166 | }; 167 | 168 | Player.prototype.resetLives = function () { 169 | this.lives = 5; 170 | }; 171 | 172 | Player.prototype.getLives = function () { 173 | return this.lives; 174 | }; 175 | 176 | 177 | // -------------- 178 | // Rescue Methods 179 | 180 | Player.prototype.addMultiplier = function () { 181 | if (this.multiplier < 5) { 182 | this.multiplier += 1; 183 | } 184 | }; 185 | 186 | Player.prototype.resetMultiplier = function () { 187 | this.multiplier = 1; 188 | }; 189 | 190 | Player.prototype.getMultiplier = function () { 191 | return this.multiplier; 192 | }; 193 | 194 | Player.prototype.addSaveCount = function () { 195 | // This function gives an extra life 196 | // when you have saved 7 family members 197 | this.saveCount += 1; 198 | if (this.saveCount > 6) { 199 | this.addLives(); 200 | this.resetSaveCount(); 201 | } 202 | }; 203 | 204 | Player.prototype.resetSaveCount = function () { 205 | this.saveCount = 0; 206 | }; 207 | 208 | 209 | // --------------- 210 | // Speed Methods 211 | 212 | Player.prototype.addSpeed = function () { 213 | this.resetSpeedTimer(); 214 | if (this.speed < 5) this.speed = 5; 215 | }; 216 | 217 | Player.prototype.getSpeed = function () { 218 | return this.speed; 219 | }; 220 | 221 | Player.prototype.tickSpeedTimer = function (du) { 222 | this.speedTimer += -du; 223 | if (this.speedTimer < 0) { 224 | this.resetSpeed(); 225 | this.resetSpeedTimer(); 226 | } 227 | }; 228 | 229 | Player.prototype.resetSpeed = function () { 230 | this.speed = 2; 231 | } 232 | 233 | Player.prototype.resetSpeedTimer = function () { 234 | this.speedTimer = 10 * SECS_TO_NOMINALS; 235 | }; 236 | 237 | 238 | // -------------- 239 | // Shield Methods 240 | 241 | Player.prototype.getShieldTime = function () { 242 | return this.shieldTime; 243 | }; 244 | 245 | Player.prototype.setShieldTime = function (time) { 246 | this.shieldTime = time * SECS_TO_NOMINALS; 247 | }; 248 | 249 | Player.prototype.addShieldTime = function() { 250 | this.activateShield(); 251 | this.shieldTime += 20 * SECS_TO_NOMINALS; 252 | if (this.shieldTime > 60 * SECS_TO_NOMINALS) { 253 | this.setShieldTime(60); 254 | }; 255 | }; 256 | 257 | Player.prototype.tickShieldTime = function (du) { 258 | this.shieldTime += -du; 259 | if (this.shieldTime < 0) { 260 | this.resetShield(); 261 | this.resetShieldTime(); 262 | } 263 | }; 264 | 265 | Player.prototype.activateShield = function () { 266 | g_canBeKilled = false; 267 | }; 268 | 269 | Player.prototype.resetShield = function () { 270 | g_canBeKilled = true; 271 | }; 272 | 273 | Player.prototype.resetShieldTime = function () { 274 | this.shieldTime = 0; 275 | } 276 | 277 | 278 | // ------------------- 279 | // Gun Methods 280 | 281 | Player.prototype.getFireRate = function () { 282 | return this.fireRate; 283 | }; 284 | 285 | Player.prototype.setFireRate = function (fireRate) { 286 | this.fireRate = fireRate; 287 | }; 288 | 289 | Player.prototype.resetFireRate = function () { 290 | this.fireRate = 20; 291 | this.hasShotgun = false; 292 | this.hasMachineGun = false; 293 | }; 294 | 295 | Player.prototype.getAmmo = function () { 296 | return this.ammo; 297 | }; 298 | 299 | Player.prototype.setAmmo = function (ammo) { 300 | this.ammo = ammo; 301 | }; 302 | 303 | Player.prototype.subtractAmmo = function () { 304 | if (this.ammo > 0) this.ammo += -1; 305 | if (this.ammo < 1) this.resetFireRate(); 306 | }; 307 | 308 | Player.prototype.addAmmo = function (ammo) { 309 | this.ammo += ammo; 310 | if (this.ammo > 500) this.setAmmo(500); 311 | }; 312 | 313 | Player.prototype.resetAmmo = function () { 314 | this.ammo = 0; 315 | }; 316 | 317 | 318 | // ------------------- 319 | // Powerup text animation Methods 320 | 321 | Player.prototype.setPowerupText = function (str) { 322 | this.powerupText = str; 323 | } 324 | 325 | Player.prototype.getPowerupText = function () { 326 | if(this.powerupText==undefined) 327 | return ""; 328 | return this.powerupText; 329 | } 330 | 331 | Player.prototype.setPowerupTime = function () { 332 | this.powerupTime = 1 * SECS_TO_NOMINALS; 333 | }; 334 | 335 | Player.prototype.getPowerupTime = function () { 336 | return this.powerupTime; 337 | }; 338 | 339 | Player.prototype.tickPowerupTime = function (du) { 340 | if (this.powerupTime < 0) return; 341 | this.powerupTime += -du; 342 | }; 343 | 344 | Player.prototype.tickColorCounter = function (du) { 345 | this.colorCounter++; 346 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Robotron 2 | ======== 3 | A remake of the classic arcade game Robotron 2084 in Javascript. A live version can be found [here](https://notendur.hi.is/~odv1/Robotron/). 4 | 5 | This is the final project of the course Computer Game Programming (TÖL308G) at the University of Iceland in November 2014. 6 | 7 | This game was programmed by (in alphabetical order): 8 | * [Bjarki Hall](https://github.com/bjarkihall) 9 | * [Eiríkur Ernir Þorsteinsson](https://github.com/Ernir) 10 | * [Jianfei John Zheng](https://github.com/jiz2) 11 | * [Oddur Vilhjálmsson](https://github.com/OddurV) 12 | 13 | Instructor: 14 | * Patrick Kerr -------------------------------------------------------------------------------- /ROBOTRON.js: -------------------------------------------------------------------------------- 1 | // ========= 2 | // ROBOTRON 3 | // ========= 4 | /* 5 | 6 | A playable version of the classic arcade game. 7 | 8 | This is the final project of the course Computer game programming (Töl308G) 9 | at the University of Iceland in november 2014. 10 | 11 | This game was programmed by (in alphabetical order): 12 | Bjarki Hall 13 | Eiríkur Ernir Þorsteinsson 14 | Jianfei John Zheng 15 | Oddur Vilhjálmsson 16 | 17 | Instructor: 18 | Patrick Kerr 19 | 20 | */ 21 | 22 | "use strict"; 23 | 24 | /* jshint browser: true, devel: true, globalstrict: true */ 25 | 26 | /* 27 | 0 1 2 3 4 5 6 7 8 28 | 12345678901234567890123456789012345678901234567890123456789012345678901234567890 29 | */ 30 | 31 | //Get the canvas & context 32 | var g_canvas = document.getElementById("myCanvas"); 33 | var g_ctx = g_canvas.getContext("2d"); 34 | 35 | // ======================= 36 | // CREATE INITIAL ENTITIES 37 | // ======================= 38 | 39 | function initializeEntities() { 40 | // TODO 41 | } 42 | var Player = new Player(); 43 | 44 | // ============= 45 | // GATHER INPUTS 46 | // ============= 47 | 48 | function gatherInputs() { 49 | // Nothing to do here! 50 | // The event handlers do everything we need for now. 51 | } 52 | 53 | 54 | // ================= 55 | // UPDATE SIMULATION 56 | // ================= 57 | 58 | // We take a very layered approach here... 59 | // 60 | // The primary `update` routine handles generic stuff such as 61 | // pausing, single-step, and time-handling. 62 | // 63 | // It then delegates the game-specific logic to `updateSimulation` 64 | 65 | 66 | // GAME-SPECIFIC UPDATE LOGIC 67 | 68 | function updateSimulation(du) { 69 | 70 | processDiagnostics(); 71 | 72 | Player.tickColorCounter(du); 73 | 74 | if (levelManager.isInMenu()) { 75 | 76 | return; 77 | 78 | } else if (levelManager.isChangingLevel()) { 79 | 80 | levelManager.reduceTimer(du); 81 | 82 | } else { 83 | 84 | if (!levelManager.isGameOver()) { 85 | entityManager.update(du); 86 | } 87 | } 88 | 89 | if (Player.getLives() === 0) { 90 | levelManager.gameOver(); 91 | }; 92 | 93 | if (entityManager.enemiesIsEmpty()) levelManager.nextLevel(); 94 | } 95 | 96 | // GAME-SPECIFIC DIAGNOSTICS 97 | 98 | var g_Debug = false; 99 | var g_canBeKilled = true; // Shield powerup effect 100 | var g_invincible = false; // Debug mode invulnerability 101 | var g_friendlyFire = true; 102 | var g_sounds = true; 103 | var g_music = true; 104 | 105 | var KEY_DEBUG = keyCode('X'); 106 | var KEY_INVINCIBLE = keyCode('K'); 107 | var KEY_FRIENDLYFIRE = keyCode('F'); 108 | var KEY_RESTART = keyCode('R'); 109 | var KEY_NEXT_LEVEL = keyCode('+'); 110 | var KEY_NEXT_LEVELN = 107; // Numpad + 111 | var KEY_PREV_LEVEL = keyCode('-'); 112 | var KEY_PREV_LEVELN = 109; // Numpad - 113 | var KEY_SOUND = keyCode('N'); 114 | var KEY_MUSIC = keyCode('M'); 115 | var KEY_VOLUMEUP = keyCode('Y'); 116 | var KEY_VOLUMEDOWN = keyCode('H'); 117 | var KEY_PWRUP_RESET = keyCode('0'); 118 | var KEY_PWRUP_RESETN = 96; // Numpad 0 119 | var KEY_EXTRA_LIFE = keyCode('1'); 120 | var KEY_EXTRA_LIFEN = 97; // Numpad 1 121 | var KEY_SPEED = keyCode('2'); 122 | var KEY_SPEEDN = 98; // Numpad 2 123 | var KEY_SCORE_MP = keyCode('3'); 124 | var KEY_SCORE_MPN = 99; // Numpad 3 125 | var KEY_MACHINEGUN = keyCode('4'); 126 | var KEY_MACHINEGUNN = 100; // Numpad 4 127 | var KEY_SHOTGUN = keyCode('5'); 128 | var KEY_SHOTGUNN = 101; // Numpad 5 129 | var KEY_SHIELD = keyCode('6'); 130 | var KEY_SHIELDN = 102; // Numpad 6 131 | var KEY_PREV_SONG = keyCode('8'); 132 | var KEY_PREV_SONGN = 104; // Numpad 8 133 | var KEY_NEXT_SONG = keyCode('9'); 134 | var KEY_NEXT_SONGN = 105; // Numpad 9 135 | 136 | function processDiagnostics() { 137 | 138 | if (eatKey(KEY_INVINCIBLE) && g_Debug) { 139 | g_invincible = !g_invincible; 140 | g_hasCheated = true; 141 | } 142 | 143 | if (eatKey(KEY_FRIENDLYFIRE) && g_Debug) { 144 | g_friendlyFire = !g_friendlyFire; 145 | g_hasCheated = true; 146 | } 147 | 148 | if (eatKey(KEY_RESTART)) { 149 | Player.resetAll(); 150 | levelManager.startLevel(); 151 | g_hasCheated = false; 152 | highScores.renderOFF(); 153 | } 154 | 155 | if ((eatKey(KEY_NEXT_LEVEL) || eatKey(KEY_NEXT_LEVELN)) && g_Debug) { 156 | levelManager.nextLevel(); 157 | g_hasCheated = true; 158 | } 159 | 160 | if ((eatKey(KEY_PREV_LEVEL) || eatKey(KEY_PREV_LEVELN)) && g_Debug) { 161 | levelManager.prevLevel(); 162 | g_hasCheated = true; 163 | } 164 | 165 | if ((eatKey(KEY_EXTRA_LIFE) || eatKey(KEY_EXTRA_LIFEN)) && g_Debug) { 166 | Player.addLives(); 167 | g_hasCheated = true; 168 | } 169 | 170 | if ((eatKey(KEY_SPEED) || eatKey(KEY_SPEEDN))&& g_Debug) { 171 | Player.addSpeed(); 172 | g_hasCheated = true; 173 | } 174 | 175 | if ((eatKey(KEY_SCORE_MP) || eatKey(KEY_SCORE_MP)) && g_Debug) { 176 | Player.addMultiplier(); 177 | g_hasCheated = true; 178 | } 179 | 180 | if ((eatKey(KEY_MACHINEGUN) || eatKey(KEY_MACHINEGUNN)) && g_Debug) { 181 | Player.hasShotgun = false; 182 | Player.hasMachineGun = true; 183 | Player.setFireRate(5); 184 | Player.addAmmo(100); 185 | g_hasCheated = true; 186 | } 187 | 188 | if ((eatKey(KEY_SHOTGUN) || eatKey(KEY_SHOTGUNN)) && g_Debug) { 189 | Player.hasShotgun = true; 190 | Player.hasMachineGun = false; 191 | Player.setFireRate(70); 192 | Player.addAmmo(100); 193 | g_hasCheated = true; 194 | } 195 | 196 | if ((eatKey(KEY_SHIELD) || eatKey(KEY_SHIELDN)) && g_Debug) { 197 | Player.addShieldTime(); 198 | g_hasCheated = true; 199 | } 200 | 201 | if ((eatKey(KEY_PWRUP_RESET) || eatKey(KEY_PWRUP_RESETN)) && g_Debug) { 202 | Player.resetAll(); 203 | g_hasCheated = true; 204 | } 205 | } 206 | 207 | function checkDebugSound() { 208 | 209 | if (eatKey(KEY_DEBUG)) g_Debug = !g_Debug; 210 | 211 | if (eatKey(KEY_SOUND)) g_sounds = !g_sounds; 212 | 213 | if (eatKey(KEY_MUSIC)) g_music = !g_music; 214 | 215 | if (eatKey(KEY_NEXT_SONG) || eatKey(KEY_NEXT_SONGN)) g_bgm.nextSong(); 216 | 217 | if (eatKey(KEY_PREV_SONG) || eatKey(KEY_PREV_SONGN)) g_bgm.prevSong(); 218 | 219 | if (g_music) g_bgm.play(); 220 | else g_bgm.pause(); 221 | 222 | // Background music volume control 223 | var prevVolume = g_bgm.getVolume; 224 | if (eatKey(KEY_VOLUMEUP)) g_bgm.incVolume(); 225 | if (eatKey(KEY_VOLUMEDOWN)) g_bgm.decVolume(); 226 | if (prevVolume !== g_bgm.getVolume) console.log("volume set to: " + g_bgm.getVolume); 227 | } 228 | 229 | // ================= 230 | // RENDER SIMULATION 231 | // ================= 232 | 233 | // We take a very layered approach here... 234 | // 235 | // The primary `render` routine handles generic stuff such as 236 | // the diagnostic toggles (including screen-clearing).1 237 | // 238 | // It then delegates the game-specific logic to `gameRender` 239 | 240 | 241 | // GAME-SPECIFIC RENDERING 242 | 243 | function renderSimulation(ctx) { 244 | 245 | if (levelManager.isInMenu()) { 246 | 247 | levelManager.renderMenu(ctx); 248 | 249 | } else if (levelManager.isChangingLevel() && 250 | !levelManager.isRefreshingLevel()) { 251 | 252 | levelManager.renderLevelChanger(ctx); 253 | 254 | } else if (levelManager.isGameOver()) { 255 | 256 | levelManager.renderGameOver(ctx); 257 | 258 | } else { 259 | 260 | entityManager.render(ctx); 261 | renderCrosshair(ctx); 262 | if (g_Debug) spatialManager.render(ctx); 263 | if (levelManager.isRefreshingLevel) { 264 | levelManager.renderLevelChanger(ctx); 265 | } 266 | } 267 | 268 | Player.render(ctx); 269 | } 270 | 271 | 272 | // ============= 273 | // PRELOAD STUFF 274 | // ============= 275 | 276 | var g_images = {}; 277 | 278 | function requestPreloads() { 279 | var requiredImages = g_imgUrls; 280 | imagesPreload(requiredImages, g_images, preloadDone); 281 | } 282 | 283 | var g_sprites = {}; 284 | 285 | function preloadDone() { 286 | // Static images 287 | g_sprites.Skull = new Sprite(g_images.Skull); 288 | g_sprites.Extralife = new Sprite(g_images.Extralife); 289 | 290 | // Spritesheets 291 | g_sprites.Dad = []; 292 | g_sprites.Mom = []; 293 | g_sprites.Child = []; 294 | g_sprites.Protagonist = []; 295 | g_sprites.Brain = []; 296 | g_sprites.Hulk = []; 297 | g_sprites.Grunt = []; 298 | g_sprites.Electrode = []; 299 | g_sprites.HumanScore = []; 300 | g_sprites.Spheroid = []; 301 | g_sprites.Quark = []; 302 | g_sprites.Tank = []; 303 | g_sprites.Enforcer = []; 304 | g_sprites.EnforcerSpark = []; 305 | g_sprites.PowerUps = []; 306 | g_sprites.Prog = []; 307 | 308 | 309 | for (var i = 0; i < 12; i++) { 310 | g_sprites.Dad.push(new Sprite(g_images.Dad, i*30, (i+1)*30)); 311 | g_sprites.Mom.push(new Sprite(g_images.Mom, i*26, (i+1)*26)); 312 | g_sprites.Child.push(new Sprite(g_images.Child, i*22, (i+1)*22)); 313 | g_sprites.Protagonist.push(new Sprite(g_images.Protagonist, i*26, (i+1)*26)); 314 | g_sprites.Brain.push(new Sprite(g_images.Brain, i*38, (i+1)*38)); 315 | g_sprites.Prog.push(new Sprite(g_images.Prog, i*30, (i+1)*30)); 316 | 317 | } 318 | 319 | g_sprites.Family = g_sprites.Dad.concat(g_sprites.Mom, g_sprites.Child); 320 | 321 | // One of the Brain sprites it misaligned on the spritesheet 322 | g_sprites.Brain[6] = new Sprite(g_images.Brain, 226, 263, 2); 323 | 324 | for (var i = 0; i < 9; i++) { 325 | g_sprites.Hulk.push(new Sprite(g_images.Hulk, i*38, (i+1)*38)); 326 | } 327 | for (var i = 0; i < 3; i++) { 328 | g_sprites.Grunt.push(new Sprite(g_images.Grunt, i*30, (i+1)*30)); 329 | } 330 | for (var i = 0; i < 5; i++) { 331 | g_sprites.HumanScore[i + 1] = new Sprite(g_images.HumanScore, 3 + (i * 34), 37 + (i * 34)); 332 | } 333 | for (var i = 0; i < 6; i++) { 334 | g_sprites.Enforcer.push(new Sprite(g_images.Enforcer, i*29, (i+1)*29)); 335 | for (var j = 0; j < 8; j++) { 336 | g_sprites.PowerUps.push(new Sprite(g_images.PowerUps, j*247/6, (j+1)*247/6, i*330/8, (i+1)*330/8)); 337 | } 338 | } 339 | 340 | // Some of the sprites weren't quite as regularly spaced as the others 341 | // and did not fit nicely in a for loop 342 | g_sprites.Electrode.push(new Sprite(g_images.Triangle, 2, 20)); 343 | g_sprites.Electrode.push(new Sprite(g_images.Triangle, 36, 48)); 344 | g_sprites.Electrode.push(new Sprite(g_images.Triangle, 70, 76)); 345 | g_sprites.Electrode.push(new Sprite(g_images.Square, 6, 22)); 346 | g_sprites.Electrode.push(new Sprite(g_images.Square, 39, 53)); 347 | g_sprites.Electrode.push(new Sprite(g_images.Square, 73, 79)); 348 | g_sprites.Electrode.push(new Sprite(g_images.Rectangle, 5, 15)); 349 | g_sprites.Electrode.push(new Sprite(g_images.Rectangle, 29, 35)); 350 | g_sprites.Electrode.push(new Sprite(g_images.Rectangle, 53, 55)); 351 | g_sprites.Electrode.push(new Sprite(g_images.Dizzy, 7, 26)); 352 | g_sprites.Electrode.push(new Sprite(g_images.Dizzy, 37, 51)); 353 | g_sprites.Electrode.push(new Sprite(g_images.Dizzy, 71, 81)); 354 | g_sprites.Electrode.push(new Sprite(g_images.Diamond, 4, 21)); 355 | g_sprites.Electrode.push(new Sprite(g_images.Diamond, 30, 44)); 356 | g_sprites.Electrode.push(new Sprite(g_images.Diamond, 59, 65)); 357 | g_sprites.Electrode.push(new Sprite(g_images.Checkers, 3, 17)); 358 | g_sprites.Electrode.push(new Sprite(g_images.Checkers, 33, 47)); 359 | g_sprites.Electrode.push(new Sprite(g_images.Checkers, 67, 73)); 360 | g_sprites.Electrode.push(new Sprite(g_images.BlackDiamond, 13, 23, 12, 22)); 361 | g_sprites.Electrode.push(new Sprite(g_images.BlackDiamond, 36, 50, 10, 24)); 362 | g_sprites.Electrode.push(new Sprite(g_images.BlackDiamond, 68, 78, 12, 22)); 363 | 364 | g_sprites.Spheroid.push(new Sprite(g_images.Spheroid, 16, 18, 20, 22)); 365 | g_sprites.Spheroid.push(new Sprite(g_images.Spheroid, 56, 62)); 366 | g_sprites.Spheroid.push(new Sprite(g_images.Spheroid, 96, 106)); 367 | g_sprites.Spheroid.push(new Sprite(g_images.Spheroid, 136, 150)); 368 | g_sprites.Spheroid.push(new Sprite(g_images.Spheroid, 176, 194)); 369 | g_sprites.Spheroid.push(new Sprite(g_images.Spheroid, 216, 238)); 370 | g_sprites.Spheroid.push(new Sprite(g_images.Spheroid, 256, 282)); 371 | g_sprites.Spheroid.push(new Sprite(g_images.Spheroid, 296, 326)); 372 | 373 | g_sprites.Quark.push(new Sprite(g_images.Quark, 16, 22)); 374 | g_sprites.Quark.push(new Sprite(g_images.Quark, 58, 64)); 375 | g_sprites.Quark.push(new Sprite(g_images.Quark, 98, 108)); 376 | g_sprites.Quark.push(new Sprite(g_images.Quark, 138, 152)); 377 | g_sprites.Quark.push(new Sprite(g_images.Quark, 178, 196)); 378 | g_sprites.Quark.push(new Sprite(g_images.Quark, 218, 240)); 379 | g_sprites.Quark.push(new Sprite(g_images.Quark, 258, 284)); 380 | g_sprites.Quark.push(new Sprite(g_images.Quark, 298, 328)); 381 | g_sprites.Quark.push(new Sprite(g_images.Quark, 340, 370)); 382 | 383 | g_sprites.Tank.push(new Sprite(g_images.Tank, 1 , 27)); 384 | g_sprites.Tank.push(new Sprite(g_images.Tank, 39 , 65)); 385 | g_sprites.Tank.push(new Sprite(g_images.Tank, 77 , 103)); 386 | g_sprites.Tank.push(new Sprite(g_images.Tank, 115, 141)); 387 | 388 | g_sprites.EnforcerSpark.push(new Sprite(g_images.EnforcerSpark, 6, 20)); 389 | g_sprites.EnforcerSpark.push(new Sprite(g_images.EnforcerSpark, 34, 44)); 390 | g_sprites.EnforcerSpark.push(new Sprite(g_images.EnforcerSpark, 58, 72)); 391 | g_sprites.EnforcerSpark.push(new Sprite(g_images.EnforcerSpark, 86, 96)); 392 | 393 | util.makeColorArray(); 394 | initializeEntities(); 395 | main.init(); 396 | } 397 | 398 | // Kick it off 399 | requestPreloads(); -------------------------------------------------------------------------------- /core/Sprite.js: -------------------------------------------------------------------------------- 1 | // ============ 2 | // SPRITE STUFF 3 | // ============ 4 | 5 | "use strict"; 6 | 7 | /* jshint browser: true, devel: true, globalstrict: true */ 8 | 9 | /* 10 | 0 1 2 3 4 5 6 7 8 11 | 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12 | */ 13 | 14 | 15 | // Construct a "sprite" from the given `image`, 16 | // 17 | function Sprite(image,leftLim,rightLim,topLim,bottomLim,scale) { 18 | 19 | if(leftLim === undefined) { 20 | this.leftLim = 0; 21 | } else { 22 | this.leftLim = leftLim; 23 | } 24 | if(rightLim === undefined) { 25 | this.rightLim = image.width; 26 | } else { 27 | this.rightLim = rightLim; 28 | } 29 | if(topLim === undefined) { 30 | this.topLim = 0; 31 | } else { 32 | this.topLim = topLim; 33 | } 34 | if(bottomLim === undefined) { 35 | this.bottomLim = image.height; 36 | } else { 37 | this.bottomLim = bottomLim; 38 | } 39 | if (scale === undefined) { 40 | this.scale = 1; 41 | } else { 42 | this.scale = scale; 43 | } 44 | 45 | this.image = image; 46 | 47 | this.width = this.rightLim - this.leftLim; 48 | this.height = this.bottomLim - this.topLim; 49 | } 50 | 51 | Sprite.prototype.drawAt = function (ctx, x, y) { 52 | ctx.drawImage( 53 | this.image, // Image 54 | this.leftLim, // x coordinate to start clipping 55 | this.topLim, // y coordinate to start clipping 56 | this.width, // the width of the clipped image 57 | this.height, // the height of the clipped image 58 | x, 59 | y, 60 | this.width, // final scaled width (scale = 1 here) 61 | this.height // final scaled height (scale = 1 here) 62 | ); 63 | }; 64 | 65 | Sprite.prototype.drawCentredAt = function (ctx, cx, cy, rotation) { 66 | if (rotation === undefined) rotation = 0; 67 | 68 | var w = this.width, 69 | h = this.height; 70 | 71 | ctx.save(); 72 | ctx.translate(cx, cy); 73 | ctx.rotate(rotation); 74 | ctx.scale(this.scale, this.scale); 75 | 76 | // drawImage expects "top-left" coords, so we offset our destination 77 | // coords accordingly, to draw our sprite centred at the origin 78 | this.drawAt(ctx,-w/2, -h/2); 79 | 80 | ctx.restore(); 81 | }; 82 | 83 | Sprite.prototype.drawWrappedCentredAt = function (ctx, cx, cy, rotation) { 84 | 85 | // Get "screen width" 86 | var sw = g_canvas.width; 87 | 88 | // Draw primary instance 89 | this.drawWrappedVerticalCentredAt(ctx, cx, cy, rotation); 90 | 91 | // Left and Right wraps 92 | this.drawWrappedVerticalCentredAt(ctx, cx - sw, cy, rotation); 93 | this.drawWrappedVerticalCentredAt(ctx, cx + sw, cy, rotation); 94 | }; 95 | 96 | Sprite.prototype.drawWrappedVerticalCentredAt = function (ctx, cx, cy, rotation) { 97 | 98 | // Get "screen height" 99 | var sh = g_canvas.height; 100 | 101 | // Draw primary instance 102 | this.drawCentredAt(ctx, cx, cy, rotation); 103 | 104 | // Top and Bottom wraps 105 | this.drawCentredAt(ctx, cx, cy - sh, rotation); 106 | this.drawCentredAt(ctx, cx, cy + sh, rotation); 107 | }; 108 | -------------------------------------------------------------------------------- /core/globals.js: -------------------------------------------------------------------------------- 1 | // ======= 2 | // GLOBALS 3 | // ======= 4 | /* 5 | 6 | Evil, ugly (but "necessary") globals, which everyone can use. 7 | 8 | */ 9 | 10 | "use strict"; 11 | 12 | /* jshint browser: true, devel: true, globalstrict: true */ 13 | 14 | var g_canvas = document.getElementById("myCanvas"); 15 | var g_ctx = g_canvas.getContext("2d"); 16 | 17 | // The "nominal interval" is the one that all of our time-based units are 18 | // calibrated to e.g. a velocity unit is "pixels per nominal interval" 19 | // 20 | var NOMINAL_UPDATE_INTERVAL = 16.666; 21 | 22 | // Multiply by this to convert seconds into "nominals" 23 | var SECS_TO_NOMINALS = 1000 / NOMINAL_UPDATE_INTERVAL; 24 | 25 | // A flag which determines wether the score is eligible 26 | // to be added to the high score list. 27 | var g_hasCheated = false; -------------------------------------------------------------------------------- /core/imagesPreload.js: -------------------------------------------------------------------------------- 1 | // Multi-Image Preloader 2 | 3 | "use strict"; 4 | 5 | /*jslint browser: true, devel: true, white: true */ 6 | 7 | var canvas = document.getElementById("myCanvas"); 8 | var ctx = canvas.getContext("2d"); 9 | 10 | /* 11 | 0 1 2 3 4 5 6 7 8 12 | 12345678901234567890123456789012345678901234567890123456789012345678901234567890 13 | */ 14 | 15 | // Extend the Image prototype (aka augment the "class") 16 | // with my asyncLoad wrapper. 17 | // 18 | // I prefer this approach to setting onload/onerror/src directly. 19 | // 20 | Image.prototype.asyncLoad = function(src, asyncCallback) { 21 | 22 | // Must assign the callback handlers before setting `this.src`, 23 | // for safety (and caching-tolerance). 24 | // 25 | // Uses the same handler for success *and* failure, 26 | // because they share a lot of the same logic. 27 | // 28 | // NB: The failure case can be identified by the "degenerate" nature 29 | // of the resulting "loaded" image e.g. test for this.width === 0 30 | // 31 | this.onload = asyncCallback; 32 | this.onerror = asyncCallback; 33 | 34 | // NB: The load operation can be triggered from any point 35 | // after setting `this.src`. 36 | // 37 | // It *may* happen immediately (on some browsers) if the image is already 38 | // in-cache, but will most likely happen some time later when the load has 39 | // occurred and the resulting event is processesd in the queue. 40 | 41 | console.log("requesting image src of ", src); 42 | this.src = src; 43 | }; 44 | 45 | 46 | // imagePreload 47 | // 48 | // Horrible stuff to deal with the asynchronous nature of image-loading 49 | // in the browser... 50 | // 51 | // It requires setting-up a bunch of handler callbacks and then waiting for them 52 | // *all* to be exectued before finally triggering our own `completionCallback`. 53 | // 54 | // Makes use of "closures" to handle the necessary state-tracking between the 55 | // intermediate callback handlers without resorting to global variables. 56 | // 57 | // IN : `requiredImages` - an object of pairs for each image 58 | // OUT : `loadedImages` - object to which our pairs will be added 59 | // IN : `completionCallback` - will be executed when everything is done 60 | // 61 | function imagesPreload(requiredImages, 62 | loadedImages, 63 | completionCallback) { 64 | 65 | var numImagesRequired, 66 | numImagesHandled = 0, 67 | currentName, 68 | currentImage, 69 | preloadHandler; 70 | 71 | // Count our `requiredImages` by using `Object.keys` to get all 72 | // "*OWN* enumerable properties" i.e. doesn't traverse the prototype chain 73 | numImagesRequired = Object.keys(requiredImages).length; 74 | 75 | // A handler which will be called when our required images are finally 76 | // loaded (or when the fail to load). 77 | // 78 | // At the time of the call, `this` will point to an Image object, 79 | // whose `name` property will have been set appropriately. 80 | // 81 | preloadHandler = function () { 82 | 83 | console.log("preloadHandler called with this=", this); 84 | loadedImages[this.name] = this; 85 | 86 | if (0 === this.width) { 87 | console.log("loading failed for", this.name); 88 | } 89 | 90 | // Allow this handler closure to eventually be GC'd (!) 91 | this.onload = null; 92 | this.onerror = null; 93 | 94 | numImagesHandled += 1; 95 | 96 | if (numImagesHandled === numImagesRequired) { 97 | console.log("all preload images handled"); 98 | console.log("loadedImages=", loadedImages); 99 | console.log(""); 100 | console.log("performing completion callback"); 101 | 102 | completionCallback(); 103 | 104 | console.log("completion callback done"); 105 | console.log(""); 106 | } 107 | }; 108 | 109 | // The "for..in" construct "iterates over the enumerable properties 110 | // of an object, in arbitrary order." 111 | // -- unlike `Object.keys`, it traverses the prototype chain 112 | // 113 | for (currentName in requiredImages) { 114 | 115 | // Skip inherited properties from the prototype chain, 116 | // just to be safe, although there shouldn't be any... 117 | 118 | // I prefer this approach, but JSLint doesn't like "continue" :-( 119 | //if (!requiredImages.hasOwnProperty(currentName)) { continue; } 120 | 121 | if (requiredImages.hasOwnProperty(currentName)) { 122 | 123 | console.log("preloading image", currentName); 124 | currentImage = new Image(); 125 | currentImage.name = currentName; 126 | 127 | currentImage.asyncLoad(requiredImages[currentName], preloadHandler); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /core/keys.js: -------------------------------------------------------------------------------- 1 | // ================= 2 | // KEYBOARD HANDLING 3 | // ================= 4 | 5 | var keys = []; 6 | //space, left, up, right, down: 7 | var _prevents = [' '.charCodeAt(0), 37, 38, 39, 40]; 8 | 9 | function handleKeydown(evt) { 10 | //This will prevent the browser from doing things you don't want it to, like scrolling the page. 11 | for (var i = 0; i<_prevents.length; i++) { 12 | if (evt.keyCode===_prevents[i] && document.getElementById("formDiv").className !== "") { 13 | evt.preventDefault(); 14 | } 15 | } 16 | if (document.getElementById("formDiv").className !== "") { 17 | keys[evt.keyCode] = true; 18 | } 19 | } 20 | 21 | function handleKeyup(evt) { 22 | keys[evt.keyCode] = false; 23 | } 24 | 25 | // Inspects, and then clears, a key's state 26 | // 27 | // This allows a keypress to be "one-shot" e.g. for toggles 28 | // ..until the auto-repeat kicks in, that is. 29 | // 30 | function eatKey(keyCode) { 31 | var isDown = keys[keyCode]; 32 | keys[keyCode] = false; 33 | return isDown; 34 | } 35 | 36 | // A tiny little convenience function 37 | function keyCode(keyChar) { 38 | return keyChar.charCodeAt(0); 39 | } 40 | 41 | window.addEventListener("keydown", handleKeydown); 42 | window.addEventListener("keyup", handleKeyup); 43 | -------------------------------------------------------------------------------- /core/main.js: -------------------------------------------------------------------------------- 1 | // ======== 2 | // MAINLOOP 3 | // ======== 4 | /* 5 | 6 | The mainloop is one big object with a fairly small public interface 7 | (e.g. init, iter, gameOver), and a bunch of private internal helper methods. 8 | 9 | The "private" members are identified as such purely by the naming convention 10 | of having them begin with a leading underscore. A more robust form of privacy, 11 | with genuine name-hiding *is* possible in JavaScript (via closures), but I 12 | haven't adopted it here. 13 | 14 | */ 15 | 16 | "use strict"; 17 | 18 | /* jshint browser: true, devel: true, globalstrict: true */ 19 | 20 | /* 21 | 0 1 2 3 4 5 6 7 8 22 | 12345678901234567890123456789012345678901234567890123456789012345678901234567890 23 | */ 24 | 25 | 26 | var main = { 27 | 28 | // "Frame Time" is a (potentially high-precision) frame-clock for animations 29 | _frameTime_ms : null, 30 | _frameTimeDelta_ms : null, 31 | 32 | }; 33 | 34 | // Perform one iteration of the mainloop 35 | main.iter = function (frameTime) { 36 | 37 | // Use the given frameTime to update all of our game-clocks 38 | this._updateClocks(frameTime); 39 | 40 | // Perform the iteration core to do all the "real" work 41 | this._iterCore(this._frameTimeDelta_ms); 42 | 43 | // Diagnostics, such as showing current timer values etc. 44 | this._debugRender(g_ctx); 45 | 46 | // Request the next iteration if needed 47 | if (!this._isGameOver) this._requestNextIteration(); 48 | }; 49 | 50 | main._updateClocks = function (frameTime) { 51 | 52 | // First-time initialisation 53 | if (this._frameTime_ms === null) this._frameTime_ms = frameTime; 54 | 55 | // Track frameTime and its delta 56 | this._frameTimeDelta_ms = frameTime - this._frameTime_ms; 57 | this._frameTime_ms = frameTime; 58 | }; 59 | 60 | main._iterCore = function (dt) { 61 | 62 | // Handle QUIT 63 | if (requestedQuit()) { 64 | this.gameOver(); 65 | return; 66 | } 67 | 68 | gatherInputs(); 69 | update(dt); 70 | render(g_ctx); 71 | }; 72 | 73 | main._isGameOver = false; 74 | 75 | main.gameOver = function () { 76 | this._isGameOver = true; 77 | g_bgm.pause(); 78 | console.log("gameOver: quitting..."); 79 | }; 80 | 81 | // Simple voluntary quit mechanism 82 | // 83 | var KEY_ESCAPE = 27; // Esc-key 84 | function requestedQuit() { 85 | return keys[KEY_ESCAPE]; 86 | } 87 | 88 | // Annoying shim for Firefox and Safari 89 | window.requestAnimationFrame = 90 | window.requestAnimationFrame || // Chrome 91 | window.mozRequestAnimationFrame || // Firefox 92 | window.webkitRequestAnimationFrame; // Safari 93 | 94 | // This needs to be a "global" function, for the "window" APIs to callback to 95 | function mainIterFrame(frameTime) { 96 | main.iter(frameTime); 97 | } 98 | 99 | main._requestNextIteration = function () { 100 | window.requestAnimationFrame(mainIterFrame); 101 | }; 102 | 103 | // Mainloop-level debug-rendering 104 | 105 | var TOGGLE_TIMER_SHOW = 'T'.charCodeAt(0); 106 | 107 | main._doTimerShow = false; 108 | 109 | main._debugRender = function (ctx) { 110 | 111 | if (eatKey(TOGGLE_TIMER_SHOW)) this._doTimerShow = !this._doTimerShow; 112 | 113 | if (!this._doTimerShow) return; 114 | 115 | var y = 350; 116 | ctx.fillText('FT ' + this._frameTime_ms, 50, y+10); 117 | ctx.fillText('FD ' + this._frameTimeDelta_ms, 50, y+20); 118 | ctx.fillText('UU ' + g_prevUpdateDu, 50, y+30); 119 | ctx.fillText('FrameSync ON', 50, y+40); 120 | }; 121 | 122 | main.init = function () { 123 | 124 | // Grabbing focus is good, but it sometimes screws up jsfiddle, 125 | // so it's a risky option during "development" 126 | // 127 | window.focus(true); 128 | 129 | // We'll be working on a black background here, 130 | // so let's use a fillStyle which works against that... 131 | // 132 | g_ctx.fillStyle = "white"; 133 | 134 | this._requestNextIteration(); 135 | }; 136 | -------------------------------------------------------------------------------- /core/render.js: -------------------------------------------------------------------------------- 1 | // GENERIC RENDERING 2 | 3 | var g_doClear = true; 4 | var g_doBox = false; 5 | var g_undoBox = false; 6 | var g_doFlipFlop = false; 7 | var g_doRender = true; 8 | 9 | var g_frameCounter = 1; 10 | var g_pauseRenderDu = 0; 11 | 12 | var TOGGLE_CLEAR = 'C'.charCodeAt(0); 13 | var TOGGLE_BOX = 'B'.charCodeAt(0); 14 | var TOGGLE_UNDO_BOX = 'U'.charCodeAt(0); 15 | var TOGGLE_FLIPFLOP = 'F'.charCodeAt(0); 16 | var TOGGLE_RENDER = 'R'.charCodeAt(0); 17 | 18 | function render(ctx) { 19 | 20 | // Process various option toggles 21 | // 22 | if (eatKey(TOGGLE_CLEAR) && g_Debug) g_doClear = !g_doClear; 23 | if (eatKey(TOGGLE_BOX) && g_Debug) g_doBox = !g_doBox; 24 | if (eatKey(TOGGLE_UNDO_BOX) && g_Debug) g_undoBox = !g_undoBox; 25 | if (eatKey(TOGGLE_FLIPFLOP) && g_Debug) g_doFlipFlop = !g_doFlipFlop; 26 | if (eatKey(TOGGLE_RENDER) && g_Debug) g_doRender = !g_doRender; 27 | 28 | // I've pulled the clear out of `renderSimulation()` and into 29 | // here, so that it becomes part of our "diagnostic" wrappers 30 | // 31 | if (g_doClear) util.clearCanvas(ctx); 32 | 33 | // The main purpose of the box is to demonstrate that it is 34 | // always deleted by the subsequent "undo" before you get to 35 | // see it... 36 | // 37 | // i.e. double-buffering prevents flicker! 38 | // 39 | if (g_doBox) util.fillBox(ctx, 200, 200, 50, 50, "red"); 40 | 41 | 42 | // The core rendering of the actual game / simulation 43 | // 44 | if (g_doRender) renderSimulation(ctx); 45 | else { 46 | // Alerts if rendering is disabled 47 | ctx.save(); 48 | var str = "RENDERING DISABLED" , hw = g_canvas.width / 2, h = g_canvas.height; 49 | ctx.textAlign = "center"; 50 | ctx.fillStyle ="white"; 51 | ctx.font = "bold 40px sans-serif"; 52 | ctx.fillText(str, hw, h * 19 / 40); 53 | 54 | str = "Press R in Pause Mode to reenable rendering"; 55 | ctx.font = "bold 28px sans-serif"; 56 | ctx.fillText(str, hw, h * 21 / 40); 57 | ctx.restore(); 58 | } 59 | 60 | 61 | // This flip-flip mechanism illustrates the pattern of alternation 62 | // between frames, which provides a crude illustration of whether 63 | // we are running "in sync" with the display refresh rate. 64 | // 65 | // e.g. in pathological cases, we might only see the "even" frames. 66 | // 67 | if (g_doFlipFlop) { 68 | var boxX = 250, 69 | boxY = g_isUpdateOdd ? 100 : 200; 70 | 71 | // Draw flip-flop box 72 | util.fillBox(ctx, boxX, boxY, 50, 50, "green"); 73 | 74 | // Display the current frame-counter in the box... 75 | ctx.fillText(g_frameCounter % 1000, boxX + 10, boxY + 20); 76 | // ..and its odd/even status too 77 | var text = g_frameCounter % 2 ? "odd" : "even"; 78 | ctx.fillText(text, boxX + 10, boxY + 40); 79 | } 80 | 81 | // Optional erasure of diagnostic "box", 82 | // to illustrate flicker-proof double-buffering 83 | // 84 | if (g_undoBox) ctx.clearRect(200, 200, 50, 50); 85 | 86 | ++g_frameCounter; 87 | 88 | // Render pause screen with flashing effect 89 | // and handle stepping and reset pause du 90 | // if skipping (e.g. due to pause-mode) 91 | // 92 | if (g_isUpdatePaused && !g_isStepping) { 93 | renderPause(ctx); 94 | if (g_pauseRenderDu < 0.75 * SECS_TO_NOMINALS) return; 95 | } 96 | if (g_isStepping) { 97 | g_isStepping = false; 98 | renderPause(ctx); 99 | } 100 | if (g_pauseRenderDu >= 1.5 * SECS_TO_NOMINALS) { 101 | g_pauseRenderDu = 0; 102 | } 103 | } 104 | 105 | function renderPause(ctx) { 106 | if (g_pauseRenderDu < 0.75 * SECS_TO_NOMINALS) { 107 | ctx.save(); 108 | var str = "PAUSED" , hw = g_canvas.width / 2, h = g_canvas.height; 109 | ctx.textAlign = "center"; 110 | ctx.fillStyle ="white"; 111 | ctx.font = "bold 20px sans-serif"; 112 | ctx.fillText(str, hw, h * 38 / 40); 113 | 114 | str = "Press P to resume"; 115 | ctx.font = "bold 10px sans-serif"; 116 | ctx.fillText(str, hw, h * 39 / 40); 117 | ctx.restore(); 118 | } 119 | } -------------------------------------------------------------------------------- /core/update.js: -------------------------------------------------------------------------------- 1 | // GENERIC UPDATE LOGIC 2 | 3 | // The "nominal interval" is the one that all of our time-based units are 4 | // calibrated to e.g. a velocity unit is "pixels per nominal interval" 5 | // 6 | var NOMINAL_UPDATE_INTERVAL = 16.666; 7 | 8 | // Dt means "delta time" and is in units of the timer-system (i.e. milliseconds) 9 | // 10 | var g_prevUpdateDt = null; 11 | 12 | // Du means "delta u", where u represents time in multiples of our nominal interval 13 | // 14 | var g_prevUpdateDu = null; 15 | 16 | // Track odds and evens for diagnostic / illustrative purposes 17 | // 18 | var g_isUpdateOdd = false; 19 | 20 | 21 | function update(dt) { 22 | 23 | checkDebugSound(); 24 | 25 | // Remember this for later 26 | // 27 | var original_dt = dt; 28 | 29 | // Warn about very large dt values -- they may lead to error 30 | // 31 | if (dt > 200) { 32 | console.log("Big dt =", dt, ": CLAMPING TO NOMINAL"); 33 | dt = NOMINAL_UPDATE_INTERVAL; 34 | } 35 | 36 | // If using variable time, divide the actual delta by the "nominal" rate, 37 | // giving us a conveniently scaled "du" to work with. 38 | // 39 | var du = (dt / NOMINAL_UPDATE_INTERVAL); 40 | 41 | // Get out if skipping (e.g. due to pause-mode) 42 | // 43 | if (shouldSkipUpdate()) { 44 | g_pauseRenderDu += du; 45 | return; 46 | } 47 | 48 | updateSimulation(du); 49 | 50 | g_prevUpdateDt = original_dt; 51 | g_prevUpdateDu = du; 52 | 53 | g_isUpdateOdd = !g_isUpdateOdd; 54 | } 55 | 56 | // Togglable Pause Mode 57 | // 58 | var KEY_PAUSE = 'P'.charCodeAt(0); 59 | var KEY_STEP = 'O'.charCodeAt(0); 60 | 61 | var g_isUpdatePaused = false; 62 | var g_isStepping = false; 63 | 64 | function shouldSkipUpdate() { 65 | if (eatKey(KEY_PAUSE)) { 66 | g_isUpdatePaused = !g_isUpdatePaused; 67 | } 68 | if (eatKey(KEY_STEP)) { 69 | g_isStepping = true; 70 | } 71 | return g_isUpdatePaused && !g_isStepping; 72 | } -------------------------------------------------------------------------------- /core/userInput.js: -------------------------------------------------------------------------------- 1 | // ================= 2 | // User text input HANDLING 3 | // ================= 4 | 5 | document.addEventListener("DOMContentLoaded",function(){ 6 | var form = document.getElementById("form"); 7 | form.addEventListener("submit", add, false); 8 | }); 9 | 10 | function add(e) { 11 | e.preventDefault(); 12 | postScore(); 13 | $("#formDiv").addClass("hidden"); 14 | } 15 | 16 | function postScore() { 17 | var str = document.getElementById("text"); 18 | var name = str.value; 19 | if(name!==""){ 20 | var xmlhttp; 21 | if (window.XMLHttpRequest) { 22 | // code for IE7+, Firefox, Chrome, Opera, Safari 23 | xmlhttp=new XMLHttpRequest(); 24 | } else { // code for IE6, IE5 25 | xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 26 | } 27 | xmlhttp.onreadystatechange=function() { 28 | if (xmlhttp.readyState==4 && xmlhttp.status==200) { 29 | if($("#highscoreTable").length===0) $("li#navHS").removeClass("hidden"); 30 | document.getElementById("output").innerHTML=xmlhttp.responseText; 31 | highScores.setName(name); 32 | highScores.addLocalScore({name: highScores.getName(), score: Player.score}); 33 | highScores.resetServerScore(); 34 | var tr = $("#highscoreTable tbody").find("tr"); 35 | for (var i = 1; i <= tr.length; i++) { 36 | console.log(tr[i-1].children[1].innerHTML); 37 | highScores.addServerScore({ 38 | name: tr[i-1].children[1].innerHTML, 39 | score: parseInt(tr[i-1].children[2].innerHTML) 40 | }); 41 | } 42 | $("#highscore").click(function() {$(this).parent().find("article").toggle("slow");}); 43 | } 44 | } 45 | if (!g_hasCheated) { 46 | xmlhttp.open("POST","phplogic/savescore.php?name="+name+"&score="+Player.getScore(),true); 47 | xmlhttp.send(); 48 | } 49 | } 50 | highScores.renderON(); 51 | } -------------------------------------------------------------------------------- /entities/Brain.js: -------------------------------------------------------------------------------- 1 | // ====== 2 | // Brain 3 | // ====== 4 | 5 | // Brains launch seeking cruise missiles 6 | // Brains turn family members into Progs 7 | 8 | "use strict"; 9 | 10 | /* jshint browser: true, devel: true, globalstrict: true */ 11 | 12 | function Brain(descr) { 13 | Enemy.call(this, descr); 14 | 15 | this.sprite = g_sprites.Brain[6]; 16 | if (g_sounds) { 17 | this.spawnSound.volume = 0.5; 18 | this.spawnSound.play(); 19 | } 20 | 21 | this.makeWarpParticles(); 22 | } 23 | 24 | Brain.prototype = Object.create(Enemy.prototype); 25 | 26 | // HACKED-IN AUDIO (no preloading) 27 | Brain.prototype.spawnSound = new Audio(g_audioUrls.brains); 28 | 29 | Brain.prototype.killFamily = true; 30 | Brain.prototype.renderPos = {cx: this.cx, cy: this.cy}; 31 | Brain.prototype.stepsize = 3; 32 | Brain.prototype.makesProgs = true; 33 | Brain.prototype.missileFireChance = 0.005; // 0.5% chance of firing a CM per update 34 | // TODO: Find a good firing interval for the missiles. 35 | Brain.prototype.dropChance = 0.9; // 90% chance of a random drop 36 | Brain.prototype.bootTime = SECS_TO_NOMINALS; 37 | Brain.prototype.facing = 0; 38 | 39 | Brain.prototype.update = function (du) { 40 | if (this.bootTime >= 0) this.bootTime += -du; 41 | 42 | spatialManager.unregister(this); 43 | 44 | if (!this.startPos) this.startPos = this.getPos(); 45 | 46 | // Handle death 47 | if (this._isDeadNow) { 48 | Player.addScore(Player.scoreValues.Brain * Player.getMultiplier()); 49 | return entityManager.KILL_ME_NOW; 50 | } 51 | 52 | if (this.isSpawning) { 53 | this.warpIn(du); 54 | } else { 55 | this.seekTarget(); 56 | 57 | if (Math.random() < this.missileFireChance) { 58 | entityManager.fireCruiseMissile(this.cx, this.cy); 59 | } 60 | 61 | this.cx += this.velX * du; 62 | this.cy += this.velY * du; 63 | this.capPositions(); 64 | } 65 | spatialManager.register(this); 66 | }; 67 | 68 | 69 | Brain.prototype.seekTarget = function () { 70 | 71 | this.findTarget(); 72 | if (this.target === null || this.target === undefined) { 73 | return; // Escaping empty-field conditions that can occur in testing 74 | } 75 | 76 | var xOffset = this.target.cx - this.cx; 77 | var yOffset = this.target.cy - this.cy; 78 | 79 | if (this.bootTime < 0) { 80 | this.velX = 0; 81 | if (xOffset > 0) { 82 | this.velX = 0.5; 83 | } else if (xOffset < 0) { 84 | this.velX = -1; 85 | } 86 | 87 | this.velY = 0; 88 | if (yOffset > 0) { 89 | this.velY = 1; 90 | } else if (yOffset < 0) { 91 | this.velY = -0.5; 92 | } 93 | } 94 | 95 | // Clamp vel to 1 pixel moving radius 96 | if (xOffset !== 0 && yOffset !== 0) { 97 | this.velX *= Math.cos(Math.PI / 4); 98 | this.velY *= Math.sin(Math.PI / 4); 99 | } 100 | }; 101 | 102 | Brain.prototype.findTarget = function () { 103 | // Brains prefer family members. 104 | this.target = entityManager.findClosestFamilyMember(this.cx, this.cy); 105 | if (this.target === null || this.target === undefined) { 106 | this.target = entityManager.findProtagonist(); 107 | } 108 | }; 109 | 110 | Brain.prototype.takeBulletHit = function () { 111 | this.kill(); 112 | this.makeExplosion(); 113 | }; 114 | 115 | Brain.prototype.render = function (ctx) { 116 | if (this.isSpawning) { 117 | return; 118 | } 119 | 120 | var distSq = util.distSq( 121 | this.cx, 122 | this.cy, 123 | this.renderPos.cx, 124 | this.renderPos.cy); 125 | var PI = Math.PI; 126 | if (distSq === 0) { 127 | var angle = 0; 128 | } else { 129 | var angle = util.wrapRange( 130 | util.angleTo( 131 | this.renderPos.cx, 132 | this.renderPos.cy, 133 | this.cx, 134 | this.cy), 135 | 0, 136 | 2 * PI); 137 | } 138 | 139 | if (distSq > 0.1) { 140 | this.facing = 3; // right 141 | if (angle > PI * 1 / 4) this.facing = 6; //down 142 | if (angle > PI * 3 / 4) this.facing = 0; //left 143 | if (angle > PI * 5 / 4) this.facing = 9; //up 144 | if (angle > PI * 7 / 4) this.facing = 3; //right 145 | } 146 | 147 | var temp; 148 | switch (true) { 149 | case distSq < util.square(this.stepsize): 150 | temp = 0; 151 | break; 152 | case distSq < util.square(this.stepsize * 2): 153 | temp = 1; 154 | break; 155 | case distSq < util.square(this.stepsize * 3): 156 | temp = 0; 157 | break; 158 | case distSq < util.square(this.stepsize * 4): 159 | temp = 2; 160 | break; 161 | default: 162 | temp = 0; 163 | this.renderPos = {cx: this.cx, cy: this.cy}; 164 | } 165 | g_sprites.Brain[this.facing + temp].drawCentredAt(ctx, this.cx, this.cy, 0); 166 | }; 167 | 168 | 169 | Brain.prototype.colors = [ 170 | {color: "blue", ratio: 0.70}, 171 | {color: "#B90CF1", ratio: 0.10}, 172 | {color: "#08FF03", ratio: 0.20} 173 | ]; 174 | -------------------------------------------------------------------------------- /entities/Bullet.js: -------------------------------------------------------------------------------- 1 | // ====== 2 | // BULLET 3 | // ====== 4 | 5 | "use strict"; 6 | 7 | /* jshint browser: true, devel: true, globalstrict: true */ 8 | 9 | /* 10 | 0 1 2 3 4 5 6 7 8 11 | 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12 | */ 13 | 14 | 15 | // A generic contructor which accepts an arbitrary descriptor object 16 | function Bullet(descr) { 17 | 18 | // Common inherited setup logic from Entity 19 | this.setup(descr); 20 | 21 | // Make a noise when I am created (i.e. fired) 22 | //this.fireSound.currentTime = 0; 23 | if (g_sounds) { 24 | if (!Player.hasMachineGun && !Player.hasShotgun) { 25 | var gunSound = new Audio(g_audioUrls.shot); 26 | gunSound.volume = 0.6; 27 | gunSound.play(); 28 | } 29 | if (Player.hasMachineGun) { 30 | var gunSound = new Audio(g_audioUrls.machineGun); 31 | gunSound.volume = 0.8; 32 | gunSound.play(); 33 | } 34 | if (Player.hasShotgun) { 35 | if (this.shotgunFire.currentTime > 0.5) this.shotgunFire.currentTime = 0; 36 | this.shotgunFire.play(); 37 | } 38 | } 39 | } 40 | 41 | Bullet.prototype = new Entity(); 42 | 43 | // Initial, inheritable, default values 44 | Bullet.prototype.shotgunFire = new Audio(g_audioUrls.shotgunFire); 45 | Bullet.prototype.rotation = 0; 46 | Bullet.prototype.bulletVel = 10; 47 | Bullet.prototype.velX = 1; 48 | Bullet.prototype.velY = 1; 49 | // Convert times from milliseconds to "nominal" time units. 50 | Bullet.prototype.lifeSpan = 3 * SECS_TO_NOMINALS; 51 | 52 | Bullet.prototype.update = function (du) { 53 | 54 | spatialManager.unregister(this); 55 | 56 | // Handle death 57 | this.lifeSpan -= du; 58 | if (this.lifeSpan < 0) return entityManager.KILL_ME_NOW; 59 | 60 | this.capPositions(); 61 | if(this.edgeBounce()) { 62 | if (Player.hasMachineGun) this.spawnFragment(5,"cyan"); 63 | if (Player.hasShotgun) this.spawnFragment(5,"orange"); 64 | if (!Player.hasMachineGun && !Player.hasShotgun) this.spawnFragment(5,"lime"); 65 | return entityManager.KILL_ME_NOW; 66 | } 67 | 68 | // Update positions 69 | this.velX = this.bulletVel * this.dirnX; 70 | this.velY = this.bulletVel * this.dirnY; 71 | 72 | this.prevX = this.cx; 73 | this.prevY = this.cy; 74 | 75 | this.cx += this.velX * du; 76 | this.cy += this.velY * du; 77 | 78 | this.rotation += 1 * du; 79 | this.rotation = util.wrapRange(this.rotation, 80 | 0, consts.FULL_CIRCLE); 81 | 82 | // Handle collisions 83 | var hitEntity = this.findHitEntity(); 84 | if (hitEntity) { 85 | // The bulletVel check is a hack to stop the shotgun bullets 86 | // from killing each other on spawn 87 | if (!hitEntity.bulletVel) { 88 | var canTakeHit = hitEntity.takeBulletHit; 89 | var canFriendlyHit = hitEntity.takeFriendlyHit; 90 | var descr = {velX : this.velX, velY : this.velY, du : du}; 91 | if (canTakeHit || (g_friendlyFire && canFriendlyHit)) { 92 | if (canTakeHit) { 93 | // Enemy takes the hit and removed from collision check 94 | canTakeHit.call(hitEntity, descr); 95 | spatialManager.unregister(hitEntity); 96 | } else { 97 | canFriendlyHit.call(hitEntity); 98 | spatialManager.unregister(hitEntity); 99 | } 100 | if (Player.hasMachineGun) this.spawnFragment(5,"cyan"); 101 | if (Player.hasShotgun) this.spawnFragment(5,"orange"); 102 | if (!Player.hasMachineGun && !Player.hasShotgun) this.spawnFragment(5,"lime"); 103 | return entityManager.KILL_ME_NOW; 104 | } 105 | } 106 | } 107 | 108 | spatialManager.register(this); 109 | }; 110 | 111 | Bullet.prototype.getRadius = function () { 112 | return 4; 113 | }; 114 | 115 | Bullet.prototype.render = function (ctx) { 116 | switch(true){ 117 | case Player.hasShotgun: 118 | ctx.save(); 119 | ctx.fillStyle = "white"; 120 | ctx.globalAlpha = 0.3; 121 | util.fillCircle(ctx, this.cx, this.cy, 6); 122 | ctx.fillStyle = "orange"; 123 | ctx.globalAlpha = 0.6; 124 | util.fillCircle(ctx, this.cx, this.cy, 4); 125 | ctx.globalAlpha = 0.8; 126 | util.fillCircle(ctx, this.cx, this.cy, 3); 127 | ctx.fillStyle = "white"; 128 | ctx.globalAlpha = 1; 129 | util.fillCircle(ctx, this.cx, this.cy, 1); 130 | ctx.restore(); 131 | break; 132 | case Player.hasMachineGun: 133 | ctx.save(); 134 | ctx.strokeStyle = "cyan"; 135 | ctx.fillStyle = "cyan"; 136 | 137 | var dirn = util.angleTo(this.cx, this.cy, this.prevX, this.prevY); 138 | var x = this.cx + 10 * Math.cos(dirn); 139 | var y = this.cy + 10 * Math.sin(dirn); 140 | 141 | ctx.globalAlpha = 0.4; 142 | ctx.beginPath(); 143 | ctx.moveTo(this.cx, this.cy); 144 | ctx.lineTo(x, y); 145 | ctx.lineWidth = 8; 146 | ctx.stroke(); 147 | util.fillCircle(ctx, this.cx, this.cy, 4); 148 | 149 | ctx.globalAlpha = 0.6; 150 | ctx.beginPath(); 151 | ctx.moveTo(this.cx, this.cy); 152 | ctx.lineTo(x, y); 153 | ctx.lineWidth = 4; 154 | ctx.stroke(); 155 | util.fillCircle(ctx, this.cx, this.cy, 2); 156 | 157 | ctx.strokeStyle = "white"; 158 | ctx.fillStyle = "white"; 159 | ctx.globalAlpha = 1; 160 | ctx.beginPath(); 161 | ctx.moveTo(this.cx, this.cy); 162 | ctx.lineTo(x, y); 163 | ctx.lineWidth = 2; 164 | ctx.stroke(); 165 | 166 | ctx.restore(); 167 | break; 168 | default: 169 | ctx.save(); 170 | ctx.fillStyle = "white"; 171 | ctx.globalAlpha = 0.5; 172 | util.fillCircle(ctx, this.cx, this.cy, 6); 173 | ctx.fillStyle = "lime"; 174 | ctx.globalAlpha = 0.8; 175 | util.fillCircle(ctx, this.cx, this.cy, 4); 176 | ctx.fillStyle = "white"; 177 | ctx.globalAlpha = 1; 178 | util.fillCircle(ctx, this.cx, this.cy, 2); 179 | ctx.restore(); 180 | } 181 | }; 182 | -------------------------------------------------------------------------------- /entities/CruiseMissile.js: -------------------------------------------------------------------------------- 1 | // ============== 2 | // Cruise Missile 3 | // ============== 4 | 5 | // Cruise missiles are periodically fired by Brains 6 | 7 | "use strict"; 8 | 9 | /* jshint browser: true, devel: true, globalstrict: true */ 10 | 11 | // A generic contructor which accepts an arbitrary descriptor object 12 | function CruiseMissile(descr) { 13 | 14 | // Common inherited setup logic from Entity 15 | this.setup(descr); 16 | 17 | // HACKED-IN AUDIO (no preloading) 18 | this.bombSound = new Audio(g_audioUrls.explosion); 19 | this.bombSound.volume = 0.5; 20 | 21 | this.target = entityManager.findProtagonist(); 22 | } 23 | 24 | CruiseMissile.prototype = new Entity(); 25 | CruiseMissile.prototype.lifeSpan = 5 * SECS_TO_NOMINALS; 26 | CruiseMissile.prototype.baseVel = 2; 27 | CruiseMissile.prototype.exploded = false; 28 | 29 | CruiseMissile.prototype.update = function (du) { 30 | 31 | spatialManager.unregister(this); 32 | 33 | // Handle death 34 | if (this.target === null || this.target === undefined) { 35 | this._isDeadNow = true; 36 | } 37 | 38 | if(this._isDeadNow) { 39 | this.spawnFragment(12); 40 | if (g_sounds) this.bombSound.play(); 41 | Player.addScore(Player.scoreValues.CruiseMissile * Player.getMultiplier()); 42 | return entityManager.KILL_ME_NOW; 43 | } 44 | 45 | this.lifeSpan -= du; 46 | if (this.lifeSpan < 0) { 47 | this.spawnFragment(12); 48 | if (g_sounds) this.bombSound.play(); 49 | return entityManager.KILL_ME_NOW; 50 | } 51 | 52 | // Update positions 53 | this.seekTarget(); 54 | 55 | this.cx += this.velX * du; 56 | this.cy += this.velY * du; 57 | 58 | // Handle collisions 59 | var hitEntity = this.findHitEntity(); 60 | if (hitEntity) { 61 | var canTakeHit = hitEntity.takeEnemyHit; 62 | if (canTakeHit) { 63 | canTakeHit.call(hitEntity); 64 | this.spawnFragment(12); 65 | if (g_sounds) this.bombSound.play(); 66 | return entityManager.KILL_ME_NOW; 67 | } 68 | } 69 | 70 | spatialManager.register(this); 71 | }; 72 | 73 | CruiseMissile.prototype.seekTarget = function () { 74 | var xOffset = this.target.cx - this.cx; 75 | var yOffset = this.target.cy - this.cy; 76 | 77 | this.velX = 0; 78 | if (xOffset > 0) { 79 | this.velX = this.baseVel; 80 | } else if (xOffset < 0) { 81 | this.velX = -this.baseVel; 82 | } 83 | 84 | this.velY = 0; 85 | if (yOffset > 0) { 86 | this.velY = this.baseVel; 87 | } else if (yOffset < 0) { 88 | this.velY = -this.baseVel; 89 | } 90 | 91 | // Clamp velocity to the radius of this.baseVel 92 | if (this.velX !== 0 && this.velY !== 0) { 93 | this.velX *= Math.cos(Math.PI / 4); 94 | this.velY *= Math.sin(Math.PI / 4); 95 | } 96 | }; 97 | 98 | CruiseMissile.prototype.takeBulletHit = function () { 99 | this.kill(); 100 | }; 101 | 102 | CruiseMissile.prototype.getRadius = function () { 103 | return 4; 104 | }; 105 | 106 | CruiseMissile.prototype.render = function (ctx) { 107 | ctx.save(); 108 | var bombThresh = CruiseMissile.prototype.lifeSpan / 15; 109 | ctx.fillStyle = "grey"; 110 | util.fillCircle(ctx, this.cx, this.cy, this.getRadius()); 111 | var descr = { 112 | cx: this.cx, 113 | cy: this.cy, 114 | color: 0 115 | }; 116 | entityManager.createParticle(descr); 117 | ctx.restore(); 118 | }; -------------------------------------------------------------------------------- /entities/Electrode.js: -------------------------------------------------------------------------------- 1 | // ========= 2 | // Electrode 3 | // ========= 4 | 5 | // Electrodes are static enemies. Touch them and die. 6 | // Electrodes also kill Grunts. 7 | 8 | "use strict"; 9 | 10 | /* jshint browser: true, devel: true, globalstrict: true */ 11 | 12 | function Electrode(descr) { 13 | 14 | // Common inherited setup logic from Entity 15 | Enemy.call(this, descr); 16 | 17 | this.sprite = g_sprites.Electrode[0]; 18 | this.capPositions(); 19 | } 20 | 21 | Electrode.prototype = Object.create(Enemy.prototype); 22 | 23 | Electrode.prototype.update = function (du) { 24 | this.animation += du; 25 | if (this.animation > SECS_TO_NOMINALS) this.animation = 0; 26 | 27 | spatialManager.unregister(this); 28 | 29 | if (!this.startPos) this.startPos = this.getPos(); 30 | 31 | // Handle death 32 | if (this._isDeadNow) { 33 | Player.addScore(Player.scoreValues.Electrode * Player.getMultiplier()); 34 | return entityManager.KILL_ME_NOW; 35 | } 36 | 37 | // Handle collisions 38 | var hitEntity = this.findHitEntity(); 39 | if (hitEntity) { 40 | var canTakeHit = hitEntity.takeElectrodeHit; 41 | if (canTakeHit) 42 | canTakeHit.call(hitEntity); 43 | } 44 | 45 | spatialManager.register(this); 46 | }; 47 | 48 | Electrode.prototype.takeBulletHit = function () { 49 | this.kill(); 50 | }; 51 | 52 | Electrode.prototype.render = function (ctx) { 53 | var temp; 54 | switch(true) { 55 | case this.animation < SECS_TO_NOMINALS/5: 56 | temp = 0; 57 | break; 58 | case this.animation < 2*SECS_TO_NOMINALS/3: 59 | temp = 1; 60 | break; 61 | default: 62 | temp = 2; 63 | } 64 | g_sprites.Electrode[(this.shapes*3)+temp].drawCentredAt(ctx, this.cx, this.cy, 0); 65 | }; -------------------------------------------------------------------------------- /entities/Enemy.js: -------------------------------------------------------------------------------- 1 | // ====== 2 | // Enemy 3 | // ====== 4 | 5 | // Object containing the logic common to all enemies. 6 | 7 | "use strict"; 8 | 9 | /* jshint browser: true, devel: true, globalstrict: true */ 10 | 11 | // A generic contructor which accepts an arbitrary descriptor object 12 | function Enemy(descr) { 13 | 14 | // Common inherited setup logic from Entity 15 | this.setup(descr); 16 | 17 | this.sprite = g_sprites.Grunt[0]; 18 | this.target = entityManager.findProtagonist(); 19 | } 20 | 21 | Enemy.prototype = new Entity(); 22 | 23 | // HACKED-IN AUDIO (no preloading) 24 | Enemy.prototype.explode = new Audio(g_audioUrls.explode); 25 | 26 | // Initial, inheritable, default values 27 | Enemy.prototype.killProtagonist = true; 28 | Enemy.prototype.rotation = 0; 29 | Enemy.prototype.velX = 0; 30 | Enemy.prototype.velY = 0; 31 | Enemy.prototype.dropChance = 0.05; // All enemies have at least a 5% chance 32 | // to drop a powerup 33 | 34 | Enemy.prototype.kill = function () { 35 | if (!this._isDeadNow) { 36 | var result = Math.random(); 37 | if (this.dropChance > result) { 38 | entityManager.createPowerup(this.cx, this.cy); 39 | } 40 | } 41 | 42 | this._isDeadNow = true; 43 | this.explode.currentTime = 0; 44 | if (g_sounds) { 45 | this.explode.volume = 0.3; 46 | this.explode.play(); 47 | } 48 | }; 49 | 50 | Enemy.prototype.getRadius = function () { 51 | return (this.sprite.width / 2) * 0.9; 52 | }; 53 | 54 | Enemy.prototype.render = function (ctx) { 55 | 56 | this.sprite.drawCentredAt( 57 | ctx, this.cx, this.cy, this.rotation 58 | ); 59 | }; 60 | 61 | 62 | // Shared defaults, used by enemies that warp in 63 | Enemy.prototype.isSpawning = true; 64 | Enemy.prototype.spawnTime = SECS_TO_NOMINALS / 2; 65 | Enemy.prototype.spawnTimeElapsed = 0; 66 | 67 | Enemy.prototype.makeWarpParticles = function () { 68 | 69 | for (var i = 0; i < this.colors.length; i++) { 70 | var colorDefinition = this.colors[i]; 71 | var numberOfParticles = colorDefinition.ratio * this.getNumberOfParticles(); 72 | for (var j = 0; j < numberOfParticles; j++) { 73 | var direction = util.randRange(0, Math.PI * 2); 74 | var speed = util.randRange(0, 2); 75 | var distance = speed * Particle.prototype.lifeSpan; 76 | 77 | var particle = { 78 | dirn: direction, 79 | speed: -speed, 80 | cx: this.cx + distance * Math.cos(direction), 81 | cy: this.cy + distance * Math.sin(direction), 82 | color: colorDefinition.color, 83 | radius: 1 84 | }; 85 | entityManager.createParticle(particle); 86 | } 87 | } 88 | }; 89 | 90 | Enemy.prototype.warpIn = function (du) { 91 | this.spawnTimeElapsed += du; 92 | if (this.spawnTimeElapsed > this.spawnTime) { 93 | this.isSpawning = false; 94 | } 95 | }; 96 | 97 | Enemy.prototype.makeExplosion = function () { 98 | 99 | for (var i = 0; i < this.colors.length; i++) { 100 | var colorDefinition = this.colors[i]; 101 | var numberOfParticles = colorDefinition.ratio * this.getNumberOfParticles(); 102 | for (var j = 0; j < numberOfParticles; j++) { 103 | var particle = { 104 | dirn: util.randRange(0, Math.PI * 2), 105 | speed: util.randRange(0, 4), 106 | cx: this.cx, 107 | cy: this.cy, 108 | color: colorDefinition.color, 109 | radius: 1 110 | }; 111 | entityManager.createParticle(particle); 112 | } 113 | } 114 | }; 115 | 116 | Enemy.prototype.getNumberOfParticles = function () { 117 | var maxNumParticlesOnScreen = 4000; 118 | var maxNumParticles = 200; 119 | var minNumParticles = 20; 120 | 121 | var numEntities = levelManager.numberOfEntities; 122 | var numParticles = maxNumParticlesOnScreen / numEntities; 123 | 124 | // Capping 125 | var numParticles = Math.max(numParticles, minNumParticles); 126 | var numParticles = Math.min(numParticles, maxNumParticles); 127 | 128 | return numParticles; 129 | }; -------------------------------------------------------------------------------- /entities/Enforcer.js: -------------------------------------------------------------------------------- 1 | // ======== 2 | // Enforcer 3 | // ======== 4 | 5 | // Enforcers fly towards the main character. 6 | // Enforcers shoot sparks. 7 | 8 | "use strict"; 9 | 10 | /* jshint browser: true, devel: true, globalstrict: true */ 11 | 12 | // A generic contructor which accepts an arbitrary descriptor object 13 | function Enforcer(descr) { 14 | 15 | // Common inherited setup logic from Entity 16 | Enemy.call(this, descr); 17 | 18 | this.sprite = g_sprites.Enforcer[0]; 19 | this.target = entityManager.findProtagonist(); 20 | } 21 | 22 | Enforcer.prototype = Object.create(Enemy.prototype); 23 | Enforcer.prototype.ammo = 20; 24 | Enforcer.prototype.sparkFireChance = 0.01; //1% chance of firing a spark/update 25 | Enforcer.prototype.spawnTime = SECS_TO_NOMINALS; 26 | 27 | Enforcer.prototype.update = function (du) { 28 | 29 | spatialManager.unregister(this); 30 | 31 | if (!this.startPos) this.startPos = this.getPos(); 32 | 33 | // Handle death 34 | if (this._isDeadNow) { 35 | Player.addScore(Player.scoreValues.Enforcer * Player.getMultiplier()); 36 | return entityManager.KILL_ME_NOW; 37 | } 38 | 39 | if (this.animation < this.spawnTime) { 40 | this.animation += du; 41 | } else { 42 | 43 | this.seekTarget(); 44 | 45 | this.cx += this.velX * du; 46 | this.cy += this.velY * du; 47 | this.capPositions(); 48 | 49 | if (Math.random() < this.sparkFireChance && this.ammo > 0) { 50 | var angle = util.angleTo( 51 | this.cx, 52 | this.cy, 53 | this.target.cx, 54 | this.target.cy 55 | ); 56 | this.ammo--; 57 | entityManager.fireSpark(this.cx, this.cy, angle); 58 | } 59 | } 60 | 61 | spatialManager.register(this); 62 | }; 63 | 64 | Enforcer.prototype.seekTarget = function () { 65 | var xOffset = this.target.cx - this.cx; 66 | var yOffset = this.target.cy - this.cy; 67 | 68 | this.velX = 0; 69 | if (xOffset > 0) { 70 | this.velX = 1; 71 | } else if (xOffset < 0) { 72 | this.velX = -1; 73 | } 74 | 75 | this.velY = 0; 76 | if (yOffset > 0) { 77 | this.velY = 1; 78 | } else if (yOffset < 0) { 79 | this.velY = -1; 80 | } 81 | 82 | // Clamp vel to 1 pixel moving radius 83 | if (xOffset !== 0 && yOffset !== 0) { 84 | this.velX *= Math.cos(Math.PI / 4); 85 | this.velY *= Math.sin(Math.PI / 4); 86 | } 87 | }; 88 | 89 | Enforcer.prototype.takeBulletHit = function () { 90 | this.kill(); 91 | this.makeExplosion(); 92 | }; 93 | 94 | Enforcer.prototype.render = function (ctx) { 95 | var temp = Math.ceil(6 * this.animation / SECS_TO_NOMINALS); 96 | if (temp > 5) temp = 0; 97 | g_sprites.Enforcer[temp].drawCentredAt(ctx, this.cx, this.cy, 0); 98 | }; 99 | 100 | Enforcer.prototype.colors = [ 101 | {color: "blue", ratio: 0.50}, 102 | {color: "#05FF05", ratio: 0.5}, // Green 103 | {color: "red", ratio: 0.10}, 104 | {color: "#8AA8B2", ratio: 0.35} // Grey 105 | 106 | ]; 107 | -------------------------------------------------------------------------------- /entities/Entity.js: -------------------------------------------------------------------------------- 1 | // ====== 2 | // ENTITY 3 | // ====== 4 | /* 5 | 6 | Provides a set of common functions which can be "inherited" by all other 7 | game Entities. 8 | 9 | JavaScript's prototype-based inheritance system is unusual, and requires 10 | some care in use. In particular, this "base" should only provide shared 11 | functions... shared data properties are potentially quite confusing. 12 | 13 | */ 14 | 15 | "use strict"; 16 | 17 | /* jshint browser: true, devel: true, globalstrict: true */ 18 | 19 | /* 20 | 0 1 2 3 4 5 6 7 8 21 | 12345678901234567890123456789012345678901234567890123456789012345678901234567890 22 | */ 23 | 24 | 25 | function Entity() { 26 | 27 | /* 28 | // Diagnostics to check inheritance stuff 29 | this._entityProperty = true; 30 | console.dir(this); 31 | */ 32 | 33 | }; 34 | 35 | //Entity.prototype.startPos = {cx : 0, cy : 0}; 36 | 37 | Entity.prototype.setup = function (descr) { 38 | 39 | // Apply all setup properies from the (optional) descriptor 40 | for (var property in descr) { 41 | this[property] = descr[property]; 42 | } 43 | 44 | // Get my (unique) spatial ID 45 | this._spatialID = spatialManager.getNewSpatialID(); 46 | 47 | // I am not dead yet! 48 | this._isDeadNow = false; 49 | 50 | this.animation = 0; 51 | }; 52 | 53 | Entity.prototype.setPos = function (cx, cy) { 54 | this.cx = cx; 55 | this.cy = cy; 56 | }; 57 | 58 | Entity.prototype.getPos = function () { 59 | return {posX: this.cx, posY: this.cy}; 60 | }; 61 | 62 | Entity.prototype.getRadius = function () { 63 | return 0; 64 | }; 65 | 66 | Entity.prototype.getSpatialID = function () { 67 | return this._spatialID; 68 | }; 69 | 70 | Entity.prototype.kill = function () { 71 | this._isDeadNow = true; 72 | }; 73 | 74 | Entity.prototype.findHitEntity = function () { 75 | var pos = this.getPos(); 76 | return spatialManager.findEntityInRange( 77 | pos.posX, pos.posY, this.getRadius() 78 | ); 79 | }; 80 | 81 | Entity.prototype.capPositions = function () { 82 | var r = this.getRadius(); 83 | this.cx = Math.max(this.cx, consts.wallLeft + r); 84 | this.cx = Math.min(this.cx, consts.wallRight - r); 85 | this.cy = Math.max(this.cy, consts.wallTop + consts.wallThickness + r); 86 | this.cy = Math.min(this.cy, consts.wallBottom - r); 87 | }; 88 | 89 | Entity.prototype.edgeBounce = function () { 90 | var bounceHappened = false; 91 | 92 | var velX = this.velX; 93 | var velY = this.velY; 94 | var cx = this.cx; 95 | var cy = this.cy; 96 | var r = this.getRadius(); 97 | 98 | if (cx + velX > consts.wallRight - r || cx + velX < consts.wallLeft + r) { 99 | bounceHappened = true; 100 | this.velX = -this.velX; 101 | } 102 | if (cy + velY > consts.wallBottom - r || cy + velY < consts.wallTop + consts.wallThickness + r) { 103 | bounceHappened = true; 104 | this.velY = -this.velY; 105 | } 106 | return bounceHappened; 107 | }; 108 | 109 | Entity.prototype.spawnFragment = function (num,specificColor) { 110 | 111 | var explosionColors = ["yellow","orange","red","grey","white"]; 112 | 113 | for (var i = 0; i < num; i++) { 114 | var dirn = Math.random()*2*Math.PI; 115 | var color; 116 | if (specificColor === undefined) { 117 | var colorId = Math.floor(Math.random()*5); 118 | color = explosionColors[colorId]; 119 | } else { 120 | color = specificColor; 121 | } 122 | var descr = {cx: this.cx, 123 | cy: this.cy, 124 | dirn: dirn, 125 | color: color}; 126 | entityManager.createParticle(descr); 127 | } 128 | }; 129 | -------------------------------------------------------------------------------- /entities/Family.js: -------------------------------------------------------------------------------- 1 | // ====== 2 | // FAMILY 3 | // ====== 4 | 5 | // The last remaining family of humans. 6 | // Rescue them to get points and increase the score multiplier. 7 | 8 | "use strict"; 9 | 10 | /* jshint browser: true, devel: true, globalstrict: true */ 11 | 12 | // A generic contructor which accepts an arbitrary descriptor object 13 | function Family(descr) { 14 | 15 | // Common inherited setup logic from Entity 16 | this.setup(descr); 17 | 18 | this.sprite = g_sprites.Dad[6]; 19 | } 20 | 21 | Family.prototype = new Entity(); 22 | 23 | // HACKED-IN AUDIO (no preloading) 24 | Family.prototype.deadSound = new Audio(g_audioUrls.familydead); 25 | Family.prototype.savedSound = new Audio(g_audioUrls.familypick); 26 | 27 | // Initial, inheritable, default values 28 | Family.prototype.rotation = 0; 29 | Family.prototype.cx = 100; 30 | Family.prototype.cy = 100; 31 | Family.prototype.velX = 0; 32 | Family.prototype.velY = 0; 33 | Family.prototype.stepsize = 10; 34 | Family.prototype.panic = 1; 35 | Family.prototype.lifeSpan = 1 * SECS_TO_NOMINALS; 36 | Family.prototype.isDying = false; 37 | Family.prototype.renderPos = {cx: this.cx, cy: this.cy}; 38 | Family.prototype.willSpawnProg = false; 39 | Family.prototype.facing = 0; 40 | 41 | Family.prototype.update = function (du) { 42 | 43 | spatialManager.unregister(this); 44 | 45 | if (!this.startPos) this.startPos = this.getPos(); 46 | 47 | // Handle death 48 | if (this._isDeadNow) { 49 | return entityManager.KILL_ME_NOW; 50 | } 51 | if (this.isDying) { 52 | if (!this.died) { 53 | this.deadSound.currentTime = 0; 54 | this.died = true; 55 | } 56 | if (g_sounds) { 57 | this.deadSound.volume = 0.3; 58 | this.deadSound.play(); 59 | } 60 | this.lifeSpan += -du; 61 | if (this.lifeSpan <= 0) { 62 | if(this.willSpawnProg){ 63 | entityManager.createProg(this.cx,this.cy); 64 | } 65 | this.kill(); 66 | } 67 | } else { 68 | if (Math.random() < 0.01 && this.panic < 3) { 69 | this.panic += 0.1; 70 | } 71 | this.randomWalk(); 72 | 73 | this.capPositions(); 74 | //TODO: Make them less likely to change direction after bouncing? 75 | this.edgeBounce(); 76 | this.cx += this.velX * du; 77 | this.cy += this.velY * du; 78 | 79 | // Handle collisions 80 | var hitEntity = this.findHitEntity(); 81 | if (hitEntity) { 82 | if (hitEntity.makesProgs){ 83 | this.willSpawnProg = true; 84 | } 85 | var canKillMe = hitEntity.killFamily; 86 | if (canKillMe) { 87 | this.takeChaserHit(); 88 | } 89 | } 90 | 91 | spatialManager.register(this); 92 | } 93 | }; 94 | 95 | Family.prototype.randomWalk = function () { 96 | if (Math.random() < 0.02 * this.panic) { 97 | //2% chance to change direction 98 | 99 | var n = Math.floor(Math.random() * 4); 100 | switch (n) { 101 | case 0: 102 | this.velX = -0.3 * this.panic; 103 | break; 104 | case 1: 105 | this.velY = -0.3 * this.panic; 106 | break; 107 | case 2: 108 | this.velX = 0.3 * this.panic; 109 | break; 110 | case 3: 111 | this.velY = 0.3 * this.panic; 112 | } 113 | } 114 | }; 115 | 116 | Family.prototype.takeChaserHit = function () { 117 | this.isDying = true; 118 | }; 119 | 120 | Family.prototype.takeProtagonistHit = function () { 121 | // I'm Saved!!! 122 | Player.addScore(Player.scoreValues.Family * Player.getMultiplier()); 123 | entityManager.createScoreImg({ 124 | cx: this.cx, 125 | cy: this.cy, 126 | m: Player.getMultiplier()}); 127 | Player.addMultiplier(); 128 | Player.addSaveCount(); 129 | this.savedSound.currentTime = 0; 130 | if (g_sounds) { 131 | this.savedSound.volume = 0.4; 132 | this.savedSound.play(); 133 | } 134 | this.kill(); 135 | }; 136 | 137 | Family.prototype.takeFriendlyHit = function () { 138 | this.isDying = true; 139 | }; 140 | 141 | Family.prototype.getRadius = function () { 142 | return (this.sprite.width / 2) * 0.9; 143 | }; 144 | 145 | Family.prototype.render = function (ctx) { 146 | if (this.isDying) { 147 | g_sprites.Skull.drawCentredAt(ctx, 148 | this.cx, 149 | this.cy, 150 | this.rotation); 151 | } else { 152 | var distSq = util.distSq(this.cx, this.cy, this.renderPos.cx, this.renderPos.cy); 153 | var angle = util.angleTo(this.renderPos.cx, this.renderPos.cy, this.cx, this.cy); 154 | var PI = Math.PI; 155 | 156 | if (distSq > 0.1) { 157 | this.facing = 3; // right 158 | if(angle > PI*1/4) this.facing = 6; //down 159 | if(angle > PI*3/4) this.facing = 0; //left 160 | if(angle > PI*5/4) this.facing = 9; //up 161 | if(angle > PI*7/4) this.facing = 3; //right 162 | } 163 | 164 | var temp; 165 | switch(true) { 166 | case distSq 0) { 64 | this.velX = this.speed; 65 | } else if (xOffset < 0) { 66 | this.velX = -this.speed; 67 | } 68 | 69 | this.velY = 0; 70 | if (yOffset > 0) { 71 | this.velY = this.speed; 72 | } else if (yOffset < 0) { 73 | this.velY = -this.speed; 74 | } 75 | 76 | // Clamp vel 77 | if (xOffset !== 0 && yOffset !== 0) { 78 | this.velX *= this.speed * Math.cos(Math.PI / 4); 79 | this.velY *= this.speed * Math.sin(Math.PI / 4); 80 | } 81 | }; 82 | 83 | // Increases the grunt's speed over time. 84 | Grunt.prototype.rage = function (du) { 85 | var timeFraction = du / this.maxRageReachedTime; 86 | this.speed += (this.maxSpeed - this.baseSpeed) * timeFraction; 87 | this.speed = Math.min(this.speed, this.maxSpeed); 88 | }; 89 | 90 | Grunt.prototype.resetRage = function () { 91 | this.speed = this.baseSpeed; 92 | }; 93 | 94 | Grunt.prototype.takeBulletHit = function () { 95 | this.kill(); 96 | this.makeExplosion(); 97 | }; 98 | Grunt.prototype.takeElectrodeHit = function () { 99 | this.takeBulletHit(); 100 | }; 101 | 102 | Grunt.prototype.render = function (ctx) { 103 | if (this.isSpawning) { 104 | return; 105 | } 106 | var distSq = util.distSq(this.cx, this.cy, this.renderPos.cx, this.renderPos.cy); 107 | 108 | var temp; 109 | switch (true) { 110 | case distSq < util.square(this.stepsize): 111 | temp = 0; 112 | break; 113 | case distSq < util.square(this.stepsize * 2): 114 | temp = 1; 115 | break; 116 | case distSq < util.square(this.stepsize * 3): 117 | temp = 0; 118 | break; 119 | case distSq < util.square(this.stepsize * 4): 120 | temp = 2; 121 | break; 122 | default: 123 | temp = 0; 124 | this.renderPos = {cx: this.cx, cy: this.cy}; 125 | } 126 | g_sprites.Grunt[temp].drawCentredAt(ctx, this.cx, this.cy, 0); 127 | }; 128 | 129 | 130 | Grunt.prototype.colors = [ 131 | {color: "red", ratio: 0.70}, 132 | {color: "yellow", ratio: 0.15}, 133 | {color: "#800080", ratio: 0.05}, 134 | {color: "#00FF00", ratio: 0.05}, 135 | {color: "white", ratio: 0.05} 136 | ]; 137 | 138 | -------------------------------------------------------------------------------- /entities/Hulk.js: -------------------------------------------------------------------------------- 1 | // ==== 2 | // Hulk 3 | // ==== 4 | 5 | // Hulks are indestructible robotrons that chase members of the last human 6 | // family. 7 | 8 | "use strict"; 9 | 10 | /* jshint browser: true, devel: true, globalstrict: true */ 11 | 12 | // A generic contructor which accepts an arbitrary descriptor object 13 | 14 | function Hulk(descr) { 15 | Enemy.call(this, descr); 16 | 17 | this.sprite = g_sprites.Hulk[3]; 18 | this.makeWarpParticles(); 19 | } 20 | 21 | Hulk.prototype = Object.create(Enemy.prototype); 22 | Hulk.prototype.timeSinceHit = Infinity; 23 | Hulk.prototype.killFamily = true; 24 | Hulk.prototype.renderPos = {cx: this.cx, cy: this.cy}; 25 | Hulk.prototype.stepsize = 12; 26 | Hulk.prototype.bootTime = 2 * SECS_TO_NOMINALS; 27 | Hulk.prototype.brainpower = 0.05; 28 | Hulk.prototype.facing = 0; 29 | 30 | Hulk.prototype.update = function (du) { 31 | this.bootTime += -du; 32 | 33 | spatialManager.unregister(this); 34 | 35 | if (!this.startPos) this.startPos = this.getPos(); 36 | 37 | // Handle death 38 | if (this._isDeadNow) { 39 | return entityManager.KILL_ME_NOW; 40 | } 41 | 42 | if (this.isSpawning) { 43 | this.warpIn(du); 44 | } else { 45 | this.seekTarget(); 46 | 47 | // Move, unless the Hulk has been shot in the last 0.2 seconds. 48 | this.timeSinceHit += du; 49 | if (this.timeSinceHit > SECS_TO_NOMINALS * 0.2) { 50 | this.move(this.velX, this.velY, du); 51 | } 52 | } 53 | 54 | spatialManager.register(this); 55 | }; 56 | 57 | Hulk.prototype.move = function (velX, velY, du) { 58 | this.cx += velX * du; 59 | this.cy += velY * du; 60 | this.capPositions(); 61 | }; 62 | 63 | Hulk.prototype.seekTarget = function () { 64 | 65 | this.findTarget(); 66 | if (this.target === null || this.target === undefined) { 67 | return; // Escaping empty-field conditions that can occur in testing 68 | } 69 | 70 | var xOffset = this.target.cx - this.cx; 71 | var yOffset = this.target.cy - this.cy; 72 | var difficulty = Math.random(); 73 | 74 | if (this.bootTime < 0 || 75 | (util.abs(xOffset) < 10 && difficulty < this.brainpower) || 76 | (util.abs(yOffset) < 10 && difficulty < this.brainpower) 77 | ) { 78 | 79 | this.velX = 0; 80 | this.velY = 0; 81 | if (util.abs(xOffset) > util.abs(yOffset)) { 82 | if (xOffset > 0) { 83 | this.velX = 1; 84 | } else { 85 | this.velX = -1; 86 | } 87 | } else { 88 | if (yOffset > 0) { 89 | this.velY = 1; 90 | } else { 91 | this.velY = -1; 92 | } 93 | } 94 | this.bootTime = 2 * SECS_TO_NOMINALS; 95 | } 96 | }; 97 | 98 | Hulk.prototype.findTarget = function () { 99 | // Hulks prefer family members. 100 | // http://www.youtube.com/watch?v=940WwmYSYLE&t=1m33s 101 | this.target = entityManager.findClosestFamilyMember(this.cx, this.cy); 102 | if (this.target === null || this.target === undefined) { 103 | this.target = entityManager.findProtagonist(); 104 | } 105 | }; 106 | 107 | Hulk.prototype.takeBulletHit = function (descr) { 108 | // Hulks can't be killed. Shooting stuns them and knocks them back. 109 | 110 | // Descr contains the speed and du of the bullet. 111 | 112 | spatialManager.unregister(this); 113 | this.move(descr.velX / 2, descr.velY / 2, descr.du); 114 | spatialManager.register(this); 115 | 116 | this.timeSinceHit = 0; 117 | }; 118 | 119 | Hulk.prototype.render = function (ctx) { 120 | if (this.isSpawning) { 121 | return; 122 | } 123 | var distSq = util.distSq(this.cx, this.cy, this.renderPos.cx, this.renderPos.cy); 124 | var angle = util.angleTo(this.renderPos.cx, this.renderPos.cy, this.cx, this.cy); 125 | var PI = Math.PI; 126 | 127 | if (distSq > 0.1) { 128 | this.facing = 3; // up or down 129 | if (angle > PI * 3 / 4 && angle < PI * 5 / 4) this.facing = 0; //left 130 | if (angle > PI * 7 / 4 || angle < PI * 1 / 4) this.facing = 6; //right 131 | } 132 | 133 | var temp; 134 | switch (true) { 135 | case distSq < util.square(this.stepsize): 136 | temp = 0; 137 | break; 138 | case distSq < util.square(this.stepsize * 2): 139 | temp = 1; 140 | break; 141 | case distSq < util.square(this.stepsize * 3): 142 | temp = 0; 143 | break; 144 | case distSq < util.square(this.stepsize * 4): 145 | temp = 2; 146 | break; 147 | default: 148 | this.renderPos = {cx: this.cx, cy: this.cy}; 149 | temp = 0; 150 | } 151 | g_sprites.Hulk[this.facing + temp].drawCentredAt(ctx, this.cx, this.cy, 0); 152 | }; 153 | 154 | Hulk.prototype.colors = [ 155 | {color: "#0EF909", ratio: 0.80}, 156 | {color: "red", ratio: 0.20} 157 | ]; -------------------------------------------------------------------------------- /entities/Powerup.js: -------------------------------------------------------------------------------- 1 | //======= 2 | //POWERUP 3 | //======= 4 | 5 | // Powerups are rarely dropped by all enemies when they die, 6 | // and frequently by Brains and Tanks. 7 | 8 | "use strict"; 9 | 10 | // A generic contructor which accepts an arbitrary descriptor object 11 | function Powerup(descr) { 12 | 13 | // Common inherited setup logic from Entity 14 | this.setup(descr); 15 | 16 | // HACKED-IN AUDIO (no preloading) 17 | this.pickupSound = new Audio(g_audioUrls.pickitem); 18 | 19 | switch(this.brand){ 20 | case 0: 21 | this.isExtralife = true; 22 | break; 23 | case 1: 24 | this.isShotgun = true; 25 | break; 26 | case 2: 27 | this.isMachinegun = true; 28 | break; 29 | case 3: 30 | this.isSpeedBoost = true; 31 | break; 32 | case 4: 33 | this.isShield = true; 34 | break; 35 | case 5: 36 | this.isScoreMultiplier = true; 37 | break; 38 | } 39 | } 40 | 41 | 42 | Powerup.prototype = new Entity(); 43 | Powerup.prototype.strNames = ["Extra Life", "Shotgun", "Machinegun", "Speed Boost", "Shield", "Score Multiplier"]; 44 | Powerup.prototype.isExtralife = false; 45 | Powerup.prototype.isSpeedBoost = false; 46 | Powerup.prototype.isScoreMultiplier = false; 47 | Powerup.prototype.isMachinegun = false; 48 | Powerup.prototype.isShotgun = false; 49 | Powerup.prototype.isShield = false; 50 | Powerup.prototype.loop = SECS_TO_NOMINALS; 51 | 52 | Powerup.prototype.update = function (du) { 53 | this.animation += du; 54 | if (this.animation > this.loop) this.animation = 0; 55 | 56 | spatialManager.unregister(this); 57 | 58 | if (this._isDeadNow) { 59 | return entityManager.KILL_ME_NOW; 60 | } 61 | 62 | spatialManager.register(this); 63 | }; 64 | 65 | Powerup.prototype.takeProtagonistHit = function () { 66 | Player.addScore(Player.scoreValues.Powerup * Player.getMultiplier()); 67 | 68 | if (g_sounds) this.pickupSound.play(); 69 | 70 | Player.setPowerupText(this.strNames[this.brand] + "!"); 71 | Player.setPowerupTime(); 72 | 73 | this.kill(); 74 | 75 | if (this.isExtralife) Player.addLives(); 76 | 77 | if (this.isSpeedBoost) Player.addSpeed(); 78 | 79 | if (this.isScoreMultiplier) Player.addMultiplier(); 80 | 81 | if (this.isMachinegun) { 82 | Player.hasShotgun = false; 83 | Player.hasMachineGun = true; 84 | Player.setFireRate(5); 85 | Player.addAmmo(100); 86 | }; 87 | 88 | if (this.isShotgun) { 89 | Player.hasShotgun = true; 90 | Player.hasMachineGun = false; 91 | Player.setFireRate(70); 92 | Player.addAmmo(100); 93 | var gunSound = new Audio(g_audioUrls.shotgunReload); 94 | if (g_sounds) gunSound.play(); 95 | }; 96 | 97 | if (this.isShield) Player.addShieldTime(); 98 | }; 99 | 100 | Powerup.prototype.getRadius = function () { 101 | return 8; 102 | }; 103 | 104 | Powerup.prototype.render = function (ctx) { 105 | var temp = Math.floor(8* this.animation / this.loop); 106 | if (temp > 7) temp = 0; 107 | g_sprites.PowerUps[8*this.brand+temp].drawCentredAt(ctx, this.cx, this.cy, 0); 108 | }; 109 | -------------------------------------------------------------------------------- /entities/Prog.js: -------------------------------------------------------------------------------- 1 | // ===== 2 | // Progs 3 | // ===== 4 | 5 | // Progs are spawned when a Brain kills a family member. 6 | // Progs walk around randomly, killing the protagonist if encountered. 7 | 8 | "use strict"; 9 | 10 | /* jshint browser: true, devel: true, globalstrict: true */ 11 | 12 | function Prog(descr) { 13 | 14 | // Common inherited setup logic from Entity 15 | Enemy.call(this, descr); 16 | 17 | this.sprite = g_sprites.Prog[0]; 18 | // TODO play spawning sound? 19 | } 20 | 21 | Prog.prototype = Object.create(Enemy.prototype); 22 | Prog.prototype.speed = 1.5; 23 | Prog.prototype.renderPos = {cx: 0, cy: 0}; 24 | Prog.prototype.stepsize = 15; 25 | Prog.prototype.facing = 0; 26 | 27 | Prog.prototype.update = function (du) { 28 | 29 | spatialManager.unregister(this); 30 | 31 | if (!this.startPos) this.startPos = this.getPos(); 32 | if (!this.renderPos) this.renderPos = this.getPos(); 33 | 34 | // Handle death 35 | if (this._isDeadNow) { 36 | Player.addScore(Player.scoreValues.Prog * Player.getMultiplier()); 37 | return entityManager.KILL_ME_NOW; 38 | } 39 | 40 | this.randomWalk(); 41 | 42 | this.capPositions(); 43 | //TODO: Make them less likely to change direction after bouncing? 44 | this.edgeBounce(); 45 | 46 | this.cx += this.velX * du; 47 | this.cy += this.velY * du; 48 | 49 | 50 | spatialManager.register(this); 51 | 52 | }; 53 | 54 | Prog.prototype.randomWalk = function () { 55 | if (Math.random() < 0.02) { 56 | //2% chance to change direction 57 | 58 | var n = Math.floor(Math.random() * 4); 59 | switch (n) { 60 | case 0: 61 | this.velX = -this.speed; 62 | break; 63 | case 1: 64 | this.velY = -this.speed; 65 | break; 66 | case 2: 67 | this.velX = this.speed; 68 | break; 69 | case 3: 70 | this.velY = this.speed; 71 | } 72 | } 73 | }; 74 | 75 | Prog.prototype.takeBulletHit = function () { 76 | this.kill(); 77 | this.makeExplosion(); 78 | }; 79 | 80 | // Overriding from Enemy. 81 | // Prog sprites are very tall, default implementation does not 82 | // give an accurate bounding circle. 83 | Prog.prototype.getRadius = function () { 84 | return (this.sprite.height / 2) * 0.9; 85 | }; 86 | 87 | Prog.prototype.render = function (ctx) { 88 | 89 | var distSq = util.distSq(this.cx, this.cy, this.renderPos.cx, this.renderPos.cy); 90 | var angle = util.angleTo(this.renderPos.cx, this.renderPos.cy, this.cx, this.cy); 91 | var PI = Math.PI; 92 | 93 | if (distSq > 0.1) { 94 | this.facing = 3; // right 95 | if(angle > PI*1/4) this.facing = 6; //down 96 | if(angle > PI*3/4) this.facing = 0; //left 97 | if(angle > PI*5/4) this.facing = 9; //up 98 | if(angle > PI*7/4) this.facing = 3; //right 99 | } 100 | 101 | var temp = 0; 102 | switch(true) { 103 | case distSq 3) Player.tickSpeedTimer(du); 55 | if (Player.getShieldTime() > 0) Player.tickShieldTime(du); 56 | if (Player.getPowerupTime() > 0) Player.tickPowerupTime(du); 57 | var vel = this.computeMovement(); 58 | this.velX = vel.x; 59 | this.velY = vel.y; 60 | 61 | this.cx += this.velX * du; 62 | this.cy += this.velY * du; 63 | this.capPositions(); 64 | 65 | this.maybeFire(); 66 | 67 | // Handle collisions 68 | var hitEntity = this.findHitEntity(); 69 | if (hitEntity) { 70 | var canSave = hitEntity.takeProtagonistHit; 71 | if (canSave) canSave.call(hitEntity); 72 | else { 73 | var canKillMe = hitEntity.killProtagonist; 74 | if (canKillMe && g_canBeKilled && !g_invincible) this.takeEnemyHit(); 75 | } 76 | } 77 | 78 | spatialManager.register(this); 79 | }; 80 | 81 | Protagonist.prototype.computeMovement = function () { 82 | var velX = 0; 83 | var velY = 0; 84 | var hasMoved = false; 85 | 86 | if (keys[this.KEY_UP]) { 87 | velY -= Player.getSpeed(); 88 | hasMoved = true; 89 | } 90 | if (keys[this.KEY_DOWN]) { 91 | velY += Player.getSpeed(); 92 | hasMoved = true; 93 | } 94 | if (keys[this.KEY_LEFT]) { 95 | velX -= Player.getSpeed(); 96 | hasMoved = true; 97 | } 98 | if (keys[this.KEY_RIGHT]) { 99 | velX += Player.getSpeed(); 100 | hasMoved = true; 101 | } 102 | // Clamp vel to 5 pixel moving radius 103 | if (velX !== 0 && velY !== 0) { 104 | velX *= Math.cos(Math.PI / 4); 105 | velY *= Math.sin(Math.PI / 4); 106 | } 107 | 108 | // Walk makes a sound if moved 109 | if (g_sounds && hasMoved) { 110 | this.walkSound.volume = 0.3; 111 | this.walkSound.play() 112 | } 113 | 114 | return {x: velX, y: velY}; 115 | }; 116 | 117 | Protagonist.prototype.maybeFire = function () { 118 | var x = 0; 119 | var y = 0; 120 | 121 | if (keys[this.KEY_SHOOTUP]) { 122 | y -= 1; 123 | } 124 | if (keys[this.KEY_SHOOTDOWN]) { 125 | y += 1; 126 | } 127 | if (keys[this.KEY_SHOOTLEFT]) { 128 | x -= 1 129 | } 130 | if (keys[this.KEY_SHOOTRIGHT]) { 131 | x += 1; 132 | } 133 | if(x != 0 || y != 0) 134 | entityManager.fire(this.cx+x, this.cy+y); 135 | else if (g_isMouseDown) 136 | entityManager.fire(g_mouseX, g_mouseY); 137 | }; 138 | 139 | Protagonist.prototype.takeEnemyHit = function () { 140 | if(g_canBeKilled && !g_invincible) { 141 | Player.subtractLives(); 142 | if (g_sounds) this.loseSound.play(); 143 | if (Player.getLives() > 0) { 144 | Player.resetMultiplier(); 145 | levelManager.continueLevel(); 146 | } else { 147 | this.kill(); 148 | } 149 | } 150 | }; 151 | 152 | Protagonist.prototype.takeElectrodeHit = function () { 153 | if(g_canBeKilled && !g_invincible) { 154 | this.takeEnemyHit(); 155 | } 156 | }; 157 | 158 | Protagonist.prototype.getRadius = function () { 159 | return (this.sprite.width / 2) * 0.9; 160 | }; 161 | 162 | Protagonist.prototype.render = function (ctx) { 163 | var distSq = util.distSq(this.cx, this.cy, this.renderPos.cx, this.renderPos.cy); 164 | var angle = util.angleTo(this.renderPos.cx, this.renderPos.cy, this.cx, this.cy); 165 | var PI = Math.PI; 166 | 167 | if (distSq > 0.1) { 168 | this.facing = 3; // right 169 | if(angle > PI*1/4) this.facing = 6; //down 170 | if(angle > PI*3/4) this.facing = 0; //left 171 | if(angle > PI*5/4) this.facing = 9; //up 172 | if(angle > PI*7/4) this.facing = 3; //right 173 | } 174 | 175 | var temp; 176 | switch(true) { 177 | case distSq= 0) { 208 | ctx.save(); 209 | var fontSize = 24; 210 | ctx.textAlign = "center"; 211 | ctx.font = "bold " + fontSize + "px sans-serif"; 212 | ctx.fillStyle ="red"; 213 | ctx.globalAlpha = Player.getPowerupTime()/SECS_TO_NOMINALS; 214 | ctx.fillText(Player.getPowerupText(), this.cx, this.cy-fontSize); 215 | ctx.restore(); 216 | } 217 | }; 218 | -------------------------------------------------------------------------------- /entities/Quark.js: -------------------------------------------------------------------------------- 1 | // ===== 2 | // Quark 3 | // ===== 4 | 5 | // Quarks spawn Tanks. 6 | // Quarks fly around quickly and randomly. 7 | 8 | function Quark(descr) { 9 | 10 | // Common inherited setup logic from Entity 11 | Enemy.call(this, descr); 12 | 13 | this.sprite = g_sprites.Quark[5]; 14 | 15 | // Initializing speed 16 | this.baseSpeed = 1; 17 | this.velX = this.baseSpeed * util.randTrinary(); 18 | this.velY = this.baseSpeed * util.randTrinary(); 19 | this.tanksSpawned = 0; 20 | // TODO play spawning sound? 21 | 22 | this.makeWarpParticles(); 23 | } 24 | 25 | Quark.prototype = Object.create(Enemy.prototype); 26 | Quark.prototype.tankSpawnChance = 0.005; //0,5% chance of spawning a tank/update 27 | // TODO: Find a good spawn interval. 28 | Quark.prototype.renderPos = {cx: this.cx, cy: this.cy}; 29 | Quark.prototype.maxTanks = 6; 30 | Quark.prototype.constructionTime = SECS_TO_NOMINALS; 31 | 32 | Quark.prototype.update = function (du) { 33 | this.animation += du; 34 | if (this.animation > SECS_TO_NOMINALS) this.animation = 0; 35 | 36 | spatialManager.unregister(this); 37 | 38 | this.constructionTime += -du; 39 | 40 | if (!this.startPos) this.startPos = this.getPos(); 41 | 42 | // Handle death 43 | if (this._isDeadNow) { 44 | Player.addScore(Player.scoreValues.Quark * Player.getMultiplier()); 45 | return entityManager.KILL_ME_NOW; 46 | } 47 | 48 | if (this.isSpawning) { 49 | this.warpIn(du); 50 | } else { 51 | 52 | // maxTanks is effectively zero-indexed 53 | if (Math.random() < this.tankSpawnChance && 54 | this.tanksSpawned < this.maxTanks && 55 | this.constructionTime < 0) { 56 | this.tanksSpawned++; 57 | entityManager.createTank(this.cx, this.cy); 58 | this.constructionTime = 2 * SECS_TO_NOMINALS; 59 | } 60 | 61 | this.randomWalk(); 62 | 63 | this.capPositions(); 64 | this.edgeBounce(); 65 | 66 | this.cx += this.velX * du; 67 | this.cy += this.velY * du; 68 | 69 | } 70 | 71 | spatialManager.register(this); 72 | 73 | }; 74 | 75 | Quark.prototype.randomWalk = function () { 76 | if (Math.random() < 0.005) { 77 | //0.5% chance to change direction 78 | 79 | var n = Math.floor(Math.random() * 4); 80 | switch (n) { 81 | case 0: 82 | this.velX = -this.baseSpeed; 83 | break; 84 | case 1: 85 | this.velY = -this.baseSpeed; 86 | break; 87 | case 2: 88 | this.velX = this.baseSpeed; 89 | break; 90 | case 3: 91 | this.velY = this.baseSpeed; 92 | } 93 | } 94 | }; 95 | 96 | Quark.prototype.takeBulletHit = function () { 97 | this.kill(); 98 | this.makeExplosion(); 99 | }; 100 | 101 | Quark.prototype.render = function (ctx) { 102 | if (this.isSpawning) { 103 | return; 104 | } 105 | var temp = Math.floor(9 * this.animation / SECS_TO_NOMINALS); 106 | if (temp > 8) temp = 8; 107 | g_sprites.Quark[temp].drawCentredAt(ctx, this.cx, this.cy, 0); 108 | }; 109 | 110 | Quark.prototype.colors = [ 111 | {color: "blue", ratio: 0.5}, 112 | {color: "#00FF09", ratio: 0.5} 113 | ]; 114 | -------------------------------------------------------------------------------- /entities/ScoreImg.js: -------------------------------------------------------------------------------- 1 | //=========== 2 | //SCORE IMAGE 3 | //=========== 4 | /* 5 | 6 | An object which displays a score for a short time 7 | 8 | */ 9 | 10 | "use strict"; 11 | 12 | /* jshint browser: true, devel: true, globalstrict: true */ 13 | 14 | /* 15 | 0 1 2 3 4 5 6 7 8 16 | 12345678901234567890123456789012345678901234567890123456789012345678901234567890 17 | */ 18 | 19 | function ScoreImg(descr) { 20 | 21 | // Apply all setup properies from the (optional) descriptor 22 | for (var property in descr) { 23 | this[property] = descr[property]; 24 | } 25 | } 26 | 27 | ScoreImg.prototype.timer = 1 * SECS_TO_NOMINALS; 28 | 29 | ScoreImg.prototype.update = function (du) { 30 | if (this.timer < 0) { 31 | return entityManager.KILL_ME_NOW; 32 | }else{ 33 | this.timer += -du; 34 | } 35 | }; 36 | 37 | ScoreImg.prototype.render = function (ctx) { 38 | g_sprites.HumanScore[this.m].drawCentredAt(ctx, this.cx, this.cy, 0); 39 | }; -------------------------------------------------------------------------------- /entities/Shell.js: -------------------------------------------------------------------------------- 1 | // =========== 2 | // Tank Shells 3 | // =========== 4 | 5 | // Tank shells are fired by tanks. 6 | // They move fast and bounce off the edges. 7 | 8 | "use strict"; 9 | 10 | /* jshint browser: true, devel: true, globalstrict: true */ 11 | 12 | // A generic contructor which accepts an arbitrary descriptor object 13 | function Shell(descr) { 14 | // Common inherited setup logic from Entity 15 | this.setup(descr); 16 | 17 | // HACKED-IN AUDIO (no preloading) 18 | this.fireSound = new Audio(g_audioUrls.shell); 19 | 20 | // Make a noise when I am created (i.e. fired) 21 | if (g_sounds) this.fireSound.play(); 22 | 23 | this.baseVel = 5; 24 | this.velX = this.baseVel*Math.cos(descr.initialAngle); 25 | this.velY = this.baseVel*Math.sin(descr.initialAngle); 26 | 27 | // Make a small cloud when fired 28 | this.spawnFragment(6,"grey"); 29 | this.spawnFragment(3,"white"); 30 | } 31 | 32 | Shell.prototype = new Entity(); 33 | Shell.prototype.lifeSpan = 5 * SECS_TO_NOMINALS; 34 | 35 | Shell.prototype.update = function (du) { 36 | spatialManager.unregister(this); 37 | 38 | // Handle death 39 | if(this._isDeadNow) { 40 | this.spawnFragment(12); 41 | Player.addScore(Player.scoreValues.Shell * Player.getMultiplier()); 42 | return entityManager.KILL_ME_NOW; 43 | } 44 | 45 | this.lifeSpan -= du; 46 | if (this.lifeSpan < 0) { 47 | this.spawnFragment(12); 48 | return entityManager.KILL_ME_NOW; 49 | } 50 | 51 | // Update positions 52 | this.capPositions(); 53 | this.edgeBounce(); 54 | 55 | this.cx += this.velX * du; 56 | this.cy += this.velY * du; 57 | 58 | // Handle collisions 59 | var hitEntity = this.findHitEntity(); 60 | if (hitEntity) { 61 | var canTakeHit = hitEntity.takeEnemyHit; 62 | if (canTakeHit) { 63 | canTakeHit.call(hitEntity); 64 | this.spawnFragment(12); 65 | return entityManager.KILL_ME_NOW; 66 | } 67 | } 68 | 69 | spatialManager.register(this); 70 | }; 71 | 72 | Shell.prototype.takeBulletHit = function () { 73 | this.kill(); 74 | }; 75 | 76 | Shell.prototype.getRadius = function () { 77 | return 6; 78 | }; 79 | 80 | Shell.prototype.render = function (ctx) { 81 | ctx.save(); 82 | ctx.fillStyle = "grey"; 83 | util.fillCircle(ctx, this.cx, this.cy, this.getRadius()); 84 | ctx.restore(); 85 | }; -------------------------------------------------------------------------------- /entities/Spark.js: -------------------------------------------------------------------------------- 1 | // =============== 2 | // Enforcer sparks 3 | // =============== 4 | 5 | // Sparks are fired by tanks. 6 | // They move fast. 7 | // When they hit a wall, they slide alongside it. 8 | 9 | "use strict"; 10 | 11 | /* jshint browser: true, devel: true, globalstrict: true */ 12 | 13 | // A contructor which accepts an arbitrary descriptor object 14 | function Spark(descr) { 15 | // Common inherited setup logic from Entity 16 | this.setup(descr); 17 | 18 | this.sprite = g_sprites.EnforcerSpark[0]; 19 | 20 | // HACKED-IN AUDIO (no preloading) 21 | this.fireSound = new Audio(g_audioUrls.spark); 22 | 23 | // Make a noise when I am created (i.e. fired) 24 | if (g_sounds) this.fireSound.play(); 25 | 26 | this.baseVel = 5; 27 | this.velX = this.baseVel * Math.cos(descr.initialAngle); 28 | this.velY = this.baseVel * Math.sin(descr.initialAngle); 29 | } 30 | 31 | Spark.prototype = new Entity(); 32 | Spark.prototype.lifeSpan = 5 * SECS_TO_NOMINALS; 33 | Spark.prototype.rotationTime = SECS_TO_NOMINALS / 2; 34 | 35 | Spark.prototype.update = function (du) { 36 | spatialManager.unregister(this); 37 | 38 | this.animation += du; 39 | if (this.animation > this.rotationTime) this.animation = 0; 40 | 41 | // Handle death 42 | if (this._isDeadNow) { 43 | this.spawnFragment(5, "red"); 44 | Player.addScore(Player.scoreValues.Spark * Player.getMultiplier()); 45 | return entityManager.KILL_ME_NOW; 46 | } 47 | 48 | this.lifeSpan -= du; 49 | if (this.lifeSpan < 0) { 50 | this.spawnFragment(5, "red"); 51 | return entityManager.KILL_ME_NOW; 52 | } 53 | 54 | // Update positions 55 | this.capPositions(); 56 | this.edgeHug(); 57 | 58 | this.cx += this.velX * du; 59 | this.cy += this.velY * du; 60 | 61 | // Handle collisions 62 | var hitEntity = this.findHitEntity(); 63 | if (hitEntity) { 64 | var canTakeHit = hitEntity.takeEnemyHit; 65 | if (canTakeHit) { 66 | canTakeHit.call(hitEntity); 67 | this.spawnFragment(5, "red"); 68 | return entityManager.KILL_ME_NOW; 69 | } 70 | } 71 | 72 | spatialManager.register(this); 73 | }; 74 | 75 | Spark.prototype.edgeHug = function () { 76 | 77 | var velX = this.velX; 78 | var velY = this.velY; 79 | var cx = this.cx; 80 | var cy = this.cy; 81 | var r = this.getRadius(); 82 | var baseVel = this.baseVel; 83 | 84 | // Checking if we hit a wall 85 | var rightWallIntersect = cx + velX > consts.wallRight - r; 86 | var leftWallIntersect = cx + velX < consts.wallLeft + r; 87 | var topWallIntersect = cy + velY < consts.wallTop + consts.wallThickness + r; 88 | var bottomWallIntersect = cy + velY > consts.wallBottom - r; 89 | 90 | // Slide if we hit a wall 91 | if (leftWallIntersect || rightWallIntersect) { // LR borders 92 | this.velX = 0; 93 | this.velY = util.sign(velY) * baseVel; 94 | } 95 | if (topWallIntersect || bottomWallIntersect) { // TB borders 96 | this.velX = util.sign(velX) * baseVel; 97 | this.velY = 0; 98 | } 99 | 100 | // Literal corner cases below. //TODO: handle all of them, and refactor. 101 | // Note: A velocity component shouldn't be exactly 0 unless the spark had been 102 | // sliding against a wall. 103 | if (topWallIntersect && this.velX === 0) { 104 | this.velX = baseVel; 105 | this.velY = 0; 106 | } 107 | if (rightWallIntersect && this.velY === 0) { 108 | this.velX = 0; 109 | this.velY = baseVel; 110 | } 111 | if (bottomWallIntersect && this.velX === 0) { 112 | this.velX = -baseVel; 113 | this.velY = 0; 114 | } 115 | if (leftWallIntersect && this.velY === 0) { 116 | this.velX = 0; 117 | this.velY = -baseVel; 118 | } 119 | }; 120 | 121 | Spark.prototype.takeBulletHit = function () { 122 | this.kill(); 123 | }; 124 | 125 | Spark.prototype.getRadius = function () { 126 | return 6; 127 | }; 128 | 129 | Spark.prototype.render = function (ctx) { 130 | var temp = Math.floor(4 * this.animation / this.rotationTime); 131 | if (temp > 3) temp = 0; 132 | g_sprites.EnforcerSpark[temp].drawCentredAt(ctx, this.cx, this.cy, 0); 133 | }; -------------------------------------------------------------------------------- /entities/Spheroid.js: -------------------------------------------------------------------------------- 1 | // ======== 2 | // Spheroid 3 | // ======== 4 | 5 | // Spheroids spawn Enforcers. 6 | // Spheroids (probably...) fly around quickly and randomly. 7 | 8 | function Spheroid(descr) { 9 | 10 | // Common inherited setup logic from Entity 11 | Enemy.call(this, descr); 12 | 13 | this.sprite = g_sprites.Spheroid[5]; 14 | 15 | // Initializing speed 16 | this.baseSpeed = 3; 17 | this.velX = this.baseSpeed * util.randTrinary(); 18 | this.velY = this.baseSpeed * util.randTrinary(); 19 | this.tanksSpawned = 0; 20 | 21 | this.makeWarpParticles(); 22 | // TODO play spawning sound? 23 | } 24 | 25 | Spheroid.prototype = Object.create(Enemy.prototype); 26 | Spheroid.prototype.tankSpawnChance = 0.005; //0,5% chance of spawning a tank/update 27 | // TODO: Find a good spawn interval. 28 | Spheroid.prototype.renderPos = {cx: this.cx, cy: this.cy}; 29 | Spheroid.prototype.maxTanks = 6; 30 | Spheroid.prototype.constructionTime = SECS_TO_NOMINALS; 31 | 32 | Spheroid.prototype.update = function (du) { 33 | this.animation += du; 34 | if (this.animation > SECS_TO_NOMINALS) this.animation = 0; 35 | 36 | spatialManager.unregister(this); 37 | 38 | this.constructionTime += -du; 39 | 40 | if (!this.startPos) this.startPos = this.getPos(); 41 | 42 | // Handle death 43 | if (this._isDeadNow) { 44 | Player.addScore(Player.scoreValues.Spheroid * Player.getMultiplier()); 45 | return entityManager.KILL_ME_NOW; 46 | } 47 | 48 | if (this.isSpawning) { 49 | this.warpIn(du); 50 | } else { 51 | // maxTanks is effectively zero-indexed 52 | if (Math.random() < this.tankSpawnChance && 53 | this.tanksSpawned < this.maxTanks && 54 | this.constructionTime < 0) { 55 | this.tanksSpawned++; 56 | entityManager.createEnforcer(this.cx, this.cy); 57 | this.constructionTime = SECS_TO_NOMINALS; 58 | } 59 | 60 | this.randomWalk(); 61 | 62 | this.capPositions(); 63 | this.edgeBounce(); 64 | 65 | this.cx += this.velX * du; 66 | this.cy += this.velY * du; 67 | 68 | } 69 | spatialManager.register(this); 70 | 71 | }; 72 | 73 | Spheroid.prototype.randomWalk = function () { 74 | if (Math.random() < 0.02) { 75 | //2% chance to change direction 76 | 77 | var n = Math.floor(Math.random() * 4); 78 | switch (n) { 79 | case 0: 80 | this.velX = -this.baseSpeed; 81 | break; 82 | case 1: 83 | this.velY = -this.baseSpeed; 84 | break; 85 | case 2: 86 | this.velX = this.baseSpeed; 87 | break; 88 | case 3: 89 | this.velY = this.baseSpeed; 90 | } 91 | } 92 | }; 93 | 94 | Spheroid.prototype.takeBulletHit = function () { 95 | this.kill(); 96 | this.makeExplosion(); 97 | }; 98 | 99 | Spheroid.prototype.render = function (ctx) { 100 | if (this.isSpawning) { 101 | return; 102 | } 103 | 104 | var temp = Math.floor(8 * this.animation / SECS_TO_NOMINALS); 105 | if (temp > 7) temp = 7; 106 | g_sprites.Spheroid[temp].drawCentredAt(ctx, this.cx, this.cy, 0); 107 | }; 108 | 109 | 110 | Spheroid.prototype.colors = [ 111 | {color: "red", ratio: 1} 112 | ]; 113 | -------------------------------------------------------------------------------- /entities/Tank.js: -------------------------------------------------------------------------------- 1 | // ==== 2 | // Tank 3 | // ==== 4 | 5 | // Tanks are spawned by Quarks. Tanks fire rebounding tank shells. 6 | // Tanks roll around randomly. 7 | 8 | "use strict"; 9 | 10 | function Tank(descr) { 11 | 12 | // Common inherited setup logic from Entity 13 | Enemy.call(this, descr); 14 | 15 | this.sprite = g_sprites.Tank[0]; 16 | this.target = entityManager.findProtagonist(); 17 | 18 | // Initializing speed 19 | this.baseSpeed = 0.9; 20 | this.velX = this.baseSpeed*util.randTrinary(); 21 | this.velY = this.baseSpeed*util.randTrinary(); 22 | // TODO play spawning sound? 23 | } 24 | 25 | Tank.prototype = Object.create(Enemy.prototype); 26 | Tank.prototype.shellFireChance = 0.01; //1% chance of firing a shell/update 27 | Tank.prototype.ammo = 20; 28 | Tank.prototype.renderPos = {cx: this.cx, cy: this.cy}; 29 | Tank.prototype.dropChance = 1; // 100% chance of a random drop 30 | Tank.prototype.renderPos = this.cx; 31 | Tank.prototype.stepsize = 3; 32 | 33 | Tank.prototype.update = function (du) { 34 | 35 | spatialManager.unregister(this); 36 | 37 | if (!this.startPos) this.startPos = this.getPos(); 38 | 39 | // Handle death 40 | if (this._isDeadNow) { 41 | Player.addScore(Player.scoreValues.Tank * Player.getMultiplier()); 42 | return entityManager.KILL_ME_NOW; 43 | } 44 | 45 | this.randomWalk(); 46 | 47 | this.capPositions(); 48 | this.edgeBounce(); 49 | 50 | this.cx += this.velX * du; 51 | this.cy += this.velY * du; 52 | 53 | if (Math.random() < this.shellFireChance && this.ammo > 0) { 54 | // TODO: Do this amazing trick shot box-in AI thing. 55 | // http://www.robotron2084guidebook.com/gameplay/tanks/ 56 | var angle = util.angleTo( 57 | this.cx, 58 | this.cy, 59 | this.target.cx, 60 | this.target.cy 61 | ); 62 | this.ammo--; 63 | entityManager.fireShell(this.cx, this.cy, angle); 64 | } 65 | 66 | spatialManager.register(this); 67 | 68 | }; 69 | 70 | Tank.prototype.randomWalk = function () { 71 | if (Math.random() < 0.005) { 72 | //0.5% chance to change direction 73 | 74 | var n = Math.floor(Math.random() * 4); 75 | switch (n) { 76 | case 0: 77 | this.velX = -this.baseSpeed; 78 | break; 79 | case 1: 80 | this.velY = -this.baseSpeed; 81 | break; 82 | case 2: 83 | this.velX = this.baseSpeed; 84 | break; 85 | case 3: 86 | this.velY = this.baseSpeed; 87 | } 88 | } 89 | }; 90 | 91 | Tank.prototype.takeBulletHit = function () { 92 | this.makeExplosion(); 93 | this.kill(); 94 | }; 95 | 96 | Tank.prototype.render = function (ctx) { 97 | 98 | var dist = this.cx - this.renderPos; 99 | var left = false; 100 | if (dist < 0) left = true; 101 | var step = 0; 102 | 103 | switch(true) { 104 | case util.abs(dist) < this.stepsize: 105 | step = 0; 106 | if (left) step = 3; 107 | break; 108 | case util.abs(dist) < this.stepsize * 2: 109 | step = 1; 110 | if (left) step = 2; 111 | break; 112 | case util.abs(dist) < this.stepsize * 3: 113 | step = 2; 114 | if (left) step = 1; 115 | break; 116 | case util.abs(dist) < this.stepsize * 4: 117 | step = 3; 118 | if (left) step = 0; 119 | break; 120 | default: 121 | step = 0; 122 | this.renderPos = this.cx; 123 | } 124 | g_sprites.Tank[step].drawCentredAt(ctx, this.cx, this.cy, 0); 125 | }; 126 | 127 | Tank.prototype.colors = [ 128 | {color: "red", ratio: 0.50}, 129 | {color: "#00FF00", ratio: 0.25}, // Green 130 | {color: "blue", ratio: 0.25} 131 | ]; 132 | -------------------------------------------------------------------------------- /index.php: -------------------------------------------------------------------------------- 1 | Player.fireRate / 4) { 351 | var gunSound = new Audio(g_audioUrls.shotgunReload); 352 | gunSound.play(); 353 | this._reload = false; 354 | } 355 | 356 | for (var c = 0; c < this._categories.length; ++c) { 357 | 358 | var aCategory = this._categories[c]; 359 | var i = 0; 360 | 361 | while (i < aCategory.length) { 362 | 363 | var status = aCategory[i].update(du); 364 | 365 | if (status === this.KILL_ME_NOW) { 366 | // remove the dead guy, and shuffle the others down to 367 | // prevent a confusing gap from appearing in the array 368 | aCategory.splice(i, 1); 369 | } 370 | else { 371 | ++i; 372 | } 373 | } 374 | } 375 | }, 376 | 377 | render: function (ctx) { 378 | 379 | for (var c = 0; c < this._categories.length; ++c) { 380 | 381 | var aCategory = this._categories[c]; 382 | 383 | for (var i = 0; i < aCategory.length; ++i) { 384 | 385 | aCategory[i].render(ctx); 386 | 387 | } 388 | } 389 | } 390 | 391 | }; 392 | 393 | // Some deferred setup which needs the object to have been created first 394 | entityManager.deferredSetup(); 395 | 396 | -------------------------------------------------------------------------------- /managers/handleMouse.js: -------------------------------------------------------------------------------- 1 | // ============== 2 | // MOUSE HANDLING 3 | // ============== 4 | 5 | "use strict"; 6 | 7 | /* jshint browser: true, devel: true, globalstrict: true */ 8 | 9 | /* 10 | 0 1 2 3 4 5 6 7 8 11 | 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12 | */ 13 | 14 | var g_mouseX = 0, 15 | g_mouseY = 0, 16 | g_isMouseDown = false, 17 | 18 | $win = $(window), 19 | w = 0,h = 0, 20 | rgba = [], 21 | getWidth = function() { 22 | w = $win.innerWidth(); 23 | h = $win.innerHeight(); 24 | }; 25 | 26 | //Background color listens to mouse position 27 | $win.resize(getWidth).mousemove(function(e) { 28 | rgba = [Math.round(e.pageX/w * 255),Math.round((h-e.pageY)/h * 255),50, 0.90]; 29 | if ($(".canvasContainer:hover").length > 0) { 30 | $(document.body).css('background','black'); 31 | $(document.body).css('transition','background 0.5s ease-out'); 32 | } else { 33 | $(document.body).css("transition", ""); 34 | $(document.body).css('background','rgba('+rgba.join(',')+')'); 35 | } 36 | }).resize(); 37 | 38 | //Navigation menu interavtivity 39 | if($("#highscoreTable").length!==0) $("li#navHS").removeClass("hidden"); 40 | $("h2").click(function() {$(this).parent().find("article").toggle("slow");}); 41 | $('a[href="#highscore"]').click(function() {$(".highscore article").toggle("slow");}); 42 | $('a[href="#instructions"]').click(function() {$(".instructions article").toggle("slow");}); 43 | $('a[href="#controls"]').click(function() {$(".controls article").toggle("slow");}); 44 | $('a[href="#about"]').click(function() {$("#about article").toggle("slow");}); 45 | 46 | function handleMouseMove(evt) { 47 | 48 | // Renew mouse positions 49 | g_mouseX = evt.clientX - g_canvas.offsetLeft; 50 | g_mouseY = evt.clientY - g_canvas.offsetTop; 51 | } 52 | 53 | function handleMouseDown(evt) { 54 | 55 | // Set mouseDown 56 | g_isMouseDown = true; 57 | } 58 | 59 | function handleMouseUp(evt) { 60 | 61 | // Set mouseDown to false 62 | g_isMouseDown = false; 63 | } 64 | 65 | // Handle "up", "down" and "move" events separately. 66 | window.addEventListener("mousedown", handleMouseDown); 67 | window.addEventListener("mousemove", handleMouseMove); 68 | window.addEventListener("mouseup", handleMouseUp); 69 | 70 | function renderCrosshair(ctx) { 71 | 72 | ctx.save(); 73 | ctx.beginPath(); 74 | ctx.lineWidth = 3; 75 | ctx.moveTo(g_mouseX - 10, g_mouseY); 76 | ctx.lineTo(g_mouseX + 10, g_mouseY); 77 | ctx.moveTo(g_mouseX, g_mouseY - 10); 78 | ctx.lineTo(g_mouseX, g_mouseY + 10); 79 | ctx.closePath(); 80 | ctx.strokeStyle = 'white'; 81 | ctx.stroke(); 82 | ctx.restore(); 83 | } -------------------------------------------------------------------------------- /managers/highScores.js: -------------------------------------------------------------------------------- 1 | //========== 2 | //HIGHSCORES 3 | //========== 4 | /* 5 | highScores.js 6 | 7 | A module which handles local high score storage and display 8 | */ 9 | 10 | "use strict"; 11 | 12 | /*jslint nomen: true, white: true, plusplus: true*/ 13 | 14 | var highScores = { 15 | 16 | // "PRIVATE" DATA 17 | 18 | _localScores: [], 19 | _serverScores: [], 20 | _name: "", 21 | _render: false, 22 | 23 | // "PRIVATE" METHODS 24 | 25 | deferredSetup: function () { 26 | for (var i = 0; i < 10; i++) { 27 | this._localScores[i] = JSON.parse(localStorage.getItem("highscore" + i)) || {name: "", score: 0}; 28 | this._serverScores[i] = {name: "", score: 0}; 29 | } 30 | }, 31 | 32 | _save: function () { 33 | for (var i = 0; i < 10; i++) { 34 | localStorage.setItem("highscore" + i, JSON.stringify(this._localScores[i])); 35 | } 36 | console.log("Score saved"); 37 | }, 38 | 39 | // PUBLIC METHODS 40 | 41 | addLocalScore: function (data) { 42 | // data is an object containing a name and a score 43 | if (g_hasCheated) return; 44 | for (var i = 0; i < 10; i++) { 45 | // Check if the score is in the top 10 46 | if (data.score > this._localScores[i].score) { 47 | // Add the score and shuffle the rest down 48 | for (var j = 9; j > i; j--) { 49 | this._localScores[j] = this._localScores[j-1]; 50 | } 51 | this._localScores[i] = data; 52 | break; 53 | } 54 | } 55 | this._save(); 56 | }, 57 | 58 | addServerScore: function (data) { 59 | this._serverScores.push(data); 60 | }, 61 | 62 | reset: function () { 63 | for (var i in this._localScores) this._localScores[i] = {name: "", score: 0}; 64 | this._save(); 65 | }, 66 | 67 | resetServerScore: function () { 68 | this._serverScores = []; 69 | }, 70 | 71 | setName: function (Name) { 72 | this._name = Name; 73 | }, 74 | 75 | getName: function () { 76 | return this._name; 77 | }, 78 | 79 | renderON: function () { 80 | this._render = true; 81 | }, 82 | 83 | renderOFF: function () { 84 | this._render = false; 85 | }, 86 | 87 | render: function (ctx) { 88 | if (this._render) { 89 | ctx.save(); 90 | 91 | // display scores 92 | ctx.fillStyle = "white"; 93 | ctx.font = "bold 20px sans-serif"; 94 | var hw = g_canvas.width / 2 , hh = g_canvas.height / 2; 95 | ctx.textAlign = "center"; 96 | ctx.fillText("LOCAL", hw * 2 / 3, hh * 2 / 3); 97 | ctx.fillText("SERVER", hw * 4 / 3, hh * 2 / 3); 98 | ctx.font = "15px sans-serif"; 99 | // local scores 100 | for (var i = 0; i < this._localScores.length; i++) { 101 | if (this._localScores[i].name === "") break; 102 | ctx.textAlign = "right"; 103 | var nameStr = this._localScores[i].name; 104 | ctx.fillText(nameStr, hw * 2 / 3 - 10, hh * 2 / 3 + (i+1)*20+30); 105 | ctx.textAlign = "left"; 106 | var scoreStr = this._localScores[i].score; 107 | ctx.fillText(scoreStr, hw * 2 / 3, hh * 2 / 3 + (i+1)*20+30); 108 | } 109 | // server scores 110 | for (var i = 0; i < $("#highscoreTable tbody").find("tr").length; i++) { 111 | ctx.textAlign = "right"; 112 | nameStr = this._serverScores[i].name; 113 | ctx.fillText(nameStr, hw * 4 / 3, hh * 2 / 3 + (i+1)*20+30); 114 | ctx.textAlign = "left"; 115 | scoreStr = this._serverScores[i].score; 116 | ctx.fillText(scoreStr, hw * 4 / 3 + 10, hh * 2 / 3 + (i+1)*20+30); 117 | }; 118 | 119 | // display title 120 | ctx.fillStyle = "red"; 121 | ctx.font = "bold 60px sans-serif"; 122 | ctx.textAlign = "center"; 123 | ctx.fillText("HIGHSCORES", hw, hh / 3); 124 | 125 | // restart hint 126 | ctx.font = "bold 20px sans-serif"; 127 | var str2 = "Press R to restart the game!"; 128 | ctx.fillText(str2, hw, hh * 14 / 8); 129 | 130 | // Music volume display 131 | var vol = Math.round(g_bgm.getVolume()*100); 132 | if (!g_music) vol = 0; 133 | var volStr = "MUSIC VOLUME: "+vol+"%"; 134 | ctx.fillStyle = "gray"; 135 | ctx.fillText(volStr,hw,2*hh-10); 136 | 137 | ctx.restore(); 138 | } else { 139 | levelManager.drawMenu(ctx, "GAME OVER", "re"); 140 | } 141 | } 142 | }; 143 | 144 | highScores.deferredSetup(); -------------------------------------------------------------------------------- /managers/levelManager.js: -------------------------------------------------------------------------------- 1 | //============= 2 | //LEVEL MANAGER 3 | //============= 4 | /* 5 | levelManager.js 6 | 7 | A module which handles level selection and transition. 8 | */ 9 | 10 | "use strict"; 11 | 12 | // Tell jslint not to complain about my use of underscore prefixes (nomen), 13 | // my flattening of some indentation (white), or my use of incr/decr ops 14 | // (plusplus). 15 | // 16 | /*jslint nomen: true, white: true, plusplus: true*/ 17 | 18 | var levelManager = { 19 | 20 | // "PRIVATE" DATA 21 | _levelSpecs: [ 22 | // Each number in the level array represents how many entities of the 23 | // corresponding type should be created. There is always one protagonist, 24 | // so we skip him in the level description 25 | // Key: 26 | // Family, Electrodes, Grunts, Hulks, Spheroids, Brains, Quarks (not the Star Trek DS9 version) 27 | 28 | [], // level "0", skipped automatically 29 | [2, 0, 6], 30 | [3, 4, 8, 2], 31 | [5, 6, 10, 4] 32 | ], 33 | 34 | _levelChangingSound: new Audio(g_audioUrls.newlevel), 35 | 36 | _isChangingLevel: false, 37 | _isRefreshingLevel: false, 38 | _changingTimer: 2 * SECS_TO_NOMINALS, 39 | 40 | _onMenu: true, 41 | _isGameOver: false, 42 | _isWon: false, 43 | 44 | // Less private data 45 | numberOfEntities: 0, // Default, overridden in startLevel(). 46 | 47 | // PUBLIC METHODS 48 | 49 | startLevel: function () { 50 | document.getElementById("formDiv").className = "hidden"; 51 | // Create a fresh level 52 | entityManager.clearAll(); 53 | spatialManager.resetAll(); 54 | this._isChangingLevel = true; 55 | this._onMenu = false; 56 | this._isGameOver = false; 57 | 58 | var randomLevelRequired = Player.level >= this._levelSpecs.length; 59 | var L = Player.level; 60 | if (L % 5 !== 0 && g_sounds) { 61 | this._levelChangingSound.volume = 0.2; 62 | this._levelChangingSound.play(); 63 | } 64 | 65 | // A hack to remove the lag from the first power up 66 | //if (L === 1) entityManager.createPowerup(0,0); 67 | 68 | if (randomLevelRequired) { 69 | var randomlevel = util.generateLevel(L); 70 | entityManager.init(randomlevel); 71 | 72 | this.numberOfEntities = randomlevel.reduce(function (a, b) { 73 | return a + b; 74 | }, 0); 75 | } 76 | else { 77 | entityManager.init(this._levelSpecs[Player.level]); 78 | this.numberOfEntities = this._levelSpecs[Player.level].reduce(function (a, b) { 79 | return a + b; 80 | }, 0); 81 | } 82 | }, 83 | 84 | continueLevel: function () { 85 | // Reset all remaining entities in the level 86 | // Used when the player dies, but has extra lives remaining 87 | this._isChangingLevel = true; 88 | this._isRefreshingLevel = true; 89 | }, 90 | 91 | nextLevel: function () { 92 | Player.addLevel(); 93 | this.startLevel(); 94 | }, 95 | 96 | prevLevel: function () { 97 | Player.subtractLevel(); 98 | this.startLevel(); 99 | }, 100 | 101 | renderLevelChanger: function (ctx) { 102 | 103 | var halfWidth = g_canvas.width / 2; 104 | var halfHeight = (g_canvas.height - consts.wallTop) / 2; 105 | var yMiddle = consts.wallTop + halfHeight; 106 | var layerOffsetX = 5; 107 | var layerOffsetY = halfHeight / (halfWidth / layerOffsetX); 108 | var layers = halfWidth / layerOffsetX; 109 | 110 | ctx.save(); 111 | 112 | if (this._isRefreshingLevel) { 113 | 114 | var alpha; 115 | if (this._changingTimer > SECS_TO_NOMINALS) { 116 | alpha = (2 * SECS_TO_NOMINALS - this._changingTimer) / SECS_TO_NOMINALS; 117 | } else { 118 | alpha = this._changingTimer / SECS_TO_NOMINALS; 119 | if (alpha < 0) alpha = 0; 120 | entityManager.clearPartial(); 121 | entityManager.resetPos(); 122 | } 123 | ctx.globalAlpha = alpha; 124 | ctx.fillStyle = "red"; 125 | ctx.fillRect( 126 | consts.wallLeft, 127 | consts.wallTop + consts.wallThickness, 128 | consts.wallRight - consts.wallThickness, 129 | consts.wallBottom - consts.wallThickness 130 | ); 131 | 132 | } else { 133 | 134 | if (this._changingTimer > SECS_TO_NOMINALS) { 135 | 136 | var range = (2 * SECS_TO_NOMINALS - this._changingTimer) / SECS_TO_NOMINALS; 137 | var currentLayer = Math.floor(range * layers); 138 | 139 | for (var i = 1; i < currentLayer; i++) { 140 | if (i % consts.colors.length < i * consts.colors.length) { 141 | ctx.fillStyle = consts.colors[i % consts.colors.length]; 142 | } 143 | ctx.fillRect( 144 | halfWidth - i * layerOffsetX, 145 | yMiddle - i * layerOffsetY, 146 | i * layerOffsetX * 2, 147 | i * layerOffsetY * 2 148 | ); 149 | } 150 | } else { 151 | 152 | var range = this._changingTimer / SECS_TO_NOMINALS; 153 | var currentLayer = Math.ceil(range * layers); 154 | 155 | for (var i = 1; i < currentLayer; i++) { 156 | if (i % consts.colors.length < i * consts.colors.length) { 157 | ctx.fillStyle = consts.colors[i % consts.colors.length]; 158 | } 159 | ctx.fillRect( 160 | i * layerOffsetX, 161 | consts.wallTop + i * layerOffsetY, 162 | g_canvas.width - i * layerOffsetX * 2, 163 | g_canvas.height - consts.wallTop - i * layerOffsetY * 2 164 | ); 165 | } 166 | 167 | range = (SECS_TO_NOMINALS - this._changingTimer) / SECS_TO_NOMINALS; 168 | currentLayer = Math.ceil(range * layers); 169 | 170 | ctx.fillStyle = "black"; 171 | ctx.fillRect( 172 | halfWidth - currentLayer * layerOffsetX, 173 | yMiddle - currentLayer * layerOffsetY, 174 | currentLayer * layerOffsetX * 2, 175 | currentLayer * layerOffsetY * 2 176 | ); 177 | } 178 | } 179 | 180 | ctx.restore(); 181 | 182 | // Reset changing timer when level changing is complete 183 | if (this._changingTimer < 0) { 184 | this._isChangingLevel = false; 185 | this._isRefreshingLevel = false; 186 | this._changingTimer = 2 * SECS_TO_NOMINALS; 187 | } 188 | }, 189 | 190 | reduceTimer: function (du) { 191 | this._changingTimer -= du; 192 | }, 193 | 194 | isChangingLevel: function () { 195 | return this._isChangingLevel; 196 | }, 197 | 198 | isRefreshingLevel: function () { 199 | return this._isRefreshingLevel; 200 | }, 201 | 202 | // ----------------- 203 | // Main Menu Methods 204 | 205 | isInMenu: function () { 206 | return this._onMenu; 207 | }, 208 | 209 | renderMenu: function (ctx) { 210 | this.drawMenu(ctx, "ROBOTRON"); 211 | }, 212 | 213 | drawMenu: function (ctx, str, re) { 214 | if (str == undefined) str = ""; 215 | if (re !== "re") re = ""; 216 | var str2 = "Press R to " + re + "start the game!"; 217 | var hw = g_canvas.width / 2 , hh = g_canvas.height / 2; 218 | 219 | ctx.save(); 220 | ctx.fillStyle = "#2b0628"; 221 | ctx.fillRect(0, hh / 2, hw * 2, hh); 222 | 223 | ctx.strokeStyle="white"; 224 | ctx.lineWidth=3; 225 | ctx.beginPath(); 226 | ctx.moveTo(0, hh / 2); 227 | ctx.lineTo(hw * 2, hh / 2); 228 | ctx.moveTo(0, hh*1.5); 229 | ctx.lineTo(hw * 2, hh*1.5); 230 | ctx.stroke(); 231 | 232 | ctx.fillStyle = "red"; 233 | ctx.textAlign = "center"; 234 | 235 | ctx.font = "bold 60px sans-serif"; 236 | ctx.fillText(str, hw, hh); 237 | 238 | ctx.font = "bold 20px sans-serif"; 239 | ctx.fillText(str2, hw, hh * 3 / 2 - 10); //10 is the font's halfheight 240 | 241 | // Music volume display 242 | var vol = Math.round(g_bgm.getVolume()*100); 243 | if (!g_music) vol = 0; 244 | var volStr = "MUSIC VOLUME: "+vol+"%"; 245 | ctx.fillStyle = "gray"; 246 | ctx.fillText(volStr,hw,2*hh-10); 247 | 248 | ctx.restore(); 249 | }, 250 | 251 | // ----------------- 252 | // Game Over Methods 253 | 254 | gameOver: function () { 255 | this._isGameOver = true; 256 | this._isChangingLevel = true; 257 | Player.addLives(); 258 | $("#formDiv").removeClass("hidden"); 259 | }, 260 | 261 | isGameOver: function () { 262 | return this._isGameOver; 263 | }, 264 | 265 | renderGameOver: function (ctx) { 266 | highScores.render(ctx); 267 | } 268 | }; -------------------------------------------------------------------------------- /managers/playlist.js: -------------------------------------------------------------------------------- 1 | //============ 2 | //BGM PLAYLIST 3 | //============ 4 | /* 5 | playlist.js 6 | 7 | A module which contains a list of background music and 8 | handles playing them. 9 | */ 10 | 11 | var g_bgm = { 12 | 13 | // Private Data 14 | // 15 | 16 | _list: [], 17 | _currentSong: 0, 18 | _volume: 1, 19 | 20 | 21 | // Public Methods 22 | // 23 | 24 | init: function () { 25 | this._list.push(new Audio(g_bgmUrls.music)); 26 | this._list.push(new Audio(g_bgmUrls.instarem)); 27 | this._list.push(new Audio(g_bgmUrls.CrazyComets)); 28 | this._list.push(new Audio(g_bgmUrls.labrat)); 29 | 30 | // Handle song changing 31 | for (var i = 0; i < this._list.length; i++) { 32 | this._list[i].addEventListener("ended", this.nextSong); 33 | } 34 | console.log(this._list); 35 | }, 36 | 37 | play: function () { 38 | this._list[this._currentSong].play(); 39 | }, 40 | 41 | pause: function () { 42 | this._list[this._currentSong].pause(); 43 | }, 44 | 45 | reset: function () { 46 | this._list[this._currentSong].currentTime = 0; 47 | }, 48 | 49 | getVolume: function () { 50 | return this._volume; 51 | }, 52 | 53 | incVolume: function () { 54 | if (this._volume < 1) { 55 | if (this._volume + 0.05 > 1) this._volume = 1; 56 | else this._volume += 0.05; 57 | this._list[this._currentSong].volume = this._volume; 58 | } 59 | }, 60 | 61 | decVolume: function () { 62 | if (this._volume > 0) { 63 | if (this._volume - 0.05 < 0) this._volume = 0; 64 | else this._volume -= 0.05; 65 | this._list[this._currentSong].volume = this._volume; 66 | } 67 | }, 68 | 69 | nextSong: function (evt) { 70 | g_bgm.pause(); 71 | g_bgm.reset(); 72 | g_bgm._currentSong++; 73 | if (g_bgm._currentSong >= g_bgm._list.length) g_bgm._currentSong = 0; 74 | g_bgm.play(); 75 | }, 76 | 77 | prevSong: function (evt) { 78 | g_bgm.pause(); 79 | g_bgm.reset(); 80 | g_bgm._currentSong--; 81 | if (g_bgm._currentSong < 0) g_bgm._currentSong = g_bgm._list.length - 1; 82 | g_bgm.play(); 83 | } 84 | } 85 | 86 | g_bgm.init(); -------------------------------------------------------------------------------- /managers/spatialManager.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | spatialManager.js 4 | 5 | A module which handles spatial lookup, as required for... 6 | e.g. general collision detection. 7 | 8 | */ 9 | 10 | "use strict"; 11 | 12 | /* jshint browser: true, devel: true, globalstrict: true */ 13 | 14 | /* 15 | 0 1 2 3 4 5 6 7 8 16 | 12345678901234567890123456789012345678901234567890123456789012345678901234567890 17 | */ 18 | 19 | var spatialManager = { 20 | 21 | // "PRIVATE" DATA 22 | 23 | _nextSpatialID: 1, // make all valid IDs non-falsey (i.e. don't start at 0) 24 | 25 | _entities: [], 26 | 27 | // "PRIVATE" METHODS 28 | // 29 | // 30 | 31 | 32 | // PUBLIC METHODS 33 | 34 | getNewSpatialID: function () { 35 | // Use it, then increment. 36 | return this._nextSpatialID++; 37 | }, 38 | 39 | register: function (entity) { 40 | var spatialID = entity.getSpatialID(); 41 | this._entities[spatialID] = entity; 42 | }, 43 | 44 | unregister: function (entity) { 45 | var spatialID = entity.getSpatialID(); 46 | 47 | // Unregistering means "deletion" from the _entities array. 48 | // This fills the array with "undefined"s, but the for-in loops (see below) 49 | // seem to not care. 50 | delete this._entities[spatialID]; 51 | }, 52 | 53 | findEntityInRange: function (posX, posY, radius) { 54 | 55 | // for-in loop used due to sparseness of the _entities array. 56 | for (var i in this._entities) { 57 | var entity = this._entities[i]; 58 | // Circle-based distance checking 59 | var distSq = util.distSq(posX, posY, entity.cx, entity.cy); 60 | var limSq = util.square(radius + entity.getRadius()); 61 | if (distSq < limSq) { 62 | return entity; 63 | } 64 | } 65 | return null; 66 | 67 | }, 68 | 69 | resetAll: function () { 70 | this._nextSpatialID = 1; 71 | this._entities.length=0; 72 | }, 73 | 74 | render: function (ctx) { 75 | var oldStyle = ctx.strokeStyle; 76 | ctx.strokeStyle = "red"; 77 | 78 | for (var ID in this._entities) { 79 | var e = this._entities[ID]; 80 | util.strokeCircle(ctx, e.cx, e.cy, e.getRadius()); 81 | } 82 | ctx.strokeStyle = oldStyle; 83 | } 84 | 85 | }; 86 | -------------------------------------------------------------------------------- /particles/AfterImage.js: -------------------------------------------------------------------------------- 1 | //========== 2 | //AfterImage 3 | //========== 4 | 5 | "use strict"; 6 | 7 | /* jshint browser: true, devel: true, globalstrict: true */ 8 | 9 | function AfterImage(descr) { 10 | // Apply all setup properies from the (optional) descriptor 11 | for (var property in descr) { 12 | this[property] = descr[property]; 13 | } 14 | } 15 | 16 | AfterImage.prototype.duration = SECS_TO_NOMINALS / 4; 17 | 18 | AfterImage.prototype.update = function (du) { 19 | this.duration += -du; 20 | if (this.duration < 0) return entityManager.KILL_ME_NOW; 21 | }; 22 | 23 | AfterImage.prototype.render = function (ctx) { 24 | ctx.save(); 25 | ctx.globalAlpha = this.duration / (2 * AfterImage.prototype.duration); 26 | this.image.drawCentredAt(ctx, this.cx, this.cy, 0); 27 | ctx.restore(); 28 | }; -------------------------------------------------------------------------------- /particles/Particle.js: -------------------------------------------------------------------------------- 1 | // ================ 2 | // Particle effects 3 | // ================ 4 | 5 | 6 | "use strict"; 7 | 8 | /* jshint browser: true, devel: true, globalstrict: true */ 9 | 10 | // A generic contructor which accepts an arbitrary descriptor object 11 | function Particle(descr) { 12 | // Apply all setup properies from the (optional) descriptor 13 | for (var property in descr) { 14 | this[property] = descr[property]; 15 | } 16 | 17 | this.animation = 0; 18 | } 19 | 20 | Particle.prototype.lifeSpan = SECS_TO_NOMINALS / 2; 21 | Particle.prototype.radius = 3; 22 | Particle.prototype.speed = 0.5; 23 | Particle.prototype.velX = 0; 24 | Particle.prototype.velY = 0; 25 | 26 | Particle.prototype.update = function (du) { 27 | 28 | this.lifeSpan -= du; 29 | if (this.lifeSpan < 0) return entityManager.KILL_ME_NOW; 30 | 31 | if (this.dirn) { 32 | this.velX = Math.cos(this.dirn) * this.speed; 33 | this.velY = Math.sin(this.dirn) * this.speed; 34 | } 35 | 36 | this.cx += this.velX * du; 37 | this.cy += this.velY * du; 38 | }; 39 | 40 | Particle.prototype.render = function (ctx) { 41 | ctx.save(); 42 | var fadeThresh = 3 * Particle.prototype.lifeSpan / 4; 43 | var radius = this.radius; 44 | if (this.lifeSpan < fadeThresh) { 45 | ctx.globalAlpha = this.lifeSpan / fadeThresh; 46 | radius = this.radius * this.lifeSpan / fadeThresh; 47 | } 48 | ctx.fillStyle = this.color; 49 | util.fillCircle(ctx, this.cx, this.cy, radius); 50 | ctx.restore(); 51 | }; -------------------------------------------------------------------------------- /phplogic/highscores.class.php: -------------------------------------------------------------------------------- 1 | pdo = $pdo; 14 | $this->pdo->exec( 15 | "CREATE TABLE IF NOT EXISTS highscores ( 16 | id INTEGER PRIMARY KEY, 17 | name TEXT, 18 | score INTEGER)" 19 | ); 20 | } 21 | 22 | public function Insert($name, $score) { 23 | //Prevent injection. 24 | $name = strip_tags($name); 25 | $score = strip_tags($score); 26 | 27 | //Insert values 28 | $query = $this->pdo->prepare( 29 | "INSERT INTO highscores (name, score) 30 | VALUES (:name, :score)" 31 | ); 32 | $result = $query->execute(array('name' => $name, 'score' => $score)); 33 | if (!$result) {return false;} 34 | 35 | //If the table has more than 10 rows, delete the one with the lowest score 36 | $query = $this->pdo->prepare( 37 | "SELECT id, name, score 38 | FROM highscores" 39 | ); 40 | $result = $query->execute(); 41 | $data = $query->fetchAll(PDO::FETCH_ASSOC); 42 | if (isset($data) && sizeof($data) > 10 && $result) { 43 | $query = $this->pdo->prepare( 44 | "DELETE FROM highscores 45 | WHERE id=( 46 | SELECT MAX(id) 47 | FROM highscores 48 | WHERE score=( 49 | SELECT MIN(score) 50 | FROM highscores 51 | ) 52 | )" 53 | ); 54 | $result = $query->execute(); 55 | } 56 | return $result; 57 | } 58 | 59 | public function ShowHighscores() { 60 | //Fetch the data in right order 61 | $query = $this->pdo->prepare( 62 | "SELECT id, name, score 63 | FROM highscores 64 | ORDER BY score 65 | DESC LIMIT 10" 66 | ); 67 | $result = $query->execute(); 68 | if (!$result) {return;} 69 | $data = $query->fetchAll(PDO::FETCH_ASSOC); 70 | if (!$data) {return;} 71 | 72 | //Put the data in the result array as induvidual highscores. 73 | $results = array(); 74 | foreach ($data as $row) { 75 | $hs = new Highscore(); 76 | $hs->id = $row['id']; 77 | $hs->name = $row['name']; 78 | $hs->score = $row['score']; 79 | 80 | $results[] = $hs; 81 | } 82 | 83 | //Output it to the output div. 84 | if(isset($results)): ?> 85 | 86 |
87 |

HIGHSCORE

88 |
89 |

Top 10 highscores

90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 |
RankNameScore
name ?>score ?>
107 |
108 |
109 | 110 | Insert($_GET['name'], $_GET['score']); 9 | if($result) {$highscores->ShowHighScores();} 10 | } 11 | } 12 | ?> -------------------------------------------------------------------------------- /utils/consts.js: -------------------------------------------------------------------------------- 1 | // consts.js 2 | // 3 | // A module of generic constants 4 | 5 | "use strict"; 6 | 7 | 8 | var consts = { 9 | 10 | FULL_CIRCLE: Math.PI * 2, 11 | RADIANS_PER_DEGREE: Math.PI / 180.0, 12 | 13 | wallThickness: 5, 14 | wallTop: 30, 15 | wallBottom: g_canvas.height - 5, 16 | wallLeft: 5, 17 | wallRight: g_canvas.width - 5, 18 | 19 | colors: [] 20 | }; -------------------------------------------------------------------------------- /utils/urls.js: -------------------------------------------------------------------------------- 1 | /* 2 | // Use this code block if you have the image and sound folders 3 | g_imgUrls = { 4 | Brain : "images/Brain.png", 5 | Child : "images/Child.png", 6 | Dad : "images/Dad.png", 7 | Enforcer : "images/Enforcer.png", 8 | Grunt : "images/Grunt.png", 9 | Hulk : "images/Hulk.png", 10 | Mom : "images/Mom.png", 11 | Protagonist : "images/Protagonist.png", 12 | Prog : "images/NewProg.png", 13 | Quark : "images/Quark.png", 14 | Spheroid : "images/Spheroid.png", 15 | Tank : "images/Tank.png", 16 | PowerUps: "images/PowerUps.png", 17 | 18 | BlackDiamond : "images/BlackDiamond.png", 19 | Checkers : "images/Checkers.png", 20 | Diamond : "images/Diamond.png", 21 | Dizzy : "images/Dizzy.png", 22 | EnforcerSpark : "images/EnforcerSpark.png", 23 | Extralife : "images/extralife.png", 24 | Rectangle : "images/Rectangle.png", 25 | Skull : "images/Skull.png", 26 | Spark : "images/Spark.png", 27 | Square : "images/Square.png", 28 | Triangle : "images/Triangle.png", 29 | HumanScore : "images/HumanScore.png" 30 | }; 31 | 32 | g_audioUrls = { 33 | brains : "sounds/brains.wav", 34 | enfspark : "sounds/enfspark.wav", 35 | explode : "sounds/explode.wav", 36 | explosion : "sounds/explosion.wav", 37 | familypick : "sounds/familypick.wav", 38 | familypickrampage : "sounds/familypickrampage.wav", 39 | familydead : "sounds/familydead.wav", 40 | firstlevel : "sounds/firstlevel.wav", 41 | newlevel : "sounds/newlevel.wav", 42 | playerdead : "sounds/playerdead.wav", 43 | shot : "sounds/shot.wav", 44 | shell : "sounds/shell.mp3", 45 | spark : "sounds/spark.mp3", 46 | startsound : "sounds/startsound.wav", 47 | walk : "sounds/walk.wav", 48 | loselife : "sounds/loselife.mp3", 49 | pickitem: "sounds/pickitem.mp3", 50 | machineGun : "sounds/laser.wav", 51 | shotgunFire : "sounds/shotgunFire.mp3", 52 | shotgunReload : "sounds/shotgunReload.mp3" 53 | }; 54 | 55 | g_bgmUrls = { 56 | CrazyComets : "sounds/CrazyComets.mp3", 57 | music : "sounds/rafmagnad11.mp3", 58 | instarem: "sounds/instant-remedy.mp3", 59 | labrat : "sounds/JazzJackrabbit2LaboratoryLevel.mp3" 60 | }; 61 | */ 62 | 63 | // Use this code block if you DO NOT have the image and sound folders 64 | g_imgUrls = { 65 | Brain : "https://notendur.hi.is/~odv1/Robotron/images/Brain.png", 66 | Child : "https://notendur.hi.is/~odv1/Robotron/images/Child.png", 67 | Dad : "https://notendur.hi.is/~odv1/Robotron/images/Dad.png", 68 | Enforcer : "https://notendur.hi.is/~odv1/Robotron/images/Enforcer.png", 69 | Grunt : "https://notendur.hi.is/~odv1/Robotron/images/Grunt.png", 70 | Hulk : "https://notendur.hi.is/~odv1/Robotron/images/Hulk.png", 71 | Mom : "https://notendur.hi.is/~odv1/Robotron/images/Mom.png", 72 | Protagonist : "https://notendur.hi.is/~odv1/Robotron/images/Protagonist.png", 73 | Prog : "https://notendur.hi.is/~odv1/Robotron/images/NewProg.png", 74 | Quark : "https://notendur.hi.is/~odv1/Robotron/images/Quark.png", 75 | Spheroid : "https://notendur.hi.is/~odv1/Robotron/images/Spheroid.png", 76 | Tank : "https://notendur.hi.is/~odv1/Robotron/images/Tank.png", 77 | PowerUps: "https://notendur.hi.is/~odv1/Robotron/images/PowerUps.png", 78 | BlackDiamond : "https://notendur.hi.is/~odv1/Robotron/images/BlackDiamond.png", 79 | Checkers : "https://notendur.hi.is/~odv1/Robotron/images/Checkers.png", 80 | Diamond : "https://notendur.hi.is/~odv1/Robotron/images/Diamond.png", 81 | Dizzy : "https://notendur.hi.is/~odv1/Robotron/images/Dizzy.png", 82 | EnforcerSpark : "https://notendur.hi.is/~odv1/Robotron/images/EnforcerSpark.png", 83 | Extralife : "https://notendur.hi.is/~odv1/Robotron/images/extralife.png", 84 | Rectangle : "https://notendur.hi.is/~odv1/Robotron/images/Rectangle.png", 85 | Skull : "https://notendur.hi.is/~odv1/Robotron/images/Skull.png", 86 | Spark : "https://notendur.hi.is/~odv1/Robotron/images/Spark.png", 87 | Square : "https://notendur.hi.is/~odv1/Robotron/images/Square.png", 88 | Triangle : "https://notendur.hi.is/~odv1/Robotron/images/Triangle.png", 89 | HumanScore : "https://notendur.hi.is/~odv1/Robotron/images/HumanScore.png" 90 | }; 91 | 92 | g_audioUrls = { 93 | brains : "https://notendur.hi.is/~odv1/Robotron/sounds/brains.wav", 94 | enfspark : "https://notendur.hi.is/~odv1/Robotron/sounds/enfspark.wav", 95 | explode : "https://notendur.hi.is/~odv1/Robotron/sounds/explode.wav", 96 | explosion : "https://notendur.hi.is/~odv1/Robotron/sounds/explosion.wav", 97 | familypick : "https://notendur.hi.is/~odv1/Robotron/sounds/familypick.wav", 98 | familypickrampage : "https://notendur.hi.is/~odv1/Robotron/sounds/familypickrampage.wav", 99 | familydead : "https://notendur.hi.is/~odv1/Robotron/sounds/familydead.wav", 100 | firstlevel : "https://notendur.hi.is/~odv1/Robotron/sounds/firstlevel.wav", 101 | newlevel : "https://notendur.hi.is/~odv1/Robotron/sounds/newlevel.wav", 102 | playerdead : "https://notendur.hi.is/~odv1/Robotron/sounds/playerdead.wav", 103 | shot : "https://notendur.hi.is/~odv1/Robotron/sounds/shot.wav", 104 | shell : "https://notendur.hi.is/~odv1/Robotron/sounds/shell.mp3", 105 | spark : "https://notendur.hi.is/~odv1/Robotron/sounds/spark.mp3", 106 | startsound : "https://notendur.hi.is/~odv1/Robotron/sounds/startsound.wav", 107 | walk : "https://notendur.hi.is/~odv1/Robotron/sounds/walk.wav", 108 | loselife : "https://notendur.hi.is/~odv1/Robotron/sounds/loselife.mp3", 109 | pickitem: "https://notendur.hi.is/~odv1/Robotron/sounds/pickitem.mp3", 110 | machineGun : "https://notendur.hi.is/~odv1/Robotron/sounds/laser.wav", 111 | shotgunFire : "https://notendur.hi.is/~odv1/Robotron/sounds/shotgunFire.mp3", 112 | shotgunReload : "https://notendur.hi.is/~odv1/Robotron/sounds/shotgunReload.mp3" 113 | }; 114 | 115 | g_bgmUrls = { 116 | CrazyComets : "https://notendur.hi.is/~odv1/Robotron/sounds/CrazyComets.mp3", 117 | music : "https://notendur.hi.is/~odv1/Robotron/sounds/rafmagnad11.mp3", 118 | instarem : "https://notendur.hi.is/~odv1/Robotron/sounds/instant-remedy.mp3", 119 | labrat : "https://notendur.hi.is/~odv1/Robotron/sounds/JazzJackrabbit2LaboratoryLevel.mp3" 120 | }; 121 | -------------------------------------------------------------------------------- /utils/util.js: -------------------------------------------------------------------------------- 1 | // util.js 2 | // 3 | // A module of utility functions, with no private elements to hide. 4 | // An easy case; just return an object containing the public stuff. 5 | 6 | "use strict"; 7 | 8 | 9 | var util = { 10 | 11 | // MATH 12 | // ====== 13 | sign: function (x) { 14 | if (x < 0) { 15 | return -1; 16 | } else if (x > 0) { 17 | return 1; 18 | } 19 | return 0; 20 | }, 21 | 22 | abs: function (x) { 23 | if (x < 0) { 24 | return -x; 25 | } 26 | return x; 27 | }, 28 | 29 | // Returns true if the two numbers are "similar" according to an arbitrary definition. 30 | similar: function(x,y) { 31 | var similarScale = 0.9*this.abs(x) <= this.abs(y) && 0.9*this.abs(y) <= this.abs(x); 32 | var sameSign = this.sign(x) === this.sign(y); 33 | if (similarScale && sameSign) { 34 | return true; 35 | } 36 | return false; 37 | }, 38 | 39 | // RANGES 40 | // ====== 41 | 42 | clampRange: function (value, lowBound, highBound) { 43 | if (value < lowBound) { 44 | value = lowBound; 45 | } else if (value > highBound) { 46 | value = highBound; 47 | } 48 | return value; 49 | }, 50 | 51 | wrapRange: function (value, lowBound, highBound) { 52 | while (value < lowBound) { 53 | value += (highBound - lowBound); 54 | } 55 | while (value > highBound) { 56 | value -= (highBound - lowBound); 57 | } 58 | return value; 59 | }, 60 | 61 | isBetween: function (value, lowBound, highBound) { 62 | if (value < lowBound) { 63 | return false; 64 | } 65 | if (value > highBound) { 66 | return false; 67 | } 68 | return true; 69 | }, 70 | 71 | 72 | // RANDOMNESS 73 | // ========== 74 | 75 | randRange: function (min, max) { 76 | return (min + Math.random() * (max - min)); 77 | }, 78 | 79 | // Returns -1, 0 or 1 80 | randTrinary: function() { 81 | return Math.floor(Math.random()*3)-1; 82 | }, 83 | 84 | randSign: function() { 85 | return Math.random() < 0.5 ? 1 : -1; 86 | }, 87 | 88 | 89 | // MISC 90 | // ==== 91 | 92 | square: function (x) { 93 | return x * x; 94 | }, 95 | 96 | angleTo: function (x1, y1, x2, y2) { 97 | var angle = Math.atan2(y2 - y1, x2 - x1); 98 | if (angle < 0) 99 | angle += 2 * Math.PI; 100 | return angle; 101 | }, 102 | 103 | 104 | // DISTANCES 105 | // ========= 106 | 107 | distSq: function (x1, y1, x2, y2) { 108 | return this.square(x2 - x1) + this.square(y2 - y1); 109 | }, 110 | 111 | wrappedDistSq: function (x1, y1, x2, y2, xWrap, yWrap) { 112 | var dx = Math.abs(x2 - x1), 113 | dy = Math.abs(y2 - y1); 114 | if (dx > xWrap / 2) { 115 | dx = xWrap - dx; 116 | } 117 | ; 118 | if (dy > yWrap / 2) { 119 | dy = yWrap - dy; 120 | } 121 | return this.square(dx) + this.square(dy); 122 | }, 123 | 124 | 125 | // CANVAS OPS 126 | // ========== 127 | 128 | clearCanvas: function (ctx) { 129 | var prevfillStyle = ctx.fillStyle; 130 | ctx.fillStyle = "black"; 131 | ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); 132 | ctx.fillStyle = prevfillStyle; 133 | 134 | //Display the color array 135 | /*ctx.save(); 136 | for (var i = 0; i < consts.colors.length; i++) { 137 | ctx.fillStyle = consts.colors[i]; 138 | ctx.fillRect(i*(g_canvas.width / consts.colors.length), 550, 139 | (i+1)*(g_canvas.width / consts.colors.length), 50 140 | ); 141 | } 142 | ctx.restore();*/ 143 | }, 144 | 145 | strokeCircle: function (ctx, x, y, r) { 146 | ctx.beginPath(); 147 | ctx.arc(x, y, r, 0, Math.PI * 2); 148 | ctx.stroke(); 149 | }, 150 | 151 | fillCircle: function (ctx, x, y, r) { 152 | ctx.beginPath(); 153 | ctx.arc(x, y, r, 0, Math.PI * 2); 154 | ctx.fill(); 155 | }, 156 | 157 | fillBox: function (ctx, x, y, w, h, style) { 158 | var oldStyle = ctx.fillStyle; 159 | ctx.fillStyle = style; 160 | ctx.fillRect(x, y, w, h); 161 | ctx.fillStyle = oldStyle; 162 | }, 163 | 164 | RGB2Color: function (r,g,b) { 165 | return '#' + this.byte2Hex(r) + this.byte2Hex(g) + this.byte2Hex(b); 166 | }, 167 | 168 | byte2Hex: function (n) { 169 | return String("0123456789ABCDEF".substr((n >> 4) & 0x0F,1)) + "0123456789ABCDEF".substr(n & 0x0F,1); 170 | }, 171 | 172 | //Called when initializing the game 173 | makeColorArray: function () { 174 | for (var i = 0; i < 32; ++i) { 175 | var r = Math.sin(0.2*i + 0) * 127 + 128; 176 | var g = Math.sin(0.2*i + 2) * 127 + 128; 177 | var b = Math.sin(0.2*i + 4) * 127 + 128; 178 | consts.colors.push(this.RGB2Color(r,g,b)); 179 | } 180 | }, 181 | 182 | 183 | 184 | // LEVEL GENERATOR 185 | // =============== 186 | 187 | generateLevel: function (L) { 188 | 189 | var randomlevel = []; 190 | 191 | switch (true) { 192 | case (L + 1) % 10 === 0: 193 | // Grunt wave 194 | if (g_Debug) console.log("grunts"); 195 | randomlevel.push(10); // Family 196 | randomlevel.push(3 + Math.floor(L / 3)); // Electrodes 197 | randomlevel.push(Math.floor(Math.random() * 6) + 2 * L); // Grunts 198 | randomlevel.push(Math.floor(Math.random() * 5)); // Hulks 199 | break; 200 | case L % 5 === 0: 201 | // Brain wave (hur hur) 202 | if (g_Debug) console.log("brains"); 203 | randomlevel.push(15); // Family 204 | randomlevel.push(3 + Math.floor(L / 3)); // Electrodes 205 | randomlevel.push(Math.floor(Math.random() * 5) + 4); // Grunts 206 | randomlevel.push(0); // Hulks 207 | randomlevel.push(0); // Spheroids 208 | randomlevel.push(Math.floor(Math.random() * 7) + Math.floor(L / 5)); // Brains 209 | break; 210 | case (L + 3) % 5 === 0: 211 | // Tank wave 212 | if (g_Debug) console.log("tanks"); 213 | randomlevel.push(10); // Family 214 | randomlevel.push(0); // Electrodes 215 | randomlevel.push(0); // Grunts 216 | randomlevel.push(3 + Math.floor(L / 2)); // Hulks 217 | randomlevel.push(0); // Spheroids 218 | randomlevel.push(0); // Brains 219 | randomlevel.push(Math.floor(L / 2)); // Quarks 220 | break; 221 | case (L + 6) % 10 === 0: 222 | // Hulk wave or Enforcer/Tank wave 223 | randomlevel.push(10); // Family 224 | randomlevel.push(3 + Math.floor(L / 3)); // Electrodes 225 | if (Math.random() < 0.5) { 226 | if (g_Debug) console.log("enforcers/tanks"); 227 | randomlevel.push(0); // Grunts 228 | randomlevel.push(0); // Hulks 229 | randomlevel.push(4 + Math.floor(L / 3)); // Spheroids 230 | randomlevel.push(0); // Brains 231 | randomlevel.push(2 + Math.floor(Math.random() * L / 4)); // Quarks 232 | } else { 233 | if (g_Debug) console.log("hulks"); 234 | randomlevel.push(Math.floor(Math.random() * 5) + 4); // Grunts 235 | randomlevel.push(6 + Math.floor(L / 2)); // Hulks 236 | randomlevel.push(Math.floor(Math.random() * 3)); // Spheroids 237 | } 238 | break; 239 | case L > 27: 240 | // Normal wave + a few Quarks 241 | if (g_Debug) console.log("normal+"); 242 | randomlevel.push(10); // Family 243 | randomlevel.push(3 + Math.floor(L / 3)); // Electrodes 244 | randomlevel.push(Math.floor(Math.random() * 6) + L); // Grunts 245 | randomlevel.push(Math.floor(Math.random() * 6) + Math.floor(L / 10)); // Hulks 246 | randomlevel.push(Math.floor(Math.random() * 3)); // Spheroids 247 | randomlevel.push(0); // Brains 248 | randomlevel.push(Math.floor(Math.random() * 3)); // Quarks 249 | break; 250 | default: 251 | // Normal wave 252 | if (g_Debug) console.log("normal"); 253 | randomlevel.push(10); // Family 254 | randomlevel.push(3 + Math.floor(L / 3)); // Electrodes 255 | randomlevel.push(Math.floor(Math.random() * 6) + L); // Grunts 256 | randomlevel.push(Math.floor(Math.random() * 6) + Math.floor(L / 10)); // Hulks 257 | randomlevel.push(Math.floor(Math.random() * 3)); // Spheroids 258 | } 259 | 260 | if (g_Debug) { 261 | console.log("This level consists of:", randomlevel); 262 | console.log("Key: [Family, Electrodes, Grunts, Hulks, Spheroids, Brains, Quarks]"); 263 | console.log(""); 264 | } 265 | 266 | return randomlevel; 267 | } 268 | }; -------------------------------------------------------------------------------- /views/canvas.php: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 |

ROBOTRON

6 |

Sorry, but your browser does not support the HTML5 canvas tag.

7 |
8 | 17 |
-------------------------------------------------------------------------------- /views/footer.php: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 |
5 |

ABOUT

6 |
7 |

About the project

8 |

This is the final project of the following courses at the University of Iceland:

9 |

    10 |
  • 11 | Computer game programming (Töl308G)
    12 | Instructor: Patrick Kerr 13 |
  • 14 |
  • 15 | Web programming (Töl306G)
    16 | Instructor: Ólafur Sverrir Kjartansson 17 |
  • 18 |
19 |

Participants (in alphabetical order):

20 | 26 |

© 2014 - All rights reserved

27 |
28 |
29 |
30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /views/header.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ROBOTRON 10 | 11 | 12 | 13 | 14 |
-------------------------------------------------------------------------------- /views/main.php: -------------------------------------------------------------------------------- 1 | 2 |
3 |
4 | ShowHighscores(); 8 | ?> 9 | 10 |
11 | 12 |
13 |

INSTRUCTIONS

14 |
15 |

Story

16 |
17 | The Robotron player 18 |
19 |

The Player

20 |

Downloaded from:

21 | StrategyWiki 22 |
23 |
24 |

25 | Inspired by his never ending quest for progress, in 2084 man perfects 26 | the Robotrons: a robot species so advanced that man is inferior to his 27 | own creation. Guided by their infallible logic, the Robotrons conclude: 28 | The human race is inefficient, and therefore must be destroyed.
29 |
30 | You are the last hope of mankind. Due to a genetic engineering error, 31 | you possess superhuman powers. Your mission is to stop the Robotrons, 32 | and save the last human family: Mommy, Daddy, and Mikey. 33 |

34 |
35 | 36 |
37 |

Gameplay summary

38 |
39 | The Robotron controller 40 |
41 |

The original controller

42 |

Downloaded from:

43 | StrategyWiki 44 |
45 |
46 |
    47 |
  • You control the player with two joysticks. One directs the movement while the other indicates which direction to fire in.
  • 48 |
  • You must eliminate every robot (except for the indestructible Hulks) in the wave to advance to the next round.
  • 49 |
  • You must avoid touching any robot or bullets or you will lose a life.
  • 50 |
  • Gather up members of the "last" family for bonus points.
  • 51 |
  • Some robots will spawn other robots if you do not destroy them quickly enough.
  • 52 |
  • On Brain waves, gather as many family members as you can before Brain robots turn them into mindless Prog zombies.
  • 53 |
  • Enemies can drop various powerups which can enhance your gameplay.
  • 54 |
  • 55 | 56 | More info about how the enemies and the scoring system works. 57 | 58 |
  • 59 |
60 |
61 |
62 | 63 |
64 |

CONTROLS

65 |
66 |

Movement

67 |
    68 |
  • W = move up
  • 69 |
  • A = move left
  • 70 |
  • S = move down
  • 71 |
  • D = move right
  • 72 |
73 |
74 | 75 |
76 |

Fire weapon

77 |
    78 |
  • Arrow keys = fire in the arrow's direction
  • 79 |
  • Mouse movement = aim
  • 80 |
  • Mouse click = fire
  • 81 |
82 |
83 |
84 |

Toggles

85 |
    86 |
  • M = Music on/off
  • 87 |
  • N = Sound effects on/off
  • 88 |
  • R = Start/Restart game
  • 89 |
  • P = Pause/Resume game
  • 90 |
  • O = When paused - continue 1 frame
  • 91 |
  • 8 = Previous song
  • 92 |
  • 9 = Next song
  • 93 |
  • Esc = Quit
  • 94 |
  • X = Toggle Diagnostics mode (shows red collision circles around entities)
  • 95 |
96 |
97 |
98 |

Sliders

99 |
    100 |
  • Y = Increase music volume
  • 101 |
  • H = Decrease music volume
  • 102 |
103 |
104 |
105 |

Diagnostics mode

106 |
    107 |
  • + = Next level
  • 108 |
  • - = Previous level
  • 109 |
  • K = Invincible mode on/off
  • 110 |
  • F = Friendly fire on/off
  • 111 |
  • 0 = Reset powerups
  • 112 |
  • 1 = Extra life
  • 113 |
  • 2 = Speed
  • 114 |
  • 3 = Score multiplier
  • 115 |
  • 4 = Machine gun
  • 116 |
  • 5 = Shotgun
  • 117 |
  • 6 = Shield
  • 118 |
  • C = Clear the screen on/off
  • 119 |
  • B = Draw a red box
  • 120 |
  • U = Draw a white box
  • 121 |
  • F = Toggle flipflop (only when paused)
  • 122 |
  • R = Toggle render (only when paused)
  • 123 |
  • T = Show timer
  • 124 |
125 |
126 |
127 |
-------------------------------------------------------------------------------- /views/navigation.php: -------------------------------------------------------------------------------- 1 | 2 | 11 | -------------------------------------------------------------------------------- /views/style.css: -------------------------------------------------------------------------------- 1 | * {margin: 0; padding: 0; box-sizing: border-box;} 2 | body {position: relative; font: 20px/2rem sans-serif; background: black; color: white;} /*Vid notum rem sem maelieiningu*/ 3 | .wrapper {max-width: 1200px; margin: 0 auto;} /*Hamarksstaerd vefsidu: 1200px, midjujafnad*/ 4 | 5 | /*Centering*/ 6 | .wrapper, main, .instructions, .shortcuts, #footerDiv, .canvasContainer {margin: 0.5rem auto;} 7 | 8 | /*Borders*/ 9 | h2, section, footer, article, nav, nav ul, nav ul li, nav ul li a, nav ul li a:hover {border-radius: 15px;} 10 | section, footer, nav {box-shadow: 0.1rem 0.1rem 0.5rem 0.25rem rgba(162,0,0,0.7);} 11 | .canvasContainer, .form {box-shadow: 0rem 0rem 2.5rem 1.5rem rgba(162,0,0,0.7);} 12 | 13 | th:first-child {border-top-left-radius: 15px;} 14 | th:last-child {border-top-right-radius: 15px;} 15 | tr:last-child td:first-child {border-bottom-left-radius: 15px;} 16 | tr:last-child td:last-child {border-bottom-right-radius: 15px;} 17 | 18 | #myCanvas, .form, section, footer, nav {border: 1px solid red;} 19 | th, td, article, nav ul li a {border: 1px solid white;} 20 | 21 | /*Sizing and canvas (max and default width: 800px height: 600px)*/ 22 | main, .instructions, .shortcuts, #footerDiv, .canvasContainer, #myCanvas, #formDiv {max-width: 800px;} 23 | .canvasContainer {height: 600px;} 24 | #myCanvas, #formDiv {position: absolute; width: 100%; max-height: 600px; height: 100%;} 25 | #myCanvas {cursor: none;} 26 | 27 | /*Heading sizes, links and lists*/ 28 | h2 {text-align: center; padding: 0.5rem 0; font: 3.5rem sans-serif; color: red; text-shadow: 0.1rem 0.1rem #ffffff;} 29 | h2:hover, article a:hover {color: #ff2828; background: #101010; text-shadow: 0.1rem 0.1rem #a20000;} 30 | .instructions h3, .highscore h3 {text-align: center;} 31 | a {color: red; text-decoration: none;} 32 | li {list-style-position: inside;} 33 | 34 | /*Form and input*/ 35 | .form {position: absolute; top:52%; right: 0; left: 0; width: 50%; margin: 0 auto; padding: 2rem; background: #2b0628;} 36 | input[type="text"], input[type="submit"] {display: block; margin: 0 auto; width: 50%; text-align: center;} 37 | .hidden, article {display: none;} 38 | 39 | /*Tables*/ 40 | table {width: 100%; border-spacing: 0px; border-collapse: separate;} 41 | th {color: red;} 42 | tr {text-align: center;} 43 | tbody tr:nth-child(odd) td {background-color: #a20000;} 44 | th, tbody tr:nth-child(even) td {background: #2b0628;} 45 | td {width: 45%;} 46 | td:first-child {width: 10%;} 47 | 48 | /*Sections, articles, nav and footer*/ 49 | section, article, nav, footer {padding: 0.5rem; background: black;} 50 | section {margin: 0.5rem auto;} 51 | article {margin: 0.25rem 0;} 52 | .instructions p:last-child {width: 82%; border-right: solid white 1px;} 53 | .figureSide {display: block; float: right; width: 18%; padding: 3rem 0;} 54 | .figureTop {border-bottom: solid white 1px;} 55 | img {display: block; margin: 0 auto;} 56 | figure p, figure a {display: block; text-align: center; font-size: 1rem;} 57 | 58 | nav {position: fixed; top: 0.5rem; left: 0.5rem; width: 12rem; height: auto;} 59 | nav ul li {list-style: none; background: #2b0628; width: 100%;} 60 | nav ul li a {display: block; text-align: center;} 61 | nav ul li a:hover {color: white; background: #a20000;} 62 | 63 | /*Using the CSS3 animations and keyframes (and -webkit-prefix for Chrome) for showing off, thanks for the semester! :)*/ 64 | .instructor {margin-left: 1rem;} 65 | .iName {position: relative; -webkit-animation: iAnim 4s infinite; animation: iAnim 4s infinite;} 66 | @-webkit-keyframes iAnim {0% {color:white; left:0;} 25% {color:red; left:2rem;} 50% {color:white; left:0;}} 67 | @keyframes iAnim {0% {color:white; left:0;} 25% {color:red; left:2rem;} 50% {color:white; left:0;}} 68 | 69 | /*Media queries*/ 70 | @media only screen and (max-width: 1236px) { 71 | .wrapper {padding-top: 2.5rem;} /*Push the site's content down.*/ 72 | nav {top: 0; left: 0; width: 100%; background: black;} 73 | nav ul {border: none;} 74 | nav ul li {display: inline;} 75 | nav ul li a {display: inline-block; overflow: hidden; float: left; width: 20%; background: #2b0628; padding: 0 0.25rem;} 76 | } 77 | 78 | @media only screen and (max-width: 820px) { 79 | /*Moving the figure from the right side to the top*/ 80 | .instructions p:last-child {width: auto; border-right: none;} 81 | .figureSide {width: auto; float: none; padding: 0; border-bottom: solid white 1px;} 82 | } 83 | 84 | @media only screen and (max-width: 600px) { 85 | h2 {font-size: 2rem;} /*Making headers smaller to prevent overflow*/ 86 | input[type="text"], input[type="submit"] {width: 100%;} 87 | nav ul li a {font-size: 1rem; font-weight: bold;} 88 | } 89 | 90 | @media only screen and (max-width: 450px), (max-device-width : 400px) { 91 | .figureTop img {width: 100%;} 92 | /*Disabling the animation by making one which has no effect*/ 93 | .iName {position: relative; -webkit-animation: noAnim 2s infinite; animation: noAnim; color: red;} 94 | } --------------------------------------------------------------------------------