cows

by Kirill

HTML

<canvas id="canvas"></canvas>

CSS

#canvas {
    width: 300px;
    height: 300px;
    border: 1px solid black;
}

JavaScript

var ctx = document.getElementById('canvas').getContext('2d');
    ctx.canvas.width = ctx.canvas.clientWidth;
    ctx.canvas.height = ctx.canvas.clientHeight;
    ctx.strokeStyle = "#00ff00";
    ctx.lineWidth = 1;
    ctx.fillStyle = "rgba(0,255,0,0.5)";
    ctx.lineJoin = "bevel";
    ctx.linecap = "square";        
function getRandomInt(min, max)
{
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
var grass = {
    x: 100,
    y: 100,
    width: 10,
    height: 10,
    eat: 100,
    isEaten: function() {
        this.eat--;
    },
    draw: function() {
        ctx.beginPath();
        ctx.rect(this.x,this.y,20,20);
        ctx.fillStyle="#0f0"
        ctx.fill();
    }
}
var cow = {
    x: 70,
    y: 50,
    tx: 200,
    ty: 200,
    speed: 1,
    area: 20,
    draw: function() {
        ctx.beginPath();
        ctx.rect(this.x,this.y,5,5);
        ctx.fillStyle="#000"
        ctx.fill();
    },
    clear: function() {
        ctx.beginPath();
        ctx.rect(this.x,this.y,20,20);
        ctx.fillStyle="#fff"
        ctx.fill();
    },
    scan: function() {
        if(Math.abs(this.x-grass.x)<this.area && Math.abs(this.y-grass.y)<this.area) {
            return {
                name: "grass",
                x: grass.x,
                y: grass.y,
            }   
        }
    },
    walk: function() {
        if(typeof(this.scan())=="object") {
            if(this.scan().name=="grass") {
                console.log("found eat!")
                this.speed = 5;
                this.tx = this.scan().x;
                this.ty = this.scan().y;
            }
        }
        this.clear();
        var distance = Math.round(Math.sqrt(Math.pow(Math.abs(this.x-this.tx),2) + Math.pow(Math.abs(this.y-this.ty),2)));
        this.x+=Math.round(((this.tx-this.x)*this.speed)/distance);
        this.y+=Math.round(((this.ty-this.y)*this.speed)/distance);
        this.draw();
    }
}
grass.draw();
setInterval (function() {
    cow.walk();
}, 1000);