I am making a simple Tic Tac Toe with html CSS and JavaScript. No computer AL player implemented. Just two players taking turns. My checkWinner function is not working and I have no clue how to determine a winner. Somebody suggested that I create two dimensional array to store winning combinations which I did in a variable called winCombos. I am looping through all of them and comparing against the currentPlayer at different locations of cells array but it is not working. Probably I am doing it completely wrong. Can somebody please help me. Thanks
var player1 = "X";
var player2 = "O";
var cells = Array.from(document.querySelectorAll(".cell"));
var currentPlayer = player1;
var winner = "";
var winCombos = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];
function checkWinner(arr, curPlayer){
arr.forEach(function(subArr){
var counter = 0;
subArr.forEach(function(elem){
if(cells[elem] === curPlayer){
counter++;
if(counter == 2 ){
winner = curPlayer;
alert(winner);
}
}
});
});
}
function move(e){
if(e.target.className === "cell" && e.target.textContent === ""){
e.target.textContent = currentPlayer;
checkWinner(winCombos, currentPlayer);
currentPlayer = (currentPlayer === player1)?player2:player1;
}
}
document.querySelector(".board").addEventListener("click", move);
.container{
width: 400px;
height: 480px;
background: tomato;
margin: 50px auto;
text-align: center;
padding: 10px;
}
.board{
width: 90%;
margin: 20px auto;
}
.board .cell{
width: 118px;
height: 100px;
float: left;
text-align: center;
line-height: 80px;
font-size: 80px;
font-weight: bold;
border: 1px solid #fff;
color: #fff;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="container">
<div class="board">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
</div>
</body>
</html>
Aucun commentaire:
Enregistrer un commentaire