Как сделать анимацию передвижения картинки (чтобы было плавно)?
Пытаюсь написать простую игру "монополия", где есть как минимум один игрок и общее игровое поле. На поле есть клетки, расположенные по кругу. Игрок нажимает на кнопку "бросить кубик" и передвигается по клеткам после (в количестве выпавшего случайного числа). Получения рандомного числа (аналогия броска игрального кубика).
Функция, которая передвигает картинку-игрока, имеет цикл, где изменяю css свойства через js. Если добавляю transition: 0.1s; для картинки, то картинка-игрок передвигается только на одну клетку (1 итерация цикла), а остальное, видимо, выполняется за эти 0.1, но не применяется к css файлу. Пробовал параллельно замедлять итерацию в js, но не помогло. Подскажите, пожалуйста, как сделать плавным каждый переход на следующую клетку.
P.S. (доп. вопрос) сделал 5 клеток, а нужно 36 (9*4), потому что было лень прописывать для каждого квадрата свои css свойства, может, можно использовать какое-нибудь циклическое css-свойство, чтобы было меньше кода, если такое имеется?
var player_colors = ["red_player", "green_player", "blue_player", "purple_player", "yellow_player"]
function createImage(src, id) {
var image = document.createElement("img");
image.style.height = "30px";
image.style.position = "absolute";
image.style.left = "21px";
image.style.top = "21px";
image.setAttribute("src", src);
image.setAttribute("id", id);
document.getElementById('play-field').appendChild(image);
}
function randomInteger(min, max) {
// случайное число от min до (max+1)
let rand = min + Math.random() * (max + 1 - min);
return Math.floor(rand);
}
class Player {
constructor(name, money, number) {
this.name = name;
this.money = money;
this.place = 0;
this.number = number;
this.color = player_colors[number];
this.near_left_wall = true;
this.near_right_wall = false;
this.near_top_wall = true;
this.near_bottom_wall = false;
let src = "images/" + String(this.color) + ".png";
let id = String(this.color);
createImage(src, id);
}
movePlayer(cell_number) {
let player_id = this.color
for (let i = 0; i < cell_number; i++) {
let player_x = document.getElementById(player_id).offsetLeft;
let player_y = document.getElementById(player_id).offsetTop;
//если игрок в верхней линии клеток, но не в последней
console.log("лево:" + this.near_left_wall +
"\nверх" + this.near_top_wall +
"\nправо" + this.near_right_wall +
"\nниз" + this.near_bottom_wall)
if (this.near_top_wall && !this.near_right_wall) {
let player_xn = player_x + 72;
document.getElementById(player_id).style.left = player_xn + "px";
if (player_xn > 72 * 9) this.near_right_wall = true;
else if (player_xn > 72) this.near_left_wall = false;
continue;
}
//если игрок в правой линии клеток, но не в последней
if (this.near_right_wall && !this.near_bottom_wall) {
let player_yn = player_y + 72;
document.getElementById(player_id).style.top = player_yn + "px";
if (player_yn > 72 * 9) this.near_bottom_wall = true;
else if (player_yn > 72) this.near_top_wall = false;
continue;
}
//если игрок в нижней линии клеток, но не в последней
if (this.near_bottom_wall && !this.near_left_wall) {
let player_xn = player_x - 72;
document.getElementById(player_id).style.left = player_xn + "px";
if (player_xn < 72) this.near_left_wall = true;
else if (player_xn < 72 * 9) this.near_right_wall = false;
continue;
}
//если игрок в ЛЕВОЙ линии клеток, но не в последней
if (this.near_left_wall && !this.near_top_wall) {
let player_yn = player_y - 72;
document.getElementById(player_id).style.top = player_yn + "px";
if (player_yn < 72) this.near_top_wall = true;
else if (player_yn < 72 * 9) this.near_bottom_wall = false;
continue;
}
//TODO дописать
}
}
}
class Game {
constructor(player_number, player_list) {
this.player_number = player_number;
this.player_list = player_list;
this.current_player = this.player_list[0];
}
rollTheDice() {
let random_num1 = randomInteger(1, 6);
let random_num2 = randomInteger(1, 6);
let result_msg = String(random_num1);
result_msg += " " + String(random_num2);
alert(result_msg);
this.current_player.movePlayer(random_num1 + random_num2);
}
}
function createGame() {
player1 = new Player("Виктор", 15000, 0);
game = new Game(1, [player1]);
}
function startGame() {
createGame();
}
#play-field {
width: 720px;
height: 720px;
margin: 0 auto;
background-color: #192124;
position: relative;
}
.roll-dice-btn {
width: 144px;
height: 72px;
position: absolute;
top: 144px;
left: 144px;
}
.dice-result-text {
width: 144px;
height: 72px;
position: absolute;
top: 144px;
left: 360px;
}
#play-field .play-cell {
width: 72px;
height: 72px;
outline: 1px solid white;
position: absolute;
}
#play-field .play-cell-1 {
left: 0;
top: 0;
}
#play-field .play-cell-2 {
left: 72px;
top: 0;
}
#play-field .play-cell-3 {
left: 144px;
top: 0;
}
#play-field .play-cell-4 {
left: 216px;
top: 0;
}
#play-field .play-cell-5 {
left: 288px;
top: 0;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Monopoly</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body onload="startGame()">
<div id="play-field">
<div class="play-cell play-cell-1"></div>
<div class="play-cell play-cell-2"></div>
<div class="play-cell play-cell-3"></div>
<div class="play-cell play-cell-4"></div>
<div class="play-cell play-cell-5"></div>
<div class="play-cell play-cell-6"></div>
<div class="play-cell play-cell-7"></div>
<div class="play-cell play-cell-8"></div>
<div class="play-cell play-cell-9"></div>
<div class="play-cell play-cell-10"></div>
<input class="roll-dice-btn" id="roll-dice-btn" value="Бросить кубик" onclick="game.rollTheDice()" type="button">
<input class="dice-result-text" type="text" name="key" placeholder="Результат">
<!-- unused -->
<!-- <img src="images/player_red.png" id="player_red"> -->
</div>
<script src="js/javascript.js"></script>
</body>
</html>