черновой набросок
<style>
.container {
position:absolute;
top:30px;
left:20px;
width:400px;
height:400px;
border:1px solid gray;
}
.animal {
width:20px;
height:20px;
transition: 0.3s;
border-radius: 10px;
background-color: red;
}
.stone {
width:20px;
height:20px;
border-radius: 10px;
background-color: black;
}
</style>
Количество животных: <input type='number' id ='aCount' value='2'>
Количество камней: <input type='number' id ='sCount' value='10'>
<input type='button' id='mainBut' value='Пуск'>
<div class='container'></div>
<script>
var field = document.querySelector('.container'),
fieldTop = +field.style.top,
fieldLeft = +field.style.left,
unit,
units = [],
animals = [],
stoneCount = 10,
animalCount = 2,
stopFlag = false;
function createUnit(unitType) {
var unitTop, unitLeft, noFree = true, unitPos = {};
do {
unitTop = (Math.round(Math.random() * 19 ) * 20 - fieldTop) + 'px';
unitLeft = (Math.round(Math.random() * 19 ) * 20 - fieldLeft) + 'px';
noFree = false;
for(var i = 0; i < units.length; i++){
if(units[i].top == unitTop && units[i].left == unitLeft) noFree = true;
}
} while (noFree);
unit = document.createElement('div');
unit.classList.add(unitType);
unit.style.position = 'absolute';
unit.style.top = unitTop;
unit.style.left = unitLeft;
field.appendChild(unit);
unitPos.top = unitTop;
unitPos.left = unitLeft;
units.push(unitPos);
if(unitType == 'animal') {
animals.push(unitPos);
unit.id = "a" + i;
unit.innerText = i;
}
}
function moveAnimals() {
var stepTop, stepLeft, unitTop, unitLeft, noFree, unitPos = {};
for(var i = 0; i<animals.length;i++) {
noFree = true;
do {
stepTop = Math.round(Math.random() * 2 - 1) * 20;
stepLeft = Math.round(Math.random() * 2 - 1) * 20;
unitTop = +animals[i].top.replace(/\D/g,"") + stepTop;
unitLeft = +animals[i].left.replace(/\D/g,"") + stepLeft;
if(unitTop < 0 || unitLeft < 0 || unitTop > 380 || unitLeft > 380) { noFree = true; }
else {
unitTop = unitTop + "px";
unitLeft = unitLeft + "px";
noFree = false;
for(var j = 0; j< units.length; j++){
if(units[j].top == unitTop && units[j].left == unitLeft) noFree = true;
}
}
} while (noFree);
units[i].top = unitTop;
units[i].left = unitLeft;
animals[i].top = unitTop;
animals[i].left = unitLeft;
var elem = document.querySelector('#a' + i);
elem.style.top = unitTop;
elem.style.left = unitLeft;
}
}
function start() {
if(stopFlag) return;
moveAnimals();
setTimeout(start, 500);
};
function startLife() {
for(var i = 0; i < animalCount;i++){
createUnit('animal');
}
for(var i = 0; i < stoneCount;i++){
createUnit('stone');
}
start();
}
document.querySelector('#mainBut').onclick = function() {
if(this.value == 'Пуск') {
stopFlag = false;
animalCount = +document.querySelector('#aCount').value;
stoneCount = +document.querySelector('#sCount').value;
this.value = 'Стоп';
startLife();
}
else {
stopFlag = true;
this.value = 'Пуск';
field.innerHTML = "";
units = [];
animals = [];
}
}
</script>