search
HomeWeb Front-endJS TutorialDetailed explanation of the source code of chess and dark chess in JS mini-game_javascript skills

The example in this article describes the chess dark chess source code of JS mini-game and is shared with everyone for your reference. The details are as follows:

After the game is running, it is as shown below:

Javascript part:

/** 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="Detailed explanation of the source code of chess and dark chess in JS mini-game_javascript skills" ></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="Detailed explanation of the source code of chess and dark chess in JS mini-game_javascript skills" >'; 
  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&#63; 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); 
}

Click here for the complete example codeDownload from this site.

I believe that what is described in this article has certain reference value for everyone’s learning of javascript game design.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python在软件源码保护中的应用实践Python在软件源码保护中的应用实践Jun 29, 2023 am 11:20 AM

Python语言作为一种高级编程语言,具有简单易学、易读易写等特点,在软件开发领域中得到了广泛的应用。然而,由于Python的开源特性,源代码很容易被他人轻易获取,这就给软件源码保护带来了一些挑战。因此,在实际应用中,我们常常需要采取一些方法来保护Python源代码,确保其安全性。在软件源码保护中,有多种针对Python的应用实践可供选择。下面将介绍几种常见

PHP代码在浏览器中如何显示源码而不被解释执行?PHP代码在浏览器中如何显示源码而不被解释执行?Mar 11, 2024 am 10:54 AM

PHP代码在浏览器中如何显示源码而不被解释执行?PHP是一种服务器端脚本语言,通常用于开发动态网页。当PHP文件在服务器上被请求时,服务器会解释执行其中的PHP代码,并将最终的HTML内容发送到浏览器以供显示。然而,有时我们希望在浏览器中直接展示PHP文件的源代码,而不是被执行。本文将介绍如何在浏览器中显示PHP代码的源码,而不被解释执行。在PHP中,可以使

网站在线看源码网站在线看源码Jan 10, 2024 pm 03:31 PM

可以使用浏览器的开发者工具来查看网站的源代码,在Google Chrome浏览器中:1、打开 Chrome 浏览器,访问要查看源代码的网站;2、右键单击网页上的任何位置,然后选择“检查”或按下快捷键 Ctrl + Shift + I打开开发者工具;3、在开发者工具的顶部菜单栏中,选择“Elements”选项卡;4、看到网站的 HTML 和 CSS 代码即可。

idea如何查看tomcat的源码idea如何查看tomcat的源码Jan 25, 2024 pm 02:01 PM

idea查看tomcat源码的步骤:1、下载Tomcat源代码;2、在IDEA中导入Tomcat源代码;3、查看Tomcat源代码;4、理解Tomcat的工作原理;5、注意事项;6、持续学习和更新;7、使用工具和插件;8、参与社区和贡献。详细介绍:1、下载Tomcat源代码,可以从Apache Tomcat的官方网站上下载源代码包,通常这些源代码包是以ZIP或TAR格式等等。

vue能显示源码吗vue能显示源码吗Jan 05, 2023 pm 03:17 PM

vue能显示源码,vue查看看源码的方法是:1、通过“git clone https://github.com/vuejs/vue.git”获取vue;2、通过“npm i”安装依赖;3、通过“npm i -g rollup”安装rollup;4、修改dev脚本;5、调试源码即可。

PHP源码错误:解决index报错问题PHP源码错误:解决index报错问题Mar 10, 2024 am 11:12 AM

PHP源码错误:解决index报错问题,需要具体代码示例随着互联网的快速发展,开发人员在编写网站和应用程序时经常会遇到各种各样的问题。其中,PHP作为一种流行的服务器端脚本语言,其源码错误是开发者们经常遇到的一个问题之一。有时候,当我们尝试打开一个网站的index页面时,会出现各种不同的错误信息,例如"InternalServerError"、"Unde

golang框架源码学习与应用全面指南golang框架源码学习与应用全面指南Jun 01, 2024 pm 10:31 PM

通过理解Golang框架源码,开发者可以掌握语言精髓和扩展框架功能。首先,获取源码并熟悉其目录结构。其次,阅读代码、跟踪执行流和理解依赖关系。实战案例展示了如何应用这些知识:创建自定义中间件并扩展路由系统。最佳实践包括分步学习、避免盲目复制粘贴、利用工具和参考在线资源。

golang框架源码解析与优化golang框架源码解析与优化Jun 02, 2024 pm 04:54 PM

本文探讨了Go框架的源码解析和优化。源码结构包括四个主要包,涉及核心框架逻辑、请求上下文、数据绑定和响应渲染。优化技巧包括:1.使用路由树优化路由处理,以显著提高路由查找速度。2.使用中间件进行缓存和压缩,以减少服务器负载和响应时间。3.避免在回调中执行耗时操作,以保持高响应性。4.启用日志记录和分析慢请求,以便识别性能瓶颈。5.定期更新框架版本,以利用最新的性能改进。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.