Недавно я сделал простую игру с мобильной головоломкой. Код прост и легко понять. Я не скажу много чепухи. Пусть все докажут все!
Давайте сначала посмотрим на визуализации:
<! Doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title> документ </title> <meta name = "viewport" id = "viewport" content = "width = width устройства, начальная масштаба = 1.0, пользовательский scalbable = no"> <стиль = type = "text/css"> html, body, ul, li, oL, dl, dd, dt, p, h1, h2, h3, h4, h5, h6, форма, fieldset, легенда, img {margin: 0; подкладка: 0} body {foanly: incul;}#picx {width: 300px; url ('img/300.jpg'); позиция: относительно; маржа: 50px auto;}. pic {width: 97px; высота: 97px; float: левый; фон: url ('img/300.jpg'); положение: абсолютное; Absolute; Color: Red; Top: 15px; слева: 300px; font-size: 20px;} </style> </head> <body> <div class = 'controller'> <h1> головоломка с призовой. Style = 'founk-position: 0px 0px; слева: 0px; top: 0px;'> </div> <div Data-index = '2' style = 'founk-position: -100px 0px; слева: 100px; top: 0px;'> </div> <div data-index = '3' style = 'founal-position: -200px 0px; слева: 200px; top: 0px; '> </div> <div data-index =' 4 'style =' founk-position: 0px -100px; слева: 0px; top: 100px; '> </div> <div data-index =' 5 'style =' founk-position: -100px -100px; слева: 100px; data-index = '6' style = 'founge-position: -200px -100px; слева: 200px; top: 100px;'> </div> <div Data-index = '7' style = 'founk-position: 0px -200px; слева: 0px; top: 200px;'> </div> <div-index = '8' style = 'founder-potos -200px; слева: 100px; top: 200px; '> </div> <script> var picbox = document.getElementbyid (' picx '); var pic = document.queryselectorall ('. Pic '); var picwidth = pic [0] .offsetwidth; var picheight = pic [0] .ffsetheight; picboxeight = picbox.offsetheight; var go = document.getElementById ('Go'); var times = document.getElementById ('times'); // время. Используется для расширения var dx, dy, newleft, newtop, starttime, endtime; go.addeventlistener ('touchStart', function () {startTime = date.parse (new Date ()); // Получить количество миллисекундов от истечения с 1 января 1970 года. {pic [i] .style.display = "block"; b) {случайный (a, b);}}}) для (var i = 0; i <pic.length; i ++) {pic [i] .addeventListener ('touchStart', function (e) {this.style.zindex = 100; // Установите значение z-Index элемента перетаскивания, чтобы он был на top.dx = e.targettouches [0] .pagex-this.offsetleft; this.Starty = this.OffSetTop; // Разница между значениями, полученными с помощью OffSetTop и т. Д., что первое не содержит PX, а последняя имеет pxthis.style.transition = 'none';}); pic [i] .AddeventListener ('touchmove', функция (e) {newleft = e.TargetTougs [0]. Горизонтальное состояние перетаскивания изменяется newtop = e.targettouches [0] .pagey-dy; if (newleft <=-picwidth/2) {// ограничить блок пограничного кода, область перетаскивания не может превышать половину граничного Newleft = -picwidth/2;} Else if (newleft> = (picboxwidth-picwidth/2)) {newleft = (picboxwidth-picwidth/2);} if (newtop <=-picheight/2) {newtop = -picwidth/2;} else if (newtop> = (picboxheight-picheight/2)) {newtop = (picboxheight-picheight/2);} this.style.left = newleft+'px'; element; pic [i] .addeventListener ('touchend', function (e) {this.style.zindex = 0; this.style.transition = 'All 0.5 ext 0s'; // Добавить эффект анимации css3 this.endx = e.changedtouches [0] .pagex-dx; this. Конец слайда, сравните его с элементом входа и судья, кто обменивается var obj = изменение (e.target, this.endx, this.endy); // в противном случае var _left = obj.style.left; obj.style.left = this.startx+'px'; this.style.left = _left; var _top = obj.style.top; obj.style.top = this.starty+'px'; this.style.top = _top; > }}); pic [i] .addeventListener ('transitionend', function () {if (issuccess ()) {console.log ('успех! // Функция обмена определяет, вступила ли позиция элемента перетаскивания в оригинал 1/2 цели if (math.abs (pic [i] .offsetleft-x) <= picwidth/2 && math.abs (pic [i] .offsettop-y) <= picheight/2 && pic [i]! pic [a]; var bele = pic [b]; var _left; _left = aele.style.left; aele.style.left = bele.style.left; bele.style.left = _left; var _top; _top = aele.style.top; aele.style. bele.style.top; bele.style.top = _top; var _index; _index = aele.getattribute ("data-index"); aele.setattribute ("data-index", bele.getattribute ("data-index"); bele.setTtribute ("data-index", _ indexcess); // Критерии для оценки успеха var str = '' for (var i = 0; i <pic.length; i ++) {str+= pic [i] .getAttribute ('data-index');} if (str == '123456789') {return true;} вернуть false;} var; setInterval (function () { / /trint funct продолжение.endtime = date.parse (new Date ()); times.innerhtml = (endtime-starttime)/1000 || '';}, 1000) </script> </body> </html>Существует много способов оптимизировать код, такие как добавление функций времени, эффекты успеха игры и звуковые эффекты, пользовательские события для скольжения пальцев, слева и правых ударов, ударов вверх и вниз, дальнейшая упаковка и т. Д., Когда вы думаете об этом, вы не можете не попытаться подать код. Полем Редактор продолжит обновлять вас позже. Давайте приедем сюда сегодня. Надеюсь, тебе понравится!