jQuery实现的五子棋游戏实例

本文实例讲述了jQuery实现的五子棋游戏。分享给大家供大家参考。具体如下:

这是一款非常不错的代码,就是人工智能方面差了一点

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>五子棋</title>
<style type="text/css">
div{margin:0;padding:0;}
div.board{width:561px; height:561px; border:1px solid #ccc; margin:0 auto;}
div.board div{ width:31px; height:31px; border:1px solid #ccc; float:left; cursor:pointer; background-repeat:no-repeat; }
div.board .person { background-image:url('images/1/files/demo/white.jpg')}
div.board .machine{ background-image:url('images/1/files/demo/black.jpg')}
div.board .person_star{background-image:url('images/1/files/demo/white_star.jpg')}
div.board .machine_star{background-image:url('images/1/files/demo/black_star.jpg')}
input.ipt{ display:block; margin:0 auto; margin-top:8px;width:70px}
</style>
</head>
<body>
<div class='board' id='board'>
</div>
<input type='button' value='开始游戏' onclick="initGame();
this.value='重新开始'" class='ipt'/>
<script type='text/javascript'>
var TRANSVERSE = 16;
var VERTICAL = 16;
var LEFT = 1;
var RIGHT = 2;
var TOP = 3;
var BOTTOM = 4;
var LEFT_TOP = 5;
var LEFT_BOTTOM = 6;
var RIGHT_TOP = 7;
var RIGHT_BOTTOM = 8;
var Chess = function()
{
 var owner = '';
 var victory = false;
 this.getOwner = function(){return owner;};
 this.setOwner = function(value){owner = value;};
 this.getVictory = function(){ return victory;}
 this.setVictory = function(value){ victory = value; }
}
var Board = function()
{
 var chessBoard = [];
 var isGameOver = false;
 this.getChess = function(point)
 {
  var x = point.x , y = point.y;
  return chessBoard[y][x];
 }
 this.setChess = function(chess , point)
 {
  var x = point.x , y = point.y;
  chessBoard[y][x] = chess;
 }
 this.setVictory = function(points)
 {
  for(var i = 0 ; i < points.length ; i ++)
  {
   for(var j = 0 ; j < points[i].length; j ++)
   {
    var chess = this.getChess(points[i][j]);
    chess.setVictory(true);
   }
  }
 }
 this.getAvaiablePoints = function()
 {
  var avaiable = new Array;
  for(var y = 0 ; y <= VERTICAL ; y ++)
  {
   for(var x = 0 ; x <= TRANSVERSE ; x ++)
   {
    if(chessBoard[y][x]) continue;
    var point = {x : x , y : y};
    avaiable.push(point);
   }
  }
  return avaiable;
 }
 this.getMap = function()
 {
  var map = {};
   for(var y = 0 ; y <= VERTICAL ; y ++)
   {
   for(var x = 0 ; x <= TRANSVERSE ; x++)
    {
    var chess = chessBoard[y][x];
     var value = '';
     if(chess)
     {
     value = chess.getOwner();
     if(chess.getVictory()) value += '_star';
     }
     else
     {
     value = '';
     }
     map[ x + ',' + y ] = value;
    }
   }
   return map;
 }
 this.gameOver = function()
 {
  return isGameOver = true;
 }
 this.isGameOver = function()
 {
  return isGameOver;
 }
 this.getNextPoint = function(point , direction)
 {
  var next = {x : point.x , y : point.y};
  switch(direction)
  {
   case LEFT :
    next.x -= 1;
    break;
   case RIGHT:
    next.x += 1;
    break;
   case TOP:
    next.y -= 1;
    break;
   case BOTTOM:
    next.y += 1;
    break;
   case LEFT_TOP:
    next.x-= 1 , next.y-= 1;
    break;
   case RIGHT_TOP:
    next.x += 1 , next.y -= 1;
    break;
   case LEFT_BOTTOM:
    next.x -= 1 , next.y += 1;
    break;
   case RIGHT_BOTTOM:
    next.x += 1 , next.y += 1;
    break;
   default :
    alert('方向错误');
  }
  return next;
 }
 var initialize = function()
 {
  for(var i = 0 ; i <= VERTICAL ; i++ ) chessBoard.push([]);
 }
 initialize();
}
var Compute = function(role)
{
 var directions = [LEFT , TOP , RIGHT , BOTTOM , LEFT_TOP , LEFT_BOTTOM , RIGHT_TOP , RIGHT_BOTTOM];
 var score = 0;
 var self = this;
 this._computeScore = function(direction)
 {
  throw new Error('未实现');
 }
 this._convertToPattern = function(chesslist)
 {
  return role.convertToPattern(chesslist)
 }
 this.compute = function(point)
 {
  score = 0;
  for(var i = 0, direction ; direction = directions[i++];)
  {
   score += this._computeScore(point , direction);
  }
 }
 this.getScore = function(refPoint)
 {
  return score ;
 }
}
var Five = function(role)
{
 Compute.call(this, role);
 var computeScore1 = function(refPoint , direction)
 {
  var predefined = 'IIII';
  var chesslist = role.find(refPoint , direction , 4);
  var pattern = role.convertToPattern(chesslist);
  if(predefined == pattern) return true;
  return false ;
 }
 var computeScore2 = function(refPoint , direction)
 {
  var prev = role.find(refPoint , direction , 2);
  var next = role.find(refPoint , role.reverseDirection(direction) , 2);
  var prevPattern = role.convertToPattern(prev);
  var nextPattern = role.convertToPattern(next);
  if(prevPattern == 'II' && nextPattern == 'II') return true;
  return false;
 }
 var computeScore3 = function(refPoint , direction)
 {
  var prev = role.find(refPoint , direction , 3);
  var next = role.find(refPoint , role.reverseDirection(direction) , 1);
  var prevPattern = role.convertToPattern(prev);
  var nextPattern = role.convertToPattern(next);
 if(prevPattern == 'III' && nextPattern == 'I') return true;
 return false;
 }
 this._computeScore = function(refPoint , direction)
 {
  if(computeScore1(refPoint , direction) || computeScore2(refPoint , direction) || computeScore3(refPoint , direction))
   return 100000;
  else return 0;
 }
}
var Four_Live = function(role)
{
 Compute.call(this, role);
 this._computeScore = function(refPoint , direction)
 {
  var score = 0;
  var prev = role.find(refPoint , direction , 4);
  var next = role.find(refPoint , role.reverseDirection(direction), 1);
  var prevPattern = this._convertToPattern(prev);
  var nextPattern = this._convertToPattern(next);
  if(prevPattern == 'III0' && nextPattern == '0') score = 10000;
 return score;
 }
}
var Four_Live1 = function(role)
{
 Compute.call(this, role);
 this._computeScore = function(refPoint , direction)
 {
  var prev = role.find(refPoint , direction , 3);
  var next = role.find(refPoint , role.reverseDirection(direction) , 2);
  var prevPattern = this._convertToPattern(prev);
  var nextPattern = this._convertToPattern(next);
  if(prevPattern == 'II0' && nextPattern == 'I0') return 10000;
  else return 0;
 }
}
var Tree_Live = function(role)
{
 Compute.call(this, role);
 this._computeScore = function(refPoint , direction)
 {
  var score = 0;
  var prev = role.find(refPoint , direction , 3);
  var next = role.find(refPoint , role.reverseDirection(direction), 2);
  var prevPattern = this._convertToPattern(prev);
  var nextPattern = this._convertToPattern(next);
  if(prevPattern == 'II0' && nextPattern == '00')
   score += 1000;
  return score;
 }
}
var Tree_Live1 = function(role)
{
 Compute.call(this, role);
 this._computeScore = function(refPoint , direction)
 {
  var prev = role.find(refPoint , direction , 2);
  var next = role.find(refPoint , role.reverseDirection(direction), 3);
  var prevPattern = this._convertToPattern(prev);
  var nextPattern = this._convertToPattern(next);
 if(prevPattern == 'I0' && nextPattern == 'I00')
  return 1000
 else return 0;
 }
}
var Two_Live = function(role)
{
 Compute.call(this, role);
 this._computeScore = function(refPoint , direction)
 {
  var prev = role.find(refPoint , direction , 3);
  var next = role.find(refPoint , role.reverseDirection(direction), 2);
  var prevPattern = this._convertToPattern(prev);
  var nextPattern = this._convertToPattern(next);
 if(prevPattern == 'I00' && nextPattern == '00') return 100;
 else return 0;
 }
}
var One_Live = function(role)
{
 Compute.call(this, role);
 this._computeScore = function(refPoint , direction)
 {
  var prev = role.find(refPoint , direction , 3);
  var next = role.find(refPoint , role.reverseDirection(direction), 3);
  var prevPattern = this._convertToPattern(prev);
  var nextPattern = this._convertToPattern(next);
 if(prevPattern == '000' && nextPattern == '000') return 10;
 else return 0;
 }
}
var Four_End = function(role)
{
 Compute.call(this, role);
 this._computeScore = function(refPoint , direction)
 {
  var prev = role.find(refPoint , direction , 3);
  var next = role.find(refPoint , role.reverseDirection(direction), 1);
  var prevPattern = this._convertToPattern(prev);
  var nextPattern = this._convertToPattern(next);
 if(prevPattern == 'III' && nextPattern == '0') return 150;
 else return 0;
 }
}
var Role = function(board)
{
 var computers = [];
 var self = this;
 var isVictory = false;
 this.isVictory = function()
 {
  return isVictory;
 }
 var getScore = function(point)
 {
  var score = 0;
  for(var i = 0 , computer; computer = computers[i++];)
  {
   computer.compute(point);
   score += computer.getScore();
  }
  var result = {score: score , point : point};
  return result;
 }
 var getScoreList = function()
 {
  var result = [];
  var avaiablePoints = board.getAvaiablePoints();
  for(var i = 0 , point; point = avaiablePoints[i++];)
  {
   result.push(getScore(point));
  }
  return result;
 }
 this.getCode = function()
 {
  throw new Error('未实现');
 }
 this.getPeak = function()
 {
  var scoreInfo = getScoreList();
  scoreInfo.sort(function(a,b){
   return b.score - a.score ;
  });
  return scoreInfo[0];
 }
 this.convertToPattern = function(chesslist)
 {
  var pattern = '';
  if(!chesslist) return '';
  for(var i = 0 ; i < chesslist.length ; i ++)
  {
   var chess = chesslist[i];
   if(chess == undefined) pattern += '0';
   else if(chess.getOwner() == this.getCode()) pattern += 'I';
   else pattern += 'Y';
  }
  return pattern ;
 }
 this.reverseDirection = function(direction)
 {
  switch(direction)
  {
   case LEFT : return RIGHT;
   case RIGHT : return LEFT;
   case TOP : return BOTTOM;
   case BOTTOM : return TOP;
   case LEFT_TOP : return RIGHT_BOTTOM;
   case RIGHT_BOTTOM : return LEFT_TOP;
   case RIGHT_TOP : return LEFT_BOTTOM;
   case LEFT_BOTTOM : return RIGHT_TOP;
   default : alert('方向错误');
  }
 }
 this._checkGameOver = function(point)
 {
  var leftRight = findVictory(point , LEFT);
  var topBottom = findVictory(point , TOP);
  var leftTopRightBottom = findVictory(point , LEFT_TOP);
  var rightTopLeftBottom = findVictory(point , RIGHT_TOP);
  var array = [leftRight , topBottom , leftTopRightBottom , rightTopLeftBottom];
  var victory = [];
  for(var i = 0 ; i < array.length ; i ++)
  {
   if(array[i].length >= 5) victory.push(array[i]);
  }
  if(victory.length > 0)
  {
   board.gameOver();
   board.setVictory(victory);
   isVictory = true;
  }
  if(board.getAvaiablePoints().length ==0) board.gameOver();
 }
 var isLicitPoint = function(point)
 {
  return point.x >= 0 && point.y >= 0 && point.x <= TRANSVERSE && point.y <= VERTICAL
   && board.getChess(point) && board.getChess(point).getOwner() == self.getCode()
 }
 var findVictory = function(refPoint , direction)
 {
  var reverse = self.reverseDirection(direction);
  var result = [];
  var nextPoint ;
  var currPoint = {x: refPoint.x , y: refPoint.y};
  while(true)
  {
   nextPoint = board.getNextPoint(currPoint, direction);
   if(!isLicitPoint(nextPoint)) break;
   currPoint = {x :nextPoint.x , y:nextPoint.y};
  }
  while(true)
  {
  result.push(currPoint);
   nextPoint = board.getNextPoint(currPoint , reverse);
   if(!isLicitPoint(nextPoint)) break;
   currPoint = { x: nextPoint.x , y: nextPoint.y };
  }
  return result;
 }
 this.find = function(point , direction , deep)
 {
  var refPoint = {x: point.x , y : point.y};
  var result = new Array;
   var index = 1;
   var nextPoint;
   while(index <= deep)
   {
   nextPoint = board.getNextPoint(refPoint, direction);
    if(nextPoint.x < 0 || nextPoint.y < 0 ||
    nextPoint.x > TRANSVERSE || nextPoint.y > VERTICAL) return null;
    var chess = board.getChess(nextPoint);
    if(chess) chess.point = {x:nextPoint.x , y:nextPoint.y};
    result.push(chess);
    refPoint = nextPoint;
    index ++;
   }
   return result;
 }
 var initialize = function()
 {
  computers.push(new Five(self));
  computers.push(new Four_Live(self));
  computers.push(new Tree_Live(self));
  computers.push(new Four_Live1(self));
  computers.push(new Tree_Live1(self));
  computers.push(new Two_Live(self));
  computers.push(new One_Live(self));
  computers.push(new Four_End(self));
 }
 initialize();
}
var Machine = function(board, rival)
{
 Role.call(this, board);
 this.setChess = function()
 {
  if(board.isGameOver()) return;
  var myPeak = this.getPeak();
  var rivalPeak = rival.getPeak();
  var peak ;
  if(myPeak.score >= rivalPeak.score) peak = myPeak;
  else peak = rivalPeak;
  var chess = new Chess();
  chess.setOwner(this.getCode());
  board.setChess(chess, peak.point);
  this._checkGameOver(peak.point);
 }
 this.getCode = function(){return 'machine';}
}
var Person = function(board , rival)
{
 Role.call(this, board);
 this.setChess = function(x,y)
 {
  if(board.isGameOver()) return;
  var point = new Object;
  point.x = x;
  point.y = y;
  var chess = new Chess()
  chess.setOwner(this.getCode());
  board.setChess(chess, point);
  this._checkGameOver(point);
 }
 this.getCode = function(){ return 'person'; }
}
var UIBase = function()
{
 var self = this;
 this._id = '$UI' + (++ UIBase.index);
 this._globalKey = "";
 this.getHTML = function()
 {
  return "";
 }
 var setGlobalKey = function()
 {
  var magic = '$UI_Items';
  self._globalKey = 'window.'+magic+'.'+self._id;
  window[magic] = window[magic] || {};
  window[magic][self._id] = self;
 }
 var formatHTML = function(html)
 {
  html = html.replace(/\$\$/g, self._globalKey);
  html = html.replace(/&&/g,self._id);
  return html;
 }
 var initUIBase = function()
 {
  setGlobalKey();
 }
 this.renderHTML = function()
 {
  return formatHTML(this.getHTML());
 }
 this.getDOM = function()
 {
 var dom = document.getElementById(this._id)
  return dom;
 }
 initUIBase();
}
UIBase.index = 0;
var ChessUI = function(board, placeholder)
{
 UIBase.call(this);
 this.setChess = function(){}
 this.getHTML = function()
 {
  var html = '';
  var map = board.getMap();
  for(var key in map)
  {
   var onclick = '';
   var className = map[key];
   if(className == '') onclick='$$._setChess('+ key +')';
  html += '<div onclick="'+ onclick +'" class="'+ className +'"></div>';
  }
  return html;
 }
 this.draw = function()
 {
  var html = this.renderHTML();
  document.getElementById(placeholder).innerHTML = html;
 }
 this._setChess = function(x,y)
 {
  this.setChess(x,y);
 }
 this.draw();
}
function getMSIEVersion()
{
 var regex = /MSIE([^;]+)/;
 var userAgent = navigator.userAgent;
 var result = regex.exec(userAgent);
 if(result) return parseInt(result[1]);
}
function initGame()
{
 var version = getMSIEVersion();
 if(version && version <= 8)
 {
  alert('请使用非IE浏览器(ie9、10除外)进行游戏(google chrome 、firefox等 )');
  return;
 }
 var board = new Board();
 var person = new Person(board);
 var machine = new Machine(board, person);
 var chessUI = new ChessUI(board, 'board');
 chessUI.setChess = function(x,y)
 {
  person.setChess(x,y);
  machine.setChess();
  chessUI.draw();
  if(board.isGameOver())
  {
   if(person.isVictory()) alert('您获得了胜利');
   else if(machine.isVictory()) alert('机器获得了胜利');
   else alert('游戏结束,胜负未分');
  }
 }
 if(Math.floor(Math.random() * 10) % 2)
 {
  alert('机器执棋');
  machine.setChess();
  chessUI.draw();
 }
 else
 {
  alert('您执棋');
 }
}
</script>
</body>
</html>

希望本文所述对大家的jQuery程序设计有所帮助。

(0)

相关推荐

  • jQuery+vue.js实现的九宫格拼图游戏完整实例【附源码下载】

    本文实例讲述了jQuery+vue.js实现的九宫格拼图游戏.分享给大家供大家参考,具体如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } /*#piclist { width: 600p

  • 使用vue.js编写蓝色拼图小游戏

    之前在网上看到<蓝色拼图>这款小游戏,作者是用jquery写的.于是便考虑能不能用vue.js优雅简单的编写出来呢? Later equals never!说干就干.首先理解游戏的规则:第一关为1*1的方块,第二关为2*2以此类推 该图为第三关3*3的方块.点击一个小方块,该方块和它相邻的方块的的颜色会从黄色变为蓝色,全部变为蓝色就过关了. 现在规则清楚了,开动吧! /*style*/ .game_bg{ background: #333; width: 600px; height: 600p

  • jQuery制作拼图小游戏

    源代码思路分析: [一]如何生成图片网格,我想到两种方法: (1)把这张大图切成16张小图,然后用img标签的src (2)只有一张大图,然后每个元素的背景图用css的background-position进行切割定位,这样就需要16个数组[0,0],[-150,0],[-300,0]..........(我采用这种) [二]图片背景定位数组与布局定位数组 在选择了使用CSS定位切图,就需要生成数据. 需要的css背景 定位数组为:[0,0],[-150,0],[-300,0],[-450,0]

  • jQuery编写网页版2048小游戏

    大致介绍 看了一个实现网页版2048小游戏的视频,觉得能做出自己以前喜欢玩的小游戏很有意思便自己动手试了试,真正的验证了这句话-不要以为你以为的就是你以为的,看视频时觉得看懂了,会写了,但是自己实现起来会遇到各种问题.比如,在最后判断游戏是否结束的时候,我写的语句语法是对的,但就是不执行.最后通过对视频源码的分析对比,发现原作者写的一个setTimeout定时器有额外的意思,本来我以为它就是简单的一个延时动画,其实他是在等待另外一个函数执行完毕.-_-||.最后还是很高兴能写出来,也改进了一些源

  • jQuery实现拼图小游戏(实例讲解)

    小熊维尼拼图 jQuery代码实现拼图小游戏,鼠标选中拼块,用上下左右键移动拼块. html代码 <div id="box-div"> <!--走不通时的提示!--> <div id="tips"> <p>\(╯-╰)/ 哎呦,走不通啦!</p> </div> <div id="container"> <div class="row"&g

  • jquery实现的美女拼图游戏实例

    本文实例讲述了jquery实现的美女拼图游戏.分享给大家供大家参考.具体如下: 这里可以自由打乱拼图次序,3*3,4*4等多种组合来进行格数拼图 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8&quo

  • JQuery开发的数独游戏代码

    用了很多Jquery的插件,支持鼠标滚轮选数字.没有什么高深的技术点.工作原因很长时间没有更新了,具体代码都有些记不清了,欢迎大家来拍砖.截图:演示地址:http://demo.jb51.net/js/jsukudo/index.html下载地址:jsukudo20081110v0.3.0.5.zip 下载列表:http://code.google.com/p/jsukudo/downloads/list 用到的JS文件 文件名 出处 说明 blockUI.js http://malsup.co

  • jQuery实现简易的天天爱消除小游戏

    今天分享一枚小demo:<天天爱消除游戏>,我想大家对这个游戏不陌生吧!?近期挺火的一款手游 妙味的讲师也很喜欢玩这款游戏 ,课余时间就写了个简易版天天的爱消除,除了PC端以外,试试在iPad.iPhone上玩吧~ 涉及知识点:JS.HTML5; 游戏截图: CSS: *{ margin:0; padding:0;} #ul1{ position:relative; margin:20px auto; background:#1b1f2b; overflow:hidden;} #ul1 li{

  • 基于Vue.js实现数字拼图游戏

    先来看看效果图: 功能分析 当然玩归玩,作为一名Vue爱好者,我们理应深入游戏内部,一探代码的实现.接下来我们就先来分析一下要完成这样的一个游戏,主要需要实现哪些功能.下面我就直接将此实例的功能点罗列在下了: 1.随机生成1~15的数字格子,每一个数字都必须出现且仅出现一次 2.点击一个数字方块后,如其上下左右有一处为空,则两者交换位置 3.格子每移动一步,我们都需要校验其是否闯关成功 4.点击重置游戏按钮后需对拼图进行重新排序 以上便是本实例的主要功能点,可见游戏功能并不复杂,我们只需一个个攻

  • 分享20款好玩的jQuery游戏

    今天本文收集了20佳基于jQuery开发的特色游戏,一起来欣赏吧! 1- Tetris with jQuery 2- Game Query- Game engine for jQuery 3- JQuery Snake Game Plugin 4- JQuery Tic Tac Toe 5- jQuery Powered Mine Sweeper 6- Browser Shooter 7- Angel Dreams 8- Sudoku 9- Basic Memory Game with jQue

  • jQuery制作可自定义大小的拼图游戏

    我把大小限制在了3-10之间,实在闲的,或者有自虐倾向的可以试试改下.. 本来准备弄图片上去的,还没弄.. pintu.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/199

  • 基于jquery的地址栏射击游戏代码

    演示地址:http://demo.jb51.net/js/2011/hunt/index.htm玩法向下看 请看地址栏上的字母 O! 你使用O来向 a射击. 使用键盘上的 左箭头 和 右箭头 移动字母O. 当O移动到 a 上时,按 空格键射击! 游戏会定时30秒时间,按ESC键重新开始. 注:请使用系统自带的IE浏览器来打开本链接. 你使用O来向 a射击. 使用键盘上的 左箭头 和 右箭头 移动字母O. 当O移动到 a 上时,按 空格键射击! // // 核心代码: 复制代码 代码如下: (fu

随机推荐