[JavaScript] jQuery编写的五子棋代码 →→→→→进入此内容的聊天室

来自 , 2019-04-19, 写在 JavaScript, 查看 101 次.
URL http://www.code666.cn/view/89db09d8
  1.            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.   <title>五子棋</title>
  5.   <style type="text/css">
  6.   div{margin:0;padding:0;}
  7.   div.board{width:561px; height:561px; border:1px solid #ccc; margin:0 auto;}
  8.   div.board div{ width:31px; height:31px; border:1px solid #ccc; float:left; cursor:pointer; background-repeat:no-repeat; }
  9.   div.board .person { background-image:url('http://www.chhblog.com/upload/1/files/demo/white.jpg')}
  10.   div.board .machine{ background-image:url('http://www.chhblog.com/upload/1/files/demo/black.jpg')}
  11.   div.board .person_star{background-image:url('http://www.chhblog.com/upload/1/files/demo/white_star.jpg')}
  12.   div.board .machine_star{background-image:url('http://www.chhblog.com/upload/1/files/demo/black_star.jpg')}
  13.   input.ipt{ display:block; margin:0 auto; margin-top:8px;width:70px}
  14.   </style>
  15. </head>
  16. <body>
  17. <div class='board' id='board'>
  18. </div>
  19. <input type='button' value='开始游戏' onclick="initGame(); this.value='重新开始'" class='ipt'/>
  20.  
  21.  
  22. <script type='text/javascript'>
  23.  
  24.  
  25. var TRANSVERSE = 16;
  26. var VERTICAL = 16;
  27.  
  28. var LEFT = 1;
  29. var RIGHT = 2;
  30. var TOP = 3;
  31. var BOTTOM = 4;
  32. var LEFT_TOP = 5;
  33. var LEFT_BOTTOM = 6;
  34. var RIGHT_TOP = 7;
  35. var RIGHT_BOTTOM = 8;
  36.  
  37. var Chess = function()
  38. {
  39.     var owner = '';
  40.         var victory = false;
  41.        
  42.         this.getOwner = function(){return owner;};
  43.         this.setOwner = function(value){owner = value;};
  44.     this.getVictory = function(){ return victory;}
  45.     this.setVictory = function(value){ victory = value; }      
  46. }
  47.  
  48. var Board = function()
  49. {
  50.     var chessBoard = [];
  51.        
  52.         var isGameOver = false;
  53.                
  54.         this.getChess = function(point)
  55.         {
  56.             var x = point.x , y = point.y;
  57.                 return chessBoard[y][x];
  58.         }
  59.        
  60.         this.setChess = function(chess , point)
  61.         {
  62.             var x = point.x , y = point.y;
  63.                 chessBoard[y][x] = chess;
  64.         }
  65.        
  66.         this.setVictory = function(points)
  67.         {
  68.             for(var i = 0 ; i < points.length ; i ++)
  69.                 {
  70.                     for(var j = 0 ; j < points[i].length; j ++)
  71.                         {
  72.                             var chess = this.getChess(points[i][j]);
  73.                                 chess.setVictory(true);
  74.                         }
  75.                 }
  76.         }
  77.        
  78.         this.getAvaiablePoints  = function()
  79.         {
  80.             var avaiable = new Array;
  81.                 for(var y = 0 ; y <= VERTICAL ; y ++)
  82.                 {
  83.                     for(var x = 0 ; x <= TRANSVERSE ; x ++)
  84.                         {
  85.                             if(chessBoard[y][x]) continue;
  86.                             var point = {x : x , y : y};
  87.                             avaiable.push(point);
  88.                         }
  89.                 }
  90.                 return avaiable;
  91.         }
  92.        
  93.         this.getMap = function()
  94.         {
  95.              var map = {};
  96.                  for(var y = 0 ; y <= VERTICAL ; y ++)
  97.                  {
  98.                      for(var x = 0 ; x <= TRANSVERSE ; x++)
  99.                          {
  100.                              var chess = chessBoard[y][x];
  101.                                  var value = '';
  102.                                  if(chess)
  103.                                  {
  104.                                      value = chess.getOwner();
  105.                                      if(chess.getVictory()) value += '_star';
  106.                                  }
  107.                                  else
  108.                                  {
  109.                                      value = '';
  110.                                  }
  111.                                  map[ x + ',' + y ] = value;
  112.                          }
  113.                  }
  114.                  return map;
  115.         }
  116.        
  117.         this.gameOver = function()
  118.         {
  119.             return isGameOver = true;
  120.         }
  121.        
  122.         this.isGameOver = function()
  123.         {
  124.             return isGameOver;
  125.         }
  126.  
  127.        
  128.         this.getNextPoint = function(point , direction)
  129.         {
  130.             var next = {x : point.x , y : point.y};
  131.                 switch(direction)
  132.                 {
  133.                     case LEFT :
  134.                             next.x -= 1;
  135.                                 break;
  136.                         case RIGHT:
  137.                             next.x += 1;
  138.                                 break;
  139.                         case TOP:
  140.                             next.y -= 1;
  141.                                 break;
  142.                         case BOTTOM:
  143.                             next.y += 1;
  144.                                 break;
  145.                         case LEFT_TOP:
  146.                             next.x-= 1 , next.y-= 1;
  147.                                 break;
  148.                         case RIGHT_TOP:
  149.                             next.x += 1 , next.y -= 1;
  150.                                 break;
  151.                         case LEFT_BOTTOM:
  152.                             next.x -= 1 , next.y += 1;
  153.                                 break;
  154.                         case RIGHT_BOTTOM:
  155.                             next.x += 1 , next.y += 1;
  156.                                 break;
  157.                         default :
  158.                             alert('方向错误');
  159.                 }
  160.                 return next;
  161.         }
  162.  
  163.         var initialize = function()
  164.         {
  165.                 for(var i = 0 ; i <= VERTICAL ; i++ ) chessBoard.push([]);
  166.         }      
  167.        
  168.         initialize();
  169. }
  170.  
  171. var Compute = function(role)
  172. {
  173.     var directions = [LEFT , TOP , RIGHT , BOTTOM , LEFT_TOP , LEFT_BOTTOM , RIGHT_TOP , RIGHT_BOTTOM];
  174.        
  175.         var score = 0;
  176.        
  177.         var self = this;
  178.                
  179.         this._computeScore = function(direction)
  180.         {
  181.             throw new Error('未实现');
  182.         }
  183.        
  184.         this._convertToPattern = function(chesslist)
  185.         {
  186.             return role.convertToPattern(chesslist)
  187.         }
  188.        
  189.         this.compute = function(point)
  190.         {
  191.             score = 0;
  192.             for(var i = 0, direction ; direction = directions[i++];)
  193.                 {
  194.                     score += this._computeScore(point , direction);
  195.                 }      
  196.         }
  197.        
  198.         this.getScore = function(refPoint)
  199.         {
  200.                 return score ;
  201.         }
  202. }
  203.  
  204. var Five = function(role)
  205. {
  206.     Compute.call(this, role);
  207.        
  208.         var computeScore1 = function(refPoint , direction)
  209.         {
  210.                 var predefined = 'IIII';
  211.                 var chesslist = role.find(refPoint , direction , 4);
  212.                 var pattern = role.convertToPattern(chesslist);
  213.                 if(predefined == pattern) return true;
  214.                 return false ;     
  215.         }
  216.        
  217.         var computeScore2 = function(refPoint , direction)
  218.         {
  219.             var prev = role.find(refPoint , direction , 2);
  220.                 var next = role.find(refPoint , role.reverseDirection(direction) , 2);
  221.                 var prevPattern = role.convertToPattern(prev);
  222.                 var nextPattern = role.convertToPattern(next);
  223.                 if(prevPattern == 'II' && nextPattern == 'II') return true;
  224.                 return false;
  225.         }
  226.        
  227.         var computeScore3 = function(refPoint , direction)
  228.         {
  229.             var prev = role.find(refPoint , direction , 3);
  230.                 var next = role.find(refPoint , role.reverseDirection(direction) , 1);
  231.                 var prevPattern = role.convertToPattern(prev);
  232.                 var nextPattern = role.convertToPattern(next);
  233.         if(prevPattern == 'III' && nextPattern == 'I') return true;
  234.         return false;          
  235.         }
  236.        
  237.         this._computeScore = function(refPoint , direction)
  238.         {
  239.                 if(computeScore1(refPoint , direction) || computeScore2(refPoint , direction) || computeScore3(refPoint , direction))
  240.                     return 100000;
  241.                 else return 0;
  242.         }
  243. }
  244.  
  245. var Four_Live = function(role)
  246. {
  247.     Compute.call(this, role);
  248.        
  249.     this._computeScore = function(refPoint , direction)
  250.         {
  251.                 var score = 0;
  252.                 var prev = role.find(refPoint , direction , 4);
  253.                 var next = role.find(refPoint , role.reverseDirection(direction), 1);
  254.                 var prevPattern = this._convertToPattern(prev);
  255.                 var nextPattern = this._convertToPattern(next);
  256.                 if(prevPattern == 'III0' && nextPattern == '0') score = 10000;     
  257.         return score;          
  258.         }
  259. }
  260.  
  261. var Four_Live1 = function(role)
  262. {
  263.     Compute.call(this, role);
  264.        
  265.         this._computeScore = function(refPoint , direction)
  266.         {
  267.             var prev = role.find(refPoint , direction , 3);
  268.                 var next = role.find(refPoint , role.reverseDirection(direction) , 2);
  269.                 var prevPattern = this._convertToPattern(prev);
  270.                 var nextPattern = this._convertToPattern(next);        
  271.                 if(prevPattern == 'II0' && nextPattern == 'I0') return 10000;
  272.                 else return 0;
  273.         }
  274. }
  275.  
  276. var Tree_Live = function(role)
  277. {
  278.     Compute.call(this, role);
  279.        
  280.     this._computeScore = function(refPoint , direction)
  281.         {
  282.             var score = 0;
  283.             var prev = role.find(refPoint , direction , 3);
  284.                 var next = role.find(refPoint , role.reverseDirection(direction), 2);
  285.                 var prevPattern = this._convertToPattern(prev);
  286.                 var nextPattern = this._convertToPattern(next);
  287.                 if(prevPattern == 'II0' && nextPattern == '00')
  288.                     score += 1000;
  289.                 return score;
  290.         }
  291. }
  292.  
  293. var Tree_Live1 = function(role)
  294. {
  295.    Compute.call(this, role);
  296.    
  297.    this._computeScore = function(refPoint , direction)
  298.    {
  299.             var prev = role.find(refPoint , direction , 2);
  300.                 var next = role.find(refPoint , role.reverseDirection(direction), 3);
  301.                 var prevPattern = this._convertToPattern(prev);
  302.                 var nextPattern = this._convertToPattern(next);
  303.         if(prevPattern == 'I0' && nextPattern == 'I00')
  304.             return 1000
  305.         else return 0;                 
  306.    }
  307. }
  308.  
  309. var Two_Live = function(role)
  310. {
  311.    Compute.call(this, role);
  312.    
  313.    this._computeScore = function(refPoint , direction)
  314.    {
  315.             var prev = role.find(refPoint , direction , 3);
  316.                 var next = role.find(refPoint , role.reverseDirection(direction), 2);  
  317.                 var prevPattern = this._convertToPattern(prev);
  318.                 var nextPattern = this._convertToPattern(next);
  319.         if(prevPattern == 'I00' && nextPattern == '00') return 100;
  320.         else return 0;         
  321.    }
  322. }
  323.  
  324. var One_Live = function(role)
  325. {
  326.    Compute.call(this, role);
  327.    
  328.    this._computeScore = function(refPoint , direction)
  329.    {
  330.             var prev = role.find(refPoint , direction , 3);
  331.                 var next = role.find(refPoint , role.reverseDirection(direction), 3);  
  332.                 var prevPattern = this._convertToPattern(prev);
  333.                 var nextPattern = this._convertToPattern(next);
  334.         if(prevPattern == '000' && nextPattern == '000') return 10;
  335.         else return 0;         
  336.    }
  337. }
  338.  
  339. var Four_End = function(role)
  340. {
  341.    Compute.call(this, role);
  342.    
  343.    this._computeScore = function(refPoint , direction)
  344.    {
  345.             var prev = role.find(refPoint , direction , 3);
  346.                 var next = role.find(refPoint , role.reverseDirection(direction), 1);  
  347.                 var prevPattern = this._convertToPattern(prev);
  348.                 var nextPattern = this._convertToPattern(next);
  349.         if(prevPattern == 'III' && nextPattern == '0') return 150;
  350.         else return 0;         
  351.    }
  352. }
  353.  
  354. var Role = function(board)
  355. {
  356.     var computers = [];
  357.        
  358.         var self = this;
  359.        
  360.         var isVictory = false;
  361.        
  362.         this.isVictory = function()
  363.         {
  364.             return isVictory;
  365.         }
  366.        
  367.     var getScore = function(point)
  368.         {
  369.             var score = 0;
  370.                 for(var i = 0 , computer; computer = computers[i++];)
  371.                 {
  372.                     computer.compute(point);
  373.                         score += computer.getScore();
  374.                 }
  375.                 var result = {score: score , point : point};
  376.                 return result;
  377.         }
  378.                
  379.     var getScoreList = function()
  380.         {
  381.             var result = [];
  382.             var avaiablePoints = board.getAvaiablePoints();
  383.                 for(var i = 0 , point; point = avaiablePoints[i++];)
  384.                 {
  385.                     result.push(getScore(point));
  386.                 }
  387.                 return result;
  388.         }
  389.        
  390.         this.getCode = function()
  391.         {
  392.             throw new Error('未实现');
  393.         }
  394.  
  395.     this.getPeak = function()
  396.     {
  397.             var scoreInfo = getScoreList();
  398.                 scoreInfo.sort(function(a,b){
  399.                     return  b.score - a.score ;
  400.                 });
  401.                 return scoreInfo[0];
  402.     }  
  403.        
  404.         this.convertToPattern = function(chesslist)
  405.         {
  406.             var pattern = '';
  407.                 if(!chesslist) return '';
  408.             for(var i = 0 ; i < chesslist.length ; i ++)
  409.                 {
  410.                     var chess = chesslist[i];
  411.                         if(chess == undefined) pattern += '0';
  412.                         else if(chess.getOwner() == this.getCode()) pattern += 'I';
  413.                         else  pattern += 'Y';
  414.                 }
  415.                 return pattern ;
  416.         }
  417.  
  418.         this.reverseDirection = function(direction)
  419.         {
  420.             switch(direction)
  421.                 {
  422.                     case LEFT : return RIGHT;
  423.                         case RIGHT : return LEFT;
  424.                         case TOP : return BOTTOM;
  425.                         case BOTTOM : return TOP;
  426.                         case LEFT_TOP : return RIGHT_BOTTOM;
  427.                         case RIGHT_BOTTOM : return LEFT_TOP;
  428.                         case RIGHT_TOP : return LEFT_BOTTOM;
  429.                         case LEFT_BOTTOM : return RIGHT_TOP;
  430.                         default : alert('方向错误');
  431.                 }
  432.         }      
  433.        
  434.         this._checkGameOver = function(point)
  435.         {
  436.             var leftRight = findVictory(point , LEFT);
  437.                 var topBottom = findVictory(point , TOP);
  438.                 var leftTopRightBottom = findVictory(point , LEFT_TOP);
  439.                 var rightTopLeftBottom = findVictory(point , RIGHT_TOP);
  440.                 var array = [leftRight , topBottom , leftTopRightBottom , rightTopLeftBottom];
  441.                 var victory = [];
  442.                 for(var i = 0 ; i < array.length ; i ++)
  443.                 {
  444.                     if(array[i].length >= 5) victory.push(array[i]);
  445.                 }
  446.                
  447.                 if(victory.length > 0)
  448.                 {
  449.                     board.gameOver();
  450.                         board.setVictory(victory);
  451.                         isVictory = true;
  452.                 }
  453.                
  454.                 if(board.getAvaiablePoints().length ==0) board.gameOver();
  455.         }
  456.        
  457.         var isLicitPoint = function(point)
  458.         {
  459.             return point.x >= 0 && point.y >= 0 && point.x <= TRANSVERSE && point.y <= VERTICAL
  460.                     && board.getChess(point) && board.getChess(point).getOwner() == self.getCode()
  461.         }
  462.        
  463.         var findVictory = function(refPoint , direction)
  464.         {
  465.             var reverse = self.reverseDirection(direction);
  466.                 var result = [];
  467.                 var nextPoint ;
  468.                 var currPoint = {x: refPoint.x , y: refPoint.y};
  469.                 while(true)
  470.                 {
  471.                     nextPoint = board.getNextPoint(currPoint, direction);
  472.                         if(!isLicitPoint(nextPoint)) break;
  473.                         currPoint = {x :nextPoint.x , y:nextPoint.y};
  474.                 }
  475.                
  476.                 while(true)
  477.                 {
  478.             result.push(currPoint);                    
  479.                     nextPoint = board.getNextPoint(currPoint , reverse);
  480.                         if(!isLicitPoint(nextPoint)) break;            
  481.                         currPoint = { x: nextPoint.x , y: nextPoint.y };
  482.                 }
  483.                
  484.                 return result;
  485.         }
  486.        
  487.         this.find = function(point , direction , deep)
  488.         {
  489.              var refPoint = {x: point.x , y : point.y};
  490.              var result = new Array;
  491.                  var index = 1;
  492.                  var nextPoint;
  493.                  while(index <= deep)
  494.                  {
  495.                      nextPoint = board.getNextPoint(refPoint, direction);
  496.                          if(nextPoint.x < 0 || nextPoint.y < 0 ||
  497.                             nextPoint.x > TRANSVERSE || nextPoint.y > VERTICAL) return null;
  498.                          var chess = board.getChess(nextPoint);
  499.                          if(chess) chess.point = {x:nextPoint.x , y:nextPoint.y};
  500.                          result.push(chess);
  501.                          refPoint = nextPoint;
  502.                          index ++;
  503.                  }
  504.                  return result;
  505.         }      
  506.        
  507.         var initialize = function()
  508.         {
  509.             computers.push(new Five(self));
  510.                 computers.push(new Four_Live(self));
  511.                 computers.push(new Tree_Live(self));
  512.                 computers.push(new Four_Live1(self));
  513.                 computers.push(new Tree_Live1(self));
  514.                 computers.push(new Two_Live(self));
  515.                 computers.push(new One_Live(self));
  516.                 computers.push(new Four_End(self));
  517.         }
  518.        
  519.         initialize();
  520. }
  521.  
  522. var Machine = function(board, rival)
  523. {
  524.     Role.call(this, board);
  525.        
  526.         this.setChess = function()
  527.         {
  528.             if(board.isGameOver()) return;
  529.             var myPeak = this.getPeak();
  530.                 var rivalPeak = rival.getPeak();
  531.                 var peak ;
  532.                 if(myPeak.score >= rivalPeak.score)  peak = myPeak;
  533.                 else  peak = rivalPeak;
  534.             var chess = new Chess();
  535.                 chess.setOwner(this.getCode());
  536.                 board.setChess(chess, peak.point);
  537.                 this._checkGameOver(peak.point);
  538.         }
  539.        
  540.         this.getCode = function(){return 'machine';}
  541. }
  542.  
  543. var Person = function(board , rival)
  544. {
  545.     Role.call(this, board);
  546.        
  547.         this.setChess = function(x,y)
  548.         {
  549.            if(board.isGameOver()) return;
  550.            var point = new Object;
  551.            point.x = x;
  552.            point.y = y;
  553.            var chess = new Chess()
  554.            chess.setOwner(this.getCode());
  555.            board.setChess(chess, point);
  556.            this._checkGameOver(point);
  557.         }
  558.        
  559.         this.getCode = function(){ return 'person'; }
  560. }
  561.  
  562.  
  563. var UIBase = function()
  564. {
  565.     var self = this;
  566.     this._id = '$UI' + (++ UIBase.index);
  567.         this._globalKey = "";
  568.         this.getHTML = function()
  569.         {
  570.             return "";
  571.         }
  572.        
  573.         var setGlobalKey = function()
  574.         {
  575.             var magic = '$UI_Items';
  576.                 self._globalKey = 'window.'+magic+'.'+self._id;        
  577.                 window[magic] = window[magic] || {};
  578.                 window[magic][self._id] = self;
  579.         }
  580.        
  581.         var formatHTML = function(html)
  582.         {
  583.                 html = html.replace(/\$\$/g, self._globalKey);
  584.                 html = html.replace(/&&/g,self._id);
  585.                 return html;
  586.         }      
  587.        
  588.         var initUIBase = function()
  589.         {
  590.             setGlobalKey();
  591.         }
  592.        
  593.         this.renderHTML = function()
  594.         {
  595.             return formatHTML(this.getHTML());
  596.         }
  597.        
  598.         this.getDOM = function()
  599.         {
  600.         var dom = document.getElementById(this._id)
  601.             return dom;
  602.         }
  603.        
  604.         initUIBase();
  605. }
  606.  
  607. UIBase.index = 0;
  608.  
  609.  
  610. var ChessUI = function(board, placeholder)
  611. {
  612.     UIBase.call(this);
  613.        
  614.         this.setChess = function(){}
  615.        
  616.         this.getHTML = function()
  617.         {
  618.             var html = '';
  619.                 var map = board.getMap();
  620.                 for(var key in map)
  621.                 {
  622.                     var onclick = '';
  623.                         var className = map[key];
  624.                         if(className == '') onclick='$$._setChess('+ key +')';
  625.             html += '<div onclick="'+ onclick +'" class="'+ className +'"></div>';
  626.                 }
  627.                 return html;
  628.         }
  629.        
  630.         this.draw = function()
  631.         {
  632.             var html = this.renderHTML();
  633.                 document.getElementById(placeholder).innerHTML = html;
  634.         }
  635.        
  636.         this._setChess = function(x,y)
  637.         {
  638.             this.setChess(x,y);
  639.         }
  640.        
  641.         this.draw();
  642. }
  643.  
  644.  
  645. function getMSIEVersion()
  646. {
  647.     var regex = /MSIE([^;]+)/;
  648.         var userAgent = navigator.userAgent;
  649.         var result = regex.exec(userAgent);
  650.         if(result) return parseInt(result[1]);
  651. }
  652. function initGame()
  653. {
  654.     var version = getMSIEVersion();
  655.     if(version && version <= 8)
  656.         {
  657.             alert('请使用非IE浏览器(ie9、10除外)进行游戏(google chrome 、firefox等 )');
  658.                 return;
  659.         }
  660.         var board = new Board();
  661.         var person = new Person(board);
  662.         var machine = new Machine(board, person);
  663.         var chessUI = new ChessUI(board, 'board');
  664.         chessUI.setChess = function(x,y)
  665.         {
  666.                 person.setChess(x,y);
  667.                 machine.setChess();
  668.                 chessUI.draw();
  669.                 if(board.isGameOver())
  670.                 {
  671.                     if(person.isVictory()) alert('您获得了胜利');
  672.                         else if(machine.isVictory()) alert('机器获得了胜利');
  673.                         else alert('游戏结束,胜负未分');
  674.                 }
  675.         }
  676.         if(Math.floor(Math.random() * 10) % 2)
  677.         {
  678.             alert('机器执棋');
  679.                 machine.setChess();
  680.                 chessUI.draw();
  681.         }
  682.         else
  683.         {
  684.             alert('您执棋');
  685.         }
  686. }
  687.  
  688. </script>
  689. </body>
  690. </html>
  691.        
  692.        
  693.        
  694. //javascript/4313

回复 "jQuery编写的五子棋代码"

这儿你可以回复上面这条便签

captcha