JavaScript imitation WeChat masturbation game sample code
This article mainly introduces the relevant code of JavaScript imitation WeChat masturbation game in detail, which has certain reference value. Interested friends can refer to it
First implement the WeChat masturbation game, First, there will be self and enemy aircraft, and canvas drawing is used to generate self and enemy aircraft.
1. Generate yourself, and you can move left and right with the left and right keys.
//生成自己,且可以左右移动 //控制飞机向右移动的函数 function moveRight(event){ context.clearRect(aligh,100,47,47); //防止飞机移除背景外 if(aligh < 260){ var img = new Image(); img.src = "../images/self.png"; img.onload = function(){ context.drawImage(img, aligh,100); } aligh += 10 ; } //当飞机即将移出背景外时,让它停在最右端 if (aligh == 260){ var img = new Image(); img.src = "../images/self.png"; img.onload = function(){ context.drawImage(img, 260,100); } } } //控制飞机向左移动的函数 function moveLeft(event){ context.clearRect(aligh,100,47,47); //防止飞机移出最左边的边界 if(aligh > 0){ var img = new Image(); img.src = "../images/self.png"; img.onload = function(){ context.drawImage(img, aligh,100); } aligh -= 10 ; } //使其控制在最左侧 if (aligh == 0){ var img = new Image(); img.src = "../images/self.png"; img.onload = function(){ context.drawImage(img, 0,100); } } } //判断按下的是哪个键,然后控制飞机左右移动 document.onkeydown = function(event){ if(event.keyCode == 37){ moveLeft(); } if(event.keyCode == 39){ moveRight(); } }
2. Generate enemy aircraft. Enemy planes randomly generate pictures on the background. Make it fall from above every second.
var createId = setInterval(function(){ var top = 0+'px'; var enemy = document.createElement("img"); enemy.src = "../images/enemy.png"; //生成随机的位置 var randomleft = Math.floor(Math.random() * 300) ; //如果生成的位置出现在背景外,则就取260 left = randomleft > 260 ? 260 + 'px': randomleft + 'px'; leftArr.push(left); //保存每个敌机的距左边的距离,方便碰撞检测的计算 arrPic.push(enemy); //将每个敌机的图片保存在数组中,方便碰撞检测后移除 main.appendChild(enemy); enemy.style.paddingLeft = left ; enemy.style.paddingTop = top; var spandom = $("#main>img:last-child");//这儿利用jquery找到最后一个img //让最后一个img动起来。则就相当于为每一个img都绑定了动画 spandom.animate({"paddingTop":420},6000,function(){ //当下落到底部时移除元素 this.remove(); arrPic.splice(0,1); //从数组中移除图片 leftArr.splice(0,1); //从数组中移除距离 fallCount ++; //检测下落了多少个飞机,超过十个没被打中,游戏就结束 }); //如果落下的飞机数超过十个没有被打中,则游戏结束 if(fallCount > 10){ clearInterval(createId); clearInterval(crashId); alert("当前得分 :"+count+" , 很遗憾,游戏结束!") } },1000);
3. Now it is mainly about collision detection. A test is performed every 2.2 seconds, because if the test platform is frequent, you can directly eliminate it by pressing and holding the left or right keys. It makes no sense
function checkCrash(){ crashId = setInterval(function(){ //由于每次自由落下的飞机在上面函数中都被移除了。所以leftArr数组中保存的就是当前页面存在的飞机的左距离数组。 for(var i = 0; i < leftArr.length; i++) { //首先将两种都转换成int型进行比较 var tempL = parseInt(leftArr[i]); var tempA = parseInt(aligh); //表示自己距左侧的位置 //当自己的中心距离处于敌机的左右两侧范围内,则表示被击中 if(tempL <= (tempA + 20) && (tempA + 20) <= (tempL + 40)){ arrPic[i].remove(); //碰撞检测,移除敌机的图片 arrPic.splice(i,1); //从图片数组中移除图片 leftArr.splice(i,1); //从记录敌机左侧距离数组中移除该敌机的距离 count++; score.innerHTML = "当前得分 "+count; break; //检测到之后直接跳出循环,进行下一个2.2秒的碰撞检测 } } },2200); } checkCrash();
The game is not complete yet, there are no bullets generated. Most functions have been implemented.
4. The renderings are as follows:
<!DOCTYPE html> <html> <head> <meta charset = "utf-8"/ > <title></title> <script type="text/javascript" src = "./fightFlight.js"></script> <script src = "../jQuery/jquery-3.2.0.min.js"></script> <style type="text/css"> *{ margin: 0px; padding: 0px; } #main{ width: 300px; height: 500px; border:1px solid red; margin: 0 auto; } #my{ position: absolute; z-index: 2; top:350px; } #background{ position: absolute; z-index: 1; width: 300px; height:500px; border: 1px solid green; background-image: url(../images/background.jpg); } img{ position: absolute; z-index: 2; } #enmey{ width: 50px; height: 50px; } #score{ position: absolute; margin-left: 50%; left: 150px; top:100px; width: 160px; font-size: 20px; font-family: "微软雅黑"; font-weight: bold; line-height: 70px; text-align: center; } </style> </head> <body> <p id = "main"> <canvas id = "background"></canvas> <canvas id = "my"></canvas> <p id = "score">当前得分:0</p> </p> </body> </html>
var main = document.getElementById('main'); var my = document.getElementById('my'); var score = document.getElementById("score"); var context = my.getContext('2d'); var crashId; var fallCount = 0; //记录没被打中的飞机数,如果超过10,游戏结束 var aligh = 0 ; var count = 0; //记录打中的飞机数,即当前得分 var leftArr = []; var arrPic = []; var left; var img = new Image(); img.src = "../images/self.png"; img.onload = function(){ context.drawImage(img,aligh,100); } //生成自己,且可以左右移动 function move(event){ event = EventUtil.getEvent(event); context.clearRect(aligh,100,47,47); if(event.keyCode == 39 && aligh < 260 ){ var img = new Image(); img.src = "../images/self.png"; img.onload = function(){ context.drawImage(img, aligh,100); } aligh += 10 ; } if (aligh == 260){ var img = new Image(); img.src = "../images/self.png"; img.onload = function(){ context.drawImage(img, 260,100); } } } document.onkeypress = move; //随机生成敌机 (function(){ var createId = setInterval(function(){ var top = 0+'px'; var enemy = document.createElement("img"); enemy.src = "../images/enemy.png"; var randomleft = Math.floor(Math.random() * 300) ; left = randomleft > 260 ? 260 + 'px': randomleft + 'px'; leftArr.push(left); //保存每个敌机的距左边的距离,方便碰撞检测的计算 arrPic.push(enemy); //将每个敌机的图片保存在数组中,方便碰撞检测后移除 main.appendChild(enemy); enemy.style.paddingLeft = left ; enemy.style.paddingTop = top; var spandom = $("#main>img:last-child");//找到最后一个span spandom.animate({"paddingTop":420},6000,function(){ //移除元素 this.remove(); arrPic.splice(0,1); //移除图片 leftArr.splice(0,1); //从数组中移除距离 fallCount ++; }); //如果落下的飞机数超过十个没有被打中,则游戏结束 if(fallCount >= 10){ clearInterval(createId); clearInterval(crashId); alert("当前得分 :"+count+" , 很遗憾,游戏结束!") } },1000); })(); //碰撞检测 function checkCrash(){ crashId = setInterval(function(){ for(var i = 0; i < leftArr.length; i++) { var tempL = parseInt(leftArr[i]); var tempA = parseInt(aligh); if(tempL <= (tempA + 20) && (tempA + 20) <= (tempL + 40)){ arrPic[i].remove(); //碰撞检测,移除敌机的图片 count++; score.innerHTML = "当前得分 "+count; continue; } } console.log(count); },2200); } checkCrash(); }
The above is the detailed content of JavaScript imitation WeChat masturbation game sample code. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



What to do with blue screen code 0x0000001? The blue screen error is a warning mechanism when there is a problem with the computer system or hardware. Code 0x0000001 usually indicates a hardware or driver failure. When users suddenly encounter a blue screen error while using their computer, they may feel panicked and at a loss. Fortunately, most blue screen errors can be troubleshooted and dealt with with a few simple steps. This article will introduce readers to some methods to solve the blue screen error code 0x0000001. First, when encountering a blue screen error, we can try to restart

The win10 system is a very excellent high-intelligence system. Its powerful intelligence can bring the best user experience to users. Under normal circumstances, users’ win10 system computers will not have any problems! However, it is inevitable that various faults will occur in excellent computers. Recently, friends have been reporting that their win10 systems have encountered frequent blue screens! Today, the editor will bring you solutions to different codes that cause frequent blue screens in Windows 10 computers. Let’s take a look. Solutions to frequent computer blue screens with different codes each time: causes of various fault codes and solution suggestions 1. Cause of 0×000000116 fault: It should be that the graphics card driver is incompatible. Solution: It is recommended to replace the original manufacturer's driver. 2,

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Termination Code 0xc000007b While using your computer, you sometimes encounter various problems and error codes. Among them, the termination code is the most disturbing, especially the termination code 0xc000007b. This code indicates that an application cannot start properly, causing inconvenience to the user. First, let’s understand the meaning of termination code 0xc000007b. This code is a Windows operating system error code that usually occurs when a 32-bit application tries to run on a 64-bit operating system. It means it should

If you need to program any device remotely, this article will help you. We will share the top GE universal remote codes for programming any device. What is a GE remote control? GEUniversalRemote is a remote control that can be used to control multiple devices such as smart TVs, LG, Vizio, Sony, Blu-ray, DVD, DVR, Roku, AppleTV, streaming media players and more. GEUniversal remote controls come in various models with different features and functions. GEUniversalRemote can control up to four devices. Top Universal Remote Codes to Program on Any Device GE remotes come with a set of codes that allow them to work with different devices. you may

What does the 0x000000d1 blue screen code mean? In recent years, with the popularization of computers and the rapid development of the Internet, the stability and security issues of the operating system have become increasingly prominent. A common problem is blue screen errors, code 0x000000d1 is one of them. A blue screen error, or "Blue Screen of Death," is a condition that occurs when a computer experiences a severe system failure. When the system cannot recover from the error, the Windows operating system displays a blue screen with the error code on the screen. These error codes

Quickly get started with Python drawing: code example for drawing Bingdundun Python is an easy-to-learn and powerful programming language. By using Python's drawing library, we can easily realize various drawing needs. In this article, we will use Python's drawing library matplotlib to draw a simple graph of ice. Bingdundun is a cute panda who is very popular among children. First, we need to install the matplotlib library. You can do this by running in the terminal

As a programmer, I get excited about tools that simplify the coding experience. With the help of artificial intelligence tools, we can generate demo code and make necessary modifications as per the requirement. The newly introduced Copilot tool in Visual Studio Code allows us to create AI-generated code with natural language chat interactions. By explaining functionality, we can better understand the meaning of existing code. How to use Copilot to generate code? To get started, we first need to get the latest PowerPlatformTools extension. To achieve this, you need to go to the extension page, search for "PowerPlatformTool" and click the Install button
