JavaScript Snake의 정식 버전은 완전히 주석 처리되었으며 객체 지향적입니다.
다음과 같이 코드 코드를 복사합니다.
<html>
<머리>
<title>스네이크 v2.4</title>
<스타일>
몸{
글꼴 크기:9pt;
}
테이블{
국경 붕괴: 붕괴;
테두리:단색 #333 1px;
}
td{
높이: 10px;
너비: 10px;
글꼴 크기: 0px;
}
.채우는{
배경색:파란색;
}
</style>
</head>
<스크립트>
함수 $(id){return document.getElementById(id);}
/**************************************************** ***** *************
* 자바스크립트 스네이크 v2.4 <br />
* v2.4에서는 뱀이 앞으로 나아갈 때 뱀 몸체 색상이 움직이도록 수정했습니다.
************************************************** *************/
//탐욕스러운 뱀
var 스네이크 = {
tbl: null,
/**
* 몸체: 뱀 몸체, 뱀의 각 부분이 배열로 배치되어 있으며,
* 데이터 구조 {x:x0, y:y0, color:color0},
* x, y는 좌표를 나타내고, color는 색상을 나타냅니다.
**/
몸: [],
//현재 이동 방향, 값 0, 1, 2, 3은 각각 위, 오른쪽, 아래, 왼쪽을 나타내며 키보드 방향 키를 눌러 변경합니다.
방향: 0,
// 타이머
타이머: null,
//속도
속도: 250,
//일시중지되었는지 여부
일시중지됨: 사실,
//행 개수
행 개수: 30,
//열 개수
열 개수: 30,
//초기화
초기화: 함수(){
var colors = ['빨간색','주황색','노란색','녹색','파란색','보라색','#ccc'];
this.tbl = $("메인");
var x = 0;
var y = 0;
var 컬러인덱스 = 0;
//초기 이동방향 생성
this.direction = Math.floor(Math.random()*4);
//테이블 구성
for(var row=0;row<this.rowCount;row++){
var tr=this.tbl.insertRow(-1);
for(var col=0;col<this.colCount;col++) {
var td=tr.insertCell(-1);
}
}
//20개의 느슨한 노드 생성
for(var i=0; i<10; i++){
x = Math.floor(Math.random()*this.colCount);
y = Math.floor(Math.random()*this.rowCount);
colorIndex = Math.floor(Math.random()*7);
if(!this.isCellFilled(x,y)){
this.tbl.rows[y].cells[x].style.BackgroundColor = 색상[colorIndex];
}
}
//뱀 머리 생성
동안(참){
x = Math.floor(Math.random()*this.colCount);
y = Math.floor(Math.random()*this.rowCount);
if(!this.isCellFilled(x,y)){
this.tbl.rows[y].cells[x].style.BackgroundColor = "검은색";
this.body.push({x:x,y:y,color:'black'});
부서지다;
}
}
this.paused = true;
//키보드 이벤트 추가
document.onkeydown=함수(e){
if (!e)e=window.event;
스위치(e.keyCode | e.which | e.charCode){
사례 13: {
if(Snake.paused){
Snake.move();
Snake.paused = 거짓;
}
또 다른{
//멈춤이 없다면 이동을 멈춘다
Snake.pause();
Snake.paused = true;
}
부서지다;
}
사례 37:{//왼쪽
//뱀이 뒤로 걷는 것을 멈추세요
if(Snake.direction==1){
부서지다;
}
Snake.direction = 3;
부서지다;
}
사례 38:{//위
//단축키는 여기서 작동합니다.
if(event.ctrlKey){
Snake.speedUp(-20);
부서지다;
}
if(Snake.direction==2){//뱀이 뒤로 걷는 것을 방지
부서지다;
}
Snake.direction = 0;
부서지다;
}
사례 39:{//오른쪽
if(Snake.direction==3){//뱀이 뒤로 걷는 것을 방지
부서지다;
}
Snake.direction = 1;
부서지다;
}
사례 40:{//아래
if(event.ctrlKey){
Snake.speedUp(20);
부서지다;
}
if(Snake.direction==0){//뱀이 뒤로 걷는 것을 방지
부서지다;
}
Snake.direction = 2;
부서지다;
}
}
}
},
//이동하다
이동: 함수(){
this.timer = setInterval(함수(){
Snake.erase();
Snake.moveOneStep();
Snake.paint();
}, this.speed);
},
//본체의 한 부분 이동
moveOneStep: 함수(){
if(this.checkNextStep()==-1){
ClearInterval(this.timer);
Alert("게임 끝!/n계속하려면 재시작을 누르세요.");
반품;
}
if(this.checkNextStep()==1){
var _point = this.getNextPos();
var _x = _point.x;
var _y = _point.y;
var _color = this.getColor(_x,_y);
this.body.unshift({x:_x,y:_y,color:_color});
//한 음식을 먹으면 또 다른 음식이 생성된다
this.generateDood();
반품;
}
//window.status = this.toString();
var point = this.getNextPos();
//첫 번째 섹션의 색상을 유지합니다.
var color = this.body[0].color;
//색상이 앞으로 이동
for(var i=0; i<this.body.length-1; i++){
this.body[i].color = this.body[i+1].color;
}
//뱀의 꼬리에서 한 섹션을 빼고 뱀의 꼬리에 한 섹션을 추가하여 뱀이 앞으로 이동하는 효과를 표시합니다.
this.body.pop();
this.body.unshift({x:point.x,y:point.y,color:color});
//window.status = this.toString();
},
//다음에 어디로 갈지 탐색
일시 중지: 함수(){
ClearInterval(Snake.timer);
this.paint();
},
getNextPos: 함수(){
var x = this.body[0].x;
var y = this.body[0].y;
var color = this.body[0].color;
//위로
if(this.direction==0){
와이--;
}
//오른쪽으로
else if(this.direction==1){
x++;
}
//아래에
else if(this.direction==2){
와++;
}
//왼쪽
또 다른{
엑스--;
}
//좌표를 반환
반환 {x:x,y:y};
},
//다음으로 이동할 단계가 무엇인지 확인
checkNextStep: 함수(){
var point = this.getNextPos();
var x = point.x;
var y = point.y;
if(x<0||x>=this.colCount||y<0||y>=this.rowCount){
return -1;//경계선을 터치하면 게임이 종료됩니다.
}
for(var i=0; i<this.body.length; i++){
if(this.body[i].x==x&&this.body[i].y==y){
return -1;//자신의 몸에 닿으면 게임이 종료됩니다.
}
}
if(this.isCellFilled(x,y)){
return 1;//뭔가가 있습니다
}
return 0;//열린 공간
},
//뱀 몸통 지우기
지우기: 함수(){
for(var i=0; i<this.body.length; i++){
this.eraseDot(this.body[i].x, this.body[i].y);
}
},
//뱀 몸통 그리기
페인트: 함수(){
for(var i=0; i<this.body.length; i++){
this.paintDot(this.body[i].x, this.body[i].y,this.body[i].color);
}
},
//섹션 지우기
eraDot: 함수(x,y){
this.tbl.rows[y].cells[x].style.BackgroundColor = "";
},
페인트점: 함수(x,y,color){
this.tbl.rows[y].cells[x].style.BackgroundColor = 색상;
},
//좌표에서 색상을 가져옵니다.
getColor: 함수(x,y){
this.tbl.rows[y].cells[x].style.BackgroundColor를 반환합니다.
},
//디버깅을 위해
toString: 함수(){
var str = "";
for(var i=0; i<this.body.length; i++){
str += "x:" + this.body[i].x + " y:" + this.body[i].y + " color:" + this.body[i].color + " - ";
}
str을 반환;
},
//좌표점이 채워졌는지 확인
isCellFilled: 함수(x,y){
if(this.tbl.rows[y].cells[x].style.BackgroundColor == ""){
거짓을 반환;
}
사실을 반환;
},
//재시작
다시 시작: 함수(){
if(this.timer){
ClearInterval(this.timer);
}
for(var i=0; i<this.rowCount;i++){
this.tbl.deleteRow(0);
}
this.body = [];
this.init();
this.speed = 250;
},
//가속
speedUp: 함수(시간){
if(!this.paused){
if(this.speed+time<10||this.speed+time>2000){
반품;
}
this.speed +=시간;
this.pause();
this.move();
}
},
//음식을 생산합니다.
generateDood: 함수(){
var colors = ['빨간색','주황색','노란색','녹색','파란색','보라색','#ccc'];
var x = Math.floor(Math.random()*this.colCount);
var y = Math.floor(Math.random()*this.rowCount);
var colorIndex = Math.floor(Math.random()*7);
if(!this.isCellFilled(x,y)){
this.tbl.rows[y].cells[x].style.BackgroundColor = 색상[colorIndex];
}
}
};
</script>
<body onload="Snake.init();">
/**************************************************** ***** ************<br />
* 자바스크립트 스네이크 v2.4<br />
************************************************** * ************/<br />
<table id="main" cellpacing="0" cellpadding="0"></table>
<input type="button" id="btn" value="Start/Pause" />게임을 시작/일시 중지하려면 왼쪽 버튼을 클릭하거나 Enter를 누르세요<br />
<input type="button" id="reset" value="다시 시작" /><br />
<input type="button" id="upSpeed" value="Accelerate" />가속하려면 왼쪽 버튼을 클릭하거나 Ctrl + ↑를 누르세요<br />
<input type="button" id="downSpeed" value="Slow down" />왼쪽 버튼을 클릭하거나 Ctrl + ↓를 눌러 속도를 늦추세요
<스크립트>
$('btn').onclick = 함수(){
if(Snake.paused){
Snake.move();
Snake.paused = 거짓;
}
또 다른{
Snake.pause();
Snake.paused = true;
}
};
$("reset").onclick = 함수(){
Snake.restart();
this.blur();
};
$("upSpeed").onclick = 함수(){
Snake.speedUp(-20);
};
$("downSpeed").onclick = 함수(){
Snake.speedUp(20);
};
</script>
</body>
</html>