Implement web puzzle game using javascript
Using javascript to write a puzzle game, you mainly need to achieve drag effect, block adsorption effect, puzzle disruption animation, and also need to do Impact checking. In order to make the experience of this game better, I also added a magnifying glass effect similar to the products on Taobao. Move the mouse up and a magnified image will appear. The effect is as follows:
##The following describes how this puzzle game works Implementation, HTML+CSS page layout is relatively simple and will not be described in detail. The focus is on how javascript achieves the effects mentioned in the first paragraph of .
(1) Puzzle generation
First you need to use js to generate the overall puzzle, as shown in the picture above; the code is as follows: function init(){
var imgArr=["pt1.jpg","pt2.jpg","pt3.jpg","pt4.jpg"];
var imgIndex=parseInt(Math.random()*imgArr.length);
var wih="";
for(var i=0;i<5;i++){
for(var j=0;j<9;j++){
data.push({
"order":order,
"left":j*100,
"top":i*100
});
wih+="<span style='background-image:url(img/拼图游戏/"+
imgArr[imgIndex]+"); background-position:"+
(-j*100)+"px "+(-i*100)+"px;' order='"+order+"'></span>";//"+(i*9+j)+"
order++;
}
}
right.innerHTML=wih;
var mps=document.querySelectorAll(".magnifier p");
for(var i=0;i<mps.length;i++){
mps[i].style.backgroundImage="url(img/拼图游戏/"+imgArr[imgIndex]+")";
}
ordersb(1);
}
<br/>
(2) Disrupt the puzzle Animation
scrambles the puzzle positions, i.e. scrambles the array that has the positions of all the tiles stored, then re-renders each tile s position. This can be achieved by using the method arr.sort() in JavaScript to scramble the array. The code implementation is as shown below:
##function ordersb(n){
var arr=[];
if(n==1){
//将数组按从小到大的顺序排列
arr=data.sort(function(a,b){
return a.order-b.order;
});
}else{
//打乱数组
arr=data.sort(function(){
return Math.random()-0.5;
});
}
for(var i=0;i<data.length;i++){
spans[i].style.transition="1s";
spans[i].style.left=data[i].left+"px";
spans[i].style.top=data[i].top+"px";
spans[i].setAttribute("order",data[i].order);
spans[i].addEventListener("transitionend",function(){
for (var j = 0; j < spans.length; j++) {
spans[j].style.transition = "none";
}
})
}
}
(3) Drag effect
##realizes drag and drop Effect Just grasp the drag and drop principle. That is, a complete drag and drop contains three steps: a. Mouse pressed; b. Mouse moved; c. Mouse raised.
(4)Adsorption effect
To achieve the adsorption effect, the explanation from the code point of view is that when the mouse moves a certain module, the mouse is lifted at a position that is not allowed for any block. At this time, the position of the block needs to be Modify it so that its position is where the block allows.
(5) Collision Detection 所谓碰撞检测,在此处的通俗说法时,移动一个元素,使其靠近另一个元素,一旦靠近到两个元素刚开始有重叠,就需要立刻检测出来。此处不但要检测出移动的图块与哪些图块有重叠,还要判断与哪个图块重叠部分最多。因为在鼠标抬起时,移动的图块需要根据与哪个图块重叠最多,来决定与哪块图块交换位置。 为了游戏的体验更好一些,在鼠标移动图块时,就判断与哪个图块重叠最多,就把这块图块表示出来。这样用户就知道若抬起鼠标,即将会与哪块图块交换位置。如下图所示: 这三种功能的实现代码,即关键代码如下所示: 在拼图完成后,点击“验证”按钮,弹出一个弹框提示拼图是否正确。 总体来说,用javascript实现拼图游戏,难度不大。本人在做的时候,遇到一个错误:图块移动到某个图块精确的位置上,此时拖拽效果和吸附效果都失效了。经过代码调试和分析,发现在对图块进行位置交换时,通过位置找到的被交换图块元素是不正确的,找到的是这个移动元素本身,导致图块的位置设置错误。找到出现bug的原因后,修改代码,在通过位置查找图块元素时,排除移动元素自身。修改后,经测试bug得到解决。<br/>
function drag(obj){
obj.onmousedown=function(ev){
obj.style.zIndex="99";
var br=obj.offsetLeft;
var bb=obj.offsetTop;
var width=obj.offsetWidth;
var height=obj.offsetHeight;
var or=right.getBoundingClientRect().left;
var ob=right.getBoundingClientRect().top;
var rMax=right.clientWidth-width;
var bMax=right.clientHeight-height;
var oOrder=obj.getAttribute("order");
var disX=ev.clientX- br-or;
var disY=ev.clientY-bb-ob;
var l,t,eel,eet,erl;
right.onmousemove=function(ev){
l=ev.clientX-disX-or;
t=ev.clientY-disY-ob;
//图块移动的边界位置范围设置
l=l>rMax?rMax:l;
l=l<0?0:l;
t=t>bMax?bMax:t;
t=t<0?0:t;
obj.style.left=l+"px";
obj.style.top=t+"px";
//修改此时图块的位置,使其在图块允许存在的位置上,并且是与某个图块重叠最多的那个图块位置
eel=Math.round(l/width)*width;
eet=Math.round(t/height)*height;
//根据图块位置找到在这个位置上的图块元素
erl=find(obj,eel,eet);
for(var i=0;i<spans.length;i++){
spans[i].style.opacity="";
}
if(erl){
erl.style.opacity=".5";
}
}
right.onmouseup=function(){
right.onmousemove=null;
obj.style.zIndex="";
if(erl){
obj.setAttribute("order",erl.getAttribute("order"));
erl.style.left=br+"px";
erl.style.top=bb+"px";
erl.style.opacity="";
erl.setAttribute("order",oOrder);
}
obj.style.left=eel+"px";
obj.style.top=eet+"px";
}
return false;
}
}
(6)游戏输赢判断
The above is the detailed content of Implement web puzzle game using javascript. 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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

The web is a global wide area network, also known as the World Wide Web, which is an application form of the Internet. The Web is an information system based on hypertext and hypermedia, which allows users to browse and obtain information by jumping between different web pages through hyperlinks. The basis of the Web is the Internet, which uses unified and standardized protocols and languages to enable data exchange and information sharing between different computers.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:
