1. 핵심 요점과 문제를 요약하십시오
1. JavaScript의 상속, 부모 클래스는 메소드 공유 만 제공하는 것이 가장 좋습니다. 부모 클래스 및 서브 클래스의 생성자의 혼란을 피하기 위해 각 서브 클래스에 속성이 기록됩니다.
2. 프로토 타입은 상속 된 코드를 시뮬레이션하고 모든 메소드 정의 전에 작성해야합니다.
코드 사본은 다음과 같습니다.
hero.prototype = 새로운 탱크 (0, 0, 0);
hero.prototype.constructor = 영웅;
hero.prototype.addlife = function () {
this.lifetimes ++;
document.querySelector ( "#life"). innerHtml = hero.lifetimes;
}
3. 사각형을 제외한 캔버스를 그리는 경우 CTX.BegInpath ()와 CTX.Closepath ();
4. CONCAT 함수는 어레이를 병합하거나 요소를 새 배열로 반환 할 수 있습니다.
5. SRC 속성이 할당 된 후 이미지가로드되지만 이미지가로드되지 않으면 고장이 발생하므로 Onload 이벤트를 사용하여 처리하십시오.
6. 배열 함수를 확장하고 지정된 요소를 삭제합니다.
코드 사본은 다음과 같습니다.
// 지정된 요소를 삭제하도록 확장합니다
Array.prototype.deleteElement = function (obj) {
if (obj) {
for (var i = 0; i <this.length; i ++) {
if (this [i] === obj) {
this.splice (i, 1);
}
}
}
}
7. TIMER SETTINSS SETINTERVAL ( "FUN", 1000) 메소드의 첫 번째 매개 변수 인 "hero.say ()"와 같은 문자열이 될 수 있습니다. 상단 매개 변수를 기능 하고이 함수의 실행중인 컨텍스트를 지정합니다. 그러나 패스가 함수에 대한 핸들이라면 매개 변수를 가져갈 수 없으며 컨텍스트를 지정할 수는 없습니다.
코드 사본은 다음과 같습니다.
// 타이머, 혼자서 운동하십시오
this.timer = setInterval ((함수 (context) {
return function () {
Bullet.prototype.move.call (컨텍스트)
}
}) (this), 30);
현재 실행 환경을 저장하고 수동으로 실행하기 위해 호출 방법을 호출했습니다.
8.이 방법의 기능 설계는 함수 외에도 이동과 같은이 함수의 조건부 감지를 포함해야하며, 여기에는 이동할 수있는 상황과 이동할 수없는 곳이 포함되어야합니다. 이 탐지는 외부 적으로 배치해서는 안됩니다.
9. 코드를 작성할 때는 디자인이나 최적화에 대해 먼저 생각하지 않아야합니다. 생각에 분명하고 혼란스럽지 말고 한 가지에 집중하십시오.
10. JavaScript는 수면 기능이 없으므로 간격 실행의 목적을 달성하기 위해 버퍼로 변수를 만들 수 있습니다.
2. 코드 구현
1.이 프로그램은 Bomb.js, Bullet.js, Draw.js, Tank.js, Index.html, IMG, Music, Music으로 나뉩니다.
2. 최종 효과
3. 코드
1. index.html
코드 사본은 다음과 같습니다.
<! doctype html>
<html>
<헤드>
<제목> </title>
<meta charset = "utf-8">
<스타일 유형 = "텍스트/CSS">
몸 {
글꼴 : 14px "Sans-Serif"
}
#지도 {
배경색 : #000000;
}
.보여주다 {
플로트 : 왼쪽
}
#가이드 {
플로트 : 왼쪽;
너비 : 200px;
높이 : 390px;
마진 왼쪽 : 5px;
배경 : #CCCCCC;
패딩 : 5px;
}
</스타일>
<script type = "text/javaScript"src = "tank.js"> </script>
<script type = "text/javaScript"src = "bullet.js"> </script>
<script type = "text/javaScript"src = "bomb.js"> </script>
<script type = "text/javaScript"src = "draw.js"> </script>
<script type = "text/javaScript">
Window.onload = function () {
// 캔버스 정보
너비 = document.getElementById ( 'map'). 너비;
높이 = document.getElementById ( 'map'). 높이;
ctx = document.getElementById ( 'map'). getContext ( '2d');
// 초기 페이지
var starimg = new image ();
starimg.src = "img/star.jpg";
starimg.onload = function () {
ctx.DrawImage (starimg, 0, 0, 너비, 높이);
}
// 키보드 모니터링 및 게임을 시작하기 위해 돌아갑니다
document.body.onkeydown = function () {
var keycode = event.keyCode;
스위치 (키 코드) {
case 13:
// 초기화 매개 변수
init ()
// 페이지를 새로 고칩니다
SetInterval (Draw, 30);
document.body.onkeydown = GameControl;
부서지다;
}
}
}
함수 init () {
// 플레이어와 컴퓨터
영웅 = 새로운 영웅 (100, 300, 0);
적 = [];
for (var i = 0; i <3; i ++) {
Enemys.push (새로운 적 (100 + i * 50, 0, 2));
}
// 배열 병합
AllTank = Enemys.concat (영웅);
//폭탄
폭탄 = [];
im = new image ();
IM2 = 새로운 이미지 ();
IM3 = 새로운 이미지 ();
im.src = "img/bomb_3.gif";
im2.src = "img/bomb_2.gif";
im3.src = "img/bomb_1.gif";
}
함수 GameControl () {
var keycode = event.keyCode;
스위치 (키 코드) {
사례 65 :
hero.moveleft ();
휴식; // 왼쪽
사례 83 :
Hero.movedown ();
휴식; // 다음
사례 87 :
hero.moveup ();
휴식; // on
사례 68 :
Hero.moveright ();
휴식; // 오른쪽
사례 74 :
hero.shot ();
부서지다;
사례 49 :
hero.addlife ()
부서지다;
}
}
// 지정된 요소를 삭제하도록 확장합니다
Array.prototype.deleteElement = function (obj) {
if (obj) {
for (var i = 0; i <this.length; i ++) {
if (this [i] === obj) {
this.splice (i, 1);
}
}
}
}
</스크립트>
</head>
<body>
<div>
<canvas id = "map">
</캔버스>
<audio id = "music"autoplay = "autoplay">
<소스 src = "music/111.wav">
</오디오>
</div>
<div id = "가이드">
<p> 게임을 시작하려면 Enter를 누르십시오 </p>
<p> 1 키를 누르려면 수명을 높이고 기본값은 1 </p>입니다.
<p> 남은 생활 수 : <레이블 ID = "Life"> 1 </label> </p>
<div id = "data">
</div>
</div>
</body>
</html>
2.Draw.js
코드 사본은 다음과 같습니다.
/**
* 14-3-18에 Alane에 의해 만들어졌습니다.
*/
함수 draw () {
// 총알과 탱크의 생명과 죽음의 탐지
checkdead ();
// 캔버스를 지우십시오
ctx.clearrect (0,0,500,400);
// 플레이어를 그립니다
if (! hero.isdead) {
DrawTank (영웅);
}또 다른{
hero.cutlife ();
}
// 적 탱크를 그립니다
for (var i = 0; i <Enemys.length; i ++) {
드로 타인 (적 [i]);
}
// 적의 총알을 그립니다
for (var j = 0; j <Enemys.length; j ++) {
var temp = 적 [j] .bulletslist;
for (var i = 0; i <temp.length; i ++) {
DrawBullet (온도 [i]);
}
}
// 플레이어의 총알을 그립니다
var temp = hero.bulletslist;
for (var i = 0; i <temp.length; i ++) {
DrawBullet (온도 [i]);
}
// 폭탄을 그리십시오
for (var i = 0; i <bombs.length; i ++) {
Drawbown (폭탄 [I]);
}
}
함수 드로 타인 (탱크) {
var x = tank.x;
var y = tank.y;
ctx.fillstyle = 탱크 .color;
if (tank.direct == 0 || tank.direct == 2) {
ctx.fillRect (x, y, 5,30);
ctx.fillRect (x+15, y, 5,30);
ctx.fillRect (x+6, y+8, 8,15);
ctx.strokestyle = tank.color;
ctx.linewidth = '1.5';
if (tank.direct == 0) {
ctx.beginpath ();
ctx.moveto (x+10, y-2);
ctx.lineto (x+10, y+8);
ctx.closepath ();
}또 다른{
ctx.beginpath ();
ctx.moveto (x+10, y+24);
ctx.lineto (x+10, y+32);
ctx.closepath ();
}
ctx.stroke ();
}또 다른{
ctx.fillRect (x, y, 30,5);
ctx.fillRect (x, y+15, 30,5);
ctx.fillRect (x+8, y+6, 15,8);
ctx.strokestyle = '#ff0000';
ctx.linewidth = '1.5';
if (tank.direct == 3) {
ctx.beginpath ();
ctx.moveto (x-2, y+10);
ctx.lineto (x+8, y+10);
ctx.closepath ();
}또 다른{
ctx.beginpath ();
ctx.moveto (x+24, y+10);
ctx.lineto (x+32, y+10);
ctx.closepath ();
}
ctx.stroke ();
}
}
함수 DrawBullet (Bullet) {
ctx.fillstyle = bullet.color;
ctx.beginpath ();
ctx.arc (bullet.x, bullet.y, 2,360, true);
ctx.closepath ();
ctx.fill ();
}
함수 드로우 버운 (obj) {
if (obj.life> 8) {
ctx.DrawImage (im, obj.x, obj.y, 50,50);
} else if (obj.life> 4) {
ctx.DrawImage (IM2, obj.x, obj.y, 50,50);
}또 다른{
ctx.DrawImage (IM3, obj.x, obj.y, 50,50);
}
obj.lifedown ();
if (obj.life <= 0) {
폭탄 (OBJ);
}
}
함수 checkDead () {
// 적의 총알의 삶과 죽음의 탐지
for (var j = 0; j <Enemys.length; j ++) {
var temp = 적 [j] .bulletslist;
for (var i = 0; i <temp.length; i ++) {
var o = 온도 [i];
if (o.isdead) {
temp.deleteelement (o);
}
}
}
// 플레이어 총알 수명과 죽음의 탐지
var temp = hero.bulletslist;
for (var i = 0; i <temp.length; i ++) {
var o = 온도 [i];
if (o.isdead) {
temp.deleteelement (o);
}
}
// 적 탱크의 생명과 죽음의 탐지
for (var i = 0; i <Enemys.length; i ++) {
var o = 적 [i];
if (o.isdead) {
적 .DeleteElement (O);
}
}
}
BOMB.JS
코드 사본은 다음과 같습니다.
/**
* 14-3-18에 Alane에 의해 만들어졌습니다.
*/
기능 폭탄 (x, y) {
this.life = 12;
this.x = x;
this.y = y;
}
bomb.prototype.lifedown = function () {
this.life-;
}
Tank.js
코드 사본은 다음과 같습니다.
/**
* 14-3-7에 Alane에 의해 만들어졌습니다.
*/
/**
* 직접 0 on
* 1 오른쪽
* 2
* 3 왼쪽
* @param x
* @param y
* @Param Direct
* @constructor
*/
// ******************************************* ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************** *********************** **************************/
// 탱크 부모 클래스
기능 탱크 (x, y, direct) {
이 .speed = 2;
}
tank.prototype.moveup = function () {
// 경계 감지
if (this.y <0) {
// 방향을 변경합니다
this.changedirect ();
반품;
}
this.y- = this.speed;
this.direct = 0;
}
tank.prototype.movedown = function () {
if (this.y> 높이 -30) {
this.changedirect ();
반품;
}
this.y += this.speed;
이것. direct = 2;
}
tank.prototype.moveleft = function () {
if (this.x <0) {
this.changedirect ();
반품;
}
this.x- = this.speed;
이것. direct = 3;
}
tank.prototype.moveright = function () {
if (this.x> 너비 -30) {
this.changedirect ();
반품;
}
this.x += this.speed;
이것. direct = 1;
}
// 방향을 변경합니다
tank.prototype.changedirect = function () {
while (true) {
var temp = math.round (math.random () * 3);
if (this.direct! = temp) {
this.direct = temp;
부서지다;
}
}
//alert("x="+ this.x+ "y ="+this.y+"direct ="+this.direct)
}
// 총알 샷
tank.prototype.shot = function () {
if (this.isdead) {
반품;
}
if (this.bulletslist.length <this.maxbulletsize) {
// 새로운 총알을 만듭니다
var bullet = null;
스위치 (this.direct) {
케이스 0 :
Bullet = New Bullet (this.x + 10, this.y -2, 0, this.color);
부서지다;
case 1:
Bullet = New Bullet (this.x + 32, this.y + 10, 1, this.color);
부서지다;
case 2:
Bullet = New Bullet (this.x + 10, this.y + 32, 2, this.color);
부서지다;
사례 3 :
Bullet = New Bullet (this.x -2, this.y + 10, 3, this.color);
부서지다;
}
// 잡지에 넣습니다
this.bulletslist.push (Bullet);
}
}
// ******************************************* ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************** *********************** **************************/
//플레이어
기능 영웅 (x, y, direct) {
this.lifetimes = 5;
this.isdead = false;
this.color = '#ff0000';
this.x = x;
this.y = y;
this.direct = direct;
this.bulletslist = [];
this.maxbulletsize = 10;
this.newlife = null;
}
hero.prototype = 새로운 탱크 (0, 0, 0);
hero.prototype.constructor = 영웅;
hero.prototype.addlife = function () {
this.lifetimes ++;
document.querySelector ( "#life"). innerHtml = hero.lifetimes;
}
hero.prototype.cutlife = function () {
if (this.lifetimes> = 1 &&! this.newlife) {
this.lifetimes-;
this.newlife = settimeout ( "hero.newlife ()", 2000);
}
}
hero.prototype.newLife = function () {
this.isdead = false;
클리어 타임 아웃 (Hero.newLife);
hero.newlife = null;
document.querySelector ( "#life"). innerHtml = hero.lifetimes;
}
// ******************************************* ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************************************************************************** 누군가 ***************************** *********************** **************************/
// 적 탱크
기능 적 (x, y, direct) {
this.isdead = false;
this.color = 'blue';
this.x = x;
this.y = y;
this.direct = direct;
this.bulletslist = [];
this.maxbulletsize = 1;
// 타이머, 자동 이동
this.timer1 = setInterval ((함수 (context) {
return function () {
//이동하다
Enemy.prototype.move.call (컨텍스트);
}
}) (this), 30);
// 타이머, 촬영
this.timer2 = setInterval ((함수 (context) {
return function () {
//촬영
tank.prototype.shot.call (컨텍스트);
}
}) (this), 2000);
// 타이머, 방향을 변경합니다
this.timer3 = setInterval ((함수 (context) {
return function () {
//촬영
tank.prototype.changedirect.call (컨텍스트);
}
}) (this), 3000);
}
Enemy.prototype = 새로운 탱크 (0, 0, 0);
Enemy.prototype.constructor = 적;
Enemy.prototype.move = function () {
스위치 (this.direct) {
케이스 0 :
this.moveup ();
부서지다;
case 1:
this.moveright ();
부서지다;
case 2:
this.movedown ();
부서지다;
사례 3 :
this.moveleft ();
부서지다;
}
}
Bullet.js
코드 사본은 다음과 같습니다.
/**
* 14-3-11에 Alane에 의해 만들어졌습니다.
*/
함수 총알 (X, Y, Direct, Color) {
this.isdead = false;
this.x = x;
this.y = y;
this.direct = direct;
이 .speed = 4;
this.color = 색상;
// 타이머, 혼자서 운동하십시오
this.timer = setInterval ((함수 (context) {
return function () {
Bullet.prototype.move.call (컨텍스트)
}
}) (this), 30);
}
Bullet.prototype.move = function () {
스위치 (this.direct) {
케이스 0 :
this.y- = this.speed;
부서지다;
case 1:
this.x += this.speed;
부서지다;
case 2:
this.y += this.speed;
부서지다;
사례 3 :
this.x- = this.speed;
부서지다;
}
// 경계 감지
if (this.y <0 || this.x> 너비 || this.y> 높이 || this.x <0) {
ClearInterval (this.Timer);
this.isdead = true;
}
// 충돌 감지는 적 탱크를 감지합니다
for (var i = 0; i <alltank.length; i ++) {
var temp = alltank [i];
if (temp.isdead) {
계속하다;
}
스위치 (temp.direct) {
케이스 0 :
사례 2 : if (this.x> temp.x && this.x <temp.x+20 && this.y> temp.y && this.y <temp.y+30) {
if (this.color == temp.color) {
부서지다;
}
폭탄 .push (새로운 폭탄 (temp.x-10, temp.y-10));
ClearInterval (this.Timer);
this.isdead = true;
temp.isdead = true;
}부서지다
case 1:
사례 3 : if (this.x> temp.x && this.x <temp.x+30 && this.y> temp.y && this.y <temp.y+20) {
if (this.color == temp.color) {
부서지다;
}
폭탄 .push (새로운 폭탄 (temp.x-10, temp.y-10));
ClearInterval (this.Timer);
this.isdead = true;
temp.isdead = true;
}부서지다;
}
}
}
소스 코드 다운로드