I've been working on a little bacteria simulator where the directions the bacteria take is "random", but it's creating a pattern where all bacteria go down the screen, why is this? what am I doing wrong?
My code:
var sandbox = "#main";
spawn(1);
for (var i = 0; i < 10; i++) {
$(sandbox).animate({
"height": $(sandbox).height()
}, 500, function() {
step();
});
}
function spawn(amount) {
var WIDTH = $(sandbox).width();
var HEIGHT = $(sandbox).height();
for (var i = 0; i < amount; i++) {
addLiving(Math.round(Math.random() * 9999999), Math.round(Math.random() * WIDTH), Math.round(Math.random() * HEIGHT), 15);
}
}
function addLiving(ID, LEFT, TOP, FOOD) {
$(sandbox).append('<div id="id' + ID + '" class="livingBeing" style="position:absolute;top:' + TOP + 'px;left:' + LEFT + 'px;background-color:#000;width:1px;height:1px" food="' + FOOD + '"></div>');
}
function step() {
$(".livingBeing").each(function() {
move(this);
eat(this);
split(this);
if (Math.round(parseInt($(this).attr("food"), 10)) > 0) {
$(this).attr("food", Math.round(parseInt($(this).attr("food"), 10) - 1));
} else {
$(this).remove();
}
});
}
function move(living) {
var way = Math.round(Math.random() * 3) + 1;
console.log(way);
if (way === 1) {
$(living).css({
'top': "+=1px"
});
}
if (way === 2) {
$(living).css({
'top': "-=1px"
});
}
if (way === 3) {
$(living).css({
'left': "-=1px"
});
}
if (way === 4) {
$(living).css({
'left': "+=1px"
});
}
if ($(living).position().top > $(sandbox).height()) {
$(living).css({
'top': "-=1px"
});
}
if ($(living).position().top < $(sandbox).height()) {
$(living).css({
'top': "+=1px"
});
}
if ($(living).position().left > $(sandbox).height()) {
$(living).css({
'left': "-=1px"
});
}
if ($(living).position().left < $(sandbox).height()) {
$(living).css({
'left': "+=1px"
});
}
}
function eat(living) {
//if livingBeing1 is now at the same spot as livingbeing2 then livingBeing2 dies and
//livingBeing1 gets livingBeing2's food
$(".livingBeing").each(function() {
if ($(this).position().top === $(living).position().top && $(this).position().left === $(living).position().left && $(this).id !== $(living).id) {
$(living).attr("food", parseInt($(living).attr("food"), 10) + parseInt($(this).attr("food"), 10));
$(this).remove();
}
});
}
function split(living) {
//if food greater than/equal (Math.random()*10)+2; then split
if (parseInt($(living).attr("food"), 10) >= (Math.random() * 20) + 10) {
addLiving(Math.round(Math.random() * 9999999), $(living).position().left + 1, $(living).position().top + 1, Math.floor(parseInt($(living).attr("food"), 10) / 2));
$(living).attr("food", Math.floor(parseInt($(living).attr("food"), 10) / 2));
}
}
#main {
position: fixed;
width: 100px;
height: 100px;
border: 1px solid #C3C3C3;
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ift.tt/J5OMPW"></script>
<title>testing</title>
</head>
<body>
<div id="main"></div>
</body>
</html>
Aucun commentaire:
Enregistrer un commentaire