1 /*2 3 File: main.js4 5 Abstract: JavaScript file for TicTacToe sample.6 7 8 9 Version: 1.010 11 12 13 Disclaimer: IMPORTANT: This Apple software is supplied to you by 14 15 Apple Inc. ("Apple") in consideration of your agreement to the16 17 following terms, and your use, installation, modification or18 19 redistribution of this Apple software constitutes acceptance of these20 21 terms. If you do not agree with these terms, please do not use,22 23 install, modify or redistribute this Apple software.24 25 26 27 In consideration of your agreement to abide by the following terms, and28 29 subject to these terms, Apple grants you a personal, non-exclusive30 31 license, under Apple's copyrights in this original Apple software (the32 33 "Apple Software"), to use, reproduce, modify and redistribute the Apple34 35 Software, with or without modifications, in source and/or binary forms;36 37 provided that if you redistribute the Apple Software in its entirety and38 39 without modifications, you must retain this notice and the following40 41 text and disclaimers in all such redistributions of the Apple Software. 42 43 Neither the name, trademarks, service marks or logos of Apple Inc. 44 45 may be used to endorse or promote products derived from the Apple46 47 Software without specific prior written permission from Apple. Except48 49 as expressly stated in this notice, no other rights or licenses, express50 51 or implied, are granted by Apple herein, including but not limited to52 53 any patent rights that may be infringed by your derivative works or by54 55 other works in which the Apple Software may be incorporated.56 57 58 59 The Apple Software is provided by Apple on an "AS IS" basis. APPLE60 61 MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION62 63 THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS64 65 FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND66 67 OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.68 69 70 71 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL72 73 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF74 75 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS76 77 INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,78 79 MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED80 81 AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),82 83 STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE84 85 POSSIBILITY OF SUCH DAMAGE.86 87 88 89 Copyright (C) 2010 Apple Inc. All Rights Reserved.90 91 */92 93 94 95 /***************************************/96 97 /* intial setup */98 99 /***************************************/100 101 var board = new Array(9);102 103 104 105 function init() {106 107 /* use touch events if they're supported, otherwise use mouse events */108 109 var down = "mousedown"; var up = "mouseup"; 110 111 if ('createTouch' in document) { down = "touchstart"; up ="touchend"; }112 113 114 115 /* add event listeners */116 117 document.querySelector("input.button").addEventListener(up, newGame, false);118 119 var squares = document.getElementsByTagName("td");120 121 for (var s = 0; s < squares.length; s++) {122 123 squares[s].addEventListener(down, function(evt){squareSelected(evt, getCurrentPlayer());}, false);124 125 }126 127 128 129 /* create the board and set the initial player */130 131 createBoard();132 133 setInitialPlayer();134 135 }136 137 138 139 140 141 /****************************************************************************************/142 143 /* creating or restoring a game board, adding Xs and Os to the board, saving game state */144 145 /****************************************************************************************/146 147 function createBoard() {148 149 150 151 /* create a board from the stored version, if a stored version exists */152 153 if (window.localStorage && localStorage.getItem('tic-tac-toe-board')) {154 155 156 157 /* parse the string that represents our playing board to an array */158 159 board = (JSON.parse(localStorage.getItem('tic-tac-toe-board')));160 161 for (var i = 0; i < board.length; i++) {162 163 if (board[i] != "") {164 165 fillSquareWithMarker(document.getElementById(i), board[i]);166 167 }168 169 }170 171 }172 173 /* otherwise, create a clean board */174 175 else { 176 177 for (var i = 0; i < board.length; i++) {178 179 board[i] = ""; 180 181 document.getElementById(i).innerHTML = "";182 183 }184 185 }186 187 }188 189 190 191 /*** call this function whenever a square is clicked or tapped ***/192 193 function squareSelected(evt, currentPlayer) {194 195 var square = evt.target;196 197 /* check to see if the square already contains an X or O marker */198 199 if (square.className.match(/marker/)) {200 201 alert("Sorry, that space is taken! Please choose another square.");202 203 return;204 205 }206 207 /* if not already marked, mark the square, update the array that tracks our board, check for a winner, and switch players */208 209 else {210 211 fillSquareWithMarker(square, currentPlayer);212 213 updateBoard(square.id, currentPlayer);214 215 checkForWinner();216 217 switchPlayers(); 218 219 }220 221 }222 223 224 225 /*** create an X or O div and append it to the square ***/226 227 function fillSquareWithMarker(square, player) {228 229 var marker = document.createElement('div');230 231 /* set the class name on the new div to X-marker or O-marker, depending on the current player */232 233 marker.className = player + "-marker";234 235 square.appendChild(marker);236 237 }238 239 240 241 /*** update our array which tracks the state of the board, and write the current state to local storage ***/242 243 function updateBoard(index, marker) {244 245 board[index] = marker;246 247 248 249 /* HTML5 localStorage only allows storage of strings - convert our array to a string */250 251 var boardstring = JSON.stringify(board);252 253 254 255 /* store this string to localStorage, along with the last player who marked a square */256 257 localStorage.setItem('tic-tac-toe-board', boardstring); 258 259 localStorage.setItem('last-player', getCurrentPlayer());260 261 }262 263 264 265 266 267 /***********************************************************************************/268 269 /* checking for and declaring a winner, after a square has been marked with X or O */270 271 /***********************************************************************************/272 273 /* Our Tic Tac Toe board, an array:274 275 0 1 2276 277 3 4 5278 279 6 7 8280 281 */282 283 function declareWinner() {284 285 if (confirm("We have a winner! New game?")) {286 287 newGame();288 289 }290 291 }292 293 294 295 function weHaveAWinner(a, b, c) {296 297 if ((board[a] === board[b]) && (board[b] === board[c]) && (board[a] != "" || board[b] != "" || board[c] != "")) {298 299 setTimeout(declareWinner(), 100);300 301 return true;302 303 }304 305 else306 307 return false;308 309 }310 311 312 313 function checkForWinner() {314 315 /* check rows */316 317 var a = 0; var b = 1; var c = 2;318 319 while (c < board.length) {320 321 if (weHaveAWinner(a, b, c)) {322 323 return;324 325 }326 327 a+=3; b+=3; c+=3;328 329 }330 331 332 333 /* check columns */334 335 a = 0; b = 3; c = 6;336 337 while (c < board.length) {338 339 if (weHaveAWinner(a, b, c)) {340 341 return;342 343 }344 345 a+=1; b+=1; c+=1;346 347 }348 349 350 351 /* check diagonal right */352 353 if (weHaveAWinner(0, 4, 8)) {354 355 return;356 357 }358 359 /* check diagonal left */360 361 if (weHaveAWinner(2, 4, 6)) {362 363 return;364 365 }366 367 368 369 /* if there's no winner but the board is full, ask the user if they want to start a new game */370 371 if (!JSON.stringify(board).match(/,"",/)) {372 373 if (confirm("It's a draw. New game?")) {374 375 newGame();376 377 }378 379 }380 381 }382 383 384 385 386 387 /****************************************************************************************/388 389 /* utilities for getting the current player, switching players, and creating a new game */390 391 /****************************************************************************************/392 393 function getCurrentPlayer() {394 395 return document.querySelector(".current-player").id;396 397 }398 399 400 401 /* set the initial player, when starting a whole new game or restoring the game state when the page is revisited */402 403 function setInitialPlayer() {404 405 var playerX = document.getElementById("X");406 407 var playerO = document.getElementById("O");408 409 playerX.className = "";410 411 playerO.className = "";412 413 414 415 /* if there's no localStorage, or no last-player stored in localStorage, always set the first player to X by default */416 417 if (!window.localStorage || !localStorage.getItem('last-player')) {418 419 playerX.className = "current-player";420 421 return;422 423 } 424 425 426 427 var lastPlayer = localStorage.getItem('last-player'); 428 429 if (lastPlayer == 'X') {430 431 playerO.className = "current-player";432 433 }434 435 else {436 437 playerX.className = "current-player";438 439 }440 441 }442 443 444 445 function switchPlayers() {446 447 var playerX = document.getElementById("X");448 449 var playerO = document.getElementById("O");450 451 452 453 if (playerX.className.match(/current-player/)) {454 455 playerO.className = "current-player";456 457 playerX.className = "";458 459 }460 461 else {462 463 playerX.className = "current-player";464 465 playerO.className = "";466 467 }468 469 }470 471 472 473 function newGame() { 474 475 /* clear the currently stored game out of local storage */476 477 localStorage.removeItem('tic-tac-toe-board');478 479 localStorage.removeItem('last-player');480 481 482 483 /* create a new game */484 485 createBoard();486 487 }
Enlace
El enlace para compartir es: