diff --git a/.github/changes/engine.js b/.github/changes/engine.js new file mode 100644 index 0000000..113e89b --- /dev/null +++ b/.github/changes/engine.js @@ -0,0 +1,497 @@ +(function () { + var lastTime = 0; + var vendors = ["ms", "moz", "webkit", "o"]; + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { + window.requestAnimationFrame = window[vendors[x] + "RequestAnimationFrame"]; + window.cancelAnimationFrame = + window[vendors[x] + "CancelAnimationFrame"] || + window[vendors[x] + "CancelRequestAnimationFrame"]; + } + + if (!window.requestAnimationFrame) + window.requestAnimationFrame = function (callback, element) { + var currTime = new Date().getTime(); + var timeToCall = Math.max(0, 16 - (currTime - lastTime)); + var id = window.setTimeout(function () { + callback(currTime + timeToCall); + }, timeToCall); + lastTime = currTime + timeToCall; + return id; + }; + + if (!window.cancelAnimationFrame) + window.cancelAnimationFrame = function (id) { + clearTimeout(id); + }; +})(); + +var Game = new (function () { + var boards = []; + + // Game Initialization + this.initialize = function (canvasElementId, sprite_data, callback) { + this.canvas = document.getElementById(canvasElementId); + + this.playerOffset = 10; + this.canvasMultiplier = 1; + this.setupMobile(); + + this.width = this.canvas.width; + this.height = this.canvas.height; + + this.ctx = this.canvas.getContext && this.canvas.getContext("2d"); + if (!this.ctx) { + return alert("Please upgrade your browser to play"); + } + + this.setupInput(); + + this.loop(); + + if (this.mobile) { + this.setBoard(4, new TouchControls()); + } + + SpriteSheet.load(sprite_data, callback); + }; + + // Handle Input + var KEY_CODES = { 37: "left", 39: "right", 32: "fire" }; + this.keys = {}; + + this.setupInput = function () { + window.addEventListener( + "keydown", + function (e) { + if (KEY_CODES[e.keyCode]) { + Game.keys[KEY_CODES[e.keyCode]] = true; + e.preventDefault(); + } + }, + false + ); + + window.addEventListener( + "keyup", + function (e) { + if (KEY_CODES[e.keyCode]) { + Game.keys[KEY_CODES[e.keyCode]] = false; + e.preventDefault(); + } + }, + false + ); + }; + + var lastTime = new Date().getTime(); + var maxTime = 1 / 30; + // Game Loop + this.loop = function () { + var curTime = new Date().getTime(); + requestAnimationFrame(Game.loop); + var dt = (curTime - lastTime) / 1000; + if (dt > maxTime) { + dt = maxTime; + } + + for (var i = 0, len = boards.length; i < len; i++) { + if (boards[i]) { + boards[i].step(dt); + boards[i].draw(Game.ctx); + } + } + lastTime = curTime; + }; + + // Change an active game board + this.setBoard = function (num, board) { + boards[num] = board; + }; + + this.setupMobile = function () { + var container = document.getElementById("container"), + hasTouch = !!("ontouchstart" in window), + w = window.innerWidth, + h = window.innerHeight; + + if (hasTouch) { + this.mobile = true; + } + + if (screen.width >= 1280 || !hasTouch) { + return false; + } + + if (w > h) { + alert("Please rotate the device and then click OK"); + w = window.innerWidth; + h = window.innerHeight; + } + + container.style.height = h * 2 + "px"; + window.scrollTo(0, 1); + + h = window.innerHeight + 2; + container.style.height = h + "px"; + container.style.width = w + "px"; + container.style.padding = 0; + + if (h >= this.canvas.height * 1.75 || w >= this.canvas.height * 1.75) { + this.canvasMultiplier = 2; + this.canvas.width = w / 2; + this.canvas.height = h / 2; + this.canvas.style.width = w + "px"; + this.canvas.style.height = h + "px"; + } else { + this.canvas.width = w; + this.canvas.height = h; + } + + this.canvas.style.position = "absolute"; + this.canvas.style.left = "0px"; + this.canvas.style.top = "0px"; + }; +})(); + +var SpriteSheet = new (function () { + this.map = {}; + + this.load = function (spriteData, callback) { + this.map = spriteData; + this.image = new Image(); + this.image.onload = callback; + this.image.src = "images/sprites.png"; + }; + + this.draw = function (ctx, sprite, x, y, frame) { + var s = this.map[sprite]; + if (!frame) frame = 0; + ctx.drawImage( + this.image, + s.sx + frame * s.w, + s.sy, + s.w, + s.h, + Math.floor(x), + Math.floor(y), + s.w, + s.h + ); + }; + + return this; +})(); + +var TitleScreen = function TitleScreen(title, subtitle, callback) { + var up = false; + this.step = function (dt) { + if (!Game.keys["fire"]) up = true; + if (up && Game.keys["fire"] && callback) callback(); + }; + + this.draw = function (ctx) { + ctx.fillStyle = "#00FF00"; + + ctx.font = "bold 40px bangers"; + var measure = ctx.measureText(title); + ctx.fillText(title, Game.width / 2 - measure.width / 2, Game.height / 2); + + ctx.font = "bold 20px bangers"; + var measure2 = ctx.measureText(subtitle); + ctx.fillText( + subtitle, + Game.width / 2 - measure2.width / 2, + Game.height / 2 + 40 + ); + }; +}; + +var GameBoard = function () { + var board = this; + + // The current list of objects + this.objects = []; + this.cnt = {}; + + // Add a new object to the object list + this.add = function (obj) { + obj.board = this; + this.objects.push(obj); + this.cnt[obj.type] = (this.cnt[obj.type] || 0) + 1; + return obj; + }; + + // Mark an object for removal + this.remove = function (obj) { + var idx = this.removed.indexOf(obj); + if (idx == -1) { + this.removed.push(obj); + return true; + } else { + return false; + } + }; + + // Reset the list of removed objects + this.resetRemoved = function () { + this.removed = []; + }; + + // Removed an objects marked for removal from the list + this.finalizeRemoved = function () { + for (var i = 0, len = this.removed.length; i < len; i++) { + var idx = this.objects.indexOf(this.removed[i]); + if (idx != -1) { + this.cnt[this.removed[i].type]--; + this.objects.splice(idx, 1); + } + } + }; + + // Call the same method on all current objects + this.iterate = function (funcName) { + var args = Array.prototype.slice.call(arguments, 1); + for (var i = 0, len = this.objects.length; i < len; i++) { + var obj = this.objects[i]; + obj[funcName].apply(obj, args); + } + }; + + // Find the first object for which func is true + this.detect = function (func) { + for (var i = 0, val = null, len = this.objects.length; i < len; i++) { + if (func.call(this.objects[i])) return this.objects[i]; + } + return false; + }; + + // Call step on all objects and them delete + // any object that have been marked for removal + this.step = function (dt) { + this.resetRemoved(); + this.iterate("step", dt); + this.finalizeRemoved(); + }; + + // Draw all the objects + this.draw = function (ctx) { + this.iterate("draw", ctx); + }; + + // Check for a collision between the + // bounding rects of two objects + this.overlap = function (o1, o2) { + return !( + o1.y + o1.h - 1 < o2.y || + o1.y > o2.y + o2.h - 1 || + o1.x + o1.w - 1 < o2.x || + o1.x > o2.x + o2.w - 1 + ); + }; + + // Find the first object that collides with obj + // match against an optional type + this.collide = function (obj, type) { + return this.detect(function () { + if (obj != this) { + var col = (!type || this.type & type) && board.overlap(obj, this); + return col ? this : false; + } + }); + }; +}; + +var Sprite = function () {}; + +Sprite.prototype.setup = function (sprite, props) { + this.sprite = sprite; + this.merge(props); + this.frame = this.frame || 0; + this.w = SpriteSheet.map[sprite].w; + this.h = SpriteSheet.map[sprite].h; +}; + +Sprite.prototype.merge = function (props) { + if (props) { + for (var prop in props) { + this[prop] = props[prop]; + } + } +}; + +Sprite.prototype.draw = function (ctx) { + SpriteSheet.draw(ctx, this.sprite, this.x, this.y, this.frame); +}; + +Sprite.prototype.hit = function (damage) { + this.board.remove(this); +}; + +var Level = function (levelData, callback) { + this.levelData = []; + for (var i = 0; i < levelData.length; i++) { + this.levelData.push(Object.create(levelData[i])); + } + this.t = 0; + this.callback = callback; +}; + +Level.prototype.step = function (dt) { + var idx = 0, + remove = [], + curShip = null; + + // Update the current time offset + this.t += dt * 1000; + + // Start, End, Gap, Type, Override + // [ 0, 4000, 500, 'step', { x: 100 } ] + while ((curShip = this.levelData[idx]) && curShip[0] < this.t + 2000) { + // Check if we've passed the end time + if (this.t > curShip[1]) { + remove.push(curShip); + } else if (curShip[0] < this.t) { + // Get the enemy definition blueprint + var enemy = enemies[curShip[3]], + override = curShip[4]; + + // Add a new enemy with the blueprint and override + this.board.add(new Enemy(enemy, override)); + + // Increment the start time by the gap + curShip[0] += curShip[2]; + } + idx++; + } + + // Remove any objects from the levelData that have passed + for (var i = 0, len = remove.length; i < len; i++) { + var remIdx = this.levelData.indexOf(remove[i]); + if (remIdx != -1) this.levelData.splice(remIdx, 1); + } + + // If there are no more enemies on the board or in + // levelData, this level is done + if (this.levelData.length === 0 && this.board.cnt[OBJECT_ENEMY] === 0) { + if (this.callback) this.callback(); + } +}; + +Level.prototype.draw = function (ctx) {}; + +var TouchControls = function () { + var gutterWidth = 10; + var unitWidth = Game.width / 5; + var blockWidth = unitWidth - gutterWidth; + + this.drawSquare = function (ctx, x, y, txt, on) { + ctx.globalAlpha = on ? 0.9 : 0.6; + ctx.fillStyle = "#CCC"; + ctx.fillRect(x, y, blockWidth, blockWidth); + + ctx.fillStyle = "#FFF"; + ctx.globalAlpha = 1.0; + ctx.font = "bold " + (3 * unitWidth) / 4 + "px arial"; + + var txtSize = ctx.measureText(txt); + + ctx.fillText( + txt, + x + blockWidth / 2 - txtSize.width / 2, + y + (3 * blockWidth) / 4 + 5 + ); + }; + + this.draw = function (ctx) { + ctx.save(); + + var yLoc = Game.height - unitWidth; + this.drawSquare(ctx, gutterWidth, yLoc, "\u25C0", Game.keys["left"]); + this.drawSquare( + ctx, + unitWidth + gutterWidth, + yLoc, + "\u25B6", + Game.keys["right"] + ); + this.drawSquare(ctx, 4 * unitWidth, yLoc, "A", Game.keys["fire"]); + + ctx.restore(); + }; + + this.step = function (dt) {}; + + this.trackTouch = function (e) { + var touch, x; + + e.preventDefault(); + Game.keys["left"] = false; + Game.keys["right"] = false; + for (var i = 0; i < e.targetTouches.length; i++) { + touch = e.targetTouches[i]; + x = touch.pageX / Game.canvasMultiplier - Game.canvas.offsetLeft; + if (x < unitWidth) { + Game.keys["left"] = true; + } + if (x > unitWidth && x < 2 * unitWidth) { + Game.keys["right"] = true; + } + } + + if (e.type == "touchstart" || e.type == "touchend") { + for (i = 0; i < e.changedTouches.length; i++) { + touch = e.changedTouches[i]; + x = touch.pageX / Game.canvasMultiplier - Game.canvas.offsetLeft; + if (x > 4 * unitWidth) { + Game.keys["fire"] = e.type == "touchstart"; + } + } + } + }; + + Game.canvas.addEventListener("touchstart", this.trackTouch, true); + Game.canvas.addEventListener("touchmove", this.trackTouch, true); + Game.canvas.addEventListener("touchend", this.trackTouch, true); + + // For Android + Game.canvas.addEventListener( + "dblclick", + function (e) { + e.preventDefault(); + }, + true + ); + Game.canvas.addEventListener( + "click", + function (e) { + e.preventDefault(); + }, + true + ); + + Game.playerOffset = unitWidth + 20; +}; + +var GamePoints = function () { + Game.points = 0; + + var pointsLength = 8; + + this.draw = function (ctx) { + ctx.save(); + ctx.font = "bold 18px arial"; + ctx.fillStyle = "#00FF00"; + + var txt = "" + Game.points; + var i = pointsLength - txt.length, + zeros = ""; + while (i-- > 0) { + zeros += "0"; + } + + ctx.fillText(zeros + txt, 10, 20); + ctx.restore(); + }; + + this.step = function (dt) {}; +}; diff --git a/.github/changes/game-fixed.js b/.github/changes/game-fixed.js new file mode 100644 index 0000000..4c059ee --- /dev/null +++ b/.github/changes/game-fixed.js @@ -0,0 +1,355 @@ +var sprites = { + ship: { sx: 0, sy: 0, w: 37, h: 42, frames: 1 }, + missile: { sx: 0, sy: 30, w: 2, h: 10, frames: 1 }, + enemy_purple: { sx: 37, sy: 0, w: 42, h: 43, frames: 1 }, + enemy_bee: { sx: 79, sy: 0, w: 37, h: 43, frames: 1 }, + enemy_ship: { sx: 116, sy: 0, w: 42, h: 43, frames: 1 }, + enemy_circle: { sx: 158, sy: 0, w: 32, h: 33, frames: 1 }, + explosion: { sx: 0, sy: 64, w: 64, h: 64, frames: 12 }, + enemy_missile: { sx: 9, sy: 42, w: 3, h: 20, frame: 1 }, +}; + +var enemies = { + straight: { x: 0, y: -50, sprite: "enemy_ship", health: 10, E: 100 }, + ltr: { + x: 0, + y: -100, + sprite: "enemy_purple", + health: 10, + B: 75, + C: 1, + E: 100, + missiles: 2, + }, + circle: { + x: 250, + y: -50, + sprite: "enemy_circle", + health: 10, + A: 0, + B: -100, + C: 1, + E: 20, + F: 100, + G: 1, + H: Math.PI / 2, + }, + wiggle: { + x: 100, + y: -50, + sprite: "enemy_bee", + health: 20, + B: 50, + C: 4, + E: 100, + firePercentage: 0.001, + missiles: 2, + }, + step: { + x: 0, + y: -50, + sprite: "enemy_circle", + health: 10, + B: 150, + C: 1.2, + E: 75, + }, +}; + +var OBJECT_PLAYER = 1, + OBJECT_PLAYER_PROJECTILE = 2, + OBJECT_ENEMY = 4, + OBJECT_ENEMY_PROJECTILE = 8, + OBJECT_POWERUP = 16; + +var startGame = function () { + var ua = navigator.userAgent.toLowerCase(); + + // Only 1 row of stars + if (ua.match(/android/)) { + Game.setBoard(0, new Starfield(50, 0.6, 100, true)); + } else { + Game.setBoard(0, new Starfield(20, 0.4, 100, true)); + Game.setBoard(1, new Starfield(50, 0.6, 100)); + Game.setBoard(2, new Starfield(100, 1.0, 50)); + } + Game.setBoard( + 3, + new TitleScreen("Alien Invasion", "Press fire to start playing", playGame) + ); +}; + +var level1 = [ + // Start, End, Gap, Type, Override + [0, 4000, 500, "step"], + [6000, 13000, 800, "ltr"], + [10000, 16000, 400, "circle"], + [17800, 20000, 500, "straight", { x: 50 }], + [18200, 20000, 500, "straight", { x: 90 }], + [18200, 20000, 500, "straight", { x: 10 }], + [22000, 25000, 400, "wiggle", { x: 150 }], + [22000, 25000, 400, "wiggle", { x: 100 }], +]; + +var playGame = function () { + var board = new GameBoard(); + board.add(new PlayerShip()); + board.add(new Level(level1, winGame)); + Game.setBoard(3, board); + Game.setBoard(5, new GamePoints(0)); +}; + +var winGame = function () { + Game.setBoard( + 3, + new TitleScreen("You win!", "Press fire to play again", playGame) + ); +}; + +var loseGame = function () { + Game.setBoard( + 3, + new TitleScreen("You lose!", "Press fire to play again", playGame) + ); +}; + +var Starfield = function (speed, opacity, numStars, clear) { + // Set up the offscreen canvas + var stars = document.createElement("canvas"); + stars.width = Game.width; + stars.height = Game.height; + var starCtx = stars.getContext("2d"); + + var offset = 0; + + // If the clear option is set, + // make the background black instead of transparent + if (clear) { + starCtx.fillStyle = "#000"; + starCtx.fillRect(0, 0, stars.width, stars.height); + } + + // Now draw a bunch of random 2 pixel + // rectangles onto the offscreen canvas + starCtx.fillStyle = "#FFF"; + starCtx.globalAlpha = opacity; + for (var i = 0; i < numStars; i++) { + starCtx.fillRect( + Math.floor(Math.random() * stars.width), + Math.floor(Math.random() * stars.height), + 2, + 2 + ); + } + + // This method is called every frame + // to draw the starfield onto the canvas + this.draw = function (ctx) { + var intOffset = Math.floor(offset); + var remaining = stars.height - intOffset; + + // Draw the top half of the starfield + if (intOffset > 0) { + ctx.drawImage( + stars, + 0, + remaining, + stars.width, + intOffset, + 0, + 0, + stars.width, + intOffset + ); + } + + // Draw the bottom half of the starfield + if (remaining > 0) { + ctx.drawImage( + stars, + 0, + 0, + stars.width, + remaining, + 0, + intOffset, + stars.width, + remaining + ); + } + }; + + // This method is called to update + // the starfield + this.step = function (dt) { + offset += dt * speed; + offset = offset % stars.height; + }; +}; + +var PlayerShip = function () { + this.setup("ship", { vx: 0, reloadTime: 0.25, maxVel: 200 }); + + this.reload = this.reloadTime; + this.x = Game.width / 2 - this.w / 2; + this.y = Game.height - Game.playerOffset - this.h; + + this.step = function (dt) { + if (Game.keys["left"]) { + this.vx = -this.maxVel; + } else if (Game.keys["right"]) { + this.vx = this.maxVel; + } else { + this.vx = 0; + } + + this.x += this.vx * dt; + + if (this.x < 0) { + this.x = 0; + } else if (this.x > Game.width - this.w) { + this.x = Game.width - this.w; + } + + this.reload -= dt; + if (Game.keys["fire"] && this.reload < 0) { + Game.keys["fire"] = false; + this.reload = this.reloadTime; + + this.board.add(new PlayerMissile(this.x, this.y + this.h / 2)); + this.board.add(new PlayerMissile(this.x + this.w, this.y + this.h / 2)); + } + }; +}; + +PlayerShip.prototype = new Sprite(); +PlayerShip.prototype.type = OBJECT_PLAYER; + +PlayerShip.prototype.hit = function (damage) { + if (this.board.remove(this)) { + loseGame(); + } +}; + +var PlayerMissile = function (x, y) { + this.setup("missile", { vy: -700, damage: 10 }); + this.x = x - this.w / 2; + this.y = y - this.h; +}; + +PlayerMissile.prototype = new Sprite(); +PlayerMissile.prototype.type = OBJECT_PLAYER_PROJECTILE; + +PlayerMissile.prototype.step = function (dt) { + this.y += this.vy * dt; + var collision = this.board.collide(this, OBJECT_ENEMY); + if (collision) { + collision.hit(this.damage); + this.board.remove(this); + } else if (this.y < -this.h) { + this.board.remove(this); + } +}; + +var Enemy = function (blueprint, override) { + this.merge(this.baseParameters); + this.setup(blueprint.sprite, blueprint); + this.merge(override); +}; + +Enemy.prototype = new Sprite(); +Enemy.prototype.type = OBJECT_ENEMY; + +Enemy.prototype.baseParameters = { + A: 0, + B: 0, + C: 0, + D: 0, + E: 0, + F: 0, + G: 0, + H: 0, + t: 0, + reloadTime: 0.75, + reload: 0, +}; + +Enemy.prototype.step = function (dt) { + this.t += dt; + + this.vx = this.A + this.B * Math.sin(this.C * this.t + this.D); + this.vy = this.E + this.F * Math.sin(this.G * this.t + this.H); + + this.x += this.vx * dt; + this.y += this.vy * dt; + + var collision = this.board.collide(this, OBJECT_PLAYER); + if (collision) { + collision.hit(this.damage); + this.board.remove(this); + } + + if (Math.random() < 0.01 && this.reload <= 0) { + this.reload = this.reloadTime; + if (this.missiles == 2) { + this.board.add(new EnemyMissile(this.x + this.w - 2, this.y + this.h)); + this.board.add(new EnemyMissile(this.x + 2, this.y + this.h)); + } else { + this.board.add(new EnemyMissile(this.x + this.w / 2, this.y + this.h)); + } + } + this.reload -= dt; + + if (this.y > Game.height || this.x < -this.w || this.x > Game.width) { + this.board.remove(this); + } +}; + +Enemy.prototype.hit = function (damage) { + this.health -= damage; + if (this.health <= 0) { + if (this.board.remove(this)) { + Game.points += this.points || 100; + this.board.add(new Explosion(this.x + this.w / 2, this.y + this.h / 2)); + } + } +}; + +var EnemyMissile = function (x, y) { + this.setup("enemy_missile", { vy: 200, damage: 10 }); + this.x = x - this.w / 2; + this.y = y; +}; + +EnemyMissile.prototype = new Sprite(); +EnemyMissile.prototype.type = OBJECT_ENEMY_PROJECTILE; + +EnemyMissile.prototype.step = function (dt) { + this.y += this.vy * dt; + var collision = this.board.collide(this, OBJECT_PLAYER); + if (collision) { + collision.hit(this.damage); + this.board.remove(this); + } else if (this.y > Game.height) { + this.board.remove(this); + } +}; + +var Explosion = function (centerX, centerY) { + this.setup("explosion", { frame: 0 }); + this.x = centerX - this.w / 2; + this.y = centerY - this.h / 2; +}; + +Explosion.prototype = new Sprite(); + +Explosion.prototype.step = function (dt) { + this.frame++; + if (this.frame >= 12) { + this.board.remove(this); + } +}; + +window.addEventListener("load", function () { + Game.initialize("game", sprites, startGame); +}); diff --git a/.github/changes/game-with-bug.js b/.github/changes/game-with-bug.js new file mode 100644 index 0000000..6c2becd --- /dev/null +++ b/.github/changes/game-with-bug.js @@ -0,0 +1,355 @@ +var sprites = { + ship: { sx: 0, sy: 0, w: 37, h: 42, frames: 1 }, + missile: { sx: 0, sy: 30, w: 2, h: 10, frames: 1 }, + enemy_purple: { sx: 37, sy: 0, w: 42, h: 43, frames: 1 }, + enemy_bee: { sx: 79, sy: 0, w: 37, h: 43, frames: 1 }, + enemy_ship: { sx: 116, sy: 0, w: 42, h: 43, frames: 1 }, + enemy_circle: { sx: 158, sy: 0, w: 32, h: 33, frames: 1 }, + explosion: { sx: 0, sy: 64, w: 64, h: 64, frames: 12 }, + enemy_missile: { sx: 9, sy: 42, w: 3, h: 20, frame: 1 }, +}; + +var enemies = { + straight: { x: 0, y: -50, sprite: "enemy_ship", health: 10, E: 100 }, + ltr: { + x: 0, + y: -100, + sprite: "enemy_purple", + health: 10, + B: 75, + C: 1, + E: 100, + missiles: 2, + }, + circle: { + x: 250, + y: -50, + sprite: "enemy_circle", + health: 10, + A: 0, + B: -100, + C: 1, + E: 20, + F: 100, + G: 1, + H: Math.PI / 2, + }, + wiggle: { + x: 100, + y: -50, + sprite: "enemy_bee", + health: 20, + B: 50, + C: 4, + E: 100, + firePercentage: 0.001, + missiles: 2, + }, + step: { + x: 0, + y: -50, + sprite: "enemy_circle", + health: 10, + B: 150, + C: 1.2, + E: 75, + }, +}; + +var OBJECT_PLAYER = 1, + OBJECT_PLAYER_PROJECTILE = 2, + OBJECT_ENEMY = 4, + OBJECT_ENEMY_PROJECTILE = 8, + OBJECT_POWERUP = 16; + +var startGame = function () { + var ua = navigator.userAgent.toLowerCase(); + + // Only 1 row of stars + if (ua.match(/android/)) { + Game.setBoard(0, new Starfield(50, 0.6, 100, true)); + } else { + Game.setBoard(0, new Starfield(20, 0.4, 100, true)); + Game.setBoard(1, new Starfield(50, 0.6, 100)); + Game.setBoard(2, new Starfield(100, 1.0, 50)); + } + Game.setBoard( + 3, + new TitleScreen("Alien Invasion", "Press fire to start playing", playGame) + ); +}; + +var level1 = [ + // Start, End, Gap, Type, Override + [0, 4000, 500, "step"], + [6000, 13000, 800, "ltr"], + [10000, 16000, 400, "circle"], + [17800, 20000, 500, "straight", { x: 50 }], + [18200, 20000, 500, "straight", { x: 90 }], + [18200, 20000, 500, "straight", { x: 10 }], + [22000, 25000, 400, "wiggle", { x: 150 }], + [22000, 25000, 400, "wiggle", { x: 100 }], +]; + +var playGame = function () { + var board = new GameBoard(); + board.add(new PlayerShip()); + board.add(new Level(level1, winGame)); + Game.setBoard(3, board); + Game.setBoard(5, new GamePoints(0)); +}; + +var winGame = function () { + Game.setBoard( + 3, + new TitleScreen("You win!", "Press fire to play again", playGame) + ); +}; + +var loseGame = function () { + Game.setBoard( + 3, + new TitleScreen("You lose!", "Press fire to play again", playGame) + ); +}; + +var Starfield = function (speed, opacity, numStars, clear) { + // Set up the offscreen canvas + var stars = document.createElement("canvas"); + stars.width = Game.width; + stars.height = Game.height; + var starCtx = stars.getContext("2d"); + + var offset = 0; + + // If the clear option is set, + // make the background black instead of transparent + if (clear) { + starCtx.fillStyle = "#0F0"; + starCtx.fillRect(0, 0, stars.width, stars.height); + } + + // Now draw a bunch of random 2 pixel + // rectangles onto the offscreen canvas + starCtx.fillStyle = "#FFF"; + starCtx.globalAlpha = opacity; + for (var i = 0; i < numStars; i++) { + starCtx.fillRect( + Math.floor(Math.random() * stars.width), + Math.floor(Math.random() * stars.height), + 2, + 2 + ); + } + + // This method is called every frame + // to draw the starfield onto the canvas + this.draw = function (ctx) { + var intOffset = Math.floor(offset); + var remaining = stars.height - intOffset; + + // Draw the top half of the starfield + if (intOffset > 0) { + ctx.drawImage( + stars, + 0, + remaining, + stars.width, + intOffset, + 0, + 0, + stars.width, + intOffset + ); + } + + // Draw the bottom half of the starfield + if (remaining > 0) { + ctx.drawImage( + stars, + 0, + 0, + stars.width, + remaining, + 0, + intOffset, + stars.width, + remaining + ); + } + }; + + // This method is called to update + // the starfield + this.step = function (dt) { + offset += dt * speed; + offset = offset % stars.height; + }; +}; + +var PlayerShip = function () { + this.setup("ship", { vx: 0, reloadTime: 0.25, maxVel: 200 }); + + this.reload = this.reloadTime; + this.x = Game.width / 2 - this.w / 2; + this.y = Game.height - Game.playerOffset - this.h; + + this.step = function (dt) { + if (Game.keys["left"]) { + this.vx = -this.maxVel; + } else if (Game.keys["right"]) { + this.vx = this.maxVel; + } else { + this.vx = 0; + } + + this.x += this.vx * dt; + + if (this.x < 0) { + this.x = 0; + } else if (this.x > Game.width - this.w) { + this.x = Game.width - this.w; + } + + this.reload -= dt; + if (Game.keys["fire"] && this.reload < 0) { + Game.keys["fire"] = false; + this.reload = this.reloadTime; + + this.board.add(new PlayerMissile(this.x, this.y + this.h / 2)); + this.board.add(new PlayerMissile(this.x + this.w, this.y + this.h / 2)); + } + }; +}; + +PlayerShip.prototype = new Sprite(); +PlayerShip.prototype.type = OBJECT_PLAYER; + +PlayerShip.prototype.hit = function (damage) { + if (this.board.remove(this)) { + loseGame(); + } +}; + +var PlayerMissile = function (x, y) { + this.setup("missile", { vy: -700, damage: 10 }); + this.x = x - this.w / 2; + this.y = y - this.h; +}; + +PlayerMissile.prototype = new Sprite(); +PlayerMissile.prototype.type = OBJECT_PLAYER_PROJECTILE; + +PlayerMissile.prototype.step = function (dt) { + this.y += this.vy * dt; + var collision = this.board.collide(this, OBJECT_ENEMY); + if (collision) { + collision.hit(this.damage); + this.board.remove(this); + } else if (this.y < -this.h) { + this.board.remove(this); + } +}; + +var Enemy = function (blueprint, override) { + this.merge(this.baseParameters); + this.setup(blueprint.sprite, blueprint); + this.merge(override); +}; + +Enemy.prototype = new Sprite(); +Enemy.prototype.type = OBJECT_ENEMY; + +Enemy.prototype.baseParameters = { + A: 0, + B: 0, + C: 0, + D: 0, + E: 0, + F: 0, + G: 0, + H: 0, + t: 0, + reloadTime: 0.75, + reload: 0, +}; + +Enemy.prototype.step = function (dt) { + this.t += dt; + + this.vx = this.A + this.B * Math.sin(this.C * this.t + this.D); + this.vy = this.E + this.F * Math.sin(this.G * this.t + this.H); + + this.x += this.vx * dt; + this.y += this.vy * dt; + + var collision = this.board.collide(this, OBJECT_PLAYER); + if (collision) { + collision.hit(this.damage); + this.board.remove(this); + } + + if (Math.random() < 0.01 && this.reload <= 0) { + this.reload = this.reloadTime; + if (this.missiles == 2) { + this.board.add(new EnemyMissile(this.x + this.w - 2, this.y + this.h)); + this.board.add(new EnemyMissile(this.x + 2, this.y + this.h)); + } else { + this.board.add(new EnemyMissile(this.x + this.w / 2, this.y + this.h)); + } + } + this.reload -= dt; + + if (this.y > Game.height || this.x < -this.w || this.x > Game.width) { + this.board.remove(this); + } +}; + +Enemy.prototype.hit = function (damage) { + this.health -= damage; + if (this.health <= 0) { + if (this.board.remove(this)) { + Game.points += this.points || 100; + this.board.add(new Explosion(this.x + this.w / 2, this.y + this.h / 2)); + } + } +}; + +var EnemyMissile = function (x, y) { + this.setup("enemy_missile", { vy: 200, damage: 10 }); + this.x = x - this.w / 2; + this.y = y; +}; + +EnemyMissile.prototype = new Sprite(); +EnemyMissile.prototype.type = OBJECT_ENEMY_PROJECTILE; + +EnemyMissile.prototype.step = function (dt) { + this.y += this.vy * dt; + var collision = this.board.collide(this, OBJECT_PLAYER); + if (collision) { + collision.hit(this.damage); + this.board.remove(this); + } else if (this.y > Game.height) { + this.board.remove(this); + } +}; + +var Explosion = function (centerX, centerY) { + this.setup("explosion", { frame: 0 }); + this.x = centerX - this.w / 2; + this.y = centerY - this.h / 2; +}; + +Explosion.prototype = new Sprite(); + +Explosion.prototype.step = function (dt) { + this.frame++; + if (this.frame >= 12) { + this.board.remove(this); + } +}; + +window.addEventListener("load", function () { + Game.initialize("game", sprites, startGame); +}); diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..8ac6b8c --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..bbbf96f --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,3 @@ +## Description: + +_Description of changes made and why._ diff --git a/.github/script/create-hotfix-pr.sh b/.github/script/create-hotfix-pr.sh new file mode 100755 index 0000000..2ddc53f --- /dev/null +++ b/.github/script/create-hotfix-pr.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Make sure this file is executable +# chmod a+x .github/script/create-hotfix-pr.sh + +echo "Set committer details" +git config user.name github-actions +git config user.email github-actions@github.com + +echo "Create hotfix branch" +RELEASE_BRANCH=hotfix-v1.0.1 +git checkout main +git pull origin main +git checkout -b $RELEASE_BRANCH + +echo "Push release branch" +git commit --allow-empty --message="Empty commit to initialize branch" +git push --set-upstream origin $RELEASE_BRANCH + +echo "Create feature branch" +git checkout main +FEATURE_BRANCH=fix-game-background +git checkout -b $FEATURE_BRANCH + +echo "Make changes to files" +cp .github/changes/game-fixed.js game.js + +echo "Commit file changes" +git add game.js +git commit -m "Set game background back to black" + +echo "Push feature branch" +git push --set-upstream origin $FEATURE_BRANCH + +echo "Restore main" +git checkout main \ No newline at end of file diff --git a/.github/script/initialize-repository.sh b/.github/script/initialize-repository.sh new file mode 100755 index 0000000..8fee8cf --- /dev/null +++ b/.github/script/initialize-repository.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Make sure this file is executable +# chmod a+x .github/script/initialize-repository.sh + +echo "Set committer details" +git config user.name github-actions +git config user.email github-actions@github.com + +echo "Create release branch" +RELEASE_BRANCH=release-v1.0 +git checkout main +git checkout -b $RELEASE_BRANCH + +echo "Push release branch" +git commit --allow-empty --message="Empty commit to initialize branch" +git push --set-upstream origin $RELEASE_BRANCH + +echo "Create feature branch" +git checkout main +FEATURE_BRANCH=update-text-colors +git checkout -b $FEATURE_BRANCH + +echo "Make changes to files" +cp .github/changes/engine.js engine.js +cp .github/changes/game-with-bug.js game.js + +echo "Commit file changes" +git add engine.js game.js +git commit -m "Changed game text colors to green" + +echo "Push feature branch" +git push --set-upstream origin $FEATURE_BRANCH + +echo "Restore main" +git checkout main \ No newline at end of file diff --git a/.github/steps/-step.txt b/.github/steps/-step.txt new file mode 100644 index 0000000..573541a --- /dev/null +++ b/.github/steps/-step.txt @@ -0,0 +1 @@ +0 diff --git a/.github/steps/0-welcome.md b/.github/steps/0-welcome.md new file mode 100644 index 0000000..9ff13a5 --- /dev/null +++ b/.github/steps/0-welcome.md @@ -0,0 +1 @@ + diff --git a/.github/steps/1-create-beta-release.md b/.github/steps/1-create-beta-release.md new file mode 100644 index 0000000..ef14f64 --- /dev/null +++ b/.github/steps/1-create-beta-release.md @@ -0,0 +1,58 @@ + + +## Step 1: Create a beta release + +_Welcome to "Release-based workflow" :sparkle:_ + +### The GitHub flow + +The [GitHub flow](https://guides.github.com/introduction/flow/) is a lightweight, branch-based workflow for projects with regular deployments. + +![github-flow](https://user-images.githubusercontent.com/6351798/48032310-63842400-e114-11e8-8db0-06dc0504dcb5.png) + +Some projects may deploy more often, with continuous deployment. There might be a "release" every time there's a new commit on main. + +But, some projects rely on a different structure for versions and releases. + +### Versions + +Versions are different iterations of updated software like operating systems, apps, or dependencies. Common examples are "Windows 8.1" to "Windows 10", or "macOS High Sierra" to "macOS Mojave". + +Developers update code and then run tests on the project for bugs. During that time, the developers might set up certain securities to protect from new code or bugs. Then, the tested code is ready for production. Teams version the code and release it for installation by end users. + +### :keyboard: Activity: Create a release for the current codebase + +In this step, you will create a release for this repository on GitHub. + +GitHub Releases point to a specific commit. Releases can include release notes in Markdown files, and attached binaries. + +Before using a release based workflow for a larger release, let's create a tag and a release. + +1. Open a new browser tab, and work on the steps in your second tab while you read the instructions in this tab. +1. Go to the **Releases** page for this repository. + - _Tip: To reach this page, click the **Code** tab at the top of your repository. Then, find the navigation bar below the repository description, and click the **Releases** heading link._ +1. Click **Create a new release**. +1. In the field for _Tag version_, specify a number. In this case, use **v0.9**. Keep the _Target_ as **main**. +1. Give the release a title, like "First beta release". If you'd like, you could also give the release a short description. +1. Select the checkbox next to **Set as a pre-release**, since it is representing a beta version. +1. Click **Publish release**. + +### :keyboard: Activity: Introduce a bug to be fixed later + +To set the stage for later, let's also add a bug that we'll fix as part of the release workflow in later steps. We've already created a `update-text-colors` branch for you so let's create and merge a pull request with this branch. + +1. Open a **new pull request** with `base: release-v1.0` and `compare: update-text-colors`. +1. Set the pull request title to "Updated game text style". You can include a detailed pull request body, an example is below: + ``` + ## Description: + - Updated game text color to green + ``` +1. Click **Create pull request**. +1. We'll merge this pull request now. Click **Merge pull request** and delete your branch. +1. Wait about 20 seconds then refresh this page (the one you're following instructions from). [GitHub Actions](https://docs.github.com/en/actions) will automatically update to the next step. diff --git a/.github/steps/2-feature-added-to-release.md b/.github/steps/2-feature-added-to-release.md new file mode 100644 index 0000000..bdebafc --- /dev/null +++ b/.github/steps/2-feature-added-to-release.md @@ -0,0 +1,55 @@ + + +## Step 2: Add a new feature to the release branch + +_Great job creating a beta release :heart:_ + +### Release management + +As you prepare for a future release, you'll need to organize more than the tasks and features. It's important to create a clear workflow for your team, and to make sure that the work remains organized. + +There are several strategies for managing releases. Some teams might use long-lived branches, like `production`, `dev`, and `main`. Some teams use simple feature branches, releasing from the main branch. + +No one strategy is better than another. We always recommend being intentional about branches and reducing long-lived branches whenever possible. + +In this exercise, you'll use the `release-v1.0` branch to be your one long-lived branch per release version. + +### Protected branches + +Like the `main` branch, you can protect release branches. This means you can protect branches from force pushes or accidental deletion. This is already configured in this repository. + +### Add a feature + +Releases are usually made of many smaller changes. Let's pretend we don't know about the bug we added earlier and we'll focus on a few features to update our game before the version update. + +- You should update the page background color to black. +- I'll help you change the text colors to green. + +### :keyboard: Activity: Update `base.css` + +1. Create a new branch off of the `main` branch and change the `body` CSS declaration in `base.css` to match what is below. This will set the page background to black. + +``` +body { + background-color: black; +} +``` + +1. Open a pull request with `release-v1.0` as the `base` branch, and your new branch as the `compare` branch. +1. Fill in the pull request template to describe your changes. +1. Click **Create pull request**. + +### Merge the new feature to the release branch + +Even with releases, the GitHub flow is still an important strategy for working with your team. It's a good idea to use short-lived branches for quick feature additions and bug fixes. + +Merge this feature pull request so that you can open the release pull request as early as possible. + +### :keyboard: Activity: Merge the pull request + +1. Click **Merge pull request**, and delete your branch. +1. Wait about 20 seconds then refresh this page (the one you're following instructions from). [GitHub Actions](https://docs.github.com/en/actions) will automatically update to the next step. diff --git a/.github/steps/3-release-pr-opened.md b/.github/steps/3-release-pr-opened.md new file mode 100644 index 0000000..e43202f --- /dev/null +++ b/.github/steps/3-release-pr-opened.md @@ -0,0 +1,36 @@ + + +## Step 3: Open a release pull request + +_Nice work adding a new feature :smile:_ + +### Release branches and `main` + +You should open a pull request between your release branch and main as early as possible. It might be open for a long time, and that's okay. + +In general, the pull request description can include: + +- A [reference to an issue](https://docs.github.com/en/articles/basic-writing-and-formatting-syntax/#mentioning-people-and-teams) that the pull request addresses. +- A description of the changes proposed in the pull request. +- [@mentions](https://docs.github.com/en/articles/basic-writing-and-formatting-syntax/#mentioning-people-and-teams) of the person or team responsible for reviewing proposed changes. + +To expedite the creation of this pull request, I've added a pull request template to the repository. When you create a pull request, default text will automatically be displayed. This should help you identify and fill out all the necessary information. If you don't want to use the template content, just remove the text from the pull request and replace it with your pull request message. + +### :keyboard: Activity: Open a release pull request + +Let's make a new pull request comparing the `release-v1.0` branch to the `main` branch. + +1. Open a **new pull request** with `base: main` and `compare: release-v1.0`. +1. Ensure the title of your pull request is "Release v1.0". +1. Include a detailed pull request body, an example is below: + ``` + ## Description: + - Changed page background color to black. + - Changed game text color to green. + ``` +1. Click **Create pull request**. +1. Wait about 20 seconds then refresh this page (the one you're following instructions from). [GitHub Actions](https://docs.github.com/en/actions) will automatically update to the next step. diff --git a/.github/steps/4-release-notes-and-merge.md b/.github/steps/4-release-notes-and-merge.md new file mode 100644 index 0000000..0f8f516 --- /dev/null +++ b/.github/steps/4-release-notes-and-merge.md @@ -0,0 +1,35 @@ + + +## Step 4: Generate release notes and merge + +_Thanks for opening that pull request :dancer:_ + +### Automatically generated release notes + +[Automatically generated release notes](https://docs.github.com/en/repositories/releasing-projects-on-github/automatically-generated-release-notes) provide an automated alternative to manually writing release notes for your GitHub releases. With automatically generated release notes, you can quickly generate an overview of the contents of a release. Automatically generated release notes include a list of merged pull requests, a list of contributors to the release, and a link to a full changelog. You can also customize your release notes once they are generated. + +### :keyboard: Activity: Generate release notes + +1. In a separate tab, go to the **Releases** page for this repository. + - _Tip: To reach this page, click the **Code** tab at the top of your repository. Then, find the navigation bar below the repository description, and click the **Releases** heading link._ +1. Click the **Draft a new release** button. +1. In the field for _Tag version_, specify `v1.0.0`. +1. To the right of the tag dropdown, click the _Target_ dropddown and select the `release-v1.0` branch. + - _Tip: This is temporary in order to generate release notes based on the changes in this branch._ +1. To the top right of the description text box, click **Generate release notes**. +1. Review the release notes in the text box and customize the content if desired. +1. Set the _Target_ branch back to the `main`, as this is the branch you want to create your tag on once the release branch is merged. +1. Click **Save draft**, as you will publish this release in the next step. + +You can now [merge](https://docs.github.com/en/get-started/quickstart/github-glossary#merge) your pull request! + +### :keyboard: Activity: Merge into main + +1. In a separate tab, go to the **Pull requests** page for this repository. +1. Open your **Release v1.0** pull request. +1. Click **Merge pull request**. +1. Wait about 20 seconds then refresh this page (the one you're following instructions from). [GitHub Actions](https://docs.github.com/en/actions) will automatically update to the next step. diff --git a/.github/steps/5-finalize-release.md b/.github/steps/5-finalize-release.md new file mode 100644 index 0000000..62fdb39 --- /dev/null +++ b/.github/steps/5-finalize-release.md @@ -0,0 +1,41 @@ + + +## Step 5: Finalize the release + +_Awesome work on the release notes :+1:_ + +### Finalizing releases + +It's important to be aware of the information what will be visible in that release. In the pre-release, the version and commit messages are visible. + +![image](https://user-images.githubusercontent.com/13326548/47883578-bdba7780-ddea-11e8-84b8-563e12f02ca6.png) + +### Semantic versioning + +Semantic versioning is a formal convention for specifying compatibility. It uses a three-part version number: **major version**; **minor version**; and **patch**. Version numbers convey meaning about the underlying code and what has been modified. For example, versioning could be handled as follows: + +| Code status | Stage | Rule | Example version | +| ------------------------------- | ------------- | ---------------------------------------------------------------------- | --------------- | +| First release | New product | Start with 1.0.0 | 1.0.0 | +| Backward compatible fix | Patch release | Increment the third digit | 1.0.1 | +| Backward compatible new feature | Minor release | Increment the middle digit and reset the last digit to zero | 1.1.0 | +| Breaking updates | Major release | Increment the first digit and reset the middle and last digits to zero | 2.0.0 | + +Check out this article on [Semantic versioning](https://semver.org/) to learn more. + +### Finalize the release + +Now let's change our recently automated release from _draft_ to _latest release_. + +### :keyboard: Activity: Finalize release + +1. In a separate tab, go to the **Releases** page for this repository. + - _Tip: To reach this page, click the **Code** tab at the top of your repository. Then, find the navigation bar below the repository description, and click the **Releases** heading link._ +1. Click the **Edit** button next to your draft release. +1. Ensure the _Target_ branch is set to `main`. +1. Click **Publish release**. +1. Wait about 20 seconds then refresh this page (the one you're following instructions from). [GitHub Actions](https://docs.github.com/en/actions) will automatically update to the next step. diff --git a/.github/steps/6-commit-hotfix.md b/.github/steps/6-commit-hotfix.md new file mode 100644 index 0000000..fae0005 --- /dev/null +++ b/.github/steps/6-commit-hotfix.md @@ -0,0 +1,51 @@ + + +## Step 6: Commit a hotfix to the release + +_Almost there :heart:_ + +Notice that I didn't delete the branch? That's intentional. + +Sometimes mistakes can happen with releases, and we'll want to be able to correct them on the same branch. + +Now that your release is finalized, we have a confession to make. Somewhere in our recent update, I made a mistake and introduced a bug. Instead of changing the text colors to green, we changed the whole game background. + +_Tip: Sometimes GitHub Pages takes a few minutes to update. Your page might not immediately show the recent updates you've made._ + +![image](https://user-images.githubusercontent.com/13326548/48045461-487dd800-e145-11e8-843c-b91a82213eb8.png) + +"Hotfixes", or a quick fix to address a bug in software, are a normal part of development. Oftentimes you'll see application updates whose only description is "bug fixes". + +When bugs come up after you release a version, you'll need to address them. We've already created a `hotfix-v1.0.1` and `fix-game-background` branches for you to start. + +We'll submit a hotfix by creating and merging the pull request. + +### :keyboard: Activity: Create and merge the hotfix pull request + +1. Open a pull request with `hotfix-v1.0.1` as the `base` branch, and `fix-game-background` as the `compare` branch. +1. Fill in the pull request template to describe your changes. You can set the pull request title to "Hotfix for broken game style". You can include a detailed pull request body, an example is below: + ``` + ## Description: + - Fixed bug, set game background back to black + ``` +1. Review the changes and click **Create pull request**. +1. We want to merge this into our hotfix branch now so click **Merge pull request**. + +Now we want these changes merged into `main` as well so let's create and merge a pull request with our hotfix to `main`. + +### :keyboard: Activity: Create the release pull request + +1. Open a pull request with `main` as the `base` branch, and `hotfix-v1.0.1` as the `compare` branch. +1. Ensure the title of your pull request is "Hotfix v1.0.1". +1. Include a detailed pull request body, an example is below: + ``` + ## Description: + - Fixed bug introduced in last production release - set game background back to black + ``` +1. Review the changes and click **Create pull request**. +1. Click **Merge pull request**. +1. Wait about 20 seconds then refresh this page (the one you're following instructions from). [GitHub Actions](https://docs.github.com/en/actions) will automatically update to the next step. diff --git a/.github/steps/7-create-hotfix-release.md b/.github/steps/7-create-hotfix-release.md new file mode 100644 index 0000000..6c1adfc --- /dev/null +++ b/.github/steps/7-create-hotfix-release.md @@ -0,0 +1,29 @@ + + +## Step 7: Create release v1.0.1 + +_One last step to go!_ + +### A final release + +You updated the source code, but users can't readily access your most recent changes. Prepare a new release, and distribute that release to the necessary channels. + +### Create release v1.0.1 + +With descriptive pull requests and auto generated release notes, you don't have to spend a lot of time working on your release draft. Follow the steps below to create your new release, generate the release notes, and publish. + +### :keyboard: Activity: Complete release + +1. In a separate tab, go to to the **Releases** page for this repository. + - _Tip: To reach this page, click the **Code** tab at the top of your repository. Then, find the navigation bar below the repository description, and click the **Releases** heading link._ +1. Click the **Draft a new release** button. +1. Set the _Target_ branch to `main`. + - _Tip: Practice your semantic version syntax. What should the tag and title for this release be?_ +1. To the top right of the description text box, click **Generate release notes**. +1. Review the release notes in the text box and customize the content if desired. +1. Click **Publish release**. +1. Wait about 20 seconds then refresh this page (the one you're following instructions from). [GitHub Actions](https://docs.github.com/en/actions) will automatically update to the next step. diff --git a/.github/steps/X-finish.md b/.github/steps/X-finish.md new file mode 100644 index 0000000..ac53c60 --- /dev/null +++ b/.github/steps/X-finish.md @@ -0,0 +1,27 @@ + + +## Finish + +celebrate + +### Congratulations friend, you've completed this course! + +Here's a recap of all the tasks you've accomplished in your repository: + +- Create a beta release. +- Add a new feature to the release branch. +- Open a release pull request +- Automate release notes. +- Merge and finalize the release branch. +- Commit a hotfix to the release. +- Create release v1.0.1. + +### What's next? + +- [We'd love to hear what you thought of this course](https://github.com/orgs/skills/discussions/categories/release-based-workflow). +- [Take another GitHub Skills course](https://github.com/skills). +- [Read the GitHub Getting Started docs](https://docs.github.com/en/get-started). +- To find projects to contribute to, check out [GitHub Explore](https://github.com/explore). diff --git a/.github/workflows/0-welcome.yml b/.github/workflows/0-welcome.yml new file mode 100644 index 0000000..487bbd8 --- /dev/null +++ b/.github/workflows/0-welcome.yml @@ -0,0 +1,68 @@ +name: Step 0, Welcome + +# This step triggers after the learner creates a new repository from the template. +# This workflow updates from step 0 to step 1. + +# This will run every time we create push a commit to `main`. +# Reference: https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows +on: + workflow_dispatch: + push: + branches: + - main + +# Reference: https://docs.github.com/en/actions/security-guides/automatic-token-authentication +permissions: + contents: write + pull-requests: write + +jobs: + # Get the current step to only run the main job when the learner is on the same step. + get_current_step: + name: Check current step number + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - id: get_step + run: | + echo "current_step=$(cat ./.github/steps/-step.txt)" >> $GITHUB_OUTPUT + outputs: + current_step: ${{ steps.get_step.outputs.current_step }} + + on_start: + name: On start + needs: get_current_step + + # We will only run this action when: + # 1. This repository isn't the template repository. + # 2. The step is currently 0. + # Reference: https://docs.github.com/en/actions/learn-github-actions/contexts + # Reference: https://docs.github.com/en/actions/learn-github-actions/expressions + if: >- + ${{ !github.event.repository.is_template + && needs.get_current_step.outputs.current_step == 0 }} + + # We'll run Ubuntu for performance instead of Mac or Windows. + runs-on: ubuntu-latest + + steps: + # We'll need to check out the repository so that we can edit the README. + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # Create a release-v1.0 branch. + - name: Initialize repository + run: ./.github/script/initialize-repository.sh + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + # Update README from step 0 to step 1. + - name: Update to step 1 + uses: skills/action-update-step@v2 + with: + token: ${{ secrets.GITHUB_TOKEN }} + from_step: 0 + to_step: 1 diff --git a/.github/workflows/1-create-beta-release.yml b/.github/workflows/1-create-beta-release.yml new file mode 100644 index 0000000..7a0c1a7 --- /dev/null +++ b/.github/workflows/1-create-beta-release.yml @@ -0,0 +1,62 @@ +name: Step 1, Create a beta release + +# This step triggers after 0-start.yml. +# This workflow updates from step 1 to step 2. + +# This will run when a release is published. +# Reference: https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows +on: + workflow_dispatch: + release: + types: [published] + +# Reference: https://docs.github.com/en/actions/security-guides/automatic-token-authentication +permissions: + contents: write + +jobs: + # Get the current step to only run the main job when the learner is on the same step. + get_current_step: + name: Check current step number + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - id: get_step + run: | + echo "current_step=$(cat ./.github/steps/-step.txt)" >> $GITHUB_OUTPUT + outputs: + current_step: ${{ steps.get_step.outputs.current_step }} + + on_beta_release_created: + name: On beta release created + needs: get_current_step + + # We will only run this action when: + # 1. This repository isn't the template repository. + # 2. The step is currently 1. + # 3. The tag for the published release is v0.9. + # Reference: https://docs.github.com/en/actions/learn-github-actions/contexts + # Reference: https://docs.github.com/en/actions/learn-github-actions/expressions + if: >- + ${{ !github.event.repository.is_template + && needs.get_current_step.outputs.current_step == 1 + && github.ref_name == 'v0.9' }} + + # We'll run Ubuntu for performance instead of Mac or Windows. + runs-on: ubuntu-latest + + steps: + # We'll need to check out the repository so that we can edit the README. + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # Update README to from step 1 to step 2. + - name: Update to step 2 + uses: skills/action-update-step@v2 + with: + token: ${{ secrets.GITHUB_TOKEN }} + from_step: 1 + to_step: 2 diff --git a/.github/workflows/2-feature-added-to-release.yml b/.github/workflows/2-feature-added-to-release.yml new file mode 100644 index 0000000..ed996cb --- /dev/null +++ b/.github/workflows/2-feature-added-to-release.yml @@ -0,0 +1,62 @@ +name: Step 2, Add feature to release branch + +# This step triggers after 1-create-beta-release.yml. +# This workflow updates from step 2 to step 3. + +# This will run when a change to base.css is pushed to the main branch. +# Reference: https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows +on: + workflow_dispatch: + push: + branches: + - release-v1.0 + paths: + - "base.css" + +permissions: + contents: write + +jobs: + # Get the current step to only run the main job when the learner is on the same step. + get_current_step: + name: Check current step number + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - id: get_step + run: | + echo "current_step=$(cat ./.github/steps/-step.txt)" >> $GITHUB_OUTPUT + outputs: + current_step: ${{ steps.get_step.outputs.current_step }} + + on_feature_added: + name: On feature added + needs: get_current_step + + # We will only run this action when: + # 1. This repository isn't the template repository. + # 2. The step is currently 2. + # Reference: https://docs.github.com/en/actions/learn-github-actions/contexts + # Reference: https://docs.github.com/en/actions/learn-github-actions/expressions + if: >- + ${{ !github.event.repository.is_template + && needs.get_current_step.outputs.current_step == 2 }} + + # We'll run Ubuntu for performance instead of Mac or Windows. + runs-on: ubuntu-latest + + steps: + # We'll need to check out the repository so that we can edit the README. + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # Update README from step 2 to step 3. + - name: Update to step 3 + uses: skills/action-update-step@v2 + with: + token: ${{ secrets.GITHUB_TOKEN }} + from_step: 2 + to_step: 3 diff --git a/.github/workflows/3-release-pr-opened.yml b/.github/workflows/3-release-pr-opened.yml new file mode 100644 index 0000000..9c31de9 --- /dev/null +++ b/.github/workflows/3-release-pr-opened.yml @@ -0,0 +1,62 @@ +name: Step 3, Release pull request opened + +# This step triggers after 2-feature-added-to-release.yml. +# This workflow updates from step 3 to step 4. + +# This will run every time a pull request is opened to main. +# Reference: https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows +on: + workflow_dispatch: + pull_request: + types: [opened] + branches: [main] + +permissions: + contents: write + +jobs: + # Get the current step to only run the main job when the learner is on the same step. + get_current_step: + name: Check current step number + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - id: get_step + run: | + echo "current_step=$(cat ./.github/steps/-step.txt)" >> $GITHUB_OUTPUT + outputs: + current_step: ${{ steps.get_step.outputs.current_step }} + + on_release_pr_opened: + name: On release pull request opened + needs: get_current_step + + # We will only run this action when: + # 1. This repository isn't the template repository. + # 2. The step is currently 3. + # 3. The pull request head branch is 'release-v1.0' + # Reference: https://docs.github.com/en/actions/learn-github-actions/contexts + # Reference: https://docs.github.com/en/actions/learn-github-actions/expressions + if: >- + ${{ !github.event.repository.is_template + && needs.get_current_step.outputs.current_step == 3 + && github.head_ref == 'release-v1.0' }} + + # We'll run Ubuntu for performance instead of Mac or Windows. + runs-on: ubuntu-latest + + steps: + # We'll need to check out the repository so that we can edit the README. + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # Update README from step 3 to step 4. + - name: Update to step 4 + uses: skills/action-update-step@v2 + with: + token: ${{ secrets.GITHUB_TOKEN }} + from_step: 3 + to_step: 4 diff --git a/.github/workflows/4-release-notes-and-merge.yml b/.github/workflows/4-release-notes-and-merge.yml new file mode 100644 index 0000000..1a083f9 --- /dev/null +++ b/.github/workflows/4-release-notes-and-merge.yml @@ -0,0 +1,67 @@ +name: Step 4, Generate release notes and merge + +# This step triggers after 3-release-pr-opened.yml. +# This workflow updates from step 4 to step 5. + +# This will run when a pull request to main is closed (merged). +# Reference: https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows +on: + workflow_dispatch: + pull_request: + types: + - closed + branches: + - main + +# Reference: https://docs.github.com/en/actions/security-guides/automatic-token-authentication +permissions: + contents: write + +jobs: + # Get the current step to only run the main job when the learner is on the same step. + get_current_step: + name: Check current step number + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - id: get_step + run: | + echo "current_step=$(cat ./.github/steps/-step.txt)" >> $GITHUB_OUTPUT + outputs: + current_step: ${{ steps.get_step.outputs.current_step }} + + on_release_merged: + name: On release-v1.0 merged + needs: get_current_step + + # We will only run this action when: + # 1. This repository isn't the template repository. + # 2. The step is currently 4. + # 3. The pull request was closed through a merge. + # 4. The pull request head branch is release-v1.0. + # Reference: https://docs.github.com/en/actions/learn-github-actions/contexts + # Reference: https://docs.github.com/en/actions/learn-github-actions/expressions + if: >- + ${{ !github.event.repository.is_template + && needs.get_current_step.outputs.current_step == 4 + && github.event.pull_request.merged == true + && github.head_ref == 'release-v1.0' }} + + # We'll run Ubuntu for performance instead of Mac or Windows. + runs-on: ubuntu-latest + + steps: + # We'll need to check out the repository so that we can edit the README. + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # Update README from step 4 to step 5. + - name: Update to step 5 + uses: skills/action-update-step@v2 + with: + token: ${{ secrets.GITHUB_TOKEN }} + from_step: 4 + to_step: 5 diff --git a/.github/workflows/5-finalize-release.yml b/.github/workflows/5-finalize-release.yml new file mode 100644 index 0000000..745e000 --- /dev/null +++ b/.github/workflows/5-finalize-release.yml @@ -0,0 +1,69 @@ +name: Step 5, Commit hotfix + +# This step triggers after 4-release-notes-and-merge.yml. +# This workflow updates from step 1 to step 2. + +# This will run when a release is published. +# Reference: https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows +on: + workflow_dispatch: + release: + types: [published] + +# Reference: https://docs.github.com/en/actions/security-guides/automatic-token-authentication +permissions: + contents: write + pull-requests: write + +jobs: + # Get the current step to only run the main job when the learner is on the same step. + get_current_step: + name: Check current step number + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - id: get_step + run: | + echo "current_step=$(cat ./.github/steps/-step.txt)" >> $GITHUB_OUTPUT + outputs: + current_step: ${{ steps.get_step.outputs.current_step }} + + on_release_published: + name: On release v1.0 published + needs: get_current_step + + # We will only run this action when: + # 1. This repository isn't the template repository. + # 2. The step is currently 5. + # 3. The tag for the published release is v1.0.0. + # Reference: https://docs.github.com/en/actions/learn-github-actions/contexts + # Reference: https://docs.github.com/en/actions/learn-github-actions/expressions + if: >- + ${{ !github.event.repository.is_template + && needs.get_current_step.outputs.current_step == 5 + && github.ref_name == 'v1.0.0' }} + + # We'll run Ubuntu for performance instead of Mac or Windows. + runs-on: ubuntu-latest + + steps: + # We'll need to check out the repository so that we can edit the README. + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # Create a release-v1.0.1 hotfix branch. + - name: Create hotfix branch + run: ./.github/script/create-hotfix-pr.sh + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + # Update README from step 5 to step 6. + - name: Update to step 6 + uses: skills/action-update-step@v2 + with: + token: ${{ secrets.GITHUB_TOKEN }} + from_step: 5 + to_step: 6 diff --git a/.github/workflows/6-commit-hotfix.yml b/.github/workflows/6-commit-hotfix.yml new file mode 100644 index 0000000..d8a6643 --- /dev/null +++ b/.github/workflows/6-commit-hotfix.yml @@ -0,0 +1,67 @@ +name: Step 6, Commit hotfix + +# This step triggers after 5-finalize-release.yml. +# This workflow updates from step 6 to step 7. + +# This will run when a pull request to main is closed (merged). +# Reference: https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows +on: + workflow_dispatch: + pull_request: + types: + - closed + branches: + - main + +# Reference: https://docs.github.com/en/actions/security-guides/automatic-token-authentication +permissions: + contents: write + +jobs: + # Get the current step to only run the main job when the learner is on the same step. + get_current_step: + name: Check current step number + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - id: get_step + run: | + echo "current_step=$(cat ./.github/steps/-step.txt)" >> $GITHUB_OUTPUT + outputs: + current_step: ${{ steps.get_step.outputs.current_step }} + + on_hotfix_merged: + name: On hotfix-v1.0.1 merged + needs: get_current_step + + # We will only run this action when: + # 1. This repository isn't the template repository. + # 2. The step is currently 6. + # 3. The pull request was closed through a merge. + # 4. The pull request head branch is hotfix-v1.0.1. + # Reference: https://docs.github.com/en/actions/learn-github-actions/contexts + # Reference: https://docs.github.com/en/actions/learn-github-actions/expressions + if: >- + ${{ !github.event.repository.is_template + && needs.get_current_step.outputs.current_step == 6 + && github.event.pull_request.merged == true + && github.head_ref == 'hotfix-v1.0.1' }} + + # We'll run Ubuntu for performance instead of Mac or Windows. + runs-on: ubuntu-latest + + steps: + # We'll need to check out the repository so that we can edit the README. + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # Update README from step 6 to step 7. + - name: Update to step 7 + uses: skills/action-update-step@v2 + with: + token: ${{ secrets.GITHUB_TOKEN }} + from_step: 6 + to_step: 7 diff --git a/.github/workflows/7-create-hotfix-release.yml b/.github/workflows/7-create-hotfix-release.yml new file mode 100644 index 0000000..e9e583d --- /dev/null +++ b/.github/workflows/7-create-hotfix-release.yml @@ -0,0 +1,62 @@ +name: Step 7, Create release v1.0.1 + +# This step triggers after 6-commit-hotfix.yml. +# This workflow updates from step 7 to step X. + +# This will run when a release is published. +# Reference: https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows +on: + workflow_dispatch: + release: + types: [published] + +# Reference: https://docs.github.com/en/actions/security-guides/automatic-token-authentication +permissions: + contents: write + +jobs: + # Get the current step to only run the main job when the learner is on the same step. + get_current_step: + name: Check current step number + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - id: get_step + run: | + echo "current_step=$(cat ./.github/steps/-step.txt)" >> $GITHUB_OUTPUT + outputs: + current_step: ${{ steps.get_step.outputs.current_step }} + + on_hotfix_release_published: + name: On hotfix release v1.0.1 published + needs: get_current_step + + # We will only run this action when: + # 1. This repository isn't the template repository. + # 2. The step is currently 7. + # 3. The tag for the published release is v1.0.1 + # Reference: https://docs.github.com/en/actions/learn-github-actions/contexts + # Reference: https://docs.github.com/en/actions/learn-github-actions/expressions + if: >- + ${{ !github.event.repository.is_template + && needs.get_current_step.outputs.current_step == 7 + && github.ref_name == 'v1.0.1' }} + + # We'll run Ubuntu for performance instead of Mac or Windows. + runs-on: ubuntu-latest + + steps: + # We'll need to check out the repository so that we can edit the README. + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # Update README from step 7 to step X. + - name: Update to finish + uses: skills/action-update-step@v2 + with: + token: ${{ secrets.GITHUB_TOKEN }} + from_step: 7 + to_step: X diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..773bfd6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +# Compiled source # +################### +*.com +*.class +*.dll +*.exe +*.o +*.so + +# Packages # +############ +# it's better to unpack these files and commit the raw source +# git has its own built in compression methods +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +# Logs and databases # +###################### +*.log +*.sql +*.sqlite + +# OS generated files # +###################### +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6c5bc3d --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) GitHub, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5df74cc --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +
+ + + +# Create a release based workflow + +_Create a release based workflow that is built on the foundations of the GitHub flow._ + +
+ + + +## Welcome + +Create a release based workflow that is built on the foundations of the [GitHub flow](https://guides.github.com/introduction/flow/). When your team uses a release-based workflow, GitHub makes it easy to collaborate with deployable iterations of your project that you can package and make available for a wider audience to download and use. + +GitHub releases allow your team to package and provide software to your users based on a specific point in the history of your project. + +- **Who is this for**: Developers, DevOps Engineers, IT Operations, managers, and teams. +- **What you'll learn**: How to follow a release-based workflow. +- **What you'll build**: You will create tags, releases, and release notes. +- **Prerequisites**: If you need to learn about branches, commits, and pull requests, take [Introduction to GitHub](https://github.com/skills/introduction-to-github) first. +- **How long**: This course takes less than 1 hour to complete. + +In this course, you will: + +1. Create a beta release +2. Add a feature to a release +3. Open a release pull request +4. Add release notes and merge +5. Finalize a release +6. Commit a hotfix +7. Create a hotfix release + +### How to start this course + + + +[![start-course](https://user-images.githubusercontent.com/1221423/235727646-4a590299-ffe5-480d-8cd5-8194ea184546.svg)](https://github.com/new?template_owner=skills&template_name=release-based-workflow&owner=%40me&name=skills-release-based-workflow&description=My+clone+repository&visibility=public) + +1. Right-click **Start course** and open the link in a new tab. +2. In the new tab, most of the prompts will automatically fill in for you. + - For owner, choose your personal account or an organization to host the repository. + - We recommend creating a public repository, as private repositories will [use Actions minutes](https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions). + - Scroll down and click the **Create repository** button at the bottom of the form. +3. After your new repository is created, wait about 20 seconds, then refresh the page. Follow the step-by-step instructions in the new repository's README. + + diff --git a/base.css b/base.css new file mode 100644 index 0000000..d51128e --- /dev/null +++ b/base.css @@ -0,0 +1,141 @@ +/* http://meyerweb.com/eric/tools/css/reset/ + v2.0 | 20110126 + License: none (public domain) +*/ + +html, +body, +div, +span, +applet, +object, +iframe, +h1, +h2, +h3, +h4, +h5, +h6, +p, +blockquote, +pre, +a, +abbr, +acronym, +address, +big, +cite, +code, +del, +dfn, +em, +img, +ins, +kbd, +q, +s, +samp, +small, +strike, +strong, +sub, +sup, +tt, +var, +b, +u, +i, +center, +dl, +dt, +dd, +ol, +ul, +li, +fieldset, +form, +label, +legend, +table, +caption, +tbody, +tfoot, +thead, +tr, +th, +td, +article, +aside, +canvas, +details, +embed, +figure, +figcaption, +footer, +header, +hgroup, +menu, +nav, +output, +ruby, +section, +summary, +time, +mark, +audio, +video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; +} +/* HTML5 display-role reset for older browsers */ +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +menu, +nav, +section { + display: block; +} +body { + /* Add background-color declaration here */ +} +ol, +ul { + list-style: none; +} +blockquote, +q { + quotes: none; +} +blockquote:before, +blockquote:after, +q:before, +q:after { + content: ""; + content: none; +} +table { + border-collapse: collapse; + border-spacing: 0; +} + +/* Center the container */ +#container { + padding-top: 50px; + margin: 0 auto; + width: 480px; +} + +/* Give canvas a background */ +canvas { + background-color: black; +} diff --git a/engine.js b/engine.js new file mode 100644 index 0000000..8c59877 --- /dev/null +++ b/engine.js @@ -0,0 +1,497 @@ +(function () { + var lastTime = 0; + var vendors = ["ms", "moz", "webkit", "o"]; + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { + window.requestAnimationFrame = window[vendors[x] + "RequestAnimationFrame"]; + window.cancelAnimationFrame = + window[vendors[x] + "CancelAnimationFrame"] || + window[vendors[x] + "CancelRequestAnimationFrame"]; + } + + if (!window.requestAnimationFrame) + window.requestAnimationFrame = function (callback, element) { + var currTime = new Date().getTime(); + var timeToCall = Math.max(0, 16 - (currTime - lastTime)); + var id = window.setTimeout(function () { + callback(currTime + timeToCall); + }, timeToCall); + lastTime = currTime + timeToCall; + return id; + }; + + if (!window.cancelAnimationFrame) + window.cancelAnimationFrame = function (id) { + clearTimeout(id); + }; +})(); + +var Game = new (function () { + var boards = []; + + // Game Initialization + this.initialize = function (canvasElementId, sprite_data, callback) { + this.canvas = document.getElementById(canvasElementId); + + this.playerOffset = 10; + this.canvasMultiplier = 1; + this.setupMobile(); + + this.width = this.canvas.width; + this.height = this.canvas.height; + + this.ctx = this.canvas.getContext && this.canvas.getContext("2d"); + if (!this.ctx) { + return alert("Please upgrade your browser to play"); + } + + this.setupInput(); + + this.loop(); + + if (this.mobile) { + this.setBoard(4, new TouchControls()); + } + + SpriteSheet.load(sprite_data, callback); + }; + + // Handle Input + var KEY_CODES = { 37: "left", 39: "right", 32: "fire" }; + this.keys = {}; + + this.setupInput = function () { + window.addEventListener( + "keydown", + function (e) { + if (KEY_CODES[e.keyCode]) { + Game.keys[KEY_CODES[e.keyCode]] = true; + e.preventDefault(); + } + }, + false + ); + + window.addEventListener( + "keyup", + function (e) { + if (KEY_CODES[e.keyCode]) { + Game.keys[KEY_CODES[e.keyCode]] = false; + e.preventDefault(); + } + }, + false + ); + }; + + var lastTime = new Date().getTime(); + var maxTime = 1 / 30; + // Game Loop + this.loop = function () { + var curTime = new Date().getTime(); + requestAnimationFrame(Game.loop); + var dt = (curTime - lastTime) / 1000; + if (dt > maxTime) { + dt = maxTime; + } + + for (var i = 0, len = boards.length; i < len; i++) { + if (boards[i]) { + boards[i].step(dt); + boards[i].draw(Game.ctx); + } + } + lastTime = curTime; + }; + + // Change an active game board + this.setBoard = function (num, board) { + boards[num] = board; + }; + + this.setupMobile = function () { + var container = document.getElementById("container"), + hasTouch = !!("ontouchstart" in window), + w = window.innerWidth, + h = window.innerHeight; + + if (hasTouch) { + this.mobile = true; + } + + if (screen.width >= 1280 || !hasTouch) { + return false; + } + + if (w > h) { + alert("Please rotate the device and then click OK"); + w = window.innerWidth; + h = window.innerHeight; + } + + container.style.height = h * 2 + "px"; + window.scrollTo(0, 1); + + h = window.innerHeight + 2; + container.style.height = h + "px"; + container.style.width = w + "px"; + container.style.padding = 0; + + if (h >= this.canvas.height * 1.75 || w >= this.canvas.height * 1.75) { + this.canvasMultiplier = 2; + this.canvas.width = w / 2; + this.canvas.height = h / 2; + this.canvas.style.width = w + "px"; + this.canvas.style.height = h + "px"; + } else { + this.canvas.width = w; + this.canvas.height = h; + } + + this.canvas.style.position = "absolute"; + this.canvas.style.left = "0px"; + this.canvas.style.top = "0px"; + }; +})(); + +var SpriteSheet = new (function () { + this.map = {}; + + this.load = function (spriteData, callback) { + this.map = spriteData; + this.image = new Image(); + this.image.onload = callback; + this.image.src = "images/sprites.png"; + }; + + this.draw = function (ctx, sprite, x, y, frame) { + var s = this.map[sprite]; + if (!frame) frame = 0; + ctx.drawImage( + this.image, + s.sx + frame * s.w, + s.sy, + s.w, + s.h, + Math.floor(x), + Math.floor(y), + s.w, + s.h + ); + }; + + return this; +})(); + +var TitleScreen = function TitleScreen(title, subtitle, callback) { + var up = false; + this.step = function (dt) { + if (!Game.keys["fire"]) up = true; + if (up && Game.keys["fire"] && callback) callback(); + }; + + this.draw = function (ctx) { + ctx.fillStyle = "#FFFFFF"; + + ctx.font = "bold 40px bangers"; + var measure = ctx.measureText(title); + ctx.fillText(title, Game.width / 2 - measure.width / 2, Game.height / 2); + + ctx.font = "bold 20px bangers"; + var measure2 = ctx.measureText(subtitle); + ctx.fillText( + subtitle, + Game.width / 2 - measure2.width / 2, + Game.height / 2 + 40 + ); + }; +}; + +var GameBoard = function () { + var board = this; + + // The current list of objects + this.objects = []; + this.cnt = {}; + + // Add a new object to the object list + this.add = function (obj) { + obj.board = this; + this.objects.push(obj); + this.cnt[obj.type] = (this.cnt[obj.type] || 0) + 1; + return obj; + }; + + // Mark an object for removal + this.remove = function (obj) { + var idx = this.removed.indexOf(obj); + if (idx == -1) { + this.removed.push(obj); + return true; + } else { + return false; + } + }; + + // Reset the list of removed objects + this.resetRemoved = function () { + this.removed = []; + }; + + // Removed an objects marked for removal from the list + this.finalizeRemoved = function () { + for (var i = 0, len = this.removed.length; i < len; i++) { + var idx = this.objects.indexOf(this.removed[i]); + if (idx != -1) { + this.cnt[this.removed[i].type]--; + this.objects.splice(idx, 1); + } + } + }; + + // Call the same method on all current objects + this.iterate = function (funcName) { + var args = Array.prototype.slice.call(arguments, 1); + for (var i = 0, len = this.objects.length; i < len; i++) { + var obj = this.objects[i]; + obj[funcName].apply(obj, args); + } + }; + + // Find the first object for which func is true + this.detect = function (func) { + for (var i = 0, val = null, len = this.objects.length; i < len; i++) { + if (func.call(this.objects[i])) return this.objects[i]; + } + return false; + }; + + // Call step on all objects and them delete + // any object that have been marked for removal + this.step = function (dt) { + this.resetRemoved(); + this.iterate("step", dt); + this.finalizeRemoved(); + }; + + // Draw all the objects + this.draw = function (ctx) { + this.iterate("draw", ctx); + }; + + // Check for a collision between the + // bounding rects of two objects + this.overlap = function (o1, o2) { + return !( + o1.y + o1.h - 1 < o2.y || + o1.y > o2.y + o2.h - 1 || + o1.x + o1.w - 1 < o2.x || + o1.x > o2.x + o2.w - 1 + ); + }; + + // Find the first object that collides with obj + // match against an optional type + this.collide = function (obj, type) { + return this.detect(function () { + if (obj != this) { + var col = (!type || this.type & type) && board.overlap(obj, this); + return col ? this : false; + } + }); + }; +}; + +var Sprite = function () {}; + +Sprite.prototype.setup = function (sprite, props) { + this.sprite = sprite; + this.merge(props); + this.frame = this.frame || 0; + this.w = SpriteSheet.map[sprite].w; + this.h = SpriteSheet.map[sprite].h; +}; + +Sprite.prototype.merge = function (props) { + if (props) { + for (var prop in props) { + this[prop] = props[prop]; + } + } +}; + +Sprite.prototype.draw = function (ctx) { + SpriteSheet.draw(ctx, this.sprite, this.x, this.y, this.frame); +}; + +Sprite.prototype.hit = function (damage) { + this.board.remove(this); +}; + +var Level = function (levelData, callback) { + this.levelData = []; + for (var i = 0; i < levelData.length; i++) { + this.levelData.push(Object.create(levelData[i])); + } + this.t = 0; + this.callback = callback; +}; + +Level.prototype.step = function (dt) { + var idx = 0, + remove = [], + curShip = null; + + // Update the current time offset + this.t += dt * 1000; + + // Start, End, Gap, Type, Override + // [ 0, 4000, 500, 'step', { x: 100 } ] + while ((curShip = this.levelData[idx]) && curShip[0] < this.t + 2000) { + // Check if we've passed the end time + if (this.t > curShip[1]) { + remove.push(curShip); + } else if (curShip[0] < this.t) { + // Get the enemy definition blueprint + var enemy = enemies[curShip[3]], + override = curShip[4]; + + // Add a new enemy with the blueprint and override + this.board.add(new Enemy(enemy, override)); + + // Increment the start time by the gap + curShip[0] += curShip[2]; + } + idx++; + } + + // Remove any objects from the levelData that have passed + for (var i = 0, len = remove.length; i < len; i++) { + var remIdx = this.levelData.indexOf(remove[i]); + if (remIdx != -1) this.levelData.splice(remIdx, 1); + } + + // If there are no more enemies on the board or in + // levelData, this level is done + if (this.levelData.length === 0 && this.board.cnt[OBJECT_ENEMY] === 0) { + if (this.callback) this.callback(); + } +}; + +Level.prototype.draw = function (ctx) {}; + +var TouchControls = function () { + var gutterWidth = 10; + var unitWidth = Game.width / 5; + var blockWidth = unitWidth - gutterWidth; + + this.drawSquare = function (ctx, x, y, txt, on) { + ctx.globalAlpha = on ? 0.9 : 0.6; + ctx.fillStyle = "#CCC"; + ctx.fillRect(x, y, blockWidth, blockWidth); + + ctx.fillStyle = "#FFF"; + ctx.globalAlpha = 1.0; + ctx.font = "bold " + (3 * unitWidth) / 4 + "px arial"; + + var txtSize = ctx.measureText(txt); + + ctx.fillText( + txt, + x + blockWidth / 2 - txtSize.width / 2, + y + (3 * blockWidth) / 4 + 5 + ); + }; + + this.draw = function (ctx) { + ctx.save(); + + var yLoc = Game.height - unitWidth; + this.drawSquare(ctx, gutterWidth, yLoc, "\u25C0", Game.keys["left"]); + this.drawSquare( + ctx, + unitWidth + gutterWidth, + yLoc, + "\u25B6", + Game.keys["right"] + ); + this.drawSquare(ctx, 4 * unitWidth, yLoc, "A", Game.keys["fire"]); + + ctx.restore(); + }; + + this.step = function (dt) {}; + + this.trackTouch = function (e) { + var touch, x; + + e.preventDefault(); + Game.keys["left"] = false; + Game.keys["right"] = false; + for (var i = 0; i < e.targetTouches.length; i++) { + touch = e.targetTouches[i]; + x = touch.pageX / Game.canvasMultiplier - Game.canvas.offsetLeft; + if (x < unitWidth) { + Game.keys["left"] = true; + } + if (x > unitWidth && x < 2 * unitWidth) { + Game.keys["right"] = true; + } + } + + if (e.type == "touchstart" || e.type == "touchend") { + for (i = 0; i < e.changedTouches.length; i++) { + touch = e.changedTouches[i]; + x = touch.pageX / Game.canvasMultiplier - Game.canvas.offsetLeft; + if (x > 4 * unitWidth) { + Game.keys["fire"] = e.type == "touchstart"; + } + } + } + }; + + Game.canvas.addEventListener("touchstart", this.trackTouch, true); + Game.canvas.addEventListener("touchmove", this.trackTouch, true); + Game.canvas.addEventListener("touchend", this.trackTouch, true); + + // For Android + Game.canvas.addEventListener( + "dblclick", + function (e) { + e.preventDefault(); + }, + true + ); + Game.canvas.addEventListener( + "click", + function (e) { + e.preventDefault(); + }, + true + ); + + Game.playerOffset = unitWidth + 20; +}; + +var GamePoints = function () { + Game.points = 0; + + var pointsLength = 8; + + this.draw = function (ctx) { + ctx.save(); + ctx.font = "bold 18px arial"; + ctx.fillStyle = "#FFFFFF"; + + var txt = "" + Game.points; + var i = pointsLength - txt.length, + zeros = ""; + while (i-- > 0) { + zeros += "0"; + } + + ctx.fillText(zeros + txt, 10, 20); + ctx.restore(); + }; + + this.step = function (dt) {}; +}; diff --git a/game.js b/game.js new file mode 100644 index 0000000..4c059ee --- /dev/null +++ b/game.js @@ -0,0 +1,355 @@ +var sprites = { + ship: { sx: 0, sy: 0, w: 37, h: 42, frames: 1 }, + missile: { sx: 0, sy: 30, w: 2, h: 10, frames: 1 }, + enemy_purple: { sx: 37, sy: 0, w: 42, h: 43, frames: 1 }, + enemy_bee: { sx: 79, sy: 0, w: 37, h: 43, frames: 1 }, + enemy_ship: { sx: 116, sy: 0, w: 42, h: 43, frames: 1 }, + enemy_circle: { sx: 158, sy: 0, w: 32, h: 33, frames: 1 }, + explosion: { sx: 0, sy: 64, w: 64, h: 64, frames: 12 }, + enemy_missile: { sx: 9, sy: 42, w: 3, h: 20, frame: 1 }, +}; + +var enemies = { + straight: { x: 0, y: -50, sprite: "enemy_ship", health: 10, E: 100 }, + ltr: { + x: 0, + y: -100, + sprite: "enemy_purple", + health: 10, + B: 75, + C: 1, + E: 100, + missiles: 2, + }, + circle: { + x: 250, + y: -50, + sprite: "enemy_circle", + health: 10, + A: 0, + B: -100, + C: 1, + E: 20, + F: 100, + G: 1, + H: Math.PI / 2, + }, + wiggle: { + x: 100, + y: -50, + sprite: "enemy_bee", + health: 20, + B: 50, + C: 4, + E: 100, + firePercentage: 0.001, + missiles: 2, + }, + step: { + x: 0, + y: -50, + sprite: "enemy_circle", + health: 10, + B: 150, + C: 1.2, + E: 75, + }, +}; + +var OBJECT_PLAYER = 1, + OBJECT_PLAYER_PROJECTILE = 2, + OBJECT_ENEMY = 4, + OBJECT_ENEMY_PROJECTILE = 8, + OBJECT_POWERUP = 16; + +var startGame = function () { + var ua = navigator.userAgent.toLowerCase(); + + // Only 1 row of stars + if (ua.match(/android/)) { + Game.setBoard(0, new Starfield(50, 0.6, 100, true)); + } else { + Game.setBoard(0, new Starfield(20, 0.4, 100, true)); + Game.setBoard(1, new Starfield(50, 0.6, 100)); + Game.setBoard(2, new Starfield(100, 1.0, 50)); + } + Game.setBoard( + 3, + new TitleScreen("Alien Invasion", "Press fire to start playing", playGame) + ); +}; + +var level1 = [ + // Start, End, Gap, Type, Override + [0, 4000, 500, "step"], + [6000, 13000, 800, "ltr"], + [10000, 16000, 400, "circle"], + [17800, 20000, 500, "straight", { x: 50 }], + [18200, 20000, 500, "straight", { x: 90 }], + [18200, 20000, 500, "straight", { x: 10 }], + [22000, 25000, 400, "wiggle", { x: 150 }], + [22000, 25000, 400, "wiggle", { x: 100 }], +]; + +var playGame = function () { + var board = new GameBoard(); + board.add(new PlayerShip()); + board.add(new Level(level1, winGame)); + Game.setBoard(3, board); + Game.setBoard(5, new GamePoints(0)); +}; + +var winGame = function () { + Game.setBoard( + 3, + new TitleScreen("You win!", "Press fire to play again", playGame) + ); +}; + +var loseGame = function () { + Game.setBoard( + 3, + new TitleScreen("You lose!", "Press fire to play again", playGame) + ); +}; + +var Starfield = function (speed, opacity, numStars, clear) { + // Set up the offscreen canvas + var stars = document.createElement("canvas"); + stars.width = Game.width; + stars.height = Game.height; + var starCtx = stars.getContext("2d"); + + var offset = 0; + + // If the clear option is set, + // make the background black instead of transparent + if (clear) { + starCtx.fillStyle = "#000"; + starCtx.fillRect(0, 0, stars.width, stars.height); + } + + // Now draw a bunch of random 2 pixel + // rectangles onto the offscreen canvas + starCtx.fillStyle = "#FFF"; + starCtx.globalAlpha = opacity; + for (var i = 0; i < numStars; i++) { + starCtx.fillRect( + Math.floor(Math.random() * stars.width), + Math.floor(Math.random() * stars.height), + 2, + 2 + ); + } + + // This method is called every frame + // to draw the starfield onto the canvas + this.draw = function (ctx) { + var intOffset = Math.floor(offset); + var remaining = stars.height - intOffset; + + // Draw the top half of the starfield + if (intOffset > 0) { + ctx.drawImage( + stars, + 0, + remaining, + stars.width, + intOffset, + 0, + 0, + stars.width, + intOffset + ); + } + + // Draw the bottom half of the starfield + if (remaining > 0) { + ctx.drawImage( + stars, + 0, + 0, + stars.width, + remaining, + 0, + intOffset, + stars.width, + remaining + ); + } + }; + + // This method is called to update + // the starfield + this.step = function (dt) { + offset += dt * speed; + offset = offset % stars.height; + }; +}; + +var PlayerShip = function () { + this.setup("ship", { vx: 0, reloadTime: 0.25, maxVel: 200 }); + + this.reload = this.reloadTime; + this.x = Game.width / 2 - this.w / 2; + this.y = Game.height - Game.playerOffset - this.h; + + this.step = function (dt) { + if (Game.keys["left"]) { + this.vx = -this.maxVel; + } else if (Game.keys["right"]) { + this.vx = this.maxVel; + } else { + this.vx = 0; + } + + this.x += this.vx * dt; + + if (this.x < 0) { + this.x = 0; + } else if (this.x > Game.width - this.w) { + this.x = Game.width - this.w; + } + + this.reload -= dt; + if (Game.keys["fire"] && this.reload < 0) { + Game.keys["fire"] = false; + this.reload = this.reloadTime; + + this.board.add(new PlayerMissile(this.x, this.y + this.h / 2)); + this.board.add(new PlayerMissile(this.x + this.w, this.y + this.h / 2)); + } + }; +}; + +PlayerShip.prototype = new Sprite(); +PlayerShip.prototype.type = OBJECT_PLAYER; + +PlayerShip.prototype.hit = function (damage) { + if (this.board.remove(this)) { + loseGame(); + } +}; + +var PlayerMissile = function (x, y) { + this.setup("missile", { vy: -700, damage: 10 }); + this.x = x - this.w / 2; + this.y = y - this.h; +}; + +PlayerMissile.prototype = new Sprite(); +PlayerMissile.prototype.type = OBJECT_PLAYER_PROJECTILE; + +PlayerMissile.prototype.step = function (dt) { + this.y += this.vy * dt; + var collision = this.board.collide(this, OBJECT_ENEMY); + if (collision) { + collision.hit(this.damage); + this.board.remove(this); + } else if (this.y < -this.h) { + this.board.remove(this); + } +}; + +var Enemy = function (blueprint, override) { + this.merge(this.baseParameters); + this.setup(blueprint.sprite, blueprint); + this.merge(override); +}; + +Enemy.prototype = new Sprite(); +Enemy.prototype.type = OBJECT_ENEMY; + +Enemy.prototype.baseParameters = { + A: 0, + B: 0, + C: 0, + D: 0, + E: 0, + F: 0, + G: 0, + H: 0, + t: 0, + reloadTime: 0.75, + reload: 0, +}; + +Enemy.prototype.step = function (dt) { + this.t += dt; + + this.vx = this.A + this.B * Math.sin(this.C * this.t + this.D); + this.vy = this.E + this.F * Math.sin(this.G * this.t + this.H); + + this.x += this.vx * dt; + this.y += this.vy * dt; + + var collision = this.board.collide(this, OBJECT_PLAYER); + if (collision) { + collision.hit(this.damage); + this.board.remove(this); + } + + if (Math.random() < 0.01 && this.reload <= 0) { + this.reload = this.reloadTime; + if (this.missiles == 2) { + this.board.add(new EnemyMissile(this.x + this.w - 2, this.y + this.h)); + this.board.add(new EnemyMissile(this.x + 2, this.y + this.h)); + } else { + this.board.add(new EnemyMissile(this.x + this.w / 2, this.y + this.h)); + } + } + this.reload -= dt; + + if (this.y > Game.height || this.x < -this.w || this.x > Game.width) { + this.board.remove(this); + } +}; + +Enemy.prototype.hit = function (damage) { + this.health -= damage; + if (this.health <= 0) { + if (this.board.remove(this)) { + Game.points += this.points || 100; + this.board.add(new Explosion(this.x + this.w / 2, this.y + this.h / 2)); + } + } +}; + +var EnemyMissile = function (x, y) { + this.setup("enemy_missile", { vy: 200, damage: 10 }); + this.x = x - this.w / 2; + this.y = y; +}; + +EnemyMissile.prototype = new Sprite(); +EnemyMissile.prototype.type = OBJECT_ENEMY_PROJECTILE; + +EnemyMissile.prototype.step = function (dt) { + this.y += this.vy * dt; + var collision = this.board.collide(this, OBJECT_PLAYER); + if (collision) { + collision.hit(this.damage); + this.board.remove(this); + } else if (this.y > Game.height) { + this.board.remove(this); + } +}; + +var Explosion = function (centerX, centerY) { + this.setup("explosion", { frame: 0 }); + this.x = centerX - this.w / 2; + this.y = centerY - this.h / 2; +}; + +Explosion.prototype = new Sprite(); + +Explosion.prototype.step = function (dt) { + this.frame++; + if (this.frame >= 12) { + this.board.remove(this); + } +}; + +window.addEventListener("load", function () { + Game.initialize("game", sprites, startGame); +}); diff --git a/game.manifest b/game.manifest new file mode 100644 index 0000000..78aa44c --- /dev/null +++ b/game.manifest @@ -0,0 +1,14 @@ +CACHE MANIFEST + +# v1.02 +CACHE: +index.html +engine.js +game.js +images/sprites.png +base.css + +NETWORK: +http://fonts.googleapis.com/ +http://www.google-analytics.com/ +http://themes.googleusercontent.com/ diff --git a/images/sprites.png b/images/sprites.png new file mode 100644 index 0000000..78c9175 Binary files /dev/null and b/images/sprites.png differ diff --git a/index.html b/index.html new file mode 100644 index 0000000..b583ba2 --- /dev/null +++ b/index.html @@ -0,0 +1,29 @@ + + + + + Alien Invasion + + + + + + + +
+ +
+ + + +