123

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
                <div class="container-fluid">

      <div class="board-container">
        <div class="row">
          <h1>Tic Tac Toe</h1>
          <button id="launch" type="button" name="button">Start Game</button>
          <button id="reset" type="button">Reset Game</button>
        </div>
        <div class="row">
          <div id="0" class="cell"></div>
          <div id="1" class="cell"></div>
          <div id="2" class="cell"></div>
        </div>
        <div class="row">
          <div id="3" class="cell"></div>
          <div id="4" class="cell"></div>
          <div id="5" class="cell"></div>
        </div>
        <div class="row">
          <div id="6" class="cell"></div>
          <div id="7" class="cell"></div>
          <div id="8" class="cell"></div>
        </div>
        <div class="row">
          <h2 class="feedback"></h2>
        </div>
      </div>
    </div>

            
          
!
            
              
* {
 /*border: 1px red dashed;*/
}



body {
    margin: 0; padding: 0;
    background: rgba(255, 0, 189, 0.33);
}

header {
    background: #999;
    color: white;
    padding: 15px 15px 0 15px;
}

header h1 {
    margin: 0;
    display: inline;
}



button {
    margin-bottom: 30px;
    margin-top: 30px;
}

.row {
    margin: 0; padding: 0;
    align: center;
}

.board-container {
    width: 500px;
    margin: 0 auto; padding: 0;
}


.board-container .cell {
    display: inline-block;
    margin: 0; padding: 0;
    width: 100px; height: 100px;
    text-align: center;
    background: lightgreen;
    font-size: 70px;
    border: 2px solid black;
    float: left;



}

footer {
    clear: both;
}

            
          
!
            
              // TicTacToe

// User Story: I can choose whether I want to play as X or O.
// User Story: I can play a game of Tic Tac Toe with the computer.
// User Story: My game will reset as soon as it's over so I can play again.


//'use strict';  // Recommended as best practice, but disabled as issues with jshint stating "$ is not defined"

var playerSymbol = "";
var computerSymbol = "";
var winner = false;     // QUESTION: does this need to be global? is this the right thing to do?

var board = [];

var availableCells = [0, 1, 2, 3, 4, 5, 6, 7, 8];
// board positions match the array positions:
// 0 1 2
// 3 4 5
// 6 7 8

var winningPlays = [
    [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 askPlayerToChooseXorO() {
    var playerInput = prompt("Would you like to be x or o?", "X or O").toUpperCase();
    while (playerInput !== 'X' && playerInput !== 'O') {
        playerInput = prompt("Invalid answer: Would you like to be x or o?", "X or O").toUpperCase();
    }
    return playerInput;
}

function setComputerSymbol(playerSymbol) {
    if (playerSymbol === 'X') {
        return 'O';
    } else if (playerSymbol === 'O') {
        return 'X';
    }
}

function getRandomAvailableCell(availableCells) {
    return availableCells[Math.floor(Math.random() * availableCells.length)];
}

function computerTurn(availableCells, board) {
    // TODO: enter a short delay to mimick some computer thinking before computer chooses a square
    console.log('board before: ' + board);
    console.log('availableCells before splice: ' + availableCells);

    // choose a random available cell
    var cellChoice = getRandomAvailableCell(availableCells);
    // update board with cellChoice
    board[cellChoice] = computerSymbol;
    $("#"+cellChoice).html(computerSymbol);

    // update availableCells array
    availableCells.splice( availableCells.indexOf(cellChoice), 1);


    console.log('board after: ' + board);
    console.log('availableCells after splice: ' + availableCells);
    console.log( checkWinner(board, computerSymbol, playerSymbol) );
}


function checkWinner(board, computerSymbol, playerSymbol) {  // QUESTION: if the args here are globals, do we still need to pass them in, or can we just leave them out? Think the Functional style would say to pass them in so that the function stays pure?
    for (var i = 0; i < winningPlays.length; i++) {
        if ( board[ winningPlays[i][0] ] === computerSymbol &&
             board[ winningPlays[i][1] ] === computerSymbol &&
             board[ winningPlays[i][2] ] === computerSymbol ) {
                 winner = 'Computer';
                 $(".feedback").html('Computer Wins... you moron!');
        } else if ( board[ winningPlays[i][0] ] === playerSymbol &&
                    board[ winningPlays[i][1] ] === playerSymbol &&
                    board[ winningPlays[i][2] ] === playerSymbol ) {
                 winner = 'Player';        // QUESTION: Is there a better way to do the winner and break out of the loop?
                 $(".feedback").html('You win, you beat a computer that has zero artificial intelligence; you should be proud!');
        } else if (availableCells.length === 0 && !winner) {
        // TODO: Extract to an isTie function?
        $(".feedback").html("It's a tie, pathetic!"); //TODO: extract to a renderResult function.
        }
    }
}

function resetBoard() {
    playerSymbol = "";
    computerSymbol = "";
    winner = false;
    board = [];
    availableCells = [0, 1, 2, 3, 4, 5, 6, 7, 8];
    $(".cell").html("");
    $(".feedback").html("");
}


$('document').ready(function(){

    // Wait for player to click Launch Game button, then set the X and O
    $('#launch').click(function() {
        if (playerSymbol === "") {
            playerSymbol = askPlayerToChooseXorO();
            console.log('Player chooses: ' + playerSymbol);
            computerSymbol = setComputerSymbol(playerSymbol);
            console.log('Computer Symbol: ' + computerSymbol);

            // This permits computer to start the game. Omit this to allow user to start first.
            computerTurn(availableCells, board, computerSymbol);
        }
    });

    // Wait for a player click, then run one iteration of the game
    $(".cell").click(function() {
        if (!winner && playerSymbol !== "") {
            // TODO: Extract player bit to it's own playerTurn function
            var cellChoice = parseInt($(this).attr('id'));
            if ( availableCells.includes(cellChoice) ){
                $(this).html(playerSymbol);
                // update board with player cellChoice
                board[cellChoice] = playerSymbol;
                // update availableCells array
                availableCells.splice( availableCells.indexOf(cellChoice), 1);
                checkWinner(board, computerSymbol, playerSymbol);
                computerTurn(availableCells, board);
            }

        }
    });

    // Reset Game
    $("#reset").click(resetBoard);

});  // end document ready

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console