Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create tic-tac-toe games with HTML+CSS+JavaScript

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to create tic-tac-toe games with HTML+CSS+JavaScript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Implement HTML

First in the head section, I'll include the css and javascript files we'll create later. I also added a Google font called Itim.

The body of HTML will be fairly simple. To wrap everything, I'll use a main tag and apply a class background to it. Inside the main wrapper, we will have five parts.

The first part will contain only our title H2.

The second part will show whose turn it is now. In the display, we have a span that contains X or O depending on the current user. We apply the class to this span to color the text.

The third part is the part with the game board. It has a container class, so we can place the tiles correctly. In this section, we have nine div, which will act as tiles on the board.

The fourth part will be responsible for announcing the final results of the competition. It is empty by default, and we will modify its contents from javascript.

The last section will save our control with a restart button.

The round of tic-tac-toe player X starts adding CSS again.

I won't go through every line of CSS in detail, but you can see the complete code in the source code.

First, I'll create the style.css file and remove any browser-defined margins and padding, and set the Google font I included in HTML for the entire document.

* {padding: 0; margin: 0; font-family: 'Itim', cursive;}

The next important thing we have to add is the style of our board. We will use the CSS grid to create the slab. We can split the container in two by providing 3x 33% space for columns and rows. We will center the container margin: 0 auto; by setting the maximum width.

.container {margin: 0 auto; display: grid; grid-template-columns: 33% 33%; grid-template-rows: 33% 33%; max-width: 300px;}

Next, we will add the style of the tiles in the board. We will apply a small white border and set the minimum width and height to 100 pixels. We will leverage the central content of Flexbox and settings justify-content and align-items to center. We will give it a large font size and apply it, cursor: pointer so that the user will know that this field is clickable.

Tile {border: 1px solid white; min-width: 100px; min-height: 100px; display: flex; justify-content: center; align-items: center; font-size: 50px; cursor: pointer;}

I used two different colors to better distinguish the two players. To do this, I create two utility classes. Player X is green and player O is blue.

.playerX {color: # 09C372;} .playerO {color: # 498AFB;} implement the Javascript part

Because we include the javascript file in. This is necessary because our script will be loaded before the browser parses the HTML body. If you don't want to include everything in this function, feel free to add defer to the script tag or move the script tag to body.

Window.addEventListener ('DOMContentLoaded', () = > {})

First, we will save the reference to the DOM node. We will use document.querySelectorAll (). We want an array, but this function returns a NodeList, so we must use Array.from (). We will also get references to the player display, the reset button, and the announcer.

Const tiles = Array.from (document.querySelectorAll ('.tile')); const playerDisplay = document.querySelector ('.display-player'); const resetButton = document.querySelector (' # reset'); const announcer = document.querySelector ('.tile')

Next, we will add the global variables needed to control the game. We will initialize a board with an array of nine empty strings. This saves the X abd O value of each block on the board. We will have a currentPlayer logo that holds the active player in the current round. The isGameActive variable will remain true until someone wins or the game ends in a draw. In these cases, we set it to false so that the remaining blocks are inactive before they are reset. We have three constants that represent the end of the game. We use these constants to avoid spelling mistakes.

Let board = ['','','']; let currentPlayer ='X', let isGameActive = true;const PLAYERX_WON = 'PLAYERX_WON';const PLAYERO_WON =' PLAYERO_WON';const TIE = 'TIE'

In the next step, we will store all the winning positions on the chessboard. In each subarray, we will store the index of the three locations where we can win the game. So this [0,1,2] will represent the situation where the first horizontal line is occupied by the player. We will use this array to determine whether we have a winner.

/ * Indexes within the board [0] [1] [2] [4] [5] [6] [7] [8] * / const winningConditions = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]

Now we will write some practical functions. In the isValidAction function, we will determine whether the user wants to perform a valid action. If the internal text of tile is XorO, we return false as invalid operation, otherwise tile is empty so the operation is valid.

Const isValidAction = (tile) = > {if (tile.innerText ='X' | | tile.innerText ='O') {return false;} return true;}

The next utility function will be very simple. In this function, we will take an index as a parameter and set the corresponding element in the chessboard array to the symbol of our current player.

Const updateBoard = (index) = > {board [index] = currentPlayer;}

We will write a small function to deal with the changes of the player. In this function, we will first start from playerDisplay. The string template text player$ {currentPlayer} will become playerX or playerO depending on the current player. Next, we will use a ternary expression to change the value of the current player. If it is X, it will be O or it will be X. Now that we have changed the value of our users, we need to update innerText's playerDisplay and apply the new player class.

Const changePlayer = () = > {playerDisplay.classList.remove (`player$ {currentPlayer} `); currentPlayer = currentPlayer = ='X'? 'O': 'currentPlayer; playerDisplay.innerText = currentPlayer; playerDisplay.classList.add (`O' {currentPlayer} `);}

Now we will write the announer function that announces the final result of the game. It will receive the end game type and the innerText updates the announcer DOM node based on the result. In the last line, we must remove the hidden class because the announcer is hidden by default until the end of the game.

Const announce = (type) = > {switch (type) {case PLAYERO_WON: ceramic [XSS _ clean] = 'Player O Won'; break; case PLAYERX_WON: ceramic [XSS _ clean] =' Player X Won'; break; case TIE: announcer.innerText = 'Tie';} announcer.classList.remove (' hide');}

Next we will write one of the most interesting parts of the project-the result assessment. First, we will create a roundWon variable and initialize it to false. Then we will iterate through the winConditions array and check each winning condition on the chessboard. For example, in the second iteration, we will examine these values: board3, board4, board5.

We will also do some optimizations, and if any field is empty, we will call continue and skip to the next iteration, because if there are empty blocks in the winning condition, you will not be able to win. If all the fields are equal, then we have a winner, so we set roundWon to true and break the for loop, because any further iterations would waste computation.

After the loop, we will check the value of the roundWon variable, and if true, we will announce the winner and make the game inactive. If we do not have a winner, we will check whether there are empty cards on the chessboard, and if we do not have a winner and there are no empty cards, we will declare a draw.

Function handleResultValidation () {let roundWon = false; for (let I = 0; I {if (isValidAction (tile) & & isGameActive) {tile.innerText = currentPlayer; tile.classList.add (`player$ {currentPlayer} `); updateBoard (index); handleResultValidation (); changePlayer ();}}

In order for the game to work properly, we must add event listeners to Tile. We can do this by looping through an array of blocks and adding an event listener for each block. For better performance, we can only add an event listener to the container and use event bubbling to capture tile clicks on the parent, but I think this is easier for beginners to understand. )

Tiles.forEach ((tile, index) = > {tile.addEventListener ('click', () = > userAction (tile, index));})

We only missed one feature: reset the game. To do this, we will write a resetBoard function. In this function, we set the chessboard X to consist of nine empty strings, make the game active, remove the announcer, and change the player back (X always starts by definition).

The last thing we have to do is iterate through the block and set the innerText back to the empty string and remove any player-specific classes from the block.

Const resetBoard = () = > {board = [',',']; isGameActive = true; announcer.classList.add ('hide'); if (currentPlayer =' O') {changePlayer ();} tiles.forEach (tile = > {tile.innerText ='; tile.classList.remove ('playerX')) Tile.classList.remove ('playerO');});}

Now we just need to register this function as the click event handler for the reset button.

ResetButton.addEventListener ('click', resetBoard); this is the end of how HTML+CSS+JavaScript creates tic-tac-toe games. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report