Объект рисуется не удовлетворяя условия......
Всем привет , я новичок в этом деле))) Проблема в следующем:
есть кнопка при нажатии на которую в html добавляется новый див( с новыми координатами он же кубик который рисуется). Есть функция которая проверяет нет ли уже дива по заданным координатам и если есть то рекурсивно вызывается новое смещение по координатам. <div id="obert"> <div id="cubik"></div> </div> <div class="top_button"> <button type="submit"> <img src="http://2.bp.blogspot.com/- Ka01fTxAf60/UgiQjKfcTAI/AAAAAAAAC3U/YZMu6PIB1cg/s1600/str_15.gif"onclick="Up()"> </button> А вот скрипт, при выводе к консоль всё ок, условие выполняется, но всё равно кубик рисуется ....( есть и другие кнопки (права,лева , низ....) var lastX, lastY, firstX, firstY, shiftX = 32, shiftY = 32; var offset = $('#cubik').offset(); lastX = offset.left; lastY = offset.top; var lookDiv = function(lX, lY) { var element = document.elementFromPoint(lastX,lastY); console.log(lastX,lastY,element); if (window.element != 'undefine') { console.log("ok"); return false; } }; var addDiv = function() { $ ( "#obert" ) .append ( "<div></div>"); $( "#obert div:last-child" ) .addClass("cube") .offset( { top: lastY, left: lastX }); }; function Up(lX, lY) { lastX = lastX; lastY -= shiftY; if (lookDiv()) { // не ресуем, а рекурсивно вызываемся повторно up(lastX, lastY); } else { addDiv(); } }; |
Ndex,
Условие на 42-й строке никогда не будет истинно, так как функция "lookDiv" всегда возвращает ложь. Каждому свое, но мне нравится этот гайд по оформлению кода. |
Да со стилем у меня бардак(((((
я решил сравнивать не со значением а с классом дива.... if (element != $('#cube')) какое значение мне в итоге возвращать ? p.S. учебник читаю))) |
Ndex,
if ($(".cube").length) { // кубик есть return true; } else { // кубика нет return false; } Можно сделать метод: function hasCube() { return $(".cube").length; } Тогда: function Up(lX, lY) { lastX = lastX; lastY -= shiftY; if (hasCube()) { // не ресуем, а рекурсивно вызываемся повторно up(lastX, lastY); } else { addDiv(); } }; Правда теперь у вас функция up войдет в бесконечную рекурсию, так как нет условия выхода. |
да именно так и происходит,
с $(".cube").length; в любой вариации происходит тоже самое.... |
$(".cube").length возвращает количество элементов с классом "cube" в документе. В javascript работает динамическое приведение типов. 0 - ложь , 1 и более - истина. Если у вас что-то не работает - значит у вас либо всегда есть элемент с таким классом и тогда надо уточнить селектор, либо его никогда нет
|
да именно в этом то и проблема ведь каждому div
присваевается класс cube $( "#obert div:last-child" ) .addClass("cube") соответственно ($(".cube").length) полюбому будет в документе. поэтому получается, что такая реализация не подойдёт.(((( может есть другие мысли о том как это сделать?):cray: |
Ndex,
Не до конца понимаю что вы хотите сделать. Объясните подробно всю задачу целиком. |
задача такова: в середине окна браузера имеется квадратик с фиксированными размерами,
Так же имеется консоль(4 кнопки: вверх вправо,влево вниз) при нажатии например кнопки вверх происходит добавление ещё одного квадрата над фиксированным. так же при нажатии других кнопок происходит это же только в соответствующих направлениях. всё отрисовывается и работает. только вот проблема если мы нарисуем квадрат этими "кубиками" и вернёмся в начальное положение и нарисует квадрат на месте где уже есть ..... мне нужно если мы натыкаемся на квадрат делать сдвиг...... |
<style> html, body, #game { width: 100%; height: 100%; position: relative; } .square { position: absolute; background: red; border: solid 1px #000; } </style> <div id="game"> <div id="controls"> <div data-direction="left" class="control">Налево</div> <div data-direction="top" class="control">Вверх</div> <div data-direction="down" class="control">Вниз</div> <div data-direction="right" class="control">Вправо</div> </div> </div> <script> /** * Объект квадрата * @param {Number} x * @param {Number} y * @param {{x: number, y: number}} size * @constructor */ var Square = function Square(x, y, size) { this.x = x; this.y = y; this.size = size; this.node = null; this.createNode(); this.setStyle(); }; /** * Создаем элемент */ Square.prototype.createNode = function () { this.node = document.createElement("DIV"); this.node.className = "square"; document.querySelector("#game").appendChild(this.node); }; /** * Добавляем к элементу стили */ Square.prototype.setStyle = function () { this.node.style.left = this.x + "px"; this.node.style.top = this.y + "px"; this.node.style.width = this.size.width + "px"; this.node.style.height = this.size.height + "px"; }; /** * Проверяем есть ли уже такой квадрат * @param {{x: number, y: number}} coords * @return {boolean} */ Square.prototype.hitTest = function (coords) { return this.x == coords.x && this.y == coords.y; }; /** * Объект игры * @constructor */ var Game = function Game() { this.collection = []; this.node = document.querySelector("#game"); this.squareSize = { width: 10, height: 10 }; this.activeSquareCoords = { x: 300, y: 300 }; this.start(); this.setHandlers(); }; /** * Назначаем обработчики на кнопки управления */ Game.prototype.setHandlers = function () { var that = this; Array.prototype.forEach.call(this.node.querySelectorAll(".control"), function (control) { control.addEventListener("click", function () { var direction = this.getAttribute("data-direction"); if (that.collection.some(function (square) { return square.hitTest(this.get()[direction]); }, that)) { alert("О господи! Там уже есть квадрат! Что же делать?"); } else { that.addSquare(that.get()[direction]); } }, false) }); }; /** * Создаем первый квадрат, запускаем игру */ Game.prototype.start = function () { this.addSquare(this.activeSquareCoords); }; /** * Добавляем квадрат * @param {{x: number, y: number}} coords */ Game.prototype.addSquare = function (coords) { this.collection.push(new Square(coords.x, coords.y, this.squareSize)); this.activeSquareCoords = { x: coords.x, y: coords.y }; }; /** * Получаем объект смещений квадрата * @return {{top: {x: number, y: number}, left: {x: number, y: number}, right: {x: number, y: number}, down: {x: number, y: number}}} */ Game.prototype.get = function () { return { top: { x: this.activeSquareCoords.x, y: this.activeSquareCoords.y - this.squareSize.height - 2 }, left: { x: this.activeSquareCoords.x - this.squareSize.width - 2, y: this.activeSquareCoords.y }, right: { x: this.activeSquareCoords.x + this.squareSize.width + 2, y: this.activeSquareCoords.y }, down: { x: this.activeSquareCoords.x, y: this.activeSquareCoords.y + this.squareSize.height + 2 } } }; var game = new Game(); </script> |
Ndex,
Вместо алерта можно поставить что-то другое. |
да, работает то так, только вот при нахождении квадрата должно выходить не сообщение, а происходить смещение и квадрат продолжать рисоваться только после найденого.....
|
Спасибо большое, допёр))) сложноватый для меня этот код..... пошёл дальше читать ещё....
|
Ndex,
Это тоже без проблем. <style> html, body, #game { width: 100%; height: 100%; position: relative; } .square { position: absolute; background: red; border: solid 1px #000; } </style> <div id="game"> <div id="controls"> <div data-direction="left" class="control">Налево</div> <div data-direction="top" class="control">Вверх</div> <div data-direction="down" class="control">Вниз</div> <div data-direction="right" class="control">Вправо</div> </div> </div> <script> /** * Объект квадрата * @param {Number} x * @param {Number} y * @param {{x: number, y: number}} size * @constructor */ var Square = function Square(x, y, size) { this.x = x; this.y = y; this.size = size; this.node = null; this.createNode(); this.setStyle(); }; /** * Создаем элемент */ Square.prototype.createNode = function () { this.node = document.createElement("DIV"); this.node.className = "square"; document.querySelector("#game").appendChild(this.node); }; /** * Добавляем к элементу стили */ Square.prototype.setStyle = function () { this.node.style.left = this.x + "px"; this.node.style.top = this.y + "px"; this.node.style.width = this.size.width + "px"; this.node.style.height = this.size.height + "px"; }; /** * Проверяем есть ли уже такой квадрат * @param {{x: number, y: number}} coords * @return {boolean} */ Square.prototype.hitTest = function (coords) { return this.x == coords.x && this.y == coords.y; }; /** * Объект игры * @constructor */ var Game = function Game() { this.collection = []; this.node = document.querySelector("#game"); this.squareSize = { width: 10, height: 10 }; this.activeSquareCoords = { x: 300, y: 300 }; this.start(); this.setHandlers(); }; /** * Назначаем обработчики на кнопки управления */ Game.prototype.setHandlers = function () { var that = this; Array.prototype.forEach.call(this.node.querySelectorAll(".control"), function (control) { control.addEventListener("click", function () { var direction = this.getAttribute("data-direction"); if (that.hitTest(that.get()[direction])) { var check = function (coords) { that.activeSquareCoords = coords; if (that.hitTest(that.get()[direction])) { check(that.get()[direction]); } else { that.addSquare(that.get()[direction]); } }; check(that.get()[direction]); } else { that.addSquare(that.get()[direction]); } }, false) }); }; /** * Проверяем наличие объекта с данными координатами в массиве квадратов * @param {{x: number, y: number}} coords */ Game.prototype.hitTest = function (coords) { return this.collection.some(function (square) { return square.hitTest(coords); }); }; /** * Создаем первый квадрат, запускаем игру */ Game.prototype.start = function () { this.addSquare(this.activeSquareCoords); }; /** * Добавляем квадрат * @param {{x: number, y: number}} coords */ Game.prototype.addSquare = function (coords) { this.collection.push(new Square(coords.x, coords.y, this.squareSize)); this.activeSquareCoords = { x: coords.x, y: coords.y }; }; /** * Получаем объект смещений квадрата * @return {{top: {x: number, y: number}, left: {x: number, y: number}, right: {x: number, y: number}, down: {x: number, y: number}}} */ Game.prototype.get = function () { return { top: { x: this.activeSquareCoords.x, y: this.activeSquareCoords.y - this.squareSize.height - 2 }, left: { x: this.activeSquareCoords.x - this.squareSize.width - 2, y: this.activeSquareCoords.y }, right: { x: this.activeSquareCoords.x + this.squareSize.width + 2, y: this.activeSquareCoords.y }, down: { x: this.activeSquareCoords.x, y: this.activeSquareCoords.y + this.squareSize.height + 2 } } }; var game = new Game(); </script> Изучайте, возьмите как образец. Это начало ООП на javascript. |
Ещё раз спасибо))):victory:
|
Часовой пояс GMT +3, время: 16:53. |