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得到解决。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!

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.


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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
