In the previous post we made the markup and applied some styles to our Dragons vs Unicorns game app. Now itβs time to implement the game logic in JavaScript. This part is what makes the game playful. First, we reference the html elements for accessing them more easily.
You can play the live version here: https://pedropcamellon.github.io/tic-tac-toe/; or you can check the repo here: https://github.com/pedropcamellon/tic-tac-toe.
forEach
, some
and every
array methods.prepend
to insert an HTML element before another.img
element src
and alt
properties.contains
method....
).We begin by referencing the HTML elements we defined in the part I of this series. Here we used the id tags we assigned in the index.html to save the values of all the board elements, winning message and the restart button. For this we used the JavaScript method getElementById().
For the winning message text element, we are going the querySelector() method which returns the first element within the document that matches the specified selector.
const board = document.getElementById("board");
const cells = document.querySelectorAll("[data-cell]");
const currentStatus = document.getElementById("currentStatus");
const resetButton = document.getElementById("resetButton");
const gameEndOverlay = document.getElementById("gameEndOverlay");
const currentBeastStatusImg = document.getElementById("currentBeastImg");
const winningMessage = document.querySelector("[data-winning-message]");
const winningMessageText = document.querySelector("[data-winning-message] p");
const winningMessageImg = document.createElement("img");
This holds an <img>
element for showing the winner image when the game ends.