이 글의 예시는 JS 미니 게임의 체스 다크 체스 소스 코드를 설명하고 참고용으로 모든 사람에게 공유됩니다. 세부 내용은 다음과 같습니다.
게임이 실행되면 아래와 같습니다.
자바스크립트 부분:
/** chinese chess * Author: fdipzone * Date: 2012-06-24 * Ver: 1.0 */ var gameimg = ['images/a1.gif','images/a2.gif','images/a3.gif','images/a4.gif','images/a5.gif','images/a6.gif','images/a7.gif','images/b1.gif','images/b2.gif','images/b3.gif','images/b4.gif','images/b5.gif','images/b6.gif','images/b7.gif','images/bg.gif','images/bg_over.gif','images/bg_sel.gif']; var chess_obj = new ChessClass(); window.onload = function(){ $('init_btn').onclick = function(){ chess_obj.init(); } var callback = function(){ chess_obj.init(); } img_preload(gameimg, callback); } // chess class function ChessClass(){ this.chess = []; this.boardrows = 4; this.boardcols = 8; this.area = 82; this.player = 1; // 1:red 2:green this.selected = null; // selected chess this.chesstype = ['', 'a', 'b']; this.isover = 0; } // init ChessClass.prototype.init = function(){ this.reset_grade(); this.create_board(); this.create_chess(); this.create_event(); this.player = 1; this.selected = null; this.isover = 0; disp('init_div','hide'); } // create board ChessClass.prototype.create_board = function(){ var board = ''; for(var i=0; i<this.boardrows; i++){ for(var j=0; j<this.boardcols; j++){ board = board + '<div id="' + i + '_' + j + '"><img src="/static/imghwm/default1.png" data-src="images/chessbg.gif" class="lazy" / alt="JS mini-game_javascript 스킬의 체스와 다크체스의 소스코드에 대한 자세한 설명" ></div>'; } } $('board').innerHTML = board; $('board').style.width = this.boardcols * (this.area + 2) + 'px'; $('board').style.height = this.boardrows * (this.area + 2) + 'px'; } // create random chess ChessClass.prototype.create_chess = function(){ // 32 chesses var chesses = ['a1','b7','a2','b7','a2','b7','a3','b7','a3','b7','a4','b6','a4','b6','a5','b5', 'a5','b5','a6','b4','a6','b4','a7','b3','a7','b3','a7','b2','a7','b2','a7','b1']; this.chess = []; while(chesses.length>0){ var rnd = Math.floor(Math.random()*chesses.length); var tmpchess = chesses.splice(rnd, 1).toString(); this.chess.push({'chess':tmpchess, 'type':tmpchess.substr(0,1), 'val':tmpchess.substr(1,1), 'status':0}); } } // create event ChessClass.prototype.create_event = function(){ var self = this; var chess_area = $_tag('div', 'board'); for(var i=0; i<chess_area.length; i++){ chess_area[i].onmouseover = function(){ // mouseover if(this.className!='onsel'){ this.className = 'on'; } } chess_area[i].onmouseout = function(){ // mouseout if(this.className!='onsel'){ this.className = ''; } } chess_area[i].onclick = function(){ // onclick self.action(this); } } } // id change index ChessClass.prototype.getindex = function(id){ var tid = id.split('_'); return parseInt(tid[0])*this.boardcols + parseInt(tid[1]); } // index change id ChessClass.prototype.getid = function(index){ return parseInt(index/this.boardcols) + '_' + parseInt(index%this.boardcols); } // action ChessClass.prototype.action = function(o){ if(this.isover==1){ // game over return false; } var index = this.getindex(o.id); if(this.selected == null){ // 未选过棋子 if(this.chess[index]['status'] == 0){ // not opened this.show(index); }else if(this.chess[index]['status'] == 1){ // opened if(this.chess[index]['type'] == this.chesstype[this.player]){ this.select(index); } } }else{ // 已选过棋子 if(index != this.selected['index']){ // 與selected不是同一位置 if(this.chess[index]['status'] == 0){ // 未打开的棋子 this.show(index); }else if(this.chess[index]['status'] == -1){ // 點空白位置 this.move(index); }else{ // 點其他棋子 if(this.chess[index]['type']==this.chesstype[this.player]){ this.select(index); }else{ this.kill(index); } } } } } // show chess ChessClass.prototype.show = function(index){ $(this.getid(index)).innerHTML = '<img src="images/' + this.chess[index]['chess'] + '.gif" / alt="JS mini-game_javascript 스킬의 체스와 다크체스의 소스코드에 대한 자세한 설명" >'; this.chess[index]['status'] = 1; // opened if(this.selected!=null){ // 清空選中 $(this.getid(this.selected.index)).className = ''; this.selected = null; } this.change_player(); this.gameover(); } // select chess ChessClass.prototype.select = function(index){ if(this.selected!=null){ $(this.getid(this.selected['index'])).className = ''; } this.selected = {'index':index, 'chess':this.chess[index]}; $(this.getid(index)).className = 'onsel'; } // move chess ChessClass.prototype.move = function(index){ if(this.beside(index)){ this.chess[index] = {'chess':this.selected['chess']['chess'], 'type':this.selected['chess']['type'], 'val':this.selected['chess']['val'], 'status':this.selected['chess']['status']}; this.remove(this.selected['index']); this.show(index); } } // kill chess ChessClass.prototype.kill = function(index){ if(this.beside(index)==true && this.can_kill(index)==true){ this.chess[index] = {'chess':this.selected['chess']['chess'], 'type':this.selected['chess']['type'], 'val':this.selected['chess']['val'], 'status':this.selected['chess']['status']}; this.remove(this.selected['index']); var killed = this.player==1? 2 : 1; $('grade_num' + killed).innerHTML = parseInt($('grade_num' + killed).innerHTML)-1; this.show(index); } } // remove chess ChessClass.prototype.remove = function(index){ this.chess[index]['status'] = -1; // empty $(this.getid(index)).innerHTML = ''; $(this.getid(index)).className = ''; } /* check is beside * @param index 目標棋子index * @param selindex 执行的棋子index,可为空, 为空则读取选中的棋子 */ ChessClass.prototype.beside = function(index,selindex){ if(typeof(selindex)=='undefined'){ if(this.selected!=null){ selindex = this.selected['index']; }else{ return false; } } if(typeof(this.chess[index])=='undefined'){ return false; } var from_info = this.getid(selindex).split('_'); var to_info = this.getid(index).split('_'); var fw = parseInt(from_info[0]); var fc = parseInt(from_info[1]); var tw = parseInt(to_info[0]); var tc = parseInt(to_info[1]); if(fw==tw && Math.abs(fc-tc)==1 || fc==tc && Math.abs(fw-tw)==1){ // row or colunm is same and interval=1 return true; }else{ return false; } } /* check can kill * @param index 被消灭的棋子index * @param selindex 执行消灭的棋子index,可为空, 为空则读取选中的棋子 */ ChessClass.prototype.can_kill = function(index,selindex){ if(typeof(selindex)=='undefined'){ // 没有指定执行消灭的棋子 if(this.selected!=null){ // 有选中的棋子 selindex = this.selected['index']; }else{ return false; } } if(this.chess[index]['type']!=this.chesstype[this.player]){ if(parseInt(this.chess[selindex]['val'])==7 && parseInt(this.chess[index]['val'])==1){ // 7 can kill 1 return true; }else if(parseInt(this.chess[selindex]['val'])==1 && parseInt(this.chess[index]['val'])==7){ // 1 can't kill 7 return false; }else if(parseInt(this.chess[selindex]['val']) <= parseInt(this.chess[index]['val'])){ // small kill big return true; } } return false; } // change player ChessClass.prototype.change_player = function(){ if(this.player == 1){ this.player = 2; // to green $('grade_img2').className = 'img_on'; $('grade_img1').className = 'img'; }else{ this.player = 1; // to red $('grade_img1').className = 'img_on'; $('grade_img2').className = 'img'; } } // reset grade ChessClass.prototype.reset_grade = function(){ $('grade_img1').className = 'img_on'; $('grade_img2').className = 'img'; $('grade_num1').innerHTML = $('grade_num2').innerHTML = 16; $('grade_res1').className = $('grade_res2').className = 'none'; $('grade_res1').innerHTML = $('grade_res2').innerHTML = ''; } // game over ChessClass.prototype.gameover = function(){ if($('grade_num1').innerHTML==0 || $('grade_num2').innerHTML==0){ // 任一方棋子为0 this.isover = 1; this.show_grade(); disp('init_div','show'); }else{ if(this.can_action()==false){ this.isover = 1; this.show_grade(); disp('init_div','show'); } } } // show grade ChessClass.prototype.show_grade = function(){ var num1 = parseInt($('grade_num1').innerHTML); var num2 = parseInt($('grade_num2').innerHTML); if(num1>num2){ // 红方胜 $('grade_res2').innerHTML = 'LOSS'; $('grade_res2').className = 'loss'; $('grade_res1').innerHTML = 'WIN'; $('grade_res1').className = 'win'; }else if(num1<num2){ // 黑方胜 $('grade_res1').innerHTML = 'LOSS'; $('grade_res1').className = 'loss'; $('grade_res2').innerHTML = 'WIN'; $('grade_res2').className = 'win'; }else{ // 平局 $('grade_res1').innerHTML = $('grade_res2').innerHTML = 'DRAW'; $('grade_res1').className = $('grade_res2').className = 'draw'; } } // check chess can action ChessClass.prototype.can_action = function(){ var chess = this.chess; for(var i=0,max=chess.length; i<max; i++){ if(chess[i].status==0){ // 有未翻开的棋子 return true; }else{ if(chess[i].status==1 && chess[i].type==this.chesstype[this.player]){ // 己方已翻开的棋子 if(this.beside(i-this.boardcols, i) && (chess[i-this.boardcols].status==-1 || this.can_kill(i-this.boardcols,i) )){ // 上 return true; } if(this.beside(i+this.boardcols, i) && (chess[i+this.boardcols].status==-1 || this.can_kill(i+this.boardcols,i) )){ // 下 return true; } if(this.beside(i-1, i) && (chess[i-1].status==-1 || this.can_kill(i-1,i) )){ // 左 return true; } if(this.beside(i+1, i) && (chess[i+1].status==-1 || this.can_kill(i+1,i) )){ // 右 return true; } } } } return false; } /** common function */ // get document.getElementBy(id) function $(id){ this.id = id; return document.getElementById(id); } // get document.getElementsByTagName function $_tag(name, id){ if(typeof(id)!='undefined'){ return $(id).getElementsByTagName(name); }else{ return document.getElementsByTagName(name); } } /* div show and hide * @param id dom id * @param handle show or hide */ function disp(id, handle){ if(handle=='show'){ $(id).style.display = 'block'; }else{ $(id).style.display = 'none'; } } /* img preload * @param img 要加载的图片数组 * @param callback 图片加载成功后回调方法 */ function img_preload(img, callback){ var onload_img = 0; var tmp_img = []; for(var i=0,imgnum=img.length; i<imgnum; i++){ tmp_img[i] = new Image(); tmp_img[i].src = img[i]; if(tmp_img[i].complete){ onload_img ++; }else{ tmp_img[i].onload = function(){ onload_img ++; } } } var et = setInterval( function(){ if(onload_img==img.length){ // 定时器,判断图片完全加载后调用callback clearInterval(et); callback(); } },200); }
전체 예제 코드를 보려면 여기를 클릭하세요이 사이트에서 다운로드하세요.
저는 이 글에 설명된 내용이 모든 사람의 자바스크립트 게임 디자인 학습에 일정한 참고 가치가 있다고 믿습니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

실제 세계에서 JavaScript의 응용 프로그램에는 서버 측 프로그래밍, 모바일 애플리케이션 개발 및 사물 인터넷 제어가 포함됩니다. 1. 서버 측 프로그래밍은 Node.js를 통해 실현되며 동시 요청 처리에 적합합니다. 2. 모바일 애플리케이션 개발은 재교육을 통해 수행되며 크로스 플랫폼 배포를 지원합니다. 3. Johnny-Five 라이브러리를 통한 IoT 장치 제어에 사용되며 하드웨어 상호 작용에 적합합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)
