即使更改,函数也会继续执行代码段

时间:2016-08-22 19:06:08

标签: javascript jquery

我目前在制作Tic-Tac-Toe游戏时遇到问题,即使我更改了“状态”变量,它仍然在其中执行代码,我该如何解决这个问题?是否有一种简单的方法可以继续执行制作游戏的常规代码?

$(document).ready(function() {
  gameManager();
});

$(document).ready(function() {
  gameManager();
});

var playerSelect, aiSelect = "";
var state = "choose";
var turn = "player";
var gameOn = true;

function gameManager() {

  if (state == "choose") {
    chooseSide();
  } else if (state == "play") {

    createGrid();

    if (turn == "player") {
      playerChoose();
      console.log("Player's turn");
    } else {
      playerChoose();
      console.log("Enemy's turn");
    }
  }
}

function playerChoose() {
  $('.gridElement').click(function() {
    $(this).html('<div class="gridElement">' + playerSelect + '</div>');
  });
}

function chooseSide() {
  console.log(state);

  $('#textContainer').html('<p> Choose Side: </p> <div class="chooseButton">X</div> <div class="chooseButton">O</div>');

  $('.chooseButton').click(function() {
    console.log(state);
    playerSelect = $(this).html();

    if (playerSelect == "X") {
      aiSelect = "O";
    } else {
      aiSelect = "X";
    }

    state = "play"
    console.log(state);
  });
}

function createGrid() {

  for (var i = 0; i < 9; i++) {
    $('#gridContainer').append('<div class="gridElement"> </div>');
  }

  var gridElementSize = $('#gridContainer').width() / 3;

  $('.gridElement').css({
    'width': gridElementSize,
    "height": gridElementSize
  });
}
#gridContainer {
  border: 2px solid blue;
  width: 200px;
  height: 200px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 40px;
}
.gridElement {
  display: inline-block;
  vertical-align: top;
  border: 1px solid black;
}
#textContainer {
  margin-left: auto;
  margin-right: auto;
}
.chooseButton {
  display: inline-block;
}
<!DOCTYPE>
<!DOCTYPE html>
<html>

<head>
  <!-- INITIALIZE -->
  <link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Black+Ops+One" rel="stylesheet">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

  <script src="https://use.fontawesome.com/ca5f7b6f9a.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

  <link rel="stylesheet" href="stylesheet.css">
  <script src="script.js"></script>

  <!--CONTENT-->
  <title>TicTacToe</title>
</head>

<body>

  <div id="textContainer">

  </div>


  <div id="gridContainer">

  </div>


</body>

</html>

1 个答案:

答案 0 :(得分:0)

正如Bamar所说,Javascript Web应用程序是事件驱动的,这意味着您需要为用户与Web页面的交互创建事件处理程序。当用户与浏览器交互时(单击页面上的元素,滚动视图等),就会发生事件。事件处理程序是Javascript函数。绑定事件处理程序时,只应将它们绑定到事件类型。您的应用程序中只需要处理两个事件:选择X或O,然后单击网格中的方块。

我重构了您的代码以说明更好的方法。选择边在initGame中绑定一次,并且网格方块单击在创建时绑定到正方形(每次通过再次选择边重置游戏时)。请注意,每次重置游戏时都需要再次绑定方形单击处理程序,因为先前的gridElements在resetGrid的顶部被删除,并且绑定到那些已删除元素的事件处理程序将丢失。

$(document).ready(function() {
  initGame();
});

var playerSelect, aiSelect = "";
var turn;
var gameOn;


function initGame() {
  $('#textContainer').html('<p> Choose Side: </p> <div class="chooseButton">X</div> <div class="chooseButton">O</div>');

  $('.chooseButton').click(function(){
    playerSelect = $(this).html();

    if(playerSelect == "X"){
      aiSelect = "O";
    } else {
      aiSelect = "X";
    }
    resetGame(); 
  });

}

function resetGame(){
  gameOn = true;
  turn = "player";    
  resetGrid();
}

function resetGrid(){
  // remove any existing grid elements
  $('.gridElement').remove();

  for(var i = 0; i < 9; i++){
    $('#gridContainer').append('<div class="gridElement"></div>');
  }

  var gridElementSize = $('#gridContainer').width()/3;

  $('.gridElement').css({'width': gridElementSize, "height": gridElementSize});

  // bind the click handler to the new elements
  $('.gridElement').click(function(e){ // e is the event
    handlePlayerClick(e);
  });
}

function checkForWinOrDraw() {
  // check for win or draw
  gameOn = true; // set to false if game is over
}

function handlePlayerClick(e) { // e is the click event
  if( gameOn == false ) {
    // the current game is over, so do nothing
    return;
  }
  if(turn == "player"){
    square = $(e.target);
    if( square.html() == "") { // if the square is empty
      $(e.target).html(playerSelect); // e.target is the grid element
      turn = "enemy";
      console.log("Player has made a move");
      // the player has made a move
      checkForWinOrDraw();
      makeEnemyMove();
    } else {
      console.log("Square has already been taken.");
    }
  } else {
    console.log("Player can't play.  It's the enemy's turn");
  } 

}

function makeEnemyMove() {
  if( gameOn == false ) {
    // the current game is over, so do nothing
    return;
  }
  // dumb AI picks first empty square.  Replace with smart AI
  els = $('.gridElement').toArray();
  var i;
  for( i = 0; i < els.length; i++ ) {
    var el = $(els[i]);
    if( el.html() == "" ) {
      el.html(aiSelect);
      console.log("Enemy has made a move");
      turn = "player";
      break;
    }
  }
  checkForWinOrDraw();
}
#gridContainer{
	border: 2px solid blue;

	width: 200px;
	height: 200px;

	margin-left: auto;
	margin-right: auto;
	margin-top: 40px;
}

.gridElement{
	display: inline-block;
	vertical-align:middle;
    text-align: center;
    padding-top: 20px;

	border: 1px solid black;
}

#textContainer{

	margin-left: auto;
	margin-right: auto;

}

.chooseButton{
	display: inline-block;
}
<!DOCTYPE>
<!DOCTYPE html>
<html>
<head>
	<!-- INITIALIZE -->
		<link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
		<link href="https://fonts.googleapis.com/css?family=Black+Ops+One" rel="stylesheet">
		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

		<script src="https://use.fontawesome.com/ca5f7b6f9a.js"></script>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

		<link rel="stylesheet" href="stylesheet.css">
		<script src="script.js"></script>

		<!--CONTENT-->
		<title>TicTacToe</title>
</head>
<body>

	<div id="textContainer">

	</div>


	<div id="gridContainer">

	</div>


</body>
</html>