A. Game Tebak Angka
Permainan ini merupakan sejenis permainan untuk menebak angka yang sudah ditetapkan oleh sistem. User hanya memperkirakan angka berapa yang ditetapkan oleh sistem, jika angka yang ditebak terlalu kecil dari angka yang ditetapkan system maka akan “Tebakan Anda terlalu kecil, coba lagi.”, begitu pula sebaliknya
Setelah sama, maka akan muncul pesan “Selamat! Anda menebak angka yang benar”
Berikut script yang digunakan
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game Tebak Angka Dengan java dan html</title>
<style>
body {
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<h3>GAME TEBAK ANGKA</h3>
<hr>
<p>Coba tebak angka berapa yang disimpan dalam komputer <br>Masukkan angka antara 1 dan 100:</p>
<input type="text" id="masukan">
<button onclick="periksaInputan()">Tebak!</button>
<p id="pesan"></p>
</body>
<script>
// buat angka random dan simpan dalam variabel angkaRandom
const angkaRandom = Math.floor(Math.random() * 100) + 1;
// menyimpan element id masukan dan pesan dalam variabel
const masukan = document.getElementById('masukan');
const pesan = document.getElementById('pesan');
// menghitung jumlah tebakan
let percobaan = 0;
// Function untuk memeriksa masukan pengguna
function periksaInputan() {
// menambah jumlah masukan percobaan
percobaan++;
// menyimpan masukan angka dari user
const masukan_user = parseInt(masukan.value);
if (masukan_user === angkaRandom) {
// membuat isi pesan
pesan.textContent = `Selamat! Anda menebak angka yang benar (${angkaRandom}) dengan ${percobaan} tebakan.`;
// mengubah warna pesan menjadi hijau
pesan.style.color = 'green';
// menonaktifkan form input
masukan.disabled = true;
} else if (masukan_user < angkaRandom) {
// membuat isi pesan
pesan.textContent = 'Tebakan Anda terlalu kecil, coba lagi.';
// mengubah warna pesan menjadi hijau
pesan.style.color = 'red';
} else if (masukan_user > angkaRandom) {
// membuat isi pesan
pesan.textContent = 'Tebakan Anda terlalu tinggi, coba lagi.';
// mengubah warna pesan menjadi hijau
pesan.style.color = 'red';
}
// kosongkan form masukan
masukan.value = '';
// fokus pada form masukan
masukan.focus();
}
</script>
</html>
B. Game Tic Tac Toe
Game ini merupakan game permainan antara dua pemain yang terdiri dari sembilan kotak. Setiap pemain memilih gerakan mereka dengan O atau X dan menandai kotak mereka di setiap kesempatan. Pemain yang berhasil membuat tanda dalam satu baris, baik secara diagonal, horizontal, atau vertikal akan menang. Tantangan bagi pemain lain adalah memblokir permainan lawannya dan juga untuk membuat rantai. Pemenangnya jika yang berhasil membuat baris diagonal, horisontal maupun vertikal.
Buatlah Folder dengan nama Game Tic Tac Toe, masukkan ketiga code dibawah ini kedalam folder Game Tic Tac Toe,

index.html
<!DOCTYPE html>
<!-- Games TIC TOC TUE -->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Game Tic Tac Toe</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
<!-- select box -->
<div class="select-box">
<header>Tic Tac Toe</header>
<div class="content">
<div class="title">Pilih anda akan menggunakan yang mana...?</div>
<div class="options">
<button class="playerX">Player (X)</button>
<button class="playerO">Player (O)</button>
</div>
<div class="credit">Didownload dari <a href="https://www.syaiflash.com" target="_blank">syaiflash.com</a></div>
</div>
</div>
<!-- playboard section -->
<div class="play-board">
<div class="details">
<div class="players">
<span class="Xturn">X memilih</span>
<span class="Oturn">O memilih</span>
<div class="slider"></div>
</div>
</div>
<div class="play-area">
<section>
<span class="box1"></span>
<span class="box2"></span>
<span class="box3"></span>
</section>
<section>
<span class="box4"></span>
<span class="box5"></span>
<span class="box6"></span>
</section>
<section>
<span class="box7"></span>
<span class="box8"></span>
<span class="box9"></span>
</section>
</div>
</div>
<!-- result box -->
<div class="result-box">
<div class="won-text"></div>
<div class="btn"><button>Ulang</button></div>
</div>
<script src="script.js"></script>
</body>
</html>
style.css
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
::selection{
color: #fff;
background:#56baed;
}
body{
background:#56baed;
}
.select-box, .play-board, .result-box{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transition: all 0.3s ease;
}
.select-box{
background: #fff;
padding: 20px 25px 25px;
border-radius: 5px;
max-width: 400px;
width: 100%;
}
.select-box.hide{
opacity: 0;
pointer-events: none;
}
.select-box header{
font-size: 30px;
font-weight: 600;
padding-bottom: 10px;
border-bottom: 1px solid lightgrey;
}
.select-box .title{
font-size: 22px;
font-weight: 500;
margin: 20px 0;
}
.select-box .options{
display: flex;
width: 100%;
}
.options button{
width: 100%;
font-size: 20px;
font-weight: 500;
padding: 10px 0;
border: none;
background: #56baed;
border-radius: 5px;
color: #fff;
outline: none;
cursor: pointer;
transition: all 0.3s ease;
}
.options button:hover,
.btn button:hover{
transform: scale(0.96);
}
.options button.playerX{
margin-right: 5px;
}
.options button.playerO{
margin-left: 5px;
}
.select-box .credit{
text-align: center;
margin-top: 20px;
font-size: 18px;
font-weight: 500;
}
.select-box .credit a{
color: #56baed;
text-decoration: none;
}
.select-box .credit a:hover{
text-decoration: underline;
}
.play-board{
opacity: 0;
pointer-events: none;
transform: translate(-50%, -50%) scale(0.9);
}
.play-board.show{
opacity: 1;
pointer-events: auto;
transform: translate(-50%, -50%) scale(1);
}
.play-board .details{
padding: 7px;
border-radius: 5px;
background: #fff;
}
.play-board .players{
width: 100%;
display: flex;
position: relative;
justify-content: space-between;
}
.players span{
position: relative;
z-index: 2;
color: #56baed;
font-size: 20px;
font-weight: 500;
padding: 10px 0;
width: 100%;
text-align: center;
cursor: default;
user-select: none;
transition: all 0.3 ease;
}
.players.active span:first-child{
color: #fff;
}
.players.active span:last-child{
color: #56baed;
}
.players span:first-child{
color: #fff;
}
.players .slider{
position: absolute;
top: 0;
left: 0;
width: 50%;
height: 100%;
background: #56baed;
border-radius: 5px;
transition: all 0.3s ease;
}
.players.active .slider{
left: 50%;
}
.players.active span:first-child{
color: #56baed;
}
.players.active span:nth-child(2){
color: #fff;
}
.players.active .slider{
left: 50%;
}
.play-area{
margin-top: 20px;
}
.play-area section{
display: flex;
margin-bottom: 1px;
}
.play-area section span{
display: block;
height: 90px;
width: 90px;
margin: 2px;
color: #56baed;
font-size: 40px;
line-height: 80px;
text-align: center;
border-radius: 5px;
background: #fff;
}
.result-box{
padding: 25px 20px;
border-radius: 5px;
max-width: 400px;
width: 100%;
opacity: 0;
text-align: center;
background: #fff;
pointer-events: none;
transform: translate(-50%, -50%) scale(0.9);
}
.result-box.show{
opacity: 1;
pointer-events: auto;
transform: translate(-50%, -50%) scale(1);
}
.result-box .won-text{
font-size: 30px;
font-weight: 500;
display: flex;
justify-content: center;
}
.result-box .won-text p{
font-weight: 600;
margin: 0 5px;
}
.result-box .btn{
width: 100%;
margin-top: 25px;
display: flex;
justify-content: center;
}
.btn button{
font-size: 18px;
font-weight: 500;
padding: 8px 20px;
border: none;
background: #56baed;
border-radius: 5px;
color: #fff;
outline: none;
cursor: pointer;
transition: all 0.3s ease;
}
script.js
//I've tried to explain each JavaScript line with comments....Hope you'll understand
//selecting all required elements
const selectBox = document.querySelector(".select-box"),
selectBtnX = selectBox.querySelector(".options .playerX"),
selectBtnO = selectBox.querySelector(".options .playerO"),
playBoard = document.querySelector(".play-board"),
players = document.querySelector(".players"),
allBox = document.querySelectorAll("section span"),
resultBox = document.querySelector(".result-box"),
wonText = resultBox.querySelector(".won-text"),
replayBtn = resultBox.querySelector("button");
window.onload = ()=>{ //once window loaded
for (let i = 0; i < allBox.length; i++) { //add onclick attribute in all available span
allBox[i].setAttribute("onclick", "clickedBox(this)");
}
}
selectBtnX.onclick = ()=>{
selectBox.classList.add("hide"); //hide select box
playBoard.classList.add("show"); //show the playboard section
}
selectBtnO.onclick = ()=>{
selectBox.classList.add("hide"); //hide select box
playBoard.classList.add("show"); //show the playboard section
players.setAttribute("class", "players active player"); //set class attribute in players with players active player values
}
let playerXIcon = "fas fa-times"; //class name of fontawesome cross icon
let playerOIcon = "far fa-circle"; //class name of fontawesome circle icon
let playerSign = "X"; //this is a global variable beacuse we've used this variable inside multiple functions
let runBot = true; //this also a global variable with boolen value..we used this variable to stop the bot once match won by someone or drawn
// user click function
function clickedBox(element){
if(players.classList.contains("player")){
playerSign = "O"; //if player choose (O) then change playerSign to O
element.innerHTML = `<i class="${playerOIcon}"></i>`; //adding circle icon tag inside user clicked element/box
players.classList.remove("active"); ///add active class in players
element.setAttribute("id", playerSign); //set id attribute in span/box with player choosen sign
}else{
element.innerHTML = `<i class="${playerXIcon}"></i>`; //adding cross icon tag inside user clicked element/box
element.setAttribute("id", playerSign); //set id attribute in span/box with player choosen sign
players.classList.add("active"); ///add active class in players
}
selectWinner(); //calling selectWinner function
element.style.pointerEvents = "none"; //once user select any box then that box can'be clicked again
playBoard.style.pointerEvents = "none"; //add pointerEvents none to playboard so user can't immediately click on any other box until bot select
let randomTimeDelay = ((Math.random() * 1000) + 200).toFixed(); //generating random number so bot will randomly delay to select unselected box
setTimeout(()=>{
bot(runBot); //calling bot function
}, randomTimeDelay); //passing random delay value
}
// bot auto select function
function bot(){
let array = []; //creating empty array...we'll store unclicked boxes index
if(runBot){ //if runBot is true
playerSign = "O"; //change the playerSign to O so if player has chosen X then bot will O
for (let i = 0; i < allBox.length; i++) {
if(allBox[i].childElementCount == 0){ //if the box/span has no children means <i> tag
array.push(i); //inserting unclicked boxes number/index inside array
}
}
let randomBox = array[Math.floor(Math.random() * array.length)]; //getting random index from array so bot will select random unselected box
if(array.length > 0){ //if array length is greater than 0
if(players.classList.contains("player")){
playerSign = "X"; //if player has chosen O then bot will X
allBox[randomBox].innerHTML = `<i class="${playerXIcon}"></i>`; //adding cross icon tag inside bot selected element
allBox[randomBox].setAttribute("id", playerSign); //set id attribute in span/box with player choosen sign
players.classList.add("active"); ///add active class in players
}else{
allBox[randomBox].innerHTML = `<i class="${playerOIcon}"></i>`; //adding circle icon tag inside bot selected element
players.classList.remove("active"); //remove active class in players
allBox[randomBox].setAttribute("id", playerSign); //set id attribute in span/box with player choosen sign
}
selectWinner(); //calling selectWinner function
}
allBox[randomBox].style.pointerEvents = "none"; //once bot select any box then user can't click on that box
playBoard.style.pointerEvents = "auto"; //add pointerEvents auto in playboard so user can again click on box
playerSign = "X"; //if player has chosen X then bot will be O right then we change the playerSign again to X so user will X because above we have changed the playerSign to O for bot
}
}
function getIdVal(classname){
return document.querySelector(".box" + classname).id; //return id value
}
function checkIdSign(val1, val2, val3, sign){ //checking all id value is equal to sign (X or O) or not if yes then return true
if(getIdVal(val1) == sign && getIdVal(val2) == sign && getIdVal(val3) == sign){
return true;
}
}
function selectWinner(){ //if the one of following winning combination match then select the winner
if(checkIdSign(1,2,3,playerSign) || checkIdSign(4,5,6, playerSign) || checkIdSign(7,8,9, playerSign) || checkIdSign(1,4,7, playerSign) || checkIdSign(2,5,8, playerSign) || checkIdSign(3,6,9, playerSign) || checkIdSign(1,5,9, playerSign) || checkIdSign(3,5,7, playerSign)){
runBot = false; //passing the false boolen value to runBot so bot won't run again
bot(runBot); //calling bot function
setTimeout(()=>{ //after match won by someone then hide the playboard and show the result box after 700ms
resultBox.classList.add("show");
playBoard.classList.remove("show");
}, 700); //1s = 1000ms
wonText.innerHTML = `Player <p>${playerSign}</p> won the game!`; //displaying winning text with passing playerSign (X or O)
}else{ //if all boxes/element have id value and still no one win then draw the match
if(getIdVal(1) != "" && getIdVal(2) != "" && getIdVal(3) != "" && getIdVal(4) != "" && getIdVal(5) != "" && getIdVal(6) != "" && getIdVal(7) != "" && getIdVal(8) != "" && getIdVal(9) != ""){
runBot = false; //passing the false boolen value to runBot so bot won't run again
bot(runBot); //calling bot function
setTimeout(()=>{ //after match drawn then hide the playboard and show the result box after 700ms
resultBox.classList.add("show");
playBoard.classList.remove("show");
}, 700); //1s = 1000ms
wonText.textContent = "Match has been drawn!"; //displaying draw match text
}
}
}
replayBtn.onclick = ()=>{
window.location.reload(); //reload the current page on replay button click
}
C. Game Batu Gunting Kertas dengan JavaScript
Aturannya sederhana, yaitu batu mengalahkan gunting, gunting mengalahkan kertas, dan kertas mengalahkan batu. Komputer memilih antara batu, gunting, atau kertas secara acak. Nantinya, pengguna perlu memasukkan opsinya, yang kemudian dibandingkan oleh komputer dengan pilihannya untuk menentukan pemenang.
Langkah pembuatannya:
- Buat folder dengan nama sembarang misalnya Game Batu Gunting Kertas
- Buat 3 File dengan nama serta extensionnya
- index.html
- style.css
- script.js
- Masukkan ketiga file tersebut kedalam folder Game Batu Gunting Kertas
- Buat script sesuai extension diatas
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Game Batu Gunting Kertas dengan JavaScript</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<section class="container">
<div class="result_field">
<div class="result_images">
<span class="user_result">
<img src="images/rock.png" alt="" />
</span>
<span class="cpu_result">
<img src="images/rock.png" alt="" />
</span>
</div>
<div class="result">Silahkan Mulai</div>
</div>
<div class="option_images">
<span class="option_image">
<img src="images/rock.png" alt="" />
<p>Batu</p>
</span>
<span class="option_image">
<img src="images/paper.png" alt="" />
<p>Kertas</p>
</span>
<span class="option_image">
<img src="images/scissors.png" alt="" />
<p>Gunting</p>
</span>
</div>
</section>
<script src="script.js" defer></script>
</body>
</html>
style.css
/* Import Google font - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: #f6f7fb;
}
::selection {
color: #fff;
background-color: #7d2ae8;
}
.container {
padding: 2rem 7rem;
border-radius: 14px;
background: #fff;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
.result_images {
display: flex;
column-gap: 7rem;
}
.container.start .user_result {
transform-origin: left;
animation: userShake 0.7s ease infinite;
}
@keyframes userShake {
50% {
transform: rotate(10deg);
}
}
.container.start .cpu_result {
transform-origin: right;
animation: cpuShake 0.7s ease infinite;
}
@keyframes cpuShake {
50% {
transform: rotate(-10deg);
}
}
.result_images img {
width: 100px;
}
.user_result img {
transform: rotate(90deg);
}
.cpu_result img {
transform: rotate(-90deg) rotateY(180deg);
}
.result {
text-align: center;
font-size: 2rem;
color: #7d2ae8;
margin-top: 1.5rem;
}
.option_image img {
width: 50px;
}
.option_images {
display: flex;
align-items: center;
margin-top: 2.5rem;
justify-content: space-between;
}
.container.start .option_images {
pointer-events: none;
}
.option_image {
display: flex;
flex-direction: column;
align-items: center;
opacity: 0.5;
cursor: pointer;
transition: opacity 0.3s ease;
}
.option_image:hover {
opacity: 1;
}
.option_image.active {
opacity: 1;
}
.option_image img {
pointer-events: none;
}
.option_image p {
color: #7d2ae8;
font-size: 1.235rem;
margin-top: 1rem;
pointer-events: none;
}
script.js
// Get to DOM elements
const gameContainer = document.querySelector(".container"),
userResult = document.querySelector(".user_result img"),
cpuResult = document.querySelector(".cpu_result img"),
result = document.querySelector(".result"),
optionImages = document.querySelectorAll(".option_image");
// Loop through each option image element
optionImages.forEach((image, index) => {
image.addEventListener("click", (e) => {
image.classList.add("active");
userResult.src = cpuResult.src = "images/rock.png";
result.textContent = "Proses...";
// Loop through each option image again
optionImages.forEach((image2, index2) => {
// If the current index doesn't match the clicked index
// Remove the "active" class from the other option images
index !== index2 && image2.classList.remove("active");
});
gameContainer.classList.add("start");
// Set a timeout to delay the result calculation
let time = setTimeout(() => {
gameContainer.classList.remove("start");
// Get the source of the clicked option image
let imageSrc = e.target.querySelector("img").src;
// Set the user image to the clicked option image
userResult.src = imageSrc;
// Generate a random number between 0 and 2
let randomNumber = Math.floor(Math.random() * 3);
// Create an array of CPU image options
let cpuImages = ["images/rock.png", "images/paper.png", "images/scissors.png"];
// Set the CPU image to a random option from the array
cpuResult.src = cpuImages[randomNumber];
// Assign a letter value to the CPU option (R for rock, P for paper, S for scissors)
let cpuValue = ["R", "P", "S"][randomNumber];
// Assign a letter value to the clicked option (based on index)
let userValue = ["R", "P", "S"][index];
// Create an object with all possible outcomes
let outcomes = {
RR: "Draw",
RP: "Komputer",
RS: "Anda",
PP: "Draw",
PR: "Anda",
PS: "Komputer",
SS: "Draw",
SR: "Komputer",
SP: "Anda",
};
// Look up the outcome value based on user and CPU options
let outComeValue = outcomes[userValue + cpuValue];
// Display the result
result.textContent = userValue === cpuValue ? "Match Draw" : `${outComeValue} Menang..!!`;
}, 2500);
});
});
Leave a Reply