자바스크립트 인베이더 소스코드 알고리즘 분석
출처: http://jsfiddle.net/ARTsinn/GgxjY/
참고사이트 : https://www.w3schools.com/
목록
그리기
- Alien (적, 외계인) : Alien.draw()
- Gun (플레이어) : Gun.draw()
- ray (총알) : Gun.ray.draw()
- 폭파 : Alien.draw()
반복 작동 : setInterval()
충돌검사 (checkCollision) : Alien.checkCollision()
키입력 : Game.onkeydown(), Game.onkeyup()
<p>사용한 이미지:</p>
<img id="alien" width="240" height="277" src="https://github.com/gregquat/inbeda/raw/master/sprite.png" alt="The Scream"style="background-color: black">
<p>Canvas:</p>
<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;background-color:black">
Your browser does not support the HTML5 canvas tag.
</Canvas>
<script>
window.onload = function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("alien");
ctx.drawImage(img, 0,0,28,20,10, 10, 28, 20);
ctx.drawImage(img, 28,0,28,20,10, 40, 28, 20);
ctx.drawImage(img, 28,0,28,20,38, 40, 28, 20);
ctx.drawImage(img, 56,0,28,20,10, 70, 28, 20);
ctx.drawImage(img, 56,0,28,20,38, 70, 28, 20);
ctx.drawImage(img, 56,0,28,20,66, 70, 28, 20);
// 메소드 설명: http://ilvjesus.tistory.com/1446
}
</script>
실행결과
사용한 이미지:

캔버스:
<그리기 예제 2>
<canvas id="aliensCanvas" class="mesCanvas" width="530" height="600">Votre navigateur ne supporte pas les Canvas :(</canvas>
<script>
var Alien = function (aType, aLine, aCol) {
this.type = aType;
this.line = aLine;
this.column = aCol;
this.alive = true;
this.height = 20;
this.width = 28;
this.positionX = 100 + this.width * this.column;
this.positionY = 100 + 30 * this.line;
this.state = 0;
this.draw = function () { //draw the alien to his new position
if (this.alive) { //draw the alien
canvas.drawImage(
pic,
this.width * (this.type - 1),
this.state,
this.width,
this.height,
this.positionX,
this.positionY,
this.width,
this.height);
}
}
};
Game = {
types: [1, 2, 2, 3, 3], //define kinds of aliens
aliens: [
[11],
[11],
[11],
[11],
[11]
],
height: 0,
width: 0,
interval: 0,
intervalDefault: 1000,
init: function (aWidth, aHeight) { //initialize default position and behaviour
for (i = 0; i < 5; i++) {
for (j = 0; j < 11; j++) {
this.aliens[i][j] = new Alien(this.types[i], i, j);
this.alives++;
this.aliens[i][j].draw();
}
}
this.play();
},
animate: function () { //move the aliens
for (i = 0; i < 5; i++) {
for (j = 0; j < 11; j++) {
this.aliens[i][j].draw();
}
}
},
play: function () { //play the game
this.interval = this.intervalDefault;
this.interval = this.interval - (this.level * 20);
this.animation = setInterval("Game.animate()", this.interval);
}
};
//define the global context of the game
var element = document.getElementById('aliensCanvas');
if (element.getContext) {
var canvas = element.getContext('2d');
var pic = new Image();
pic.src = 'https://github.com/gregquat/inbeda/raw/master/sprite.png';
Game.init(530, 500);
}
</script>
실행결과
Alien
Gun
Game