Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: c8e47545f4
Fred Sauer February 15, 2013
file 374 lines (332 sloc) 11.269 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
// Copyright 2012 Google Inc. All Rights Reserved.

/**
* @fileoverview
* Provides methods for the TicTacToe sample UI and interaction with the
* TicTacToe API.
*
* @author danielholevoet@google.com (Dan Holevoet)
*/

/** google global namespace for Google projects. */
var google = google || {};

/** devrel namespace for Google Developer Relations projects. */
google.devrel = google.devrel || {};

/** samples namespace for DevRel sample code. */
google.devrel.samples = google.devrel.samples || {};

/** TicTacToe namespace for this sample. */
google.devrel.samples.ttt = google.devrel.samples.ttt || {};

/**
* Client ID of the application (from the APIs Console).
* @type {string}
*/
google.devrel.samples.ttt.CLIENT_ID =
    'YOUR-CLIENT-ID';

/**
* Scopes used by the application.
* @type {string}
*/
google.devrel.samples.ttt.SCOPES =
    'https://www.googleapis.com/auth/userinfo.email';

/**
* Response type of the auth token.
* @type {string}
*/
google.devrel.samples.ttt.RESPONSE_TYPE = 'token id_token';

/**
* Status for an unfinished game.
* @type {number}
*/
google.devrel.samples.ttt.NOT_DONE = 0;

/**
* Status for a victory.
* @type {number}
*/
google.devrel.samples.ttt.WON = 1;

/**
* Status for a loss.
* @type {number}
*/
google.devrel.samples.ttt.LOST = 2;

/**
* Status for a tie.
* @type {number}
*/
google.devrel.samples.ttt.TIE = 3;

/**
* Strings for each numerical status.
* @type {Array.number}
*/
google.devrel.samples.ttt.STATUS_STRINGS = [
    "NOT_DONE",
    "WON",
    "LOST",
    "TIE"
];

/**
* Whether or not the user is signed in.
* @type {boolean}
*/
google.devrel.samples.ttt.signedIn = false;

/**
* Whether or not the game is waiting for a user's move.
* @type {boolean}
*/
google.devrel.samples.ttt.waitingForMove = true;

/**
* Loads the application UI after the user has completed auth.
*/
google.devrel.samples.ttt.userAuthed = function() {
  var request = gapi.client.oauth2.userinfo.get().execute(function(resp) {
    if (!resp.code) {
      var token = gapi.auth.getToken();
      // Use id_token instead of bearer token
      token.access_token = token.id_token;
      gapi.auth.setToken(token);
      google.devrel.samples.ttt.signedIn = true;
      document.getElementById('userLabel').innerHTML = resp.email;
      document.getElementById('signinButton').innerHTML = 'Sign out';
      google.devrel.samples.ttt.setBoardEnablement(true);
      google.devrel.samples.ttt.queryScores();
    }
  });
};

/**
* Handles the auth flow, with the given value for immediate mode.
* @param {boolean} mode Whether or not to use immediate mode.
* @param {Function} callback Callback to call on completion.
*/
google.devrel.samples.ttt.signin = function(mode, callback) {
  gapi.auth.authorize({client_id: google.devrel.samples.ttt.CLIENT_ID,
      scope: google.devrel.samples.ttt.SCOPES, immediate: mode,
      response_type: google.devrel.samples.ttt.RESPONSE_TYPE},
      callback);
};

/**
* Presents the user with the authorization popup.
*/
google.devrel.samples.ttt.auth = function() {
  if (!google.devrel.samples.ttt.signedIn) {
    google.devrel.samples.ttt.signin(false,
        google.devrel.samples.ttt.userAuthed);
  } else {
    google.devrel.samples.ttt.signedIn = false;
    document.getElementById('userLabel').innerHTML = '(not signed in)';
    document.getElementById('signinButton').innerHTML = 'Sign in';
    google.devrel.samples.ttt.setBoardEnablement(false);
  }
};

/**
* Handles a square click.
* @param {MouseEvent} e Mouse click event.
*/
google.devrel.samples.ttt.clickSquare = function(e) {
  if (google.devrel.samples.ttt.waitingForMove) {
    var button = e.target;
    button.innerHTML = 'X';
    button.removeEventListener('click', google.devrel.samples.ttt.clickSquare);
    google.devrel.samples.ttt.waitingForMove = false;

    var boardString = google.devrel.samples.ttt.getBoardString();
    var status = google.devrel.samples.ttt.checkForVictory(boardString);
    if (status == google.devrel.samples.ttt.NOT_DONE) {
      google.devrel.samples.ttt.getComputerMove(boardString);
    } else {
      google.devrel.samples.ttt.handleFinish(status);
    }
  }
};

/**
* Resets the game board.
*/
google.devrel.samples.ttt.resetGame = function() {
  var buttons = document.querySelectorAll('td');
  for (var i = 0; i < buttons.length; i++) {
    var button = buttons[i];
    button.removeEventListener('click', google.devrel.samples.ttt.clickSquare);
    button.addEventListener('click', google.devrel.samples.ttt.clickSquare);
    button.innerHTML = '-';
  }
  document.getElementById('victory').innerHTML = '';
  google.devrel.samples.ttt.waitingForMove = true;
};

/**
* Gets the computer's move.
* @param {string} boardString Current state of the board.
*/
google.devrel.samples.ttt.getComputerMove = function(boardString) {
  gapi.client.tictactoe.board.getmove({'state': boardString}).execute(
      function(resp) {
    google.devrel.samples.ttt.setBoardFilling(resp.state);
    var status = google.devrel.samples.ttt.checkForVictory(resp.state);
    if (status != google.devrel.samples.ttt.NOT_DONE) {
      google.devrel.samples.ttt.handleFinish(status);
    } else {
      google.devrel.samples.ttt.waitingForMove = true;
    }
  });
};

/**
* Sends the result of the game to the server.
* @param {number} status Result of the game.
*/
google.devrel.samples.ttt.sendResultToServer = function(status) {
  gapi.client.tictactoe.scores.insert({'outcome':
      google.devrel.samples.ttt.STATUS_STRINGS[status]}).execute(
      function(resp) {
    google.devrel.samples.ttt.queryScores();
  });
};

/**
* Queries for results of previous games.
*/
google.devrel.samples.ttt.queryScores = function() {
  gapi.client.tictactoe.scores.list().execute(function(resp) {
    var history = document.getElementById('gameHistory');
    history.innerHTML = '';
    if (resp.items) {
      for (var i = 0; i < resp.items.length; i++) {
        var score = document.createElement('li');
        score.innerHTML = resp.items[i].outcome;
        history.appendChild(score);
      }
    }
  });
};

/**
* Shows or hides the board and game elements.
* @param {boolean} state Whether to show or hide the board elements.
*/
google.devrel.samples.ttt.setBoardEnablement = function(state) {
  if (!state) {
    document.getElementById('board').classList.add('hidden');
    document.getElementById('gameHistoryWrapper').classList.add('hidden');
    document.getElementById('warning').classList.remove('hidden');
  } else {
    document.getElementById('board').classList.remove('hidden');
    document.getElementById('gameHistoryWrapper').classList.remove('hidden');
    document.getElementById('warning').classList.add('hidden');
  }
};

/**
* Sets the filling of the squares of the board.
* @param {string} boardString Current state of the board.
*/
google.devrel.samples.ttt.setBoardFilling = function(boardString) {
  var buttons = document.querySelectorAll('td');
  for (var i = 0; i < buttons.length; i++) {
    var button = buttons[i];
    button.innerHTML = boardString.charAt(i);
  }
};

/**
* Checks for a victory condition.
* @param {string} boardString Current state of the board.
* @return {number} Status code for the victory state.
*/
google.devrel.samples.ttt.checkForVictory = function(boardString) {
  var status = google.devrel.samples.ttt.NOT_DONE;

  // Checks rows and columns.
  for (var i = 0; i < 3; i++) {
    var rowString = google.devrel.samples.ttt.getStringsAtPositions(
        boardString, i*3, (i*3)+1, (i*3)+2);
    status |= google.devrel.samples.ttt.checkSectionVictory(rowString);

    var colString = google.devrel.samples.ttt.getStringsAtPositions(
      boardString, i, i+3, i+6);
    status |= google.devrel.samples.ttt.checkSectionVictory(colString);
  }

  // Check top-left to bottom-right.
  var diagonal = google.devrel.samples.ttt.getStringsAtPositions(boardString,
      0, 4, 8);
  status |= google.devrel.samples.ttt.checkSectionVictory(diagonal);

  // Check top-right to bottom-left.
  diagonal = google.devrel.samples.ttt.getStringsAtPositions(boardString, 2,
      4, 6);
  status |= google.devrel.samples.ttt.checkSectionVictory(diagonal);

  if (status == google.devrel.samples.ttt.NOT_DONE) {
    if (boardString.indexOf('-') == -1) {
      return google.devrel.samples.ttt.TIE;
    }
  }

  return status;
};

/**
* Checks whether a set of three squares are identical.
* @param {string} section Set of three squares to check.
* @return {number} Status code for the victory state.
*/
google.devrel.samples.ttt.checkSectionVictory = function(section) {
  var a = section.charAt(0);
  var b = section.charAt(1);
  var c = section.charAt(2);
  if (a == b && a == c) {
    if (a == 'X') {
      return google.devrel.samples.ttt.WON;
    } else if (a == 'O') {
      return google.devrel.samples.ttt.LOST
    }
  }
  return google.devrel.samples.ttt.NOT_DONE;
};

/**
* Handles the end of the game.
* @param {number} status Status code for the victory state.
*/
google.devrel.samples.ttt.handleFinish = function(status) {
  var victory = document.getElementById('victory');
  if (status == google.devrel.samples.ttt.WON) {
    victory.innerHTML = 'You win!';
  } else if (status == google.devrel.samples.ttt.LOST) {
    victory.innerHTML = 'You lost!';
  } else {
    victory.innerHTML = 'You tied!';
  }
  google.devrel.samples.ttt.sendResultToServer(status);
};

/**
* Gets the current representation of the board.
* @return {string} Current state of the board.
*/
google.devrel.samples.ttt.getBoardString = function() {
  var boardStrings = [];
  var buttons = document.querySelectorAll('td');
  for (var i = 0; i < buttons.length; i++) {
    boardStrings.push(buttons[i].innerHTML);
  }
  return boardStrings.join('');
};

/**
* Gets the values of the board at the given positions.
* @param {string} boardString Current state of the board.
* @param {number} first First element to retrieve.
* @param {number} second Second element to retrieve.
* @param {number} third Third element to retrieve.
*/
google.devrel.samples.ttt.getStringsAtPositions = function(boardString, first,
    second, third) {
  return [boardString.charAt(first),
          boardString.charAt(second),
          boardString.charAt(third)].join('');
};

/**
* Initializes the application.
* @param {string} apiRoot Root of the API's path.
*/
google.devrel.samples.ttt.init = function(apiRoot) {
  // Loads the OAuth and Tic Tac Toe APIs asynchronously, and triggers login
  // when they have completed.
  var apisToLoad;
  var callback = function() {
    if (--apisToLoad == 0) {
      google.devrel.samples.ttt.signin(true,
          google.devrel.samples.ttt.userAuthed);
    }
  }

  apisToLoad = 2; // must match number of calls to gapi.client.load()
  gapi.client.load('tictactoe', 'v1', callback, apiRoot);
  gapi.client.load('oauth2', 'v2', callback);

  var buttons = document.querySelectorAll('td');
  for (var i = 0; i < buttons.length; i++) {
    var button = buttons[i];
    button.addEventListener('click', google.devrel.samples.ttt.clickSquare);
  }

  var reset = document.querySelector('#restartButton');
  reset.addEventListener('click', google.devrel.samples.ttt.resetGame);
};
Something went wrong with that request. Please try again.