我目前正在創建一個javascript tic tac toe遊戲。我設法顯示哪個球員贏了。不知何故,我目前正在努力如何在遊戲以平局結束時顯示消息。Tic Tac Toe javascript。如何存儲玩家獲勝並提醒是否有領帶?
還有一件事是我該如何創建記分牌,並在其中一名玩家贏得了三次遊戲時發出提醒。
這是我的代碼。
<html>
<title>Tic Tac Toe</title>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="js/app.js"></script>
</head>
<body onload="startGame();">
<h1>Tic Tac Toe</h1>
<h2>By Irsyad</h2>
<div id ="message"><h3> messages will go here<h3></div>
<div>
<a href="javascript:startGame();">Restart</a>
</div>
<table>
<tr>
<td id="s1" class="square" onclick="nextMove(this);"></td>
<td id="s2" class="square" onclick="nextMove(this);"></td>
<td id="s3" class="square" onclick="nextMove(this);"></td>
</tr>
<tr>
<td id="s4" class="square" onclick="nextMove(this);"></td>
<td id="s5" class="square" onclick="nextMove(this);"></td>
<td id="s6" class="square" onclick="nextMove(this);"></td>
</tr>
<tr>
<td id="s7" class="square" onclick="nextMove(this);"></td>
<td id="s8" class="square" onclick="nextMove(this);"></td>
<td id="s9" class="square" onclick="nextMove(this);"></td>
</tr>
</table>
</body>
</html>
這是javascript。
function startGame() {
for (var i = 1; i <= 9; i++) {
clearBox(i);
}
document.turn = "X" ;
if (Math.random() < 0.5) {
document.turn = "O" ;
}
document.winner = null;
setMessage(document.turn + " gets to start");
}
function setMessage(msg) {
document.getElementById('message').innerText = msg;
}
function nextMove(square) {
if (document.winner != null) {
setMessage(document.winner + " already won the game");
}
else if (square.innerText == ""){
square.innerText = document.turn;
switchTurn();
} else {
setMessage("That square is already used");
}
}
function switchTurn() {
if (checkForWinner(document.turn)) {
setMessage("Congratulations, " + document.turn + " ! You win!");
document.winner = document.turn;
}
else if (document.turn == "X") {
document.turn = "O";
setMessage("It's " + document.turn + " 's turn")
} else {
document.turn = "X";
setMessage("It's " + document.turn + " 's turn")
}
}
function checkForWinner(move) {
var result= false;
if (checkRow(1, 2, 3, move) ||
checkRow(4, 5, 6, move) ||
checkRow(7, 8, 9, move) ||
checkRow(1, 4, 7, move) ||
checkRow(2, 5, 8, move) ||
checkRow(3, 6, 9, move) ||
checkRow(1, 5, 9, move) ||
checkRow(3, 5, 7, move)) {
result = true;
return result;
}
}
function checkRow(a, b, c, move) {
var result = false;
if (getBox(a) == move && getBox(b) == move && getBox(c) == move){
result = true;
}
return result;
}
function getBox(number) {
return document.getElementById("s" + number).innerText;
}
function clearBox(number) {
document.getElementById("s" + number).innerText = "";
}
對於記分板,簡單地做'變種記分牌= {X:0,O- :0};如果(++記分牌[贏家] == 3){ \t \t alert(「遊戲結束!」+贏家+ \t} }' – tewathia