xxxxxxxxxx
139
class Food{
constructor(){
this.visible = false;
this.rad = 70
this.x = 0
this.y = 0
}
draw(){
if (this.visible){
fill(255,0,0)
circle(this.x, this.y, this.rad)
}
}
spawn(){
this.visible = true
this.x = random(width)
this.y = random(height)
}
kill(){
this.visible = false
}
contains(x,y){
if (dist(x,y,this.x,this.y)<this.rad){
return true;
}
else return false;
}
}
food = new Food()
class SlowCircle{
constructor(x,y,rad, targetDist){
this.x = x
this.y = y
this.rad = rad
this.targetX = 0
this.targetY = 0
this.speedX = 3
this.speedY = 3
this.targetDist = targetDist
}
draw(){
fill(255)
if (abs(this.targetX-this.x)>this.targetDist){
if (this.targetX>this.x){
this.x = this.x + this.speedX
} else {
this.x = this.x - this.speedX
}
}
if (abs(this.targetY-this.y)>this.targetDist){
if (this.targetY>this.y){
this.y = this.y + this.speedY
} else {
this.y = this.y - this.speedY
}
}
// if (this.targetX>this.x){
// this.x = this.x + this.speedX
// } else {
// this.x = this.x - this.speedX
// }
// if (this.targetY>this.y){
// this.y = this.y + this.speedY
// } else {
// this.y = this.y - this.speedY
// }
ellipse(this.x,this.y,this.rad)
}
}
class Snake{
constructor(rad, pieces, x, y){
this.rad = rad
this.x = x
this.y = y
this.targetX = 0
this.targetY = 0
this.circles = []
for(let i=0;i<pieces;i++){
this.circles[i] = new SlowCircle(x,y,rad, rad/2)
x = x+rad/4
y = y+rad/4
}
}
draw(){
this.circles[0].targetX = this.targetX
this.circles[0].targetY = this.targetY
this.circles[0].draw()
this.x = this.circles[0].x
this.y = this.circles[0].y
this.circles[1].targetX = this.circles[0].x
this.circles[1].targetY = this.circles[0].y
this.circles[1].draw()
let xdiff = this.circles[1].x - this.circles[0].x
let ydiff = this.circles[1].y - this.circles[0].y
for(let i = 2;i<this.circles.length;i++){
this.circles[i].targetX = this.circles[i-1].targetX + xdiff
this.circles[i].targetY = this.circles[i-1].targetY + ydiff
this.circles[i].draw()
}
}
addPiece(){
let lastcircle = this.circles[this.circles.length-1]
let newcircle = new SlowCircle(lastcircle.x + this.rad, lastcircle.y + this.rad, this.rad, this.rad/2)
newcircle.targetX = lastcircle.x
newcircle.targetY = lastcircle.y
this.circles.push(newcircle)
}
}
let snake = new Snake(50,4, 10,10)
function setup() {
createCanvas(windowWidth, windowHeight);
food.spawn()
}
function draw() {
background(0);
snake.targetX = mouseX
snake.targetY = mouseY
snake.draw()
food.draw()
if (food.contains(snake.x,snake.y)){
food.spawn()
snake.addPiece()
}
}