Membuat Tic Tac Toe Game JavaScript HTML CSS

5 Desember 2022
Membuat Tic Tac Toe Game JavaScript HTML CSS

Sharing Teknologi – Membuat Tic Tac Toe Game JavaScript HTML CSS Di WordPress. Apakah Sobat teknologi[dot]visitklaten[dot]com ingin Membuat Tic Tac Toe Game Menggunakan JavaScript HTML CSS Di WordPress. 

Membuat Tic Tac Toe Game JavaScript HTML CSS

CSS adalah singkatan dari Cascading Style Sheets yang terdapat 3 versi yaitu CSS1, CSS2, dan CSS3. CSS adalah suatu aturan untuk mengatur beberapa komponen di dalam sebuah web sehingga membuat lebih terstruktur dan seragam.

CSS3 merupakan versi CSS terbaru yang bisa melakukan banyak hal terkait desain website. CSS3 mampu membuat animasi warna sampai animasi 3D di halaman website.

CSS sangat membantu untuk mempercantik tampilan website seperti dengan memberi warna, box shadow, padding, margin, align, posisi, dan efek pengetikan atau typing effect .

HTML (Hypertext markup language) adalah sebuah bahasa markah (markup language) yang paling mendominasi saat ini dalam hal pembuatan sebuah website.

Dengan adanya HTML, maka sebuah website bisa dikreasikan sedemikian rupa menjadi lebih interaktif dan menarik. Karena HTML memadukan berbagai elemen seperti teks, multimedia, dan link, dan juga elemen pendukung lainnya menjadi sebuah kesatuan.

Sebelumnya kami mengucapkan banyak terima kasih kepada para pengunjung teknologi[dot]visitklaten[dot]com yang rela meluangkan waktu untuk mengunjungi ataupun sekedar melihat-lihat web kami yang masih banyak kekurangan ini. Kami menerima segala masukkan dan kritikan agar web dan diri kami menjadi lebih baik lagi..

Di kesempatan kali ini, kami akan berbagi tutorial Membuat Tic Tac Toe Game Menggunakan JavaScript HTML CSS. 

NB: kami menggunakan tambahan CSS dari bootstrap.

Membuat Tic Tac Toe Game

Silakan Copas kode dibawah ini. Rekan-rekan bisa mengubahnya sesuai kebutuhan. Silakan nanti bisa disesuaikan dengan kebutuhan.

HTML

<div class="malibubeach position-relative px-3 py-5 my-1 tictactogame overflow-auto">
    <div class="playerSelection">
      <h4>What do you want to be?</h4>
      <div>✕</div>
      <div>O</div>
    </div>
    
    <div class="board">
      <div id="1" class="top left"></div>
      <div id="2" class="top"></div>
      <div id="3" class="top right"></div>
      <div id="4" class="left"></div>
      <div id="5" class=""></div>
      <div id="6" class="right"></div>
      <div id="7" class="bottom left"></div>
      <div id="8" class="bottom"></div>
      <div id="9" class="bottom right"></div>
    </div>
    
    <div class="displayResult">
      <h4 id="winner">It's a tie.</h4>
      <div id="playAgain">Play again?</div>
    </div>
</div>

 

CSS

.tictactogame .playerSelection {
  width: 400px;
  margin: 5% auto;
  border-radius: 1px;
  text-align: center;
}

.tictactogame .playerSelection h4 {
  font-weight: 300;
  margin-bottom: 40px;
}

.tictactogame .playerSelection div {
  display: inline-block;
  padding: 30px 50px;
  font-size: 35px;
  border-radius: 2px;
  cursor: pointer;
}

.tictactogame .playerSelection div:hover {
  background-color: #FFF;
  color: #222;
}

.tictactogame .board {
  width: 500px;
  text-align: center;
  margin: 4% auto;
  display: none;
}

.tictactogame .board div {
  display: inline-block;
  width: 160px;
  height: 120px;
  font-size: 60px;
  cursor: pointer;
  margin: -4px;
  vertical-align: middle;
  padding-top: 45px;
}

.tictactogame .top {
  border-bottom: 2px solid #FFF;
}

.tictactogame .left {
  border-right: 2px solid #FFF;
}

.tictactogame .right {
  border-left: 2px solid #FFF;
}

.tictactogame .bottom {
  border-top: 2px solid #FFF;
}


/*
** Match result
*/

.tictactogame .displayResult {
  width: 400px;
  margin: 5% auto;
  border-radius: 1px;
  text-align: center;
  display: none;
}

.tictactogame .displayResult h4 {
  font-weight: 300;
  margin-bottom: 40px;
  font-size: 50px;
}

.tictactogame .displayResult div {
  display: inline-block;
  padding: 20px;
  font-size: 25px;
  border-radius: 2px;
  cursor: pointer;
  background-color: #FFF;
  color: #222;
}

.tictactogame .displayResult div:hover {
  background-color: #DDD;
}

 

JavaScript

jQuery(document).ready(function ($) {
"use strict";
// Cross - ✕
// Circle - O

var selectionDiv = document.getElementsByClassName('playerSelection')[0],
  board = document.getElementsByClassName('board')[0],
  user, computer;

// initial box to ask for user's preference - if we wants "x" or "o"
selectionDiv.addEventListener("click", function(e) {

  if (e.target.innerHTML === "✕" || e.target.innerHTML === "O") {

    user = e.target.innerHTML;

    computer = (user === "✕") ? "O" : "✕"; // setting computer's symbol to compliment of user's symbol
    document.getElementById("1").innerHTML = computer; // filling the first box with computer's move

    // hiding selection panel and displaying playing baord	
    selectionDiv.style.display = "none";
    board.style.display = "block";

  }
});

/**\
 ** =============================
 ** ====Main Game Logic =========
 ** =============================
\**/

// these are the only ways in which a user can win
// every time we compare user's and computer's array with this
var winningMoves = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
    [1, 4, 7],
    [2, 5, 8],
    [3, 6, 9],
    [1, 5, 9],
    [3, 5, 7]
  ],
  userMoves = [], // array for storing user's moves
  computerMoves = [1], // array for storing computer's moves - one is already filled
  resultDiv = document.getElementsByClassName('displayResult')[0],
  winner = document.getElementById('winner'),
  playAgain = document.getElementById('playAgain');

// if a user clicks then check if the cell is empty
// if it is then fill it and decide computer's moce by calling nextComputerMove()
board.addEventListener("click", function(e) {
  var clickedBox = parseInt(e.target.getAttribute('id'));
  if (e.target.innerHTML === "") {
    e.target.innerHTML = user;
    userMoves.push(clickedBox);

    // after every move checking to see if game is over or not
    if (isGameOver(userMoves)) {
      displayResult("You");
      return;
    }
    nextComputerMove(clickedBox);
  }
});

// function to decide computer's move randomly
function nextComputerMove(num) {
  var move = Math.floor(Math.random() * 9 + 1);
  if (userMoves.indexOf(move) === -1 && computerMoves.indexOf(move) === -1) {
    setTimeout(function() {
      document.getElementById(String(move)).innerHTML = computer;
      computerMoves.push(move);

      // after every move checking to see if game is over or not
      if (!isGameOver(computerMoves) && userMoves.length + computerMoves.length >= 9) {
        board.style.display = "none";
        resultDiv.style.display = "block";
      } else if (isGameOver(computerMoves)) {
        displayResult("Computer");
        return;
      }
    }, 500);
    return;
  } else {
    nextComputerMove(num); // need to keep calling this function untill an empty cell is found
  }
}

// function to check if the game is over
// comparing user and computer array with eleemnts of winning array
function isGameOver(arr) {
  for (var i = 0; i < winningMoves.length; i++) {
    var count = 0;
    for (var j = 0; j < winningMoves[i].length; j++) {
      if (arr.indexOf(winningMoves[i][j]) !== -1) {
        count++;
      }
    }
    if (count === 3) {
      console.log(winningMoves[i]);
      return true;
    }
  }
  return false;
}

// displaying result
function displayResult(result) {
  board.style.display = "none";
  resultDiv.style.display = "block";
  winner.innerHTML = result + " won."
}

// relaoding window on click of 'play again' button
playAgain.addEventListener('click', function() {
  window.location.href = location.href;
});
});

 

Hasil

Tampilannya kurang lebih bisa dilihat dibawah ini.

What do you want to be?

✕
O

It's a tie.

Play again?

 

Terima kasih telah mengunjungi website kami.

Share jika bermanfaat, jika ada kritik, tambahan, pertanyaan atau saran silakan hubungi kami atau silakan isi di kolom komentar.

Referensi :
codepen.io/lalwanivikas/pen/xVBBBN

Postingan Terkait

Komentar

Leave a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

Scroll to Top