>  기사  >  웹 프론트엔드  >  HTML5가 아닌 것을 사용하여 js 보드 Lianliankan 게임 샘플 code_javascript 기술 구현

HTML5가 아닌 것을 사용하여 js 보드 Lianliankan 게임 샘플 code_javascript 기술 구현

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

아래 그림과 같이 js 버전의 Lianliankan 게임을 구현하는 방법을 알려드리겠습니다.

먼저 index.html 파일의 html 레이아웃을 살펴보세요.

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





Lianliankan



< ;div id="gamePanel" tabindex="0">

>

javascript" src="js/piece.js">

< /body>



css 폴더의 index.css 파일은 다음과 같습니다.



코드 복사

코드는 다음과 같습니다.

테두리 : 1px 더블 #999999; 테두리 너비 : 5px
폭 : 800px ;
높이: 505px ;
위치: 상대;

#gamePanel {

폭: 602px ;
높이: 502px ;
배경: url(../img/ground.gif) 반복
위치: 절대

#pieces 🎜>
여백: 35px;
테두리: 1px #999999;
폭: 546px;
높이: 434px;

} 🎜>
#pieces .piece {

너비: 32px;
높이: 36px;
위치: 상대;
float: 왼쪽; >
}

#pieces .track {

너비: 32px;
높이: 36px;
위치: 상대
float: 왼쪽;
}
#pieces .track2 {

너비: 32px;
높이: 36px;
위치: 상대
float: 왼쪽; : 빨간색;

}

여백: 60px;
테두리: 1px #999999; 왼쪽: 607px; >너비: 187px;
높이: 73px;
배경: url(../img/logo.gif);
위치: 절대

# ScorePanel {

테두리: 1px 솔리드 #999999;
왼쪽: 607px;
위쪽: 200px;
높이: 30px;

}

#score {

테두리: 1px #999999;
왼쪽: 607px;
너비: 187px;
높이: 30px;
위치: 절대;

#timePanel {

테두리: 1px 솔리드
왼쪽: 607px;
상단: 300px;
너비: 187px;
높이: 30px;
위치: 절대

#time {

테두리: 1px 솔리드 #999999; 왼쪽: 607px;
너비: 187px;
위치: 절대값; 🎜>
#버튼 {

테두리 : 1px #999999;
왼쪽 : 607px
너비 : 187px; 🎜>위치 : 절대;


}


js 부분은 게임이라는 세 개의 소스 파일로 나누어져 있습니다. js, map.js, Piece 각 .js 소스 파일은 클래스에 해당합니다. 이 게임은 지도 및 그림 조각 개체를 조작하기 위해 게임 클래스를 사용합니다.

game.js 코드는 다음과 같습니다.




코드 복사


코드는 다음과 같습니다.

// 게임 제어 클래스
var Game = {

// 게임 배경
gamePanel: null,

// 점수
점수: 0 ,

// 시간
time: 0,

// 그림 매핑 테이블
pieceMap: null,

// 그림 목록
pieceList: [],

//사진 목록에 사진이 없습니다
pieceImgList: [],

// 사진 난수 목록
randomList: [],

// 트랙 목록
trackList: [],

// 게임 시작 여부
isGameBigin: false,

// 게임 종료 여부
isGameOver : false,

// 게임 재설정 여부
isGameReset: false,

// 그림 요소를 처음 클릭했는지 여부
isFirstClick: true,

// 게임 시작
start : function() {

document.getElementById("start").disabled = true
document.getElementById("reset").disabled = false;

if (this.isGameReset) {

this.isGameOver = false
this.startTime()

} else if (this.isGameBegin) {

return;

} else {

this.init();


}

},

reset : function() {

document.getElementById("start").disabled =
document.getElementById( "reset").disabled = true;

this.clear();
this.initImgPieces(); >document.getElementById("time").innerHTML = 0;

this.score = 0;
document.getElementById("score").innerHTML = 0; isGameReset = true;
this.isGameBegin = true;

// 초기화
init : function() {

if (this.isGameBegin ) {

return;

}

this.pieceMap = new Map()

var _this

this; .time = 0;
this.startTime();

this.gamePanel = document.getElementById("pieces")

this.initPieces(); initImgPieces();

this.isGameBegin = true;

},

// 캔버스에 무작위로 생성된 150개의 그림 추가
initPieces: function() {

var _this = this;

this.initRandomList();

//무작위 목록 정렬 중단
this.messRandomList(); for (var i = 0; i < 204; i ) {

var Piece = new Piece(this)
this.pieceList.push(piece); = (i );
var y = Math.floor(i/17);

this.pieceMap.put(x "," y, 조각); (x, y);
this.gamePanel.appendChild(piece.dom);

if (x == 0 || x == 16 || y == 0 || y == 11 ) {

piece.track = document.createElement("div");
piece.track.className = "track"
piece.dom.appendChild(piece.track); >piece.isTracked = true;

계속;

} else {

if (x == 1 || x == 15 || y == 1 || y == 10) {

piece.setAtEdge(true);

}

this.pieceImgList.push(piece)

}

}

},

//사진 초기화
initImgPieces: function() {

for (var i = 0; i < this. PieceImgList.length; i ) {

this.pieceImgList[i].initImg();
this.pieceImgList[i].img.src = "img/pieces/" this.randomList[i] ".gif"
this.pieceImgList[i].setImgSrc(this.pieceImgList[i].img.src)

// 이미지 클릭 이벤트
this.pieceImgList[i]를 실행합니다. onClick();

}

},

// 랜덤 테이블 초기화
initRandomList: function() {

// 쌍으로 나타나는 난수 시퀀스
for (var i = 0; i < 75; i ) {

var random =parseInt(Math.random()*22*10000, 10); 🎜>var 숫자 = 무작위#;
this.randomList.push(숫자);
this.randomList.push(숫자)

},

// 무작위 테이블 중단
messRandomList : function() {

for (var i = 0; i < this.randomList.length; i ) {

var random = parsInt(Math.random()* 15*10000, 10);
var 숫자 = 무작위 0;

temp = this.randomList[i]; this.randomList[i] = this.randomList[번호];
this.randomList[번호] = temp;

},

// 시작 timing
startTime : function() {

var _this = this;

if (this.isGameOver) {

return; {

this.time ;
document.getElementById("time").innerHTML = this.time;
this.isGameBegin =
setTimeout() {_this.startTime ();}, 1000);

}

},

// Clear
clear : function() {

for (var i = 0; i < this.pieceList.length; i ) {

this.gamePanel.removeChild(this.pieceList[i].dom)

this.pieceList = [];
this.randomList = [];
this.pieceImgList = [];

this.isGameOver =
false; 🎜>
}

}

window.onload = function() {

document.getElementById("start").disabled =
document; .getElementById("reset").disabled = true;

}

// 게임 시작 항목
function Start() {

Game.start();

}

//게임 재설정 항목
function Reset() {

Game.reset()

}


맞춤형 js 버전 매핑 구조 map.js 소스 파일은 다음과 같습니다.
코드 복사 코드는 다음과 같습니다.

var Map = function(){

this.data = []

}

Map.prototype = {

put : function(key, value) {

this.data[key] = value
},

get : function(key) {

return this. data[key];

remove: function(key) {

this.data[key] =

},

isEmpty : function() {

return this.data.length == 0
},

size : function() {

return this.data.length;
}

}

그림 클래스 조각.js 소스 파일은 다음과 같습니다.

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

var Piece = function(game) {

// 게임 객체
this.game = game

// 엣지 요소인지
this.isEdge = false;

// edge 요소 옆인지 여부
this.atEdge = false

// 이미지 dom 요소
this.dom = null ;

// 이미지 요소
this.img = null;

// 이미지 요소 소스
this.src = null;
this.track = null;

// 트랙으로 사용 가능 여부
this.isTracked = false;

// 표시 요소를 선택하세요
. selected = null;

// 사진이 가로로 정렬됨
this.x = 0

// 사진이 세로로 정렬됨
this.y = 0; 🎜>// 사진 깜박임 ID
this .flashId = null;

// 이미지 클릭 여부
this.onClicked = false; 🎜>this.flashCount = 0;

this.init();

}

Piece.prototype = {

// 초기화
init: function() {

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

this.selected = document. createElement("img");

} ,

//이미지 초기화
initImg: function() {

this.img = document.createElement("img ");

this.dom.appendChild (this.img);

},

// 알고리즘 만족 후 트랙 요소 초기화
initTrack: 함수 () {

if (this.flashId != null) {

// 깜박임 중지
this.stopFlash()

}

//alert("initTrack middle");
if ( this.track != null) {

return;
}

this.onClicked

this.dom.removeChild(this.img);

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

},

// 비트 이미지 설정 소스
setImgSrc : function(src) {

this.src = src;

},

//그림의 2차원 배치 위치 설정
setPosition : function(x, y) {

this.x = x;
this.y = y;

} ,

//이미지에 대해 선택한 요소 설정
setSelected: function() {

if (this.flashCount % 2 == 0) {

//this .dom.removeChild(this.img)
//this.selected.src = "img/selected.gif";
//this.dom.appendChild(this.selected);
this.img.src = "img/pieces/flash.gif"

} else {

//if (this.selected != null) {

// this .dom.removeChild(this.selected)

//}

this.img. src = this.src;
//this.dom.appendChild(this.img) ;

}

},

// 가장자리 요소
setEdge: function(isEdge) {

this.isEdge = isEdge ;

},

// 가장자리 요소 옆에 있는지 설정
setAtEdge: function(atEdge) {

this.atEdge = atEdge;

},

// 플래싱 시작
flash : function() {

var _this = this;
this.flashId = setInterval(function() {_this.setSelected( );}, 500)

},

// 중지 flashing
stopFlash: function() {

clearInterval(this.flashId)

if (this.flashCount % 2 == 1) {

//if (this.selected != null) {

// this.dom.removeChild(this.selected )

//}

this.img.src = this .src;
//this.dom.appendChild(this.img);

}

},

// 선택한 객체의 내부 기능
onClick: function() {

if (this.onClicked) {

return

}

var _this

this.img.onclick = function() {

if (!document.getElementById(" start").disabled) {

return; 🎜>
if (_this.onClicked) {

return;

}

if (_this.checkPiece()) {

return;

}

_this.flash();
_this.onClicked = true ;

},

// 클릭한 사진이 있는지 확인
checkPiece: function() {

for (var i = 0; i < this.game.pieceList.length; i ) {

if (this.game.pieceList[i].onClicked && !this.game.pieceList[i].equal(this )) {

if (this.game.pieceList[i].equalImage(this )) {

//alert("동일한 이미지");
this.searchTrack( this.game.pieceList[i])

} else {

this.game.pieceList[i].stopFlash();
this.game.pieceList[i].onClicked = false
this.onClicked = false; 🎜>
}

true를 반환합니다.

} else {

계속;

}

return false;

},

// 동일한 객체인지 여부
equal : function(piece) {

return (this.x == 조각.x && this.y == 조각.y);

},

// 같은 그림인지 여부
equalImage : function(piece) {

return this.src == Piece.src;

},

// 검색 경로
searchTrack: function(piece) {

if (this. isNear(조각)) {

this.linkTrack(조각);

return;
}

if (this.isReach(조각) || this.isReach2 (조각)) {

this.linkTrack(piece);

return;
}

},

// 인접 여부
isNear : 함수(조각) {

var a = (Math.abs(piece.x - this.x) == 1) && (piece.y == this.y)
|| (Math.abs(piece.y - this.y) == 1) && (piece.x == this.x)

return a;,

// 直线
isStraightReach : function(piece) {
//alert("isStraightReach");
if (this.isNear(piece)) {

true를 반환합니다.

}

var a = false;
var b = false;

// 沿y轴方向搜索
if (this.x == Piece.x) {
//alert("!!!!!!!!!!!!");
for (var i = this.min(this.y, Piece.y) 1; i < this.max(this.y, Piece.y); i ) {
//alert("this .x == 조각.x: " 조각.x "," i);
if (this.game.pieceMap.get(piece.x "," i).isPass()) {

a = true;

this.game.trackList.push(this.game.pieceMap.get(piece.x "," i));

계속;
} else {

a = false;
this.game.trackList = [];

반환;
}

}

}

// 沿x轴方向搜索
if (this.y == Piece.y) {
/ /알리다("!!!!!!!!!!!");
for (var i = this.min(this.x, Piece.x) 1; i < this.max(this.x, Piece.x); i ) {
//alert("this .y == 조각.y: "i"," 조각.y);
if (this.game.pieceMap.get(i "," Piece.y).isPass()) {

b = true;
this.game.trackList.push(this.game.pieceMap.get(i "," Piece.y));

계속;
} else {

b = false
this.game.trackList = [];

b를 돌려주세요;
}

}

}

||를 반환합니다. 비;
},


// 拐一次弯搜索
isReach1 : function(piece) {
//alert("isReach1");
var Corner_1 = this.game.pieceMap.get(this.x "," Piece.y);
var Corner_2 = this.game.pieceMap.get(piece.x "," this.y);

var _this = this;


if ((_this.isStraightReach(corner_1))
&& (corner_1.isStraightReach(piece))
&& Corner_1.isPass()) {

// Alert("corner_1: "this.x","piece.y);
this.game.trackList.push(corner_1);

참을 반환합니다.
}

if ((_this.isStraightReach(corner_2))
&& (corner_2.isStraightReach(piece))
&& Corner_2.isPass()) {
//alert( "corner_2: " 조각.x "," this.y);
this.game.trackList.push(corner_2);

참을 반환합니다.
}

false를 반환합니다.
},

// 直接或拐一次弯搜索
isReach : function(piece) {

var a = this.isStraightReach(piece);

var b = this.isReach1(piece);

||를 반환합니다. 비;
},

// 拐两次弯搜索
isReach2 : function(piece) {

// 沿x轴正向搜索
for (var i = this.x 1; i < 17; i ) {

if (!this.game.pieceMap.get(i "," this.y).isPass()) {

this.game.trackList = [];

휴식;

} else if (this.game.pieceMap.get(i "," this.y).isReach(piece)
&& this.game.pieceMap.get(i "," this.y ).isPass()) {

this.game.trackList.push(this.game.pieceMap.get(i "," this.y));

참을 반환합니다.
}

}

// 沿x轴搜索
for (var i = this.x - 1; i >= 0; i --) {

if (!this.game.pieceMap.get(i "," this.y).isPass()) {

this.game.trackList = [];

휴식;

} else if (this.game.pieceMap.get(i "," this.y).isReach(piece)
&& this.game.pieceMap.get(i "," this.y ).isPass()) {

this.game.trackList.push(this.game.pieceMap.get(i "," this.y));

참을 반환합니다.
}

}

// 沿y轴搜索
for (var i = this.y - 1; i >= 0; i --) {

if (!this.game.pieceMap.get(this.x "," i).isPass()) {

this.game.trackList = [];

휴식;

} else if (this.game.pieceMap.get(this.x "," i).isReach(piece)
&& this.game.pieceMap.get(this.x "," i ).isPass()) {

this.game.trackList.push(this.game.pieceMap.get(this.x "," i));

참을 반환합니다.
}

}

// 沿y轴正向搜索
for (var i = this.y 1; i < 12; i ) {

if (!this.game.pieceMap.get(this.x "," i).isPass()) {

this.game.trackList = [];

휴식;
} else if (this.game.pieceMap.get(this.x "," i).isReach(piece)
&& this.game.pieceMap.get(this.x "," i).isPass ()) {

this.game.trackList.push(this.game.pieceMap.get(this.x "," i));

참을 반환합니다.
}

}

false를 반환합니다.
},

// 路径连接
linkTrack : function(piece) {

this.initTrack();
piece.initTrack();
this.changeScore();
this.showTrack(조각);

},

// 显示足迹
showTrack : function(piece) {

this.game.trackList.push(piece);
this.track.className = "트랙2";

for (var i = 0; i < this.game.trackList.length; i ) {
//alert(i);
this.game.trackList[i].track.className = "트랙2";

}

var _this = this;
setTimeout(function() {_this.hideTrack()}, 500);

},

// 隐匿足迹
hideTrack : function() {

for (var i = 0; i < this.game.trackList.length ; i ) {

this.game.trackList[i].track.className = "트랙";

}

this.game.trackList = [];
this.track.className = "트랙";
this.isTracked = true;

},

//점수 증가
changeScore: function() {

this.game.score = 100;
document.getElementById("score").innerHTML = this. game.score

},

min : function(a, b) {

if (a < b) {

return a;

} else {

return b;

}

},

max : 함수(a, b) {

if (a > b) {

return a;

} else {

return b; 🎜>},

//
isPass: function() {

return this.track != null
}

}

위는 소스 파일의 코드입니다. 구체적인 구현 코드는 CSDN의 zhangjinpeng66 다운로드에 주의하세요. Lianliankan 게임의 핵심 부분인 js에서 구현된 검색 경로에 대해 이야기해 보겠습니다.

js에서 검색 경로 알고리즘을 구현하는 첫 번째이자 간단한 방법은 두 그림이 함수 코드에 직선으로 도달할 수 있는지 판단하는 것입니다.



코드 복사
코드는 다음과 같습니다. // 직선isStraightReach: function(piece) { //alert(" isStraightReach");
if (this.isNear(piece)) {

return true;

}

var a = false;
var b = false;

//y축 방향 검색
if (this.x == Piece.x) {
//alert("!!!!!!!!!!!! !!");
for (var i = this.min (this.y, Piece.y) 1; i < this.max(this.y, Piece.y); i ) {
/ /alert("this.x == 조각.x: " 조각.x "," i)
if (this.game.pieceMap.get(piece.x "," i).isPass()) {

a = true;

this.game.trackList.push(this.game.pieceMap.get(piece.x "," i))

계속;
} else {

a = false;
this.game.trackList = [];

return a; >
}

// x축 방향 검색
if (this.y == Piece.y) {
//alert("!!!!!!! !!!!!");
for (var i = this.min (this.x, Piece.x) 1; i < this.max(this.x, Piece.x); i ) {
//alert("this.y == 조각.y: " i " ," 조각.y)
if (this.game.pieceMap.get(i "," 조각.y).isPass( )) {

b = true;
this.game .trackList.push(this.game.pieceMap.get(i "," Piece.y))

계속;
} else {

b = false
this .game.trackList = [];

return b;
}

return a || b;
},


이 함수는 Lianliankan의 가장 간단한 단계를 구현하여 두 사진이 연결 조건을 충족하는지 확인합니다. 우회 검색을 수행합니다.




코드 복사


코드는 다음과 같습니다.


// 구석구석 검색
isReach1: 함수(조각) {
//alert("isReach1");
var Corner_1 = this.game.pieceMap.get(this.x "," Piece.y)
var Corner_2 = this.game .pieceMap.get(piece.x "," this.y); var _this = this; if ((_this.isStraightReach(corner_1)) && (corner_1.isStraightReach(조각))
&& Corner_1.isPass()) {

//alert("corner_1: " this.x "," 조각.y); this.game .trackList.push(corner_1);

return true;
}

if ((_this.isStraightReach(corner_2))
&& (corner_2.isStraightReach(piece ))
&& Corner_2.isPass()) {
//alert("corner_2: " Piece.x "," this.y)
this.game.trackList.push(corner_2)

return true;
}

return false;
},


검색 기능에서도 직접 검색 기능이 호출됩니다. 가장 복잡합니다. 2회전 검색은 1회전 검색 기능도 호출합니다.




코드 복사


코드는 다음과 같습니다.

// 拐两次弯搜索
isReach2 : function(piece) {

// 沿x轴正向搜索
for (var i = this.x 1; i < 17; i ) {

if (!this.game.pieceMap.get(i "," this.y).isPass()) {

this.game.trackList = [];

휴식;

} else if (this.game.pieceMap.get(i "," this.y).isReach(piece)
&& this.game.pieceMap.get(i "," this.y ).isPass()) {

this.game.trackList.push(this.game.pieceMap.get(i "," this.y));

참을 반환합니다.
}

}

// 沿x轴搜索
for (var i = this.x - 1; i >= 0; i --) {

if (!this.game.pieceMap.get(i "," this.y).isPass()) {

this.game.trackList = [];

휴식;

} else if (this.game.pieceMap.get(i "," this.y).isReach(piece)
&& this.game.pieceMap.get(i "," this.y ).isPass()) {

this.game.trackList.push(this.game.pieceMap.get(i "," this.y));

참을 반환합니다.
}

}

// 沿y轴搜索
for (var i = this.y - 1; i >= 0; i --) {

if (!this.game.pieceMap.get(this.x "," i).isPass()) {

this.game.trackList = [];

휴식;

} else if (this.game.pieceMap.get(this.x "," i).isReach(piece)
&& this.game.pieceMap.get(this.x "," i ).isPass()) {

this.game.trackList.push(this.game.pieceMap.get(this.x "," i));

참을 반환합니다.
}

}

// 沿y轴正向搜索
for (var i = this.y 1; i < 12; i ) {

if (!this.game.pieceMap.get(this.x "," i).isPass()) {

this.game.trackList = [];

휴식;
} else if (this.game.pieceMap.get(this.x "," i).isReach(piece)
&& this.game.pieceMap.get(this.x "," i).isPass ()) {

this.game.trackList.push(this.game.pieceMap.get(this.x "," i));

참을 반환합니다.
}

}

false를 반환합니다.
},

该函数以点击的图文为中心分别沿x轴,y轴展开搜索。
以上是本游戏代码的内容。具体游戏源码请到CSDN中zhangjinpeng66의 资源里下载.
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.