PROJECT 1: Tic-Tac-Toe

Objective: Build a browser game

Tools: HTML, CSS, JavaScript

Laying the Foundations

Our first project was to build a functioning game of Tic-Tac-Toe in the browser. All we had at this point was basic HTML, CSS, and JavaScript. Although I had done some coding before SEB71, I still felt quite inexperienced, especially with JavaScript which, funnily enough, was going to be the main focus.

I knew roughly at this point what each language did: HTML made up the actual page that was going to be displayed, CSS was for styling all the HTML elements, and JavaScript could... do things?

Eh, good enough to start the project.

Alright so maybe it wasn't that bad. I understood that JavaScript could be used to make and run functions which, yeah, basically just do things. Still, it took me a while to decide how to begin. Eventually, I figured that if I wanted to play Tic-Tac-Toe, I had to go and draw the grid first so that was what I started with.


                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <link rel="icon" type="image/x-icon" href="images/tic-tac-toe.ico">
                    <title>Tic-Tac-Toe</title>
                    <link rel="stylesheet" href="style.css">
                    <link rel="preconnect" href="https://fonts.googleapis.com">
                    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
                    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Special+Elite&display=swap">
                </head>
                <body>
                    <div class="bg-image"></div>
                    <header>Tic-Tac-Toe</header>
                    <div class="game-wrapper">
                        <aside class="scoreboard">❌ Player 1 Score ❌ <span class="score-counter">0</span></aside>
                        <div class="board">
                            <div class="tileEmpty"></div>
                            <div class="tileEmpty"></div>
                            <div class="tileEmpty"></div>
                            <div class="tileEmpty"></div>
                            <div class="tileEmpty"></div>
                            <div class="tileEmpty"></div>
                            <div class="tileEmpty"></div>
                            <div class="tileEmpty"></div>
                            <div class="tileEmpty"></div>
                        </div>
                        <aside class="scoreboard">⭕ Player 2 Score ⭕<span class="score-counter">0</span></aside>
                    </div>
                    <h3 class="message-text">"Player 1, click a tile to begin!"</h3>
                    <div class="buttons-div">
                        <button class="trivia-btn">Trivia</button>
                        <button class="new-round-btn">New Round</button>
                        <button class="reset-btn">Reset</button>
                    </div>
                    <p class="trivia-paragraph">Did you know: <span class="trivia-content">
                    You can press the trivia button to learn something new about Tic-Tac-Toe!
                    </span></p>
                    <script src="app.js"></script>
                </body>
                </html>
                
And so it begins...

This may be the only time my HTML is short enough to explain in full:

  • The header is for my Tic-Tac-Toe title,
  • the whole grid and sideboards are wrapped together by a div with the class game-wrapper,
  • my grid is just 9 divs inside a board div,
  • the scoreboards are just two asides before and after the board,
  • 3 buttons for the, well, buttons
  • and a h3 for my game message and a p for my trivia paragraph

The only odd thing out is the bg-image div at the very top. That's definitely a leftover from an unused idea that I'll go into later. Seems quite straightforward but mind you, this is just the HTML without the styling. Witness it in all it's natural glory below...

Yep. If that's Tic-Tac-Toe, then I'm a gorgeous supermodel.

Time for some CSS.


                * {
                    box-sizing: border-box;
                    margin: 0px 0px;
                }
                
                body {
                    background-color: bisque;
                    font-family: "Special Elite", system-ui;
                    font-weight: 400;
                    font-style: normal;
                }
                
                .game-wrapper {
                    max-width: 80%;
                    margin: 0 auto;
                    text-align: center;
                    display: grid;
                    grid-template-columns: 1fr 1fr 1fr;
                }
                
                aside.scoreboard {
                    margin: auto 0;
                    font-size: 1.1rem;
                }
                
                .score-counter {
                    display: block;
                    padding: 60px;
                    font-size: 2rem;
                }
                
                .message-text {
                    margin: 20px auto;
                    display: block;
                    max-width: 50%;
                    text-align: center;
                    color: black;
                }
                
                header {
                    font-size: 3rem;
                    padding: 20px;
                    text-align: center;
                }
                
                .board {
                    display: grid;
                    grid-template-columns: 1fr 1fr 1fr;
                    margin: 0 auto;
                    overflow: hidden;
                }
                
                .board div {
                    height: 100px;
                    width: 100px;
                    outline: 1px solid;
                }
                
                .tileO {
                    background-image: url(images/o.png);
                    background-size: cover;
                }
                
                .tileX {
                    background-image: url(images/x.png);
                    background-size: cover;    
                }
                
                .buttons-div {
                    max-width: 50%;
                    margin: 0 auto;
                    text-align: center;
                }
                
                button {
                    font-family: "Special Elite", system-ui;
                    padding: 10px;
                    background-color: black;
                }
                
                .trivia-btn {
                    color: blue;
                }
                
                .new-round-btn {
                    color: green;
                }
                
                .reset-btn {
                    color: red;
                }
                
                .trivia-paragraph {
                    line-height: 1.5;
                    margin: 20px auto;
                    display: block;
                    max-width: 50%;
                }
                  
Ah, where I began my love-hate relationship with CSS. Mostly hate.

A lot of stuff is fairly self-explanatory so I'll stick to the interesting ones. Of note is all the grid styling I did:


                    .game-wrapper {
                        max-width: 80%;
                        margin: 0 auto;
                        text-align: center;
                        display: grid;
                        grid-template-columns: 1fr 1fr 1fr;
                    }
                    
                    .board {
                        display: grid;
                        grid-template-columns: 1fr 1fr 1fr;
                        margin: 0 auto;
                        overflow: hidden;
                    }
                    
                    .board div {
                        height: 100px;
                        width: 100px;
                        outline: 1px solid;
                    }
                      

So to begin with, the two sideboards are arranged in a 3 column grid with the actual board grid. Then the board grid itself is also a 3 columnn grid, each column having 3 tile divs. The tiles were also given some height and width. Otherwise, they wouldn't make any shape, which is the reason why the pure HTML has nothing resembling a Tic-Tac-Toe board.

Lastly, and probably most interesting, is the overflow: hidden in the board styling. This is what's getting rid of all the outer borders of the board, leaving it looking like a hash tag. The way this works - but don't quote me on this - is because the borders flow outside the div by nature of being borders, meaning they get hidden. Whatever it is, it's not something I would have worked out without looking it up.

Regardless, I think it all looks much better now...

The Function Revolution

Great, so the site looks alright now but we still can't play yet. Right now, it's all purely aesthetic. Even the buttons don't do anything. This is where JavaScript comes in:


                let isPlayerOne = true
                let concluded = false
                let playerMoves = 0
                let playerOneScore = 0
                let playerTwoScore = 0
                let triviaIndex = 0

                const tileArray = document.querySelectorAll('.tileEmpty')

                for (tile of tileArray) {
                    tile.addEventListener('click', playerMove)
                }

                function playerMove(event) {
                    let targetTile = event.target
                    if (targetTile.classList.contains('tileEmpty')) {
                        if (isPlayerOne) {
                            targetTile.classList = 'tileX'
                            isPlayerOne = false
                            mainMessage.textContent = "Player 2's turn!"
                        } else {
                            targetTile.classList = 'tileO'
                            isPlayerOne = true
                            mainMessage.textContent = "Player 1's turn!"
                        }
                    }
                    playerMoves++
                    checkVictory()
                }

                function checkVictory() {
                    if (playerMoves >= 5) {
                        scanRows()
                        scanColumns()
                        scanDiagonals()
                        if (playerMoves === 9 && !concluded) {
                            mainMessage.textContent = "It's a draw!"
                            concluded = true
                        } else if (concluded) {
                            mainMessage.textContent = `${winner} has won!`
                        }
                    }
                }
            

This is just a snippet of my surprisingly verbose code but it's where almost all the game logic is. Anything relevant to the state of the game, like player scores and who's turn it is, are all kept track of in variables. From here, it's just assigning functions to elements that need to do things when clicked. The key methods for this were document.querySelector and the similar document.querySelectorAll. This allowed me to select certain elements like the empty tiles on the grid, which was stored as an array under tileArray. With all the tiles selected, I could then let them detect if they were clicked through the addEventListener method.

At this point, if any of the tiles were clicked, the clicked tile would run the assigned function playerMove(). This function takes the tile itself as its target and checks its class. If it is empty, it checks to see which player's turn it is and then changes the tile's class to the current player's symbol, filling it with an X or O.

If you notice, I am also checking whether a player has won with every single move they make through the checkVictory() function. However, it only goes through with the rest of its code if the minimum number of moves for a victory have been made to save computing power. The way I actually check for a victory is through 3 functions which each scan every possible winning row, column, or diagonal:


                function scanRows() {
                    if (!concluded) {
                        i = 0
                        let rowArray = []
                
                        while (i < 7 && !concluded) {
                            rowArray = [];
                            let tile1 = tileArray[i].classList
                            let tile2 = tileArray[i+1].classList
                            let tile3 = tileArray[i+2].classList
                            rowArray.push(tile1,tile2,tile3)
                
                            if (!tile1.contains('tileEmpty')) {
                                if (rowArray.every(checkClassX)) {
                                    playerOneVictory()
                                } else if (rowArray.every(checkClassO)) {
                                    playerTwoVictory()
                                } else {
                                    i += 3
                                }
                            } else {
                                i += 3
                            }
                        }
                    }
                }
                
                function scanColumns() {
                    if (!concluded) {
                        i = 0
                        let columnArray = []
                
                        while (i < 3 && !concluded) {
                            columnArray = []
                            let tile1 = tileArray[i].classList
                            let tile2 = tileArray[i+3].classList
                            let tile3 = tileArray[i+6].classList
                            columnArray.push(tile1,tile2,tile3)
                
                            if (!tile1.contains('tileEmpty')) {
                                if (columnArray.every(checkClassX)) {
                                    playerOneVictory()
                                } else if (columnArray.every(checkClassO)) {
                                    playerTwoVictory()
                                } else {
                                    i++
                                }
                            } else {
                                i++
                            }
                        }
                    }
                }
                
                function scanDiagonals() {
                    let middleTile = tileArray[4].classList
                    let firstDiagonal = [
                        tileArray[0].classList,
                        middleTile,
                        tileArray[8].classList,
                    ]
                
                    let secondDiagonal = [
                        tileArray[2].classList,
                        middleTile,
                        tileArray[6].classList,
                    ]
                
                    if (!middleTile.contains('tileEmpty')) {
                        if (firstDiagonal.every(checkClassX) || secondDiagonal.every(checkClassX)) {
                            playerOneVictory()
                        } else if (firstDiagonal.every(checkClassO) || secondDiagonal.every(checkClassO)) {
                            playerTwoVictory()
                        }
                    }
                }
            

There might be better ways to check for a victory, and yeah most of my classmates had different methods, but it does work for my purposes. Of course, if any of these functions return a true result (i.e. there's a three-in-a-row somewhere) then the round concludes and the winning player's score is incremented. If the players want to continue, then there are buttons for a new round or a whole new game, both of which simply set things back to the way they were. That's really all there is to the code for Tic-Tac-Toe: letting elements 'listen' for clicks and then doing stuff to change things.

What could have been...

Remember how I had that leftover bg-image div? The reason why it was there was because I wanted to go for a 'history' theme. The background would change depending on how the game was going (e.g. going from Ancient Egypt to Ancient Rome as the board filled up). Everyone else was doing Tic-Tac-Toe too so everyone figured that they needed to do something unique and this was my idea. Unfortunately, I couldn't figure out how to make the game UI fit nicely with the wildly different backgrounds and also I did not have the time or willpower to do something like this for my first project, especially one that wasn't graded on aesthetics.

Instead, I made a compromise and included a trivia button. All it does it cycle through an array of Tic-Tac-Toe trivia that I picked up from Wikipedia and displays it on the web page. I only wish I could have made it cooler somehow.


                let triviaIndex = 0

                const triviaBtn = document.querySelector('.trivia-btn')

                triviaBtn.addEventListener('click', handleTrivia)

                let triviaContent = document.querySelector('.trivia-content')
                
                const triviaArray = [
                    "The earliest recorded games of Tic-Tac-Toe date back to 1300 BC in Ancient Egypt, played on roof tilings of all things.",
                    "There was a variation of Tic-Tac-Toe that the Romans played. It was called terni lapilli and each player only had three counters which they had to keep moving around.",
                    "No one is really sure where the name Tic-Tac-Toe came from. The first time the name was used was in the 1880s, apparently from the sounds pencils made when you drew the symbols.",
                    "Alternative names for Tic-Tac-Toe include 'Noughts and Crosses' and 'Xs and O's'. Some weirdos may also call it 'Tick-Tat-Toe' or 'Tit-Tat-Toe'.",
                    "Tic-Tac-Toe was one of the first video games ever created, under the name OXO in 1952. Players could even play, and lose, against a computer player.",
                    "In 1975, an entire computer capable of playing Tic-Tac-Toe was made out of Tinkertoys - basically sets of colorful sticks and strings for little kids. Still better than my gaming setup.",
                    "Tic-Tac-Toe is a classic example of a 'solved game' and in its case, a 'futile game'. Assuming both players have a functional brain, the game will always be forcibly ended in a tie.",
                    "Because of its simplicity, Tic-Tac-Toe is often used as a teaching tool for kids to learn things like sportsmanship. Perhaps some gamers would stand to benefit from playing a bit more Tic-Tac-Toe."
                ]

                function handleTrivia() {
                    //let randomTriviaIndex = Math.floor(Math.random() * triviaArray.length)
                    triviaContent.textContent = triviaArray[triviaIndex]
                    triviaIndex++
                    if (triviaIndex === triviaArray.length) {
                        triviaIndex = 0
                    }
                }
                
Does anyone even read anymore?

Anyway, that’s it for Tic-Tac-Toe! Feel free to move on to my other projects: Project 2: GameShare™, Project 3: Petrol Down Under, or Project 4