JS小游戏之象棋暗棋源码详解


Posted in Javascript onSeptember 25, 2014

本文实例讲述了JS小游戏的象棋暗棋源码,分享给大家供大家参考。具体如下:

游戏运行后如下图所示:

JS小游戏之象棋暗棋源码详解

Javascript 部分:

/** 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="images/chessbg.gif" /></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" />'; 
  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   目?似遄?ndex 
* @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游戏设计的学习有一定的借鉴价值。

Javascript 相关文章推荐
图片完美缩放
Sep 07 Javascript
TypeScript 学习笔记之基本类型
Jun 19 Javascript
javascript实现在网页中运行本地程序的方法
Feb 03 Javascript
javascript插件开发的一些感想和心得
Feb 28 Javascript
通过node-mysql搭建Windows+Node.js+MySQL环境的教程
Mar 01 Javascript
jQuery Validate验证表单时多个name相同的元素只验证第一个的解决方法
Dec 24 Javascript
jquery validation验证表单插件
Jan 07 Javascript
使用BootStrap实现标签切换原理解析
Mar 14 Javascript
VUE中使用Vue-resource完成交互
Jul 21 Javascript
基于Vue单文件组件详解
Sep 15 Javascript
浅谈vue的iview列表table render函数设置DOM属性值的方法
Sep 30 Javascript
Vue.js实现表格渲染的方法
Sep 07 Javascript
我用的一些Node.js开发工具、开发包、框架等总结
Sep 25 #Javascript
jquery中使用循环下拉菜单示例代码
Sep 24 #Javascript
用C/C++来实现 Node.js 的模块(二)
Sep 24 #Javascript
用C/C++来实现 Node.js 的模块(一)
Sep 24 #Javascript
JS实现一个列表中包含上移下移删除等功能
Sep 24 #Javascript
一个JavaScript函数把URL参数解析成Json对象
Sep 24 #Javascript
js监听鼠标点击和键盘点击事件并自动跳转页面
Sep 24 #Javascript
You might like
json的键名为数字时的调用方式(示例代码)
2013/11/15 PHP
PHP zip扩展Linux下安装过程分享
2014/05/05 PHP
点弹代码 点击页面任何位置都可以弹出页面效果代码
2012/09/17 Javascript
js修改原型的属性使用介绍
2014/01/26 Javascript
用Jquery.load载入页面后样式没了页面混乱的解决方法
2014/10/20 Javascript
JS排序方法(sort,bubble,select,insert)代码汇总
2016/01/30 Javascript
js事件冒泡、事件捕获和阻止默认事件详解
2016/08/04 Javascript
Javascript中字符串replace方法的第二个参数探究
2016/12/05 Javascript
AngularJS实现使用路由切换视图的方法
2017/01/24 Javascript
JS对象深度克隆实例分析
2017/03/16 Javascript
浅谈在Vue-cli里基于axios封装复用请求
2017/11/06 Javascript
JavaScript基础心法 数据类型
2018/03/05 Javascript
深入理解Vue Computed计算属性原理
2018/05/29 Javascript
dts文件中删除一个node或属性的操作方法
2018/08/05 Javascript
js异步上传多张图片插件的使用方法
2018/10/22 Javascript
浅谈JS的原型和继承
2019/05/08 Javascript
jquery实现动态改变css样式的方法分析
2019/05/27 jQuery
JS Array.from()将伪数组转换成数组的方法示例
2020/03/23 Javascript
vue中watch的用法汇总
2020/12/28 Vue.js
使用python的chardet库获得文件编码并修改编码
2014/01/22 Python
zbar解码二维码和条形码示例
2014/02/07 Python
python中使用urllib2伪造HTTP报头的2个方法
2014/07/07 Python
将Python代码打包为jar软件的简单方法
2015/08/04 Python
python中的错误处理
2016/04/10 Python
python实战教程之自动扫雷
2018/07/13 Python
Python选择网卡发包及接收数据包
2019/04/04 Python
在linux下实现 python 监控usb设备信号
2019/07/03 Python
对Django 中request.get和request.post的区别详解
2019/08/12 Python
解决python中0x80072ee2错误的方法
2020/07/19 Python
python 使用xlsxwriter循环向excel中插入数据和图片的操作
2021/01/01 Python
秘书行业自我鉴定范文
2013/12/30 职场文书
护理个人求职信范文
2014/01/08 职场文书
公安领导班子四风问题个人整改措施思想汇报
2014/10/09 职场文书
小学生安全教育主题班会
2015/08/12 职场文书
创业分两种人:那么哪些适合创业?,哪些适合不适合创业呢?
2019/08/23 职场文书
python使用matplotlib绘制图片时x轴的刻度处理
2021/08/30 Python