xxxxxxxxxx
151
size=40;
var speed=20;
var xvel=0;
var yvel=0;
var xarr=[];
var yarr=[];
var foodx;
var foody;
var len=1;
function preload() {
img = loadImage('/pj2.jpeg');
}
function setup() {
createCanvas(600, 600);
frameRate(10);
xarr.push(size);
yarr.push(size);
foodx=random(width);
foody=random(height);
}
function draw() {
background(220);
fill("skyblue")
rect(0,0, width/2, height);
fill("black");
rect(width/2, 0, width/2, height);
fill("white");
circle(foodx, foody, 20);
for(var i=0; i<xarr.length; i++)
{
if(i%2)
{
fill("purple");
}
else
{
fill("blue");
}
circle(xarr[i], yarr[i], size);
}
imageMode(CENTER);
image(img,xarr[0], yarr[0], size, size);
for(var i=xarr.length-1; i>0; i--)
{
xarr[i]=xarr[i-1];
yarr[i]=yarr[i-1];
}
xarr[0]+=xvel;
yarr[0]+=yvel;
if(xarr[0]>width)
{
xarr[0]=0;
}
else if(xarr[0]<0)
{
xarr[0]=width-size;
}
else if (yarr[0]>height)
{
yarr[0]=0;
}
else if(yarr[0]<0)
{
yarr[0]=height;
}
checkFood();
}
function keyPressed()
{
//console.log(keyCode);
switch (keyCode)
{
case 37: xvel=-1*speed;
yvel=0;
break;
case 38: xvel=0;
yvel=-1*speed;
break;
case 39: xvel=1*speed;
yvel=0;
break;
case 40: xvel=0;
yvel=1*speed;
break;
}
}
function checkFood()
{
if(dist(xarr[0], yarr[0], foodx, foody) <size/2)
{
foodx=random(width);
foody=random(height);
if(xvel<0)
{
xarr.push(xarr[0]+size);
yarr.push(yarr[0]);
}
else if(xvel>0)
{
xarr.push(xarr[0]-size);
yarr.push(yarr[0]);
}
else if(yvel<0)
{
yarr.push(yarr[0]+size);
xarr.push(xarr[0]);
}
else if(yvel>0)
{
yarr.push(yarr[0]-size);
xarr.push(xarr[0]);
}
//xarr.push(xarr[0]);
//yarr.push(yarr[0]);
}
}