Skip to content

Instantly share code, notes, and snippets.

@ttseng
Last active May 19, 2018 06:38
Show Gist options
  • Save ttseng/906c2486b498d790f0f53b2bf8c500dc to your computer and use it in GitHub Desktop.
Save ttseng/906c2486b498d790f0f53b2bf8c500dc to your computer and use it in GitHub Desktop.
Space Invaders
// client-side js
// run by the browser each time your view template is loaded
var player;
var playerSrc = "https://cdn.glitch.com/43e0016d-c8a0-4e4b-9451-241a4af8fb4f%2Fplayer.svg?1526019694966";
var invaderSrc = "https://cdn.glitch.com/43e0016d-c8a0-4e4b-9451-241a4af8fb4f%2Finvader.svg?1526019377700";
var dimension = 20; // base width and height for drawable objects
var canvasBound = 25;
var gameover = false;
(function(){
class Main {
constructor(){
// get canvas & context
this.canvas = document.getElementById("canvas");
this.context = this.canvas.getContext('2d');
// create player
player = new Player(this);
player.initialize();
// create space invaders
this.invaders = [];
this.invaders = this.invaders.concat(createInvaders(this));
// run timer
this.timer();
}
// update() - update the positions of the player and invaders, to be drawn in draw()
update(){
player.update();
// update invaders position
for(var i = 0; i < this.invaders.length; i++){
this.invaders[i].update();
}
}
draw(canvas, context){
context.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
// draw player
context.drawImage(player.playerSVG, player.position.x, player.position.y, player.size.width, player.size.height);
// draw invaders
for(var i=0; i < this.invaders.length; i++){
var invaderSVG = new Image();
invaderSVG.src = invaderSrc;
context.drawImage(invaderSVG, this.invaders[i].position.x, this.invaders[i].position.y, this.invaders[i].size.width, this.invaders[i].size.height);
}
}
// timer() - update canvas for each animation frame
timer(){
this.update();
this.draw(this.canvas, this.context);
var self = this;
var delayInMilliseconds = 0; // a delay to help with debugging
setTimeout(function() {
if(!gameover){
requestAnimationFrame(() => { self.timer() })
// requestAnimationFrame(self.timer());
}else{
// game over sequence
self.context.clearRect(0, 0, self.canvas.width, self.canvas.height);
self.context.textAlign = "center";
self.context.fillText("GAME OVER!", self.canvas.width/2, self.canvas.height/2);
}
}, delayInMilliseconds);
}
}
// Player that can be controlled using left and right arrow keys
class Player{
constructor(main){
this.main = main;
this.size = {width: dimension, height: dimension};
this.position = {x: this.main.canvas.width/2-dimension/2, y: this.main.canvas.height-dimension};
}
initialize(){
this.playerSVG = new Image();
this.playerSVG.src = playerSrc;
var self = this;
this.playerSVG.onload = function(){
// place player in middle of board to begin with
self.main.context.drawImage(self.playerSVG, self.position.x, self.position.y, self.size.width, self.size.height);
}
}
update(direction){
if(direction == "left" && this.position.x > 0){
this.position.x -= 5;
}else if(direction == "right" && this.position.x < this.main.canvas.width-this.size.width){
this.position.x += 5;
}
}
}
// listen for keyboard events to control player
window.addEventListener('keydown', function(e){
var left = 37; // keycode for left
var right = 39; // keycode for right
var key = e.keyCode ? e.keyCode : e.which;
if(key == left){
// console.log('left');
player.update("left");
}else if(key == right){
// console.log('right');
player.update("right");
}
});
class Invader{
constructor(main, position){
this.main = main;
this.size = {width: dimension, height: dimension};
this.position = position;
this.bounds = 0; // the bounds in which the invaders are still viewable in the convas
this.xShift = 1; // amount the invader moves per timer increment
}
update(){
if(this.bounds > canvasBound || this.bounds < -canvasBound){
this.xShift = -this.xShift;
this.position.y += 10;
if(this.position.y > (this.main.canvas.height-player.size.height*2)){
// touching the player - game is over!
// console.log('game over!')
gameover = true;
}
}
this.position.x += this.xShift;
this.bounds += this.xShift;
}
}
// createInvaders() creates an array of 24 invaders (6 columns, 4 rows)
function createInvaders(main){
var invadersArray = [];
for(var i=0; i<24; i++){
var x = canvasBound + (i % 8) * canvasBound;
var y = canvasBound + (i % 3) * canvasBound;
invadersArray.push(new Invader(main, {x: x, y: y}));
}
return invadersArray;
}
// runs application when the window has loaded
window.addEventListener('load', function() {
new Main();
});
})()
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tiff's Space Invader</title>
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- import the webpage's stylesheet -->
</head>
<body>
<canvas id="canvas" width="250px" height="250px"></canvas>
<!-- import the webpage's client-side javascript file -->
<script src="/client.js"></script>
</body>
</html>
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 175.7 175.7" style="enable-background:new 0 0 175.7 175.7;" xml:space="preserve">
<style type="text/css">
.st0{fill:#231F20;}
</style>
<title>svgOutput</title>
<desc>made with tinkercad</desc>
<path class="st0" d="M59.5,2.8h56.7v56.7h28.3v56.7h28.3v56.7h-28.3h-28.3H59.5H2.8v-56.7h28.3V59.5h28.3V2.8z"/>
</svg>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment