JavaScript makes windows classic minesweeper game

  • 2020-05-24 05:07:44
  • OfStack

The code is very simple, so I'm not going to talk about that


<html>
<head>
<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title> Mine clearance -JavaScript Mine Sweeper</title>
<style type="text/css">
table{TABLE-LAYOUT: fixed;cursor:pointer}
td{width: 20px; height: 20px; font-size: 12px; font-family: Verdana;font-weight:bold; text-align:center;background:#CECECE;}
td.Normal, .Flag{border-left:2px solid #F5F5F5; border-right:2px outset #F5F5F5; border-top:2px solid #F5F5F5; border-bottom:2px outset #F5F5F5; font-weight:bold}
.Mine, .Boom, .M0, .M1, .M2, .M3, .M4, .M5, .M6, .M7, .M8{background:#C5C5C5;border-right:1px solid #B4B4B4; border-bottom:1px solid #B4B4B4;}
td.Mine{background: url(http://sandbox.runjs.cn/uploads/rs/202/xyovf5xj/mine.gif) no-repeat center}
td.Boom{background:#F00 url(http://sandbox.runjs.cn/uploads/rs/202/xyovf5xj/mine.gif) no-repeat center}
td.Flag, td.ErrFlag{background-image: url(http://sandbox.runjs.cn/uploads/rs/202/xyovf5xj/flag.gif);background-repeat: no-repeat; background-position: center;}
td.ErrFlag{background:#0F0}
td.M1 {color: #00f}
td.M2 {color: #008000}
td.M3 {color: #f00}
td.M4 {color: #000080}
td.M5 {color: #800000}
td.M6 {color: #008080}
td.M7 {color: #000}
td.M8 {color: #808080}
</style>
<script>
var $=function(id){return document.getElementById(id)},
  MouseButton=LeftMouse=0,// Count of double key clicks, mouseup Event set 0 . mousedown Event + 1 when MouseButton=2 Indicates that the double key is clicked simultaneously ; Whether the left mouse button is pressed or not, when the left mouse button is pressed 1 , loosen to 0
  FlagImg=new Image(),
  HappyImg=new Image(),
  MineImg=new Image(),
  SadImg=new Image(),
  SuccessImg=new Image(),
 
  WhichButton=function(e){
    e=e||window.event;
    var b=getOs();
    if(b!=2){ // non FF
      switch(e.button){
        case 2:
          return 0;
        case 0:
          return b==1?0:1; //b==1,IE
        default:
          return 1;
      }
    }else{ //FF
      return e.which==3?0:1;
    }
  },
 
OMine={
  MaxX:9,MaxY:9,// Maximum coordinate 
  MineCount:10,// Define the number of mines , Can be changed 
  FlagCount:0, // The number of flags marked 
  OpenedCount:0, // The number of areas that have been opened 
  MaxOpenCount:0,// The maximum number of regions that should be opened 
  // when OpenedCount=MaxOpenCount&&FlagCount=MineCount when , Judge the game to be successful 
  Mine:[],
  GameOver:false, //true The game ends in failure 
  Success:false, //true The game ends successfully 
  aClear:[],// An array of temporary lightning charges 
   
  // Initializes when refreshing the page 
  fInit:function(){
    var T=this,MaxX=T.MaxX,MaxY=T.MaxY,nX,nY=MaxY,MineCount=T.MineCount,
      AStr=['<table bordercolor="#000000" border="0" cellpadding="0" cellspacing="0" height="'+20*MaxY+'px" width="'+20*MaxX+'px" style="border: 10px inset #a0a0a0">'],
      i=0,TAr,TMine=T.Mine;
    T.MaxOpenCount=MaxX*MaxY-MineCount;
    while(nY--){
      AStr[++i]='<tr>';
      TAr=TMine[nY]=[];
      nX=MaxX;
      while(nX--){
        AStr[++i]='<td class="Normal" onmousedown="OMine.fMouseDown('+nX+','+nY+',event);" onmouseup="OMine.fMouseUp('+nX+','+nY+',event);" onmouseover="OMine.fButtonMouseOver('+nX+','+nY+')" onmouseout="OMine.fButtonMouseOut('+nX+','+nY+')" id="Img'+nX+'_'+nY+'"> </td>';
        TAr[nX]={
          Mine:0, //0 No thunder ,1 Said a ray 
          State:0,//0 Means not open ,1 Means the left button is opened ,2 Right click mark 
          MineCount:0// There are some thunder around 
        }
      }
       AStr[++i]='</tr>';
    }
    AStr[++i]='</table>';
    $('dMap').innerHTML=T.InitStr=AStr.join('');
    $('txtFlagCount').value=MineCount;
    T.fInitMine();
    $('btnRefreshMap').src='http://sandbox.runjs.cn/uploads/rs/202/xyovf5xj/happy.gif';
    T.GameOver=T.Success=false;
    T.OpenedCount=T.FlagCount=T.aClear.lenght=0;
  },
   
  // To facilitate circular assignments , When you assign a value to an array of tables XY It's circular the other way around , So you have to go back when you call it 
  // Let's say I want to get whether there's a ray in that cell , with OMine.fGetMine(x,y).Mine;
  fGetMine:function(X,Y){return this.Mine[Y][X]},
   
  // Large table characters are not initialized only when the restart button is pressed 
  fRefreshMap:function(){
    var T=this;
    $('dMap').innerHTML=T.InitStr;
    T.fResetOMine();// You have to reset it OMine, To reset the 99 A ray 
    T.fInitMine();
    T.GameOver=T.Success=false;
    $('btnRefreshMap').src='http://sandbox.runjs.cn/uploads/rs/202/xyovf5xj/happy.gif';
    $('txtFlagCount').value=T.MineCount;
    T.OpenedCount=T.FlagCount=T.aClear.lenght=0;
  },
 
  // reset OMine.Mine An array of 
  fResetOMine:function(){
    var T=this,MaxY=T.MaxY,MaxX=T.MaxX,X,Y=MaxY,M,Mine=T.Mine,TAr;
    while(Y--){
      X=MaxX;
      TAr=Mine[Y];
      while(X--)(M=TAr[X]).Mine=M.State=M.MineCount=0;
    }
  },
   
  // Initializes an array of mines 
  fInitMine:function(){
    var T=this,MaxX=T.MaxX,MaxY=T.MaxY,a,fGetMine=T.fGetMine,
      aOld=[],x,y=MaxY,n=0,l=T.MineCount,xRand; //1 Random number 
    while(y--){
      x=MaxX;
      while(x--)aOld[n++]=[x,y];
    }
    while(l--){
      a=aOld[xRand=Math.floor(Math.random()*(n-1))];
      T.fGetMine(a[0],a[1]).Mine=1;
      aOld.splice(xRand,1);
      --n;
    }
  },
 
  // When the mouse moves over a cell 
  fButtonMouseOver:function(X,Y){
    var T=this;
    switch(MouseButton){
      case 2:// The state where the double bond is pressed 
        var arr=T.fGetAround(X,Y),i=arr.length,TAr;
        while(i--)T.fButtonDown((TAr=arr[i])[0],TAr[1]);
      case 1:
        LeftMouse==1&&T.fButtonDown(X,Y); // The left button is pressed 
    }
  },
   
  // When the mouse moves out of a cell 
  fButtonMouseOut:function(X,Y){
    var T=this;
    switch(MouseButton){
      case 2:// The state where the double bond is pressed 
        var arr=T.fGetAround(X,Y),i=arr.length,TAr;
        while(i--)T.fButtonUp((TAr=arr[i])[0],TAr[1]);
      case 1:
        LeftMouse==1&&T.fButtonUp(X,Y); // The left button is pressed 
    }
  },
 
  // When the mouse is pressed, the unopened grid rendering is pressed 
  fButtonDown:function(X,Y){
    var srcEle=$('Img'+X+'_'+Y);
    srcEle.className=='Normal'&&(srcEle.className='M0');
  },
   
  // Let unenabled and already rendered pressed grid reply Normal
  fButtonUp:function(X,Y){
    var srcEle=$('Img'+X+'_'+Y);
    srcEle.className=='M0'&&!this.fGetMine(X,Y).State&&(srcEle.className='Normal');
  },
   
  // To obtain 8 Coordinates in the four directions 
  fGetAround:function(X,Y){
    var TX,TY,i=8,MX=this.MaxX-1,MY=this.MaxY-1,
      Arr=[[-1,0],[-1,-1],[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1]],
      newArr=[],TAr;
    while(i--){
      TX=X+(TAr=Arr[i])[0];
      TY=Y+TAr[1];
      !(TX<0||TX>MX||TY<0||TY>MY)&&newArr.push([TX,TY]);
    }
    return newArr;
  },
   
  // Mouse down on the grid 
  fMouseDown:function(X,Y,evt){
    var T=this;
    if(T.GameOver){
      alert(' The game failed , Make persistent efforts !');
      return;
    }
    if(T.Success){
      alert(' Congratulations on the game ! Come again 1 Bureau? ');
      return;
    }
    var srcEle=$('Img'+X+'_'+Y),ObXY=T.fGetMine(X,Y),arr,i,TAr;
    ++MouseButton;
    evt=evt||window.event;
    switch(MouseButton){
      case 2:
        arr=T.fGetAround(X,Y);i=arr.length;
        while(i--)T.fButtonDown((TAr=arr[i])[0],TAr[1]);
        break;
      case 1:
        if(WhichButton(evt)){
          LeftMouse=1;
          T.fButtonDown(X,Y);
        }else{
          switch(ObXY.State){
            case 0:
              ObXY.State=2;
              srcEle.className='Flag';
              --$('txtFlagCount').value;
              ++T.FlagCount;
              break;
            case 2:
              ObXY.State=0;
              srcEle.className='Normal';
              ++$('txtFlagCount').value;
              --T.FlagCount;
          }
        }
      }
  },
   
  // The mouse bounces over the lattice 
  fMouseUp:function(X,Y,evt){
    var T=this;
    evt=evt||window.event;
    var srcEle=$('Img'+X+'_'+Y),ObXY=T.fGetMine(X,Y),arr,i,TAr;
    switch(MouseButton){
      case 2: //MouseDown Click and press for both keys, optionally 1 All of them are double bond bounces 
        LeftMouse=0;
        // Mouse up, to show the state of the grid was pressed to restore 
        arr=T.fGetAround(X,Y);i=arr.length;
        while(i--)T.fButtonUp((TAr=arr[i])[0],TAr[1]);
        !ObXY.State&&T.fButtonUp(X,Y);
        ObXY.State==1&&ObXY.MineCount&&T.fOpenFlagMine(X,Y);
        break;
      case 1: // when MouseDown for 1 When you click, MouseUp Only to 1 A key pop-up 
        if(WhichButton(evt)){
        // Only in the State=0 works , It doesn't matter if there's thunder 
            LeftMouse=0;
            if(ObXY.State){break;}
            ObXY.Mine?(
              // gori , End of the agency 
              T.fFail(),
              srcEle.className='Boom'
            ):(
              ObXY.State=1, // Set the stack to already open before pressing 
              T.aClear.push([X,Y]),
              T.fClearMine()
            )
        }
    }
    MouseButton=0;
    if(T.OpenedCount==T.MaxOpenCount&&T.FlagCount==T.MineCount){
      T.fSuccess();
      alert(' Congratulations on the game ! Come again 1 Bureau? ');
      return;
    }
    // When the number of remaining unopened cells = the number of remaining flags, it is done automatically 
    T.MaxOpenCount+T.MineCount-T.OpenedCount-T.FlagCount==$('txtFlagCount').value&&(
      T.fSuccess(),
      T.fAutoFlag(),
      alert(' Congratulations on the game ! Come again 1 Bureau? ')
    )
  },
   
  // Automatically fill the unopened area of the mine 
  fAutoFlag:function(){
    var T=this,nX,nY=T.MaxY,MaxX=T.MaxX,Mine=T.Mine,TAr;
    while(nY--){
      nX=MaxX;
      TAr=Mine[nY];
      while(nX--)!TAr[nX].State&&($('Img'+nX+'_'+nY).className='Flag');
    }
    $('txtFlagCount').value=0;
  },
   
  // Recursive ray 
  fClearMine:function(){
    var T=this;
    if(T.aClear.length==0){return}
    ++T.OpenedCount;
    var aXY=T.aClear.pop(),X=aXY[0],Y=aXY[1],TX,TY,
      aTmpClear=[], //1 Temporary array 
      srcEle=$('Img'+X+'_'+Y),
      ObXY,ObTXTY,
      countMine=0, // Gets the number of nearby mines 
    // It starts on the right left 8 A direction 
      arr=T.fGetAround(X,Y),i=arr.length,TAr;
    while(i--){
      //TX,TY Get the coordinates around this case 
      (ObTXTY=T.fGetMine(TX=(TAr=arr[i])[0],TY=TAr[1])).Mine==1&&++countMine;
      !ObTXTY.State&&aTmpClear.push([TX,TY]);
    }
    ObXY=T.fGetMine(X,Y);
    ObXY.MineCount=countMine;
    srcEle.className='M'+countMine;
    if(!countMine){
      Array.prototype.push.apply(T.aClear,aTmpClear);
      i=aTmpClear.length;
      while(i--)T.fGetMine((TAr=aTmpClear[i])[0],TAr[1]).State=1;
    }else{
      getOs()==2?
        srcEle.textContent=countMine
        :srcEle.innerText=countMine
    }
    T.fClearMine();
  },
   
  // Get the double bond assist to open 
  fOpenFlagMine:function(X,Y){
    var T=this,FlagCount=0,TX,TY,ObXY,ObTXTY,aTmpClear=[],FlagErr=false,
      arr=T.fGetAround(X,Y),i=arr.length,TAr;
    while(i--){
      //TX,TY Get the coordinates around this case 
      ObTXTY=T.fGetMine(TX=(TAr=arr[i])[0],TY=TAr[1]);
      switch(ObTXTY.State){
        case 0: // Not open, not marked 
          !ObTXTY.Mine&&aTmpClear.push([TX,TY]); // Adds to the array that is assisted to open when there is no ray or flag }
          break;
        case 2: // Flags were marked 
          ++FlagCount; // As long as the flag is marked , Whether rightly or wrongly , Both record the number of tags +1
          !ObTXTY.Mine&&(FlagErr=true); // There was no thunder but the flag was marked , Mark error 
      }
    }
    if(FlagCount<T.fGetMine(X,Y).MineCount||aTmpClear.length==0)return;
    // Flags are less thunder than they are , Right or wrong , Don't open 
    // There are no open Spaces to provide 
    if(FlagErr){ // An error is handled to close the game 
      T.fFail();
      return;
    }
    Array.prototype.push.apply(T.aClear,aTmpClear);
    i=aTmpClear.length;
    while(i--)T.fGetMine((TAr=aTmpClear[i])[0],TAr[1]).State=1;
    T.fClearMine();
  },
   
  // Show all the thunder 
  fShowMine:function(){
    var T=this,X=0,Y=T.MaxY,MaxX=T.MaxX,Mine=T.Mine,TAr,TArX;
    while(Y--){
      X=MaxX;
      TAr=Mine[Y];
      while(X--){
        TArX=TAr[X];
        switch(TArX.Mine){
          case 0:
            TArX.State==2&&($('Img'+X+'_'+Y).className='ErrFlag');
            break;
          case 1:
            $('Img'+X+'_'+Y).className='Mine';
        }
      }
    }
  },
 
  // Game ends successfully 
  fSuccess:function(){
    this.Success=true;
    $('btnRefreshMap').src='http://sandbox.runjs.cn/uploads/rs/202/xyovf5xj/success.gif';
  },
   
  // Game ends in failure 
  fFail:function(){
    this.GameOver=true;
    $('btnRefreshMap').src='http://sandbox.runjs.cn/uploads/rs/202/xyovf5xj/sad.gif';
    this.fShowMine();
  }
},
 
// In the map 
ChangeMap=function(Map){
  var O=OMine;
  switch(Map){
    case 1:
      O.MaxX=O.MaxY=9;
      O.MineCount=10;
      break;
    case 2:
      O.MaxX=O.MaxY=16;
      O.MineCount=40;
      break;
    case 3:
      O.MaxX=30;
      O.MaxY=16;
      O.MineCount=99;
  }
  O.fInit();
},
 
getOs=function(){
  if(navigator.userAgent.indexOf("MSIE")>0)return 1;
  if(isFirefox=navigator.userAgent.indexOf("Firefox")>0)return 2;
  if(isSafari=navigator.userAgent.indexOf("Safari")>0)return 3;  
  if(isCamino=navigator.userAgent.indexOf("Camino")>0)return 4;
  if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0)return 5;
  return 0;
};
 
 
FlagImg.src='http://sandbox.runjs.cn/uploads/rs/202/xyovf5xj/flag.gif';
HappyImg.src='http://sandbox.runjs.cn/uploads/rs/202/xyovf5xj/happy.gif';
MineImg.src='http://sandbox.runjs.cn/uploads/rs/202/xyovf5xj/mine.gif';
SadImg.src='http://sandbox.runjs.cn/uploads/rs/202/xyovf5xj/sad.gif';
SuccessImg.src='http://sandbox.runjs.cn/uploads/rs/202/xyovf5xj/success.gif';
</script>
</head>
<body topmargin="0" oncontextmenu="return false" ondragstart="return false" onselectstart="return false" onload="OMine.fInit()" bgcolor="#808080">
<center>
<div id="dTop" align="center" style="border-style: inset; border-width: 10;width:400">
<table cellpadding="0" cellspacing="0" style="border-collapse: collapse;" width="380" height="44">
 <tr>
  <td style="width: 102; height:50px">
  <input type="text" id="txtFlagCount" size="20" style="width: 60; height: 30; color:#FF0000; text-align:center; font-family:Verdana; font-weight:bold; background-color:#000000; font-size:13pt" value=""></td>
  <td style="width: 136; height:50px">
  <input onclick="OMine.fRefreshMap()" type="image" id="btnRefreshMap" src="happy.gif"><input onclick="OMine.fShowMine();" type="button" name="B3" value=" Show the thunder "style="display:none"></td>
  <td style="width: 142; height:50px">
  <input type="radio" value="V1" checked name="R1" id="R1" onclick="ChangeMap(1)"> primary <input type="radio" value="V1" name="R1" id="R2" onclick="ChangeMap(2)"> The intermediate <input type="radio" value="V1" name="R1" id="R3" onclick="ChangeMap(3)"> senior </td>
 </tr>
 
</table>
</div>
<div id="dMap" align="center"></div>
</center>
</body>
</html>

That's all for this article, I hope you enjoy it.


Related articles: