开始后的html游戏界面

 >  기사  >  웹 프론트엔드  >  js 버전의 핀볼 게임 샘플 code_javascript 기술의 비html5 구현

js 버전의 핀볼 게임 샘플 code_javascript 기술의 비html5 구현

WBOY
WBOY원래의
2016-05-16 17:21:551257검색

시작 전 html 페이지
js 버전의 핀볼 게임 샘플 code_javascript 기술의 비html5 구현
시작 후 html 게임 인터페이스
js 버전의 핀볼 게임 샘플 code_javascript 기술의 비html5 구현
html 페이지 레이아웃, 즉 index.html 파일의 소스코드는 다음과 같습니다. 🎜>

코드 복사 코드는 다음과 같습니다.



< Meta http-equiv="Content-Type" content ="text/html; charset=utf-8"/>
핀볼 게임





점수:
0 >




< ;script type="text/javascript" src="js/ball.js">





index.css 파일의 소스코드는 다음과 같습니다.



코드를 복사하세요

코드는 다음과 같습니다: #gamePanel{ width:504px; 🎜>위치:상대적;
}

#gamePanel .score{

font-size:20px;
color:White
위치:절대;
왼쪽:0;
상단:0;
z- 색인: 9999

#gamePanel .bullet{

너비:5px ;
높이:15px;
위치:절대;
배경:url(../img/bullet.png)
오버플로:숨김; 🎜>#gamePanel .stick{

너비:80px;
높이:18px;
위치:절대
배경:파랑

#gamePanel .ball{

너비:15px;
위치:절대
배경:url(../img/ball.gif);
}

#gamePanel .brick {

너비: 28px;
높이: 28px;
배경: url(../img /brick.gif);
float: 왼쪽;

#gamePanel .hideBrick {

높이: 28px; >위치: 상대;
배경: 검정;

}

#gamePanel .magic {

너비: 27px; 높이: 11px;
위치: 절대;
배경: 녹색;

#gamePanel .shortMagic {

너비: 28px; : 12px;
위치: 절대;
배경: 노란색;

#gamePanel .bingo{

너비: 18px; 18px;
위치:절대;
배경:url(../img/bingo2.png)

}

#startBtn{

경계 너비:20px; 테두리 스타일: 단색
테두리 색상: 검정 검정 검정 녹색
왼쪽: 240px;
위쪽: 240px; :pointer;
width:0px;
height:0px;
overflow:hidden;

}


JavaScript 부분은 5개의 소스 파일로 나누어집니다. 즉, ball.js(공 유형), brick.js(벽돌 유형), game.js(Game 클래스), Magic.js(Magic Wand 클래스), Stick.js(Baffle 클래스)

공 코드




코드 복사


코드는 다음과 같습니다.

// Ball
var Ball = function() {

// 핀볼 DOM 요소
this.dom = null

// 활성화 여부
this.isFirst = true;

//핀볼 이동 방향
this.direction = null

this.init();
Ball.prototype = {

// 핀볼의 가로 이동 속도
movepx: 3,

// 핀볼의 세로 이동 속도
movepy: 2 ,

// 핀볼 이동 빈도
movesp : 20,

// 핀볼 이동 빈도 맵
movespMap : {

1 : 75,
2 : 65 ,
3 : 50,
4 : 40

},

// 초기화
init : function() {

this.dom = document.createElement("div");
this.dom.className = "ball";

},

// 핀볼의 초기 위치, x 및 y 좌표를 설정합니다.
setPosition: function(x, y) {

this.dom.style.left = x "px";
this.dom.style.top = y "px"

},

// 핀볼 애니메이션은 움직임을 의미합니다.
animation: function(gameWidth, gameHeight, Stick) {

var _this = this;

// 실제 측면 이동 속도, 왼쪽 또는 오른쪽
var _movepx = this.dom.offsetLeft > gameWidth/2 ?
var _movepy = this.dom.offsetTop > gameHeight/2 ? this.movepy : -1*this.movepy;

// 프로세스 이동 함수
var process = function () {

// 핀볼의 x, y 좌표
var left = _this.dom.offsetLeft;
var top = _this.dom.offsetTop

// 방향을 바꿀지 여부
if (왼쪽 <= 0 || 왼쪽 >= gameWidth - _this.dom.clientWidth) {

_movepx *= -1;

}

var isCrashStick = _this.OnCheckCrashStick();
var isCrashBall = _this.OnCheckCrashBrick();

// 방향을 위쪽으로 변경할지 결정
if (top < 0 || isCrashStick || isCrashBall) {

_movepy *= -1;

}

// 아래로 이동
top = top
left = left _movepx;

//핀볼 위치 설정
_this.dom.style.top = 위쪽 "px"
_this.dom.style.left = 왼쪽 "px"

if (top > gameHeight) {

_this.onend();
alert("You Lose")

} else {

setTimeout( process, _this .movesp);

}

// 핀볼의 이동 방향 결정
if (_movepx > 0 && _movepy < 0) {

_this . 방향 = "RightUp";

return;

}

if (_movepx > 0 && _movepy > 0) {

_this.direction = "RightDown";

return;

}

if (_movepx < 0 && _movepy < 0) {

_this.direction = " ";

return;

}

if (_movepx < 0 && _movepy > 0) {

_this.direction = "LeftDown" ;

return;

}

// 이동 ​​시작

},

// 외부 인터페이스, 마술 지팡이에 부딪혔는지 감지
OnCheckCrashStick: function() {},

// 외부 인터페이스, 벽돌에 부딪혔는지 감지
OnCheckCrashBrick: function () {},

// 핀볼 종료 이벤트
onend : function() {},

// 게임 종료
gameover : function() {}

}


브릭 코드는 다음과 같습니다. brick.js 소스 파일:



코드 복사

코드는 다음과 같습니다. // Brick 클래스 var Brick = function(gamePanel) { // Brick의 dom 요소
this.dom = null ;

//브릭이 위치한 캔버스
this.gamePanel = gamePanel;

// 활성화 여부
this.isLive = true; // 마술봉 보유 여부
this.magic = null;

this.width = 28;
this.height = 28; 🎜>this.top = 0;

this.init();

}

Brick.prototype = {

// 초기화
init : function() {

this.dom = document.createElement("div");
this.dom.className = "brick"

},

// 위치: 상대 브릭 초기화 위치
setPosition: function(x, y) {

this.left = x
this.top = y; },

//위치에 대한 Brick 크기 초기화: 상대
setSize: function(width, height) {

this.width =
this.height = height;

},

//마법봉 초기화
initMagic: function() {

var _this = this
// 임의의 숫자
varrandom=parseInt(Math.random()*1000 1, 10);

var type = 무작위 % 5 == 0 ? "좋음" : 무작위 % 4 == 0 ? "none";

//새 마술 지팡이 개체 만들기
var Magic = new Magic(type)

this.magic =

magic; initPosition(this); // 벽돌에 마술 지팡이 추가
this.gamePanel.appendChild(magic.dom)

magic.onEnd = function() {

_this .gamePanel.removeChild(magic.dom);

magic.animation(this.gamePanel.clientHeight),

/ / 적중 후 작업
onEnd : function() {

this.isLive = false
this.dom.className = "hideBrick"
this.initMagic( );

}

}


마법봉 클래스 코드, 즉 Magic.js 소스 파일은 다음과 같이 구현됩니다.
코드 복사 코드는 다음과 같습니다.

//Magic wand class
var Magic = function(type) {

// Magic의 dom 요소
this.dom = null;

// 매직 DOM 정보
this.left = 0;
this.width = 0; 🎜>
this.type = 유형 ;

this.init();

}

Magic.prototype = {

// 매직 지팡이 유형
magicType : {

"good" : "magic",
"bad" : "shortMagic",
"none" : ""

},

// 매번 이동 변위
movepy: 3,

// 이동 ​​속도
movespeed: 20,

// 초기화 마술 지팡이
init: function() {

this.dom = document.createElement("div");

this.dom.className = this.magicType[this.type]
/ /this.dom.style.display = " 없음";

this.width =parseInt(this.dom.style.width, 10)
this.height =parseInt(this.dom.style .height, 10);

},

//마법봉 초기화 위치
initPosition: function(brick) {

this.left = brick.left;
this.top = brick.top ;

this.dom.style.left = this.left "px";
this.dom.style.top = this.top "px";

},

//위치 업데이트
update : function() {

this.dom.style.left = this.left "px"
this.dom.style.top = this .top "px";

},

// 마술 지팡이 애니메이션, 높이는 게임 배경의 높이
애니메이션: 기능 (높이) {

if (this .type == "none") {

return

}

var _this

// 함수를 아래로 이동
var downMove = function() {

_this.top = _this.top _this.movepy;
_this.update(); >// 마술 지팡이가 경계를 넘어 아래로 움직이는지 여부, Hit Stick
if (_this.top < height && !_this.isBeatStick()) {

setTimeout(downMove, _this.movespeed );

} else {

//애니메이션 종료 트리거 이벤트
_this.onEnd()

};
downMove();

} ,

//애니메이션 종료 트리거 이벤트, 외부 커버리지
onEnd : function() {},

// 여부 마술봉이 배플에 부딪힌 후 이벤트를 처리하는데, external Override
isBeatStick: function() {}

}


베젤 클래스 코드가 스틱입니다.




코드 복사

코드는 다음과 같습니다.

// 새로운 스틱 클래스 생성
var Stick = function() {

// 항공기에 해당하는 DOM 요소
this.dom = null

/ / 공이 움직이는지
this.isMove = false;

// 이동 ​​ID
this.moveId = null

//
this.isSend = false;

// 마크를 더 크게 만듭니다
this.bigCount = 0;

// 마크를 더 작게 만듭니다
= 0;

// 막대의 너비가 커지거나 작아짐에 따라 저장
this.width = 0

this.init(); }

Stick.prototype = {

// 게임 배경 Dom
gamePanel: null,

// 게임 배경 너비
gameWidth: 0,

// 게임 배경 높이
gameHeight: 0,

// 마술 지팡이 이동 속도
movepx: 10,

// 마술 지팡이 이동 주파수
movep: 30,

/ / 방향 키 값은
keyCodeAndDirection: {

37 : "left",
39 : "right"

}에 해당합니다. ,

// 초기화
init : function() {

this.dom = document.createElement("div")
this.dom.className = "stick" ;

},

//위치 설정
setPosition: function(gamePanel, width, height) {

// 게임 배경에 마술 지팡이 추가
this.gamePanel = gamePanel;
this .gamePanel.appendChild(this.dom);

// 항공기의 초기 위치 설정
this.dom.style.left = ( width - this.dom.clientWidth)/2 "px";
this.dom.style.top = height - this.dom.clientHeight "px"

// 너비와 높이를 가져옵니다. 게임 배경
this.gameWidth = width;
this .gameHeight = height;

},

// 키보드 누름 이벤트
keydown: function(e) {

var keyCode = e.keyCode;

if (!this.isMove) {

this.move(keyCode)

}

},

// 키보드 해제 이벤트
keyup: function(e) {

// 키보드 해제 여부를 확인
if (this.keyCodeAndDirection[e .keyCode]) {

// 이동 ​​중지
this.stopMove()

} else if (e.keyCode == 32) {

// 촬영하지 않음으로 설정
this.isSend = false;

}

},

// Move
move: function(keyCode) {

// 이동으로 설정
this.isMove = true;
var _this = this;

// 이동 ​​방향 결정
switch(this.keyCodeAndDirection[keyCode]) {

case "left" : {

this.moveId = setInterval(function() {_this.moveLeft();}, _this.movesp)
break;
}

case "right" : {

this.moveId = setInterval(function() {_this.moveRight();}, _this.movesp)
break;

}

default : break;

}

},

// 왼쪽으로 이동
moveLeft: function() {

var left = this.dom[ "offsetLeft"];
left = left - this.movepx >= 0 ? left - this.movepx : 0; ["왼쪽"] = 왼쪽 "px";

if (왼쪽 == 0) {

this.stopMove()

},

// 오른쪽으로 이동
moveRight : function() {

var left = this.dom["offsetLeft"]
var maxDistance = this.gameWidth - this .dom.clientWidth;
왼쪽 = 왼쪽 this.movepx <= maxDistance;
this.dom.style["left"] = 왼쪽 "px"; >if (왼쪽 == maxDistance) {

this.stopMove();

}

},

// 작게 만들기
changeSmall : function() {

if ( this.smallCount >= 1) {

return

} else {

this.dom.style .width = 80 "px";
this.smallCount

this.bigCount >= 1 ? this.bigCount

}

this.dom.style.left = parsInt( this.dom.style.left, 10) 20 "px";
this.dom.style.width = 40 "px"

},

// 더 커짐
changeBig : function() {

if (this.bigCount >= 1) {

return; 🎜>} else {

this.dom.style.width = 80 "px";
this.bigCount ;

this.smallCount >= 1 ? : this.smallCount 0

}

if (parseInt(this.dom.style.left, 10) <= 75 ) {

this.dom.style .width = parsInt(this.dom.style.width, 10) 75 parsInt(this.dom.style.left, 10) "px";
this.dom.style.left = 0 "px"; >
return;

} else if (this.dom.style.width 150 parsInt(this.dom.style.left, 10) >= this.gamePanel.clientWidth) {

this.dom.style.left = parsInt(this .dom.style.left, 10) - 150 "px";
this.dom.style.width = this.dom.style.width 150 "px" ;

return;

} else {

this.dom.style.left =parseInt(this.dom.style.left, 10) - 75 "px";
this.dom.style.width = 150 " px";

}

},

// 이동 ​​중지
stopMove: function() {

this.isMove = false;
clearInterval(this.moveId);

},

// 핀볼 실행, 외부 인터페이스,
onSendBall: 함수 () {},


//점수 변경 외부 인터페이스
onChangeScore: function() {}

}


몇 가지 어려운 기술의 구현

키보드의 왼쪽 및 오른쪽 화살표 키를 통해 베젤을 이동하는 코드 구현:
코드 복사 코드는 다음과 같습니다.

// 키보드 누름 이벤트
keydown : function(e) {

var keyCode = e.keyCode;

if ( !this.isMove) {

this.move(keyCode)

}

},

// 키보드 해제 이벤트
keyup: function(e) {

// 키보드 해제 여부 확인
if (this.keyCodeAndDirection[e.keyCode]) {

// 이동 중지
this.stopMove( ;

},

// 이동 ​​
move : function(keyCode) {

// 이동으로 설정
this.isMove = true;
var _this = this;

// 이동 ​​방향 결정
switch(this.keyCodeAndDirection[keyCode]) {

case "left" : {

this.moveId = setInterval(function() {_this.moveLeft();}, _this.movesp)
break

case "right" : {

this.moveId = setInterval(function() {_this.moveRight();}, _this.movesp)
break;

}

default : break;

}

},

// 왼쪽으로 이동
moveLeft: function() {

var left = this .dom["offsetLeft"];
왼쪽 = 왼쪽 - this.movepx >= 0 ? 왼쪽 - this.movepx :
this.dom.style["left"] = 왼쪽 "px";

if (왼쪽 == 0) {

this.stopMove();

}

},

// 이동 right
moveRight : function( ) {

var left = this.dom["offsetLeft"]
var maxDistance = this.gameWidth - this.dom.clientWidth
left = left this.movepx <= maxDistance ? 왼쪽 this.movepx: maxDistance;
this.dom.style["left"] = 왼쪽 "px"

if (왼쪽 == maxDistance) {

this.stopMove( );

}

},

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.