Implementing a simple whack-a-mole game in JavaScript

Implementing a simple whack-a-mole game in JavaScript

This article shares the specific code for JavaScript to implement the whack-a-mole game for your reference. The specific content is as follows

The effect is as follows:

HTML code:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title></title>
  <script src="js/index.js"></script>
  <link rel="stylesheet" type="text/css" href="css/index.css" />
  <style type="text/css">
  </style>
 </head>
 <body>
  <div id="controlCenter">
   <div class="buttons">
    <button class="buttonCss" onclick="startGame()">Start</button>
    <button class="buttonCss" onclick="pauseGame()">Pause</button>
    <button class="buttonCss" onclick="stopGame()">Stop</button>
   </div>
   <div class="buttons">
    <div class="score"><span>Score:</span><span class="spanCss" id="scoreId">0</span></div>
    <div class="score">Time:<span class="spanCss" id="timeId">00:00</span></div>
   </div>
  </div>
  <div id="mainFrame" class="mouseMiddle">
   
  </div>
 </body>
</html>

js code:

var columns = 4;
var rows = 3;
var gameFrameWidth = 0;
var gameFrameHeight = 0;
var caveWidth = 0;
var caveHeight = 0;
var caveCoord = []; //All cave coordinates var caveCoordMark = [];
var mouseOffsetX = 10; //Offset of the X axis after changing to a hammervar mouseOffsetY = 15; //Offset of the Y axisvar mouseTimeQueue = []; //Time queue of mouse existencevar nowMouseTime = []; //Life cycle of mousevar bulgeQueue = []; //Queue of mice that are peeking outvar destroyQueue = []; //Queue of mice that are actually destroyedvar maxMouseNum = 5; //Maximum number of mice that can exist at the same timevar startLoop = undefined; //Start the switchvar pauseFlag = false; //Pause flagvar minTime = 10; //Minimum time period of survivalvar maxTime = 15;//Maximum time period of survivalvar mouseFrameNum = 5; //Number of frames of the picturevar leftWidth = 0;
var topHeight = 0;
//var preTimeStamp = 0;
 
var score = 0;
 
window.onload = function() {
 init();
 mainFrameOnclick();
}
 
function init() {
// preTimeStamp = Date.parse(new Date());
 gameFrameWidth = mainFrame.offsetWidth;
 gameFrameHeight = mainFrame.offsetHeight;
 caveWidth = Math.floor(gameFrameWidth / (columns + 2));
 caveHeight = Math.floor(gameFrameHeight / (rows + 2));
 caveHeight = caveWidth = Math.min(caveHeight, caveWidth); //Use the smallest side of the calculated cave length and width as the length and width of the cave caveCoord = drawCave();
 mouseAnimationUpdate();
 scoreAutomationChange();
}
 
function timeChange(){
 let timestamp = Date.parse(new Date());
 let time = document.getElementById("timeId");
 let m = 0;
 let s = 0;
 setInterval(()=>{
  let now = Date.parse(new Date());
  let v = (now - timestamp)/1000;
// console.log(v);
  let str = "";
  s = v % 60;
  m = Math.floor(v/60);
  str = str + (m>9?m:"0"+m);
  str = str + ":";
  str = str + (s>9?s:"0"+s);
  time.innerText = str;
 },1000);
}
 
function scoreAutomationChange(){
 leftWidth = mainFrame.getBoundingClientRect().left;
 topHeight = mainFrame.getBoundingClientRect().top;
 mainFrame.addEventListener("click",(event)=>{
  CheckHitMouse(event.pageX,event.pageY);
// CheckHitMouse(event.pageX - left, event.pageY - top);
 });
}
 
 
function CheckHitMouse(xx,yy) {
 let x = xx + mouseOffsetX; //Calculate mouse offset let y = yy + mouseOffsetY;
 //The location where the mouse is clicked // let c = document.createElement("div");
// c.style.backgroundColor = "red";
// c.style.width = "10px";
// c.style.height = "10px";
// c.style.left = x-5 + "px";
// c.style.top = y-5 + "px";
// c.style.position = "absolute";
// mainFrame.appendChild(c);
// console.log("**"+x+" "+y);
 let flag = false;
 for(let i = 0; i < bulgeQueue.length; i ++ ){
  let mouse = document.getElementById("mouseId"+bulgeQueue[i][2]);
  let left = mouse.getBoundingClientRect().left;
  let top = mouse.getBoundingClientRect().top;
  console.log(left+" "+top);
  if(x>left&&x<left+caveWidth&&y>top&&y<top+caveHeight){
   playHitAnimation(xx-leftWidth,yy-topHeight,i);
   score+=1;
   document.getElementById("scoreId").innerText = score;
  }
 }
}
 
function playHitAnimation(x,y,index){
 let a = document.createElement("img");
 a.src = "img/4.png";
 a.width = caveWidth;
 a.hheight = caveHeight;
 a.classList.add("caveCss");
 a.style.left = x-5 + "px";
 a.style.top = y-5 + "px";
 mainFrame.appendChild(a);
 setTimeout(()=>{
  mainFrame.removeChild(a);
  let v = bulgeQueue[index];
  let element = document.getElementById("mouseId"+v[2]);
  element.src = "img/mouse0.png";
  caveCoord.push(v);
  bulgeQueue.splice(index,1);
  nowMouseTime.splice(index,1);
  mouseTimeQueue.splice(index,1);
 },100);
}
 
function startGame() {
 pauseFlag = false;
 window.clearInterval();
 timeChange();
 startLoop = setInterval(()=>{
  if(pauseFlag) return;
  for(let i = 0; i < bulgeQueue.length; i ++ ){
   if(nowMouseTime[i] >= mouseFrameNum && nowMouseTime[i] <= mouseTimeQueue[i]){
    nowMouseTime[i]+=1;
   }
  }
  if(bulgeQueue.length<maxMouseNum){//The number of mice is less than 5 let index = getRandom(caveCoord.length);
   bulgeQueue.push(caveCoord[index]);
   caveCoord.splice(index,1);
   mouseTimeQueue.push(getRandomTime());
   nowMouseTime.push(0);
  }
 },500);
}
 
function mouseAnimationUpdate(){
 setInterval(()=>{
  if(pauseFlag) return;
  for(let i = 0; i < bulgeQueue.length; i ++ ){
   if(nowMouseTime[i]<mouseFrameNum){
    nowMouseTime[i]+=1;
    let mouse = bulgeQueue[i];
    let element = document.getElementById("mouseId"+mouse[2]);
    element.src = "img/mouse"+nowMouseTime[i]+".png";
   }
   else if(nowMouseTime[i]>mouseTimeQueue[i]){
    let mouse = bulgeQueue[i];
    let element = document.getElementById("mouseId"+mouse[2]);
    if(nowMouseTime[i]-mouseTimeQueue[i] >= mouseFrameNum+1){
     caveCoord.push(bulgeQueue[i]);
     bulgeQueue.splice(i,1);
     nowMouseTime.splice(i,1);
     mouseTimeQueue.splice(i,1);
     break;
    }
    element.src = "img/mouse"+(mouseFrameNum-nowMouseTime[i]+mouseTimeQueue[i])+".png";
    nowMouseTime[i]+=1;
   }
  }
 },200);
}
 
function pauseGame() {
 pauseFlag = pauseFlag ? false : true;
}
 
function stopGame() {
 location.reload();
}
 
function getRandomTime(){
 return minTime + getRandom(maxTime - minTime);
}
 
 
function mainFrameOnclick() {
 let mf = document.getElementById("mainFrame");
 mf.onclick = function(e) {
  mf.style.cursor = "url(img/01.ico),auto";
  setTimeout(() => {
   mf.style.cursor = "url(img/21.ico),auto";
  }, 200);
  setTimeout(() => {
   mf.style.cursor = "url(img/11.ico),auto";
  }, 400);
 }
}
 
function drawCave() {
 let coord = getAxialCoord();
 let count = getRandom(2) + 1;
 let mark = [];
 let newCoord = [];
 for(let i = 0; i < count; i++) {
  mark[getRandom(columns * rows)] = true;
 }
 for(let i = 0; i < coord.length; i++)
  if(mark[i] == undefined) {
   coord[i].push(i);
   newCoord.push(coord[i]);
   CreateCaveElement(coord[i][0], coord[i][1],i);
  }
 return newCoord;
}
 
function CreateCaveElement(axialX, axialY,index) {
 let createImg = document.createElement("img");
 createImg.width = caveWidth;
 createImg.height = caveHeight;
 createImg.style.left = axialX + "px";
 createImg.style.top = axialY + "px";
 createImg.classList.add("caveCss");
 createImg.id = "mouseId"+index;
 createImg.src = "img/mouse0.png";
 mainFrame.appendChild(createImg);
}
 
function getAxialCoord() {
 let location = [];
 let xWidth = Math.floor(gameFrameWidth / columns);
 let xRange = xWidth - caveWidth;
 let yHeight = Math.floor(gameFrameHeight / rows);
 let yRange = yHeight - caveHeight;
 for(let i = 0; i < rows; i++) {
  for(let j = 0; j < columns; j++) {
   let coord = [];
   coord.push(j * xWidth + getRandom(xRange));
   coord.push(i * yHeight + getRandom(yRange));
   location.push(coord);
  }
 }
 return location;
}
 
function getRandom(max) {
 let a = Math.random();
 return Math.floor(a * max);
}

Project resources: js whack-a-mole game

More interesting classic mini-game implementation topics to share with you:

C++ Classic Mini Games Collection

Python classic games summary

Python Tetris game collection

Play classic JavaScript games

Java classic games collection

JavaScript classic games summary

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Implementation of whack-a-mole game in JavaScript
  • Detailed explanation of the logic flow of whack-a-mole game based on JavaScript+HTML5 (with complete code)
  • JavaScript implements whack-a-mole game
  • js to realize the whack-a-mole game
  • JavaScript whack-a-mole game code explanation

<<:  Detailed explanation of inline elements and block-level elements in commonly used HTML tags

>>:  Solve the problem that MySQL read-write separation causes data not to be selected after insert

Recommend

Docker renames the image name and TAG operation

When using docker images, images with both REPOSI...

Summary of 28 common JavaScript string methods and usage tips

Table of contents Preface 1. Get the length of a ...

Several principles for website product design reference

The following analysis is about product design pr...

Dynamically edit data in Layui table row

Table of contents Preface Style Function Descript...

Attributes and usage of ins and del tags

ins and del were introduced in HTML 4.0 to help au...

HTML+CSS implementation code for rounded rectangle

I was bored and suddenly thought of the implementa...

Summary and examples of vue3 component communication methods

The communication modes of vue3 components are as...

Introduction to setting up Tomcat to start automatically on Linux system

1. Enter the /etc/init.d directory: cd /etc/init....

Summary of Kubernetes's application areas

Kubernetes is the leader in the container orchest...

A simple example of how to implement fuzzy query in Vue

Preface The so-called fuzzy query is to provide q...

How to build mysql master-slave server on centos7 (graphic tutorial)

This article mainly introduces how to build a MyS...

Let's talk about my understanding and application of React Context

Table of contents Preface First look at React Con...

Implementation of Docker deployment of SQL Server 2019 Always On cluster

Table of contents Docker deployment Always on clu...

Complete steps to install Anaconda3 in Ubuntu environment

Table of contents Introduction to Anaconda 1. Dow...