扫雷游戏(设置炸弹和声称获胜者) - JavaScript

时间:2017-03-02 19:33:07

标签: javascript

我是JavaScript的新手,想要了解更多信息。我正在尝试创建我自己的MineSweeping游戏,但我无法将我的一块瓷砖设置为陷阱,并在玩家按下所有瓷砖并避开陷阱时宣告获胜者。我想知道是否有人可以帮助我?我知道如果玩家点击陷阱,我会休息一下;最后的功能是结束游戏并显示“Game Over”,但我不确定如何设置要调用的tile函数?如果玩家点击3/4正确的牌,它会说“你赢了!”我的功能是否包含类似的东西 if (clicked_tile != trap) { document.getElementById("info").innerHTML = "You won!"?
任何帮助,将不胜感激! 谢谢。

<html>
<head>
<style>
.container {
width:200px;
height:200px;
}
#t1, #t2, #t3, #t4{
  width: 45px;
  height: 45px;
}
#t1{background-color: red;}
#t2{background-color: blue;}
#t3{background-color: green;}
#t4{background-color: yellow;}
</style>
<script>

  var trap = Math.floor(Math.random()*4+1);
  function play_game(id)
  {
    var tile_id = "t" + id;
    var clicked_tile = document.getElementById(tile_id);
    if (clicked_tile.style.backgroundColor == "grey"){
      document.getElementById("info").innerHTML =
      "This was already clicked";
    }
    else
    {
              clicked_tile.style.backgroundColor = "grey";
              document.getElementById("info").innerHTML =
              "The trap is " + trap;
    }
  }
     </script>
   </head>

  <body>
   <div class = "container">
      <div id="t1" onclick="play_game('1')"></div>
      <div id="t2" onclick="play_game('2')"></div>
      <div id="t3" onclick="play_game('3')"></div>
      <div id="t4" onclick="play_game('4')"></div>
   </div>
  <div id="info"></div>

 </body> 
 </html>

1 个答案:

答案 0 :(得分:0)

You're on the right track. For the losing condition (clicking the trap), you could consider adding another if statement:

else if (id == trap){ ... you lose! ... }

The winning condition is a bit tougher. You might consider a structure using JavaScript objects:

//create a default minefield
var mineboard = {
    'tile1': {
        'safe': true,
        'clicked': false
    },
    'tile2': {
        'safe': true,
        'clicked': false
    },
    'tile3': {
        'safe': true,
        'clicked': false
    },
    'tile4': {
        'safe': true,
        'clicked': false
    }
};

//set the trap
var trap = Math.floor(Math.random()*4+1); //will be something like 'tile2'
mineboard['tile' + trap].safe = false; //now a tile is not safe!

You could use an object like this to keep track of the state of your application. As the user clicks tiles, set clicked to true. Each time the user clicks, check all your tiles--if you count three places where safe is true and clicked is true, you know your user has won.