Итак, в приведенном ниже коде (который был дан мне в другом вопросе, который я задал) он создает сетку определенных область, по которой игрок может свободно перемещать пешки. Я сделал так, чтобы ajax-запрос мог сохранять каждую координату пешки в базу данных в виде 0,1 3,4 и т.д.
В целом все работает, но проблема в том, что я могу' Я сохраняю положение каждой пешки в своей сетке, чтобы при перезагрузке страницы пешки вернулись к своим первоначальным координатам. Более того, если я этого не выясню, я не смогу сделать так, чтобы другие игроки видели координаты пешек.
Итак, вот код, который я получил на данный момент:
Код: Выделить всё
let gridSize = 7,
//characters array is empty usually because it gets all the pawn infos from the db
characters = [ {"id" : "1" , "name" : "Test", "hp" : "112"}
];
$('.grid')
.css(`grid-template-columns`, `repeat(${gridSize}, 4rem)`)
.html([...Array(gridSize**2)].map(() => '').join(''));
$('.characters')
.html(characters.map((character) =>
`${character.name}
hp: ${character.hp}
`).join(``))
.add('.grid .cell')
.sortable({
connectWith: '.characters, .grid .cell',
cursor: 'grabbing',
receive: (e, ui) => {
if(ui.item.parent().hasClass('cell')) {
let $cell = $(e.target),
$character = ui.item,
$characters = $cell.find('.character').not($character),
coords = [$cell.index() % gridSize, Math.floor($cell.index() / gridSize)];
coords = coords.toString();
let characterId = $character.find('.stats').attr('id');
updateCharacterPosition(characterId, coords)//writes the new pawn's position to the db
}
}
});
function updateCharacterPosition(characterId, coords) {
$.ajax({
url: "/coords/" + characterId,
method: 'PATCH',
data: {
_token: $('meta[name="csrf-token"]').attr('content'),
newcoords: coords
},
success: function(response) {
console.log('Character position updated successfully');
},
error: function(xhr, status, error) {
console.error('Error updating character position:', error);
}
});
}
Код: Выделить всё
.grid{
border: 2px solid gray;
display: grid;
width: fit-content;}
.grid .cell{
align-items: center;
aspect-ratio: 1 / 1;
border: 1px solid lightgray;
display: flex;
justify-content: center;
overflow: visible;}
.grid .cell:has(.character):hover{
border-width: 2px;
box-sizing: border-box;}
.characters{
border: 2px solid gray;
display: flex;
gap: 1rem;
margin-top: 1rem;
min-height: 3rem;
min-width: 6rem;
padding: 1rem;
width: fit-content;}
.character{
align-items: end;
background-color: #000000;
border-radius: 50%;
color: #ffffff;
display: flex;
height: 3rem;
justify-content: center;
text-align: center;
width: 3rem;}
.character .stats{
background-color: inherit;
padding: 4px;}
.character p{
font-size: .66rem;
margin: 0;
white-space: nowrap;}
Код: Выделить всё
Подробнее здесь: https://stackoverflow.com/questions/782 ... ach-elemen