您好,登錄后才能下訂單哦!
這篇文章主要講解了“如何用js代碼實現拼圖小游戲”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“如何用js代碼實現拼圖小游戲”吧!
用js做得小游戲
1、先創建div盒子
<style> div,body{ margin: 0; height: 0; } #box{ width: 800px; height: 800px; background-color: burlywood; position: relative; } #box div { width: 200px; height: 200px; background: url(./imgs/bg.jpg) no-repeat; position: absolute; } </style> </head> <body> <div id="box"></div> </body>
2.寫js
<script> // 獲取標簽 var box = document.getElementById("box"); var arrs = []; // 循環創建16個對象,添加到數組中 for(var i = 0; i < 4; i++){ for(var j = 0; j < 4; j++){ var divNode = document.createElement("div") divNode.style.top = 200 * i + "px" divNode.style.left = 200 * j + "px" // 創建對象 var pox = { left: 200* i, top:200*j, } // 創建好的對象添加到數組里 if( i !== 3 || j !== 3 ){ arrs.push(pox) }else{ divNode.style.background = "none"; divNode.className = "space" } box.appendChild(divNode) } } console.log(arrs); // 隨機抽取對象 for(var i = 0; i < 15; i++){ var ranNum = parseInt(Math.random() * (15 - i)) var x = arrs[ranNum].left; var y = arrs[ranNum].top; box.children[i].style.backgroundPosition = - x + "px "+ - y + "px"; arrs.splice(ranNum,1); } // 鍵盤事件 document.onkeyup = function(event) { // 得到按的那個鍵 var key = event.keyCode // 上 if (key == 38) { var x = box.querySelector(".space").style.left var y = box.querySelector(".space").style.top for (var i = 0; i < 16; i++) { if (parseInt(box.children[i].style.top) == parseInt(y) - 200 && parseInt(box.children[i].style.left) == parseInt(x)) { box.children[i].style.top = y box.querySelector(".space").style.top = parseInt(y) - 200 + "px" } } // 下 }else if (key == 40) { var x = box.querySelector(".space").style.left var y = box.querySelector(".space").style.top // 遍歷所有小div,找到空白上面得那張 賦值 為y for(var i = 0; i < 16; i++){ if (parseInt(box.children[i].style.top) == parseInt(y) + 200 && parseInt(box.children[i].style.left) == parseInt(x)) { box.children[i].style.top = y box.querySelector(".space").style.top = parseInt(y) + 200 + "px" } } // 左 }else if (key = 38) { var x = box.querySelector(".space").style.left var y = box.querySelector(".space").style.top for (var i = 0; i < 16; i++) { if (parseInt(box.children[i].style.left) == parseInt(x) - 200 && parseInt(box.children[i].style.top) == parseInt(y)) { box.children[i].style.left = x box.querySelector(".space").style.left = parseInt(x) - 200 + "px" } } // 右 }else if (key = 39) { var x = box.querySelector(".space").style.left var y = box.querySelector(".space").style.top for (var i = 0; i < 16; i++) { if (parseInt(box.children[i].style.left) == parseInt(x) + 200 && parseInt(box.children[i].style.top) == parseInt(y)) { box.children[i].style.left = x box.querySelector(".space").style.left = parseInt(x) + 200 + "px" } } } } </script>
效果圖
完成效果圖
感謝各位的閱讀,以上就是“如何用js代碼實現拼圖小游戲”的內容了,經過本文的學習后,相信大家對如何用js代碼實現拼圖小游戲這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。