0
我正在使用JavaScript編寫簡單的tictactoe遊戲,但它顯示(有人贏了!!!)在第一次點擊板上,我知道我很接近但我無法找到我的問題碼。tictactoe with javascript using css3
<!DOCTYPE html>
<html>
<head>
<style>
.board{
display: flex;
width: 600px;
height: 600px;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
}
.square{
width: 200px;
height: 200px;
box-sizing: border-box;
border: 5px solid black;
font-size: 5em;
display: flex;
justify-content: center;
align-items: center;
}
.square:hover{
cursor: pointer;
background-color: #80cd92;
}
</style>
</head>
<body>
<div class="board">
<div class="square"> </div>
<div class="square"> </div>
<div class="square"> </div>
<div class="square"> </div>
<div class="square"> </div>
<div class="square"> </div>
<div class="square"> </div>
<div class="square"> </div>
<div class="square"> </div>
</div>
<script>
var PLAYER_ONE_SYMBOL = 'X'
var PLAYER_TWO_SYMBOL = 'O'
var currentTurn = PLAYER_ONE_SYMBOL
var board = document.querySelector('.board')
board.addEventListener('click',function(e) {
e.target.innerHTML = currentTurn
currentTurn = currentTurn === PLAYER_ONE_SYMBOL ? PLAYER_TWO_SYMBOL : PLAYER_ONE_SYMBOL
if (checkForWinner())
{alert(" somebody won !!! ")}
})
function checkForWinner(){
var squares = Array.prototype.slice.call(document.querySelectorAll('.square'), 0)
var symbols = squares.map(function(square) {
return square.innerHTML
})
var winningCombos = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
return winningCombos.find(function(combo)
{
if(symbols[combo[0]]==symbols[combo[1]]&&symbols[combo[1]]==symbols[combo[2]])
{return symbols[combo[0]]}
else {return false}
})
}
</script>
</body>
</html>
非常感謝羅比你解決了這個問題!我在這段代碼上花了幾個小時試圖看看有什麼不對,我很高興你能幫助我,再次感謝 – gualgui