Membuat Game Space Invaders Menggunakan HTML5 + Javascript



Halo semuanya, selamat datang di fivser.com, kesempatan kali ini saya akan memberikan panduan untuk membuat sebuah game berbasis web dengan nama "Game Space Invader". Game Space Invader adalah game tembak-tembakan yang menampilkan grafik 2D. Game ini akan kita buat menggunakan HTML5 + Javascript.

Tujuan game ini adalah pemain menembak seluruh alien yang ada menggunakan meriam laser dan mencetak skor setinggi mungkin.

Fitur yang tersedia pada Game Space Invaders ini:


Demo





  • Start : Memulai permainan
  • Pause : Memberhentikan sementara permainan
  • Resume : Melanjutkan permainan
  • Retry  : Mencoba ulang kembali permainan
  • Score : Menghitung skor yang didapat
  • Alien : Objek game yang harus ditembak
  • Meriam Laser  : Alat untuk menembak objek game. Meriam laser dapat digerakkan dengan menggunakan tombol "A" untuk ke kiri dan tombol "D" untuk kekanan.
Silahkan ikuti tutorial dibawah ini, pastikan langkah yang diikuti sesuai:

1. Buat folder baru di desktop dengan nama "spaceinvaders".
2. Didalam folder tersebut buat sub-folder lagi, dengan nama "js".
3. Sehingga susunan folder terlihat seperti gambar dibawah ini

4. Selanjutnya buka Code Editor yang kalian pakai untuk coding, disini saya pakai Sublime Text 3. Salin coding dibawah ini. dan simpan dengan nama Shooter.js, simpan didalam subfolder js. Shooter.js berfungsi untuk membuat meriam laser didalam game.

  1. Shooter.js

  2. class Shooter{ constructor(){ // initiator for shooter this.w = 80; this.h = 30; this.x = cw / 2 - this.w / 2; this.y = ch - 40; this.pos = { x: 400, y: 10, w:73, h:60 } } draw(){ ctx.save(); ctx.drawImage(image,this.pos.x,this.pos.y,this.pos.w,
  3. this.pos.h,this.x,this.y,this.w,this.h); ctx.restore(); } }
5. Salin lagi coding dibawah ini. dan simpan dengan nama Bullet.js, simpan didalam subfolder js. Bullet.js berfungsi untuk membuat peluru/laser didalam game.

  1. Bullet.js

  2. class Bullet{ constructor(x){ // initiator for bullet this.w = 3; this.h = 7; this.x = x; this.y = ch - 50; } update(){ this.y -= 5; } draw(){ ctx.save(); ctx.beginPath(); ctx.fillStyle = 'white'; ctx.rect(this.x,this.y,this.w,this.h); ctx.fill(); ctx.closePath(); ctx.restore(); } }
6. Jika sudah, salin lagi coding dibawah ini. dan simpan dengan nama Alien.js, simpan didalam subfolder js. Alien.js berfungsi untuk membuat objek alien didalam game.


  1. Alien.js

  2. class Alien{ constructor(x,y,sx){ // initiator for alien this.w = 30; this.h = 20; this.sx = sx; this.x = x; this.y = y; this.pos = { y:0, h:80 }; if(this.sx == 1){ this.pos.w = 110; this.pos.x = 0; } else if(this.sx == 3){ this.pos.w = 80; this.pos.x = 230; } } update(){ if(this.sx == 1){ this.sx = 2; this.pos.x = 115; }else if(this.sx == 2){ this.sx = 1; this.pos.x = 0; }else if(this.sx == 3){ this.sx = 4; this.pos.x = 315; }else if(this.sx == 4){ this.sx = 3; this.pos.x = 230; } } move(){ if(game.dir == 1){ this.x += 1; }else if(game.dir == 2){ this.x -= 1; }else if(game.dir == 3){ this.y += 30; } } draw(){ ctx.save(); ctx.drawImage(image,this.pos.x,this.pos.y,this.pos.w,
  3. this.pos.h,this.x,this.y,this.w,this.h); ctx.restore(); } }
7. Jika sudah, salin lagi coding dibawah ini. dan simpan dengan nama Game.js, simpan didalam subfolder js. 

  1. Game.js

  2. class Game{ constructor(){ // initiator for one round of game this.score = 0; this.bullet = []; this.shooter = null; this.alien = []; this.highscore = 0; this.started = false; this.over = false; this.miliseconds = 0; this.paused = false; this.dir = 1; this.lastDir = 1; this.state = 'PAUSE'; // first function to run this.cekHighscore(); this.ready(); } cekHighscore(){ if(typeof(localStorage.highscore) == 'undefined'){ localStorage.highscore = 0; } this.highscore = localStorage.highscore; } ready(){ ctx.save(); ctx.beginPath(); ctx.fillStyle = 'white'; ctx.rect(cw / 2 - 60, ch / 2 - 20, 120 ,40); ctx.fill(); ctx.closePath(); ctx.beginPath(); ctx.textAlign = 'center' ctx.font = '20px Arial'; ctx.fillStyle='black'; ctx.fillText('START', cw / 2, ch/2 + 8); ctx.closePath(); ctx.beginPath(); ctx.textAlign = 'center' ctx.font = '20px Arial'; ctx.fillStyle='white'; ctx.fillText('Highscore: ' + this.highscore, cw / 2, ch/2 - 40); ctx.closePath(); ctx.restore(); } endGame(){ // if the alien touch the boundary near the shooter / player if(localStorage.highscore < this.score){ localStorage.highscore = this.score; } ctx.clearRect(0,0,cw,ch); ctx.save(); ctx.beginPath(); ctx.fillStyle = 'white'; ctx.rect(cw / 2 - 60, ch / 2 - 20, 120 ,40); ctx.fill(); ctx.closePath(); ctx.beginPath(); ctx.textAlign = 'center' ctx.font = '20px Arial'; ctx.fillStyle='black'; ctx.fillText('RETRY', cw / 2, ch/2 + 8); ctx.closePath(); ctx.beginPath(); ctx.textAlign = 'center' ctx.font = '20px Arial'; ctx.fillStyle='white'; ctx.fillText('Your Score: ' + this.score, cw / 2, ch/2 - 40); ctx.closePath(); ctx.restore(); } start(){ this.started = true; this.generate(); this.update(); this.draw(); } update(){ // to clear the console so no error showed console.clear(); if(this.started && !this.over && !this.paused){ this.miliseconds +=10; this.bullet.forEach((bullet)=>{ bullet.update(); if(bullet.y + bullet.h <= 0){ // console.log('lewaat'); this.bullet.splice(0,1); } }); this.cekCollide(); this.cekOver(); this.alien.forEach((alien,index)=>{ if(alien.x + alien.w == cw && this.dir == 1){ let rand = [1,3]; let sx = rand[Math.floor(Math.random()*rand.length)]; for(let x = 0 ; x < 11; x++){ this.alien.push(new Alien(x* 30 + x * 15 + 320,50,sx)); } this.lastDir = this.dir; this.dir = 3; return; }else if(alien.x <= 0 && this.dir == 2){ let rand = [1,3]; let sx = rand[Math.floor(Math.random()*rand.length)]; for(let x = 0 ; x < 11; x++){ this.alien.push(new Alien(x* 30 + x * 15 + 1,50,sx)); } this.lastDir = this.dir; this.dir = 3; return; } }) this.alien.forEach((alien,index)=>{ alien.move(); if(this.alien.length == index + 1){ if(this.dir == 3){ this.dir = this.lastDir % 2 + 1; } } }) if(this.miliseconds % 500 == 0){ this.alien.forEach((alien)=>{ alien.update(); }) } } setTimeout(()=>{ this.update(); },10); } cekOver(){ // if the alien touch the boundary near the shooter / player let p1 = 0; let p2 = 800; let p3 = 410; let p4 = 480; this.alien.forEach((alien,index)=>{ let a1 = alien.x; let a2 = alien.x + alien.w; let a3 = alien.y; let a4 = alien.y + alien.h; if(p1 <= a2 && p2 >= a1 && p3 <= a4 && p4 >= a3){ this.over = true; this.endGame(); } }) } cekCollide(){ // if the bullet touch the alien so the alien and the bullet removed and the score increased this.bullet.forEach((bullet)=>{ let p1 = bullet.x; let p2 = bullet.x + bullet.w; let p3 = bullet.y; let p4 = bullet.y + bullet.h; this.alien.forEach((alien,index)=>{ let a1 = alien.x; let a2 = alien.x + alien.w; let a3 = alien.y; let a4 = alien.y + alien.h; if(p1 <= a2 && p2 >= a1 && p3 <= a4 && p4 >= a3){ this.alien.splice(index,1); this.bullet.splice(0,1); this.score += 10; } }) }) } generate(){ // generate shooter , alien this.shooter = new Shooter(); for(let y = 0; y < 5; y++){ for(let x = 0; x < 11 ; x++){ if(y < 3){ this.alien.push(new Alien(x * 30 + x*15 + 1, y * 20 + y*10 + 80,1)); }else{ this.alien.push(new Alien(x * 30 + x*15 + 1, y * 20 + y*10 + 80,3)); } } } } draw(){ // draw the canvas if(this.started && !this.over && !this.paused){ ctx.clearRect(0,0,cw,ch); this.drawBoundary(); game.drawPause(); game.drawScore(); this.shooter.draw(); this.bullet.forEach((bullet)=>{ bullet.draw(); }); this.alien.forEach((alien,index)=>{ alien.draw(); }) } setTimeout(()=>{ this.draw(); },10); } drawBoundary(){ // draw the boundary near the player / shooter ctx.save(); ctx.beginPath(); ctx.fillStyle = 'gray'; ctx.rect(0 , 400 ,cw , 80); ctx.fill(); ctx.restore(); } drawPause(){ // draw the pause button ctx.save(); ctx.beginPath(); ctx.fillStyle = 'gray'; ctx.rect(cw - 130,10,120,40); ctx.fill(); ctx.closePath(); ctx.beginPath(); ctx.fillStyle = 'white'; ctx.textAlign = 'center'; ctx.font = '20px Arial'; if(this.paused){ this.state = 'RESUME'; }else{ this.state = 'PAUSE'; } ctx.fillText(this.state,cw - 70, 38); ctx.closePath(); ctx.restore(); } drawScore(){ // draw the score above ctx.save(); ctx.beginPath(); ctx.fillStyle = 'white'; ctx.textAlign = 'center'; ctx.font = '20px Arial' ctx.fillText('Score: ' + this.score, cw / 2, 40); ctx.restore(); } pause(){ // if the pause button clicked this.paused = (this.paused + 1) % 2; this.drawPause(); } clicked(x,y){ // function to execute if the canvas is clicked if(!this.started && !this.over){ if(x >= cw / 2 - 60 && x <= cw / 2 +60 && y>= ch / 2 - 20 && y <= ch /2 + 20){ game.start(); } }else if(this.started && !this.over){ if(x >= 670 && x<=790 && y>= 10 && y <= 50){ game.pause(); } }else if(this.started && this.over){ if(x >= cw / 2 - 60 && x <= cw / 2 +60 && y>= ch / 2 - 20 && y <= ch /2 + 20){ location.reload(); } } } move(isright){ // move the shooter if(this.started && !this.over && !this.paused){ if(isright){ this.shooter.x += 20; }else{ this.shooter.x -= 20; } } } shoot(){ // shoot the bullet if(this.bullet.length == 0 && this.started && !this.over && !this.paused){ this.bullet.push(new Bullet(this.shooter.x + this.shooter.w / 2)); } } }
    7. Jika sudah, salin lagi coding dibawah ini. dan simpan dengan nama main.js, simpan didalam subfolder js. 

    1. main.js

    2. // first the document loaded window.onload = init(); function init(){ setCanvas(); setImage(); game = new Game(); } function setCanvas(){ // set canvas and its context canvas = document.getElementById('canvas'); cw = canvas.width; ch = canvas.height; ctx = canvas.getContext('2d'); } function setImage(){ // set image that its use to sprite the alien and the shooter image = new Image(); image.src = 'sprite.png'; } canvas.addEventListener('click',function(e){ // if canvas clicked var x = e.offsetX, y = e.offsetY; game.clicked(x,y); }); window.addEventListener('keydown',function(e){ // if player press button to move or shoot a = e.keyCode; if(game.started && !game.over){ if(a == 65){ game.move(false); }else if(a == 68){ game.move(true); }else if(a == 32){ game.shoot(); } } })

    7. Jika semua file javascript telah disalin dan disimpan. maka isi folder akan telihat seperti gambar dibawah ini:


    8. lalu kembali ke folder utama, downloadlah gambar pendukung yang sudah saya siapkan linknya dibawah ini. 

    https://drive.google.com/open?id=1S1qo6x_TwaGNYV1V9S0_OcefIBBEu0sB

    9. Download gambar diatas, setelah didownload. simpan gambar tersebut di folder utama space invaders. Akan terlihat seperti gambar dibawah ini.




     10. Lalu, langkah terakhir salin coding dibawah ini berikan nama dengan index.html. Jalankan file ini jika ingin memainkan game.



    1. index.html

    2. <!DOCTYPE html> <html> <head> <title>Space Invanders</title> <style> html,body{ width:100%; height:100%; margin:0px; padding:0px; } .container{ width:100%; height:100%; display:flex; justify-content: center; align-items: center; } canvas{ background:black; } </style> </head> <body> <div class='container'> <canvas id='canvas' width='800' height='480'></canvas> </div> </body> <script type='text/javascript' src='js/Shooter.js'></script> <script type='text/javascript' src='js/Bullet.js'></script> <script type='text/javascript' src='js/Alien.js'></script> <script type='text/javascript' src='js/Game.js'></script> <script type='text/javascript' src='js/main.js'></script> </html>

    11. Jika sudah maka susunan folder akan terlihat seperti gambar dibawah ini:


    Susunan Folder

    Akhir Kata


    Bagaiamana? Mudah bukan?
    Itulah coding untuk membuat Game Space Invaders menggunakan HTML5 + Javascript. mohon maaf jika masih banyak kekurangan didalam gamenya, Jika masih bingung atau ada yang ingin ditanyakan. silahkan bertanya di kolom komentar ya.

    Content Creator For Fivser.com

    Post a Comment

    Jangan Spam, Jangan Berkata Kasar dan Kotor
    © Fivser. All rights reserved. Developed by Jago Desain