Cara Membuat Game Match The Colors dengan JavaScript
Game match the color
Dengan bahasa pemrograman CSS dan JavaScript, kita dapat dengan mudah membuat game match the color. Game match the color disebut juga dengan game pencocokan warna. Lalu, bagaimana cara membuat game match the color dengan CSS dan JavaScript? Yuk buka komputer kamu, dan ikuti beberapa langkah di bawah ini.
Cara Membuat Game Match The Colors dengan JavaScript
1. Buka XAMPP Control Panel, serta aktifkan Apache.
2. Buka program teks editor yang ter-install di komputer kamu, disini saya menggunakan teks editor Notepad++. Ketikkan kode HTML5 berikut ini.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Raleway:300,400" rel="stylesheet"> <link rel="stylesheet" href="style.css"> <title>Membuat Game Match Color dengan JavaScript</title> </head> <body> <h1>Match the colors</h1> <div class="play-area"> <div class="computer-pane"> <div class="computer-circle"> <span class="color-to-match"></span> </div> </div> <div class="controls"> <h2>Move the sliders</h2> <span class="mobile-colorinfo">Red: 0, Green: 0, Blue: 0</span> <div class="color-details"> <span class="btn-change decrement">-</span> <span>Red: <span class="red-value color-value">0</span></span> <span class="btn-change increment">+</span> </div> <div class="mobile-controls"> <span class="mobile-decrement decrement-mobile">-</span> <input id="red" type="range" max="255" min="0" value="0" oninput="changeColor()"> <span class="mobile-decrement increment-mobile">+</span> </div> <div class="color-details"> <span class="btn-change decrement">-</span> <span>Green: <span class="green-value color-value">0</span></span> <span class="btn-change increment">+</span> </div> <div class="mobile-controls"> <span class="mobile-decrement decrement-mobile">-</span> <input id="green" type="range" max="255" min="0" value="0" oninput="changeColor()"> <span class="mobile-decrement increment-mobile">+</span> </div> <div class="color-details"> <span class="btn-change decrement">-</span> <span>Blue: <span class="blue-value color-value">0</span></span> <span class="btn-change increment">+</span> </div> <div class="mobile-controls"> <span class="mobile-decrement decrement-mobile">-</span> <input id="blue" type="range" max="255" min="0" value="0" oninput="changeColor()"> <span class="mobile-decrement increment-mobile">+</span> </div> <div class="game-buttons"> <button id="btn-match">Match</button> <button id="btn-end-game">Cheat</button> <button id="reset"><i class="fas fa-redo-alt"></i></button> </div> <div class="score-text"></div> </div> <div class="user-pane"> <div class="user-circle"> <p>Match Me!</p> </div> </div> </div> <script src="main.js"></script> </body> </html>
Simpan kode HTLM5 di atas di folder xampplite – htdocs – buat folder baru dengan nama MatchColors – simpan kode di atas dengan nama index.html.
3. Untuk melihat hasil script code di atas, kamu bisa buka browser kamu ketiklah http://localhost/MatchColors.
4. Ketikkan kode CSS berikut ini.
* { margin:0; padding:0; box-sizing: border-box; } body { font-family: "Raleway", sans-serif; font-size:16px; height:100vh; } h1 { text-align: center; padding:32px; text-transform: uppercase; font-weight: 300; display: flex; align-items: center; } h1::after, h1::before { display: flex; flex:1; content:""; height:1px; background:#222; margin:0 32px; } h2 { padding:32px; } .play-area { padding:24px; display:flex; justify-content: space-between; height:500px; } .user-circle, .computer-circle { border-radius:50%; border:2px solid black; height:400px; width:400px; margin:32px 0; display: flex; align-items: center; justify-content: center; } .user-circle { display:flex; align-items: center; justify-content: center; } .user-circle p { background:black; color:white; padding:8px 32px; } .controls { text-align: center; width:100%; padding:0 16px; } /* Sliders */ input[type="range"] { padding: 24px 0; } /* Style custom slider */ input[type=range] { -webkit-appearance: none; width: 100%; background: transparent; } input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; } input[type=range]:focus { outline: none; } input[type=range]::-ms-track { width: 100%; cursor: pointer; background: transparent; border-color: transparent; color: transparent; } /* The Slider Thumb */ input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; border: 1px solid #000000; height: 36px; width: 16px; border-radius: 3px; background: #ffffff; cursor: pointer; margin-top: -14px; } input[type=range]::-moz-range-thumb { border: 1px solid #000000; height: 36px; width: 16px; border-radius: 3px; background: #ffffff; cursor: pointer; } /* Slider - the track */ input[type=range]::-webkit-slider-runnable-track { width: 100%; height: 8.4px; cursor: pointer; background: #3071a9; border-radius: 1.3px; border: 0.2px solid #010101; } input[type=range]:focus::-webkit-slider-runnable-track { background: #367ebd; } input[type=range]::-moz-range-track { width: 100%; height: 8.4px; cursor: pointer; background: #3071a9; border-radius: 1.3px; border: 0.2px solid #010101; } input[type=range]::-ms-track { width: 100%; height: 8.4px; cursor: pointer; background: transparent; border-color: transparent; border-width: 16px 0; color: transparent; } input[type=range]::-ms-fill-lower { background: #2a6495; border: 0.2px solid #010101; border-radius: 2.6px; } input[type=range]:focus::-ms-fill-lower { background: #3071a9; } input[type=range]::-ms-fill-upper { background: #3071a9; border: 0.2px solid #010101; border-radius: 2.6px; } input[type=range]:focus::-ms-fill-upper { background: #367ebd; } /* Custom slider colors */ #red::-webkit-slider-runnable-track { background: red; } #red:focus::-webkit-slider-runnable-track { background: red; } #red::-moz-range-track { background: red; } #red::-ms-fill-lower { background: red; } #red:focus::-ms-fill-lower { background: red; } #red::-ms-fill-upper { background: red; } #red:focus::-ms-fill-upper { background: red; } /* Custom slider colors - Green */ #green::-webkit-slider-runnable-track { background: green; } #green:focus::-webkit-slider-runnable-track { background: green; } #green::-moz-range-track { background: green; } #green::-ms-fill-lower { background: green; } #green:focus::-ms-fill-lower { background: green; } #green::-ms-fill-upper { background: green; } #green:focus::-ms-fill-upper { background: green; } /* Custom slider colors - Blue*/ #blue::-webkit-slider-runnable-track { background: blue; } #blue:focus::-webkit-slider-runnable-track { background: blue; } #blue::-moz-range-track { background: blue; } #blue::-ms-fill-lower { background: blue; } #blue:focus::-ms-fill-lower { background: blue; } #blue::-ms-fill-upper { background: blue; } #blue:focus::-ms-fill-upper { background: blue; } /* Decrement and increment buttons */ .btn-change { padding:8px 16px; background:black; color:white; cursor:pointer; font-weight:normal; font-size:24px; display: flex; align-items: center; } .score-text, .color-to-match { padding:8px; font-size:32px; font-weight:bold; } .score-text { font-size:24px; } .game-buttons { display: flex; } #btn-match, #btn-end-game, #reset { height:42px; flex:2; background:lightblue; border:1px solid black; cursor: pointer; font-family:"Raleway", sans-serif; font-weight:bold; font-size:18px; margin: 4px; border-radius:8px; } #reset { flex:1; } #btn-match:focus, #btn-end-game:focus { outline:none; } .color-to-match { visibility: hidden; background:black; color:white; font-size:20px; } .blue-color { color:blue; } .red-color { color:red; } .green-color { color:green; } .color-value { display:inline-block; width:64px; font-weight:bold; } /* Color Details */ .color-details { display:flex; justify-content: space-around; align-items: center; } /* Cheated */ .cheated { background:red !important; color:#fff; font-size:20px; } /* Mobile Controls Hide */ .mobile-decrement { display:none; } .mobile-colorinfo { display:none; } /* Media Queries */ @media(max-width:1200px) { .user-circle, .computer-circle { border-radius:8px; height:400px; width:300px; } } @media(max-width:1024px) { .play-area { flex-direction: column; padding:0; } .user-circle, .computer-circle { height:120px; width:100%; border-radius:0; padding:0; margin:0; } h1 { padding:16px; font-size:24px; font-weight: bold; } h2 { font-size:20px; padding:20px; } .score-text { font-size:16px; } .color-details { display:none; } .mobile-controls { display:flex; align-items: center; margin:4px 0; } .mobile-decrement { display:flex; align-items: center; justify-content: center; font-size:32px; font-weight:bold; border-radius:16px; border:1px solid black; padding:4px 16px; margin:0 8px; color:#000; cursor:pointer; } .mobile-colorinfo { display:block; } }
Simpan kode CSS di folder xampplite – htdocs – buat folder baru dengan nama MatchColors– simpan code CSS dengan nama style.css.
5. Reload alamat url : http://localhost/MatchColors. Tampilan awal game match the colors, namun warna dalam game belum muncul.
6. Untuk menampilkan warna dalam game, buka kembali text editor dan ketikkan kode JavaScript berikut.
const computerCircle = document.querySelector(".computer-circle"); const userCircle = document.querySelector(".user-circle"); const btnMatch = document.getElementById("btn-match"); const red = document.getElementById("red"); const green = document.getElementById("green"); const blue = document.getElementById("blue"); const redValue = document.querySelector(".color-details .red-value"); const greenValue = document.querySelector(".color-details .green-value"); const blueValue = document.querySelector(".color-details .blue-value"); const decrement = document.querySelectorAll(".decrement"); const increment = document.querySelectorAll(".increment"); const decrementMobile = document.querySelectorAll(".decrement-mobile"); const incrementMobile = document.querySelectorAll(".increment-mobile"); const mobileColorInfo = document.querySelector(".mobile-colorinfo"); const scoreText = document.querySelector(".score-text"); const endGame = document.getElementById("btn-end-game"); const colorToMatch = document.querySelector(".color-to-match"); const resetBtn = document.getElementById("reset"); // Initialize function init() { let r = Math.floor(Math.random() * 255) + 1; let g = Math.floor(Math.random() * 255) + 1; let b = Math.floor(Math.random() * 255) + 1; computerColor = "<span class='red-color'>Red: " + r + ",</span> <span class='green-color'>Green: " + g + ",</span> <span class='blue-color'>Blue: " + b + "</span>"; computerCircle.style.backgroundColor = "rgb(" + r + ", " + g + ", " + b + ")"; userCircle.style.backgroundColor = "rgb(0, 0, 0)"; btnMatch.style.pointerEvents = "auto"; } init(); // Decrement the color for Desktop Version for (let i = 0; i < decrement.length; i++) { decrement[i].addEventListener("click", function (e) { decrement[i].parentElement.nextSibling.nextSibling.firstElementChild.nextSibling.nextSibling.value -= 1; changeColor(); }) } // Decrement for Mobile Version for (let i = 0; i < decrementMobile.length; i++) { decrementMobile[i].addEventListener("click", function (e) { decrementMobile[i].nextSibling.nextSibling.value -= 1; changeColor(); }) } // Increment the color - desktop version for (let i = 0; i < increment.length; i++) { increment[i].addEventListener("click", function (e) { let slider = increment[i].parentElement.nextSibling.nextSibling.firstElementChild.nextSibling.nextSibling; newValue = parseInt(slider.value) + 1; slider.value = newValue; changeColor(); }) } // Increment for Mobile Version for (let i = 0; i < incrementMobile.length; i++) { incrementMobile[i].addEventListener("click", function (e) { newValue = parseInt(incrementMobile[i].previousSibling.previousSibling.value) + 1; incrementMobile[i].previousSibling.previousSibling.value = newValue; changeColor(); }) } function decrementColor(color) { return color - 1; } // Change the user Color function changeColor() { userCircle.style.backgroundColor = "rgb(" + red.value + ", " + green.value + ", " + blue.value + ")"; redValue.innerHTML = red.value; greenValue.innerHTML = green.value; blueValue.innerHTML = blue.value; mobileColorInfo.innerHTML = "Red: " + red.value + ", Green: " + green.value + ", Blue: " + blue.value; } // Click handler for Match Button btnMatch.addEventListener("click", function () { let userColor = userCircle.style.backgroundColor; let computerColor = computerCircle.style.backgroundColor; let rgbColorUser = userColor.substring(userColor.indexOf('(') + 1, userColor.lastIndexOf(')')).split(/,s*/); let rgbColorComputer = computerColor.substring(computerColor.indexOf('(') + 1, computerColor.lastIndexOf(')')).split(/,s*/); console.log(rgbColorUser); console.log(rgbColorComputer); calculateScore(rgbColorUser, rgbColorComputer); }) // Calculate the Score function calculateScore(userColor, PCColor) { if (isNaN(parseInt(userColor[0]))) { userColor = [0, 0, 0]; let score = calculateDifference(userColor, PCColor); scoreText.innerHTML = "You are off by " + score; } else { calculateDifference(userColor, PCColor); let score = calculateDifference(userColor, PCColor); if (score == 0) { scoreText.innerHTML = "You Won!! Colors Match!"; } else { scoreText.innerHTML = "You are off by " + score; } } } // Calculate the difference function calculateDifference(userColor, PCColor) { let rScore = Math.abs(parseInt(PCColor[0] - parseInt(userColor[0]))); let gScore = Math.abs(parseInt(PCColor[1] - parseInt(userColor[1]))); let bScore = Math.abs(parseInt(PCColor[2] - parseInt(userColor[2]))); return parseInt(rScore) + parseInt(gScore) + parseInt(bScore); } // Show the original colors (Cheat) endGame.addEventListener("click", function () { colorToMatch.style.visibility = "visible"; colorToMatch.innerHTML = computerColor; endGame.classList.add("cheated"); btnMatch.style.pointerEvents = "none"; scoreText.innerHTML = "Press the Reset Button to start a new game"; }) // Reset the game resetBtn.addEventListener("click", function () { location.reload(); })
Simpan kode JavaScript di folder xampplite – htdocs – buat folder baru dengan nama MatchColors– simpan code JavaScript dengan nama main.js.
7. Reload alamat url : http://localhost/MatchColors. Tampilan awal game match the color. Atur nilai red, green, dan blue untuk mendapatkan warna yang sesuai. Klik tombol match untuk melihat selisih perbedaan warna. Klik cheat untuk mengetahui nilai red, green dan blue. Klik ikon refresh untuk mendapatkan permainan baru.
8. Selesai.
Demikian penjelasan dari tutorial ‘Cara Membuat Game Match The Colors dengan JavaScript’. Selamat mencoba.