Соединить два элемента
Всем привет. Помогите соединить два однопалубных корабля в один двухпалубный корабль.
Я пытаюсь создать морской бой и у меня не получается сделать разные виды кораблей. Каждый корабль можно перетаскивать и вставлять в ячейку. Помогите или подскажите как сделать разные виды кораблей. Я думаю это можно реализовать при помощи"склеивания" однопалубных кораблей. <!DOCTYPE html> <html> <head> <title>Untitled</title> <meta charset="utf-8"> <style type="text/css"> td, div.ship{ box-sizing: border-box; width: 40px; height: 40px; border: 1px solid #000000; text-align: center; background-color: rgba(30, 144, 255, 1); margin: 0; padding: 0; } div.ship { background-color: rgba(105, 105, 105, 1); display: inline-block; margin-right: 2px; } td div.ship { display: block; margin: 0; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <script> $(function() { var mytable = $('<table/>').appendTo('body'), tr, td = $.map(Array(100),function(el,i) { i % 10 || (tr = $('<tr/>').appendTo(mytable)); return $('<td/>').appendTo(tr); }), ship = $.map(Array(4),function(i) { return $('<div class="ship"/>').appendTo('body'); }); $(td).droppable({ accept: ".ship", drop: function(event, ui) { ui.draggable.appendTo(this) } }); $(ship).draggable({ cancel: "a.ui-icon", revert: "invalid", containment: "document", helper: "clone", cursor: "move" }); }); </script> </head> <body> </body> </html> |
Пришло время избавиться от таблицы)
|
Неееееет:cray:
|
И как сделать, в виде массива?
|
Retro_1477,
При перетаскивании кораблей возникает масса проблем: 1. Нужно иметь в исходном наборе корабли как горизонтальной, так и вертикальной ориентации либо как-то указывать ориентацию при вставке. При двойном наборе при использовании одного варианта нужно удалять двойника из второго варианта. 2. Контроль возможности вставки как по границам, так и по уже вставленным кораблям. М.б. вставлять-убирать кликами? |
да, можно так сделать
|
Мне нужно сделать игровое поле куда будут помещаться корабли (желательно по правилам морского боя)
|
Для начала
<!DOCTYPE html> <html> <head> <title>Untitled</title> <meta charset="utf-8"> <style type="text/css"> td { box-sizing: border-box; width: 40px; height: 40px; border: 1px solid #000000; text-align: center; background-color: rgba(30, 144, 255, 1); margin: 0; padding: 0; } .ship { background-color: rgba(105, 105, 105, 1); } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <script> $(function() { var count = 0, marina = [], i, j; for (i = 0; i < 11; i++){ marina[i] = []; for (j = 0; j < 11; j++){ marina [i][j] = false; } }; var mytable = $('<table/>').appendTo('body'), tr, td = $.map(Array(100),function(el,i) { i % 10 || (tr = $('<tr/>').appendTo(mytable)); return $('<td/>').appendTo(tr); }) $('td').on('click', function() { i = this.parentNode.rowIndex; j = this.cellIndex; if($(this).hasClass('ship')) { count--; marina[i][j] = false; $(this).toggleClass('ship'); } else { if(count < 20) { testSet(i,j,this); } else { alert('Уже расставлены все корабли'); }; }; $('#count').html(count); }); function testSet(row,col, that) { var k, m, ok = true; loop: for (k = (row == 0)? 1: (row - 1) ; k < row + 2; k += 2) { for(m = (col == 0)? 1: (col - 1); m < col + 2; m += 2) { if(marina[k][m]) { alert("Нельзя ставить новый корабль вплотную"); ok = false; break loop; } }; }; if (ok) { marina[row][col] = true; count++; $(that).toggleClass('ship'); } } }); </script> </head> <body> <div id="count"></div> </body> </html> |
Retro_1477,
Принцип думаю понятен) Нативный Drag and Drop пример, динамическое создание сетки (Grid), абсолютное позиционирование: <pre> Draggable: purple, silver, gray-black, pink-white Droppable: brown-orange, blue-red, green Rotatable (dblclick): all draggable, brown-orange </pre> <script> var grid = { create: function (type, left, top, cWidth, cHeight, cBg, gWidth, gHeight, gBg, gSpace) { var rect = document.createElement('div'); rect.className = type; var style = rect.style; style.position = 'absolute'; style.left = left + 'px'; style.top = top + 'px'; // cell if (arguments.length < 7) { style.width = cWidth + 'px'; style.height = cHeight + 'px'; style.background = cBg; return rect; } // grid var wSpace = cWidth + gSpace; var hSpace = cHeight + gSpace; var gWidth = gSpace + gWidth * wSpace; var gHeight = gSpace + gHeight * hSpace; for (var cTop = gSpace; cTop < gHeight; cTop += hSpace) { for (var cLeft = gSpace; cLeft < gWidth; cLeft += wSpace) { rect.appendChild(grid.create(type + '-cell', cLeft, cTop, cWidth, cHeight, cBg)); } } style.width = gWidth + 'px'; style.height = gHeight + 'px'; style.background = gBg; return rect; } }; var list = { assignProperty: function (nodes, property, value) { for (var i = 0; i < nodes.length; i++) { nodes[i][property] = value; } }, attachEvent: function (nodes, event, listener) { for (var i = 0; i < nodes.length; i++) { nodes[i].addEventListener(event, listener, false); } }, appendTo: function (nodes, parent) { var f = document.createDocumentFragment(); for (var i = 0; i < nodes.length; i++) { f.appendChild(nodes[i]); } parent.appendChild(f); } }; var dnd = { dragged: null, attachDrag: function (nodes, onDragStart) { list.assignProperty(nodes, 'draggable', true); list.attachEvent(nodes, 'dragstart', onDragStart); }, attachDrop: function (nodes, onDragOver, onDrop) { list.attachEvent(nodes, 'dragover', onDragOver); list.attachEvent(nodes, 'drop', onDrop); } }; var ships = [] ships.push(grid.create('ship', 400, 30, 40, 40, 'purple')); ships.push(grid.create('ship', 400, 90, 60, 20, 'silver')); ships.push(grid.create('ship', 400, 130, 20, 20, 'black', 1, 2, 'gray', 5)); ships.push(grid.create('ship', 400, 200, 10, 20, 'white', 3, 1, 'pink', 10)); dnd.attachDrag(ships, function (e) { e.dataTransfer.setData('text', ''); dnd.dragged = e.target; }); var seas = []; seas.push(grid.create('sea', 10, 70, 20, 40, 'orange', 8, 4, 'brown', 10)); seas.push(grid.create('sea', 120, 100, 20, 20, 'red', 10, 5, 'blue', 5)); seas.push(grid.create('sea', 30, 150, 25, 15, 'green', 10, 10, 'transparent', 1)); dnd.attachDrop(seas, function (e) { e.preventDefault(); }, function (e) { e.preventDefault(); if (e.target.classList.contains('sea-cell')) { dnd.dragged.style.left = this.offsetLeft + e.target.offsetLeft + 'px'; dnd.dragged.style.top = this.offsetTop + e.target.offsetTop + 'px'; } }); list.attachEvent(ships.concat(seas[0]), 'dblclick', function (e) { var s = this.style, c = this.children; var w = s.width, h = s.height; if (w == h) return; s.width = h, s.height = w; for (var i = 0; i < c.length; i++) { s = c[i].style; w = s.width, h = s.height; if (w != h) s.width = h, s.height = w; w = s.left, h = s.top; if (w != h) s.left = h, s.top = w; } }); list.appendTo(seas.concat(ships), document.body); </script> |
Часовой пояс GMT +3, время: 20:35. |