xxxxxxxxxx
108
class Segment{
constructor(head, rad){
this.head = head
this.rad = rad
this.x = this.head.x + rad/2
this.y = this.head.y + rad/2
}
updatePos(sine, cosine){
this.x = this.head.x + 4*this.rad*sine
this.y = this.head.y + 4*this.rad*cosine
}
draw(){
fill(255)
ellipse(this.x, this.y, this.rad)
}
}
class Snake{
constructor(){
this.rad = windowWidth/15
this.x = windowWidth/2
this.y = windowHeight/2
this.speed = 5
this.xdiff=0
this.ydiff=0
this.segments = []
}
addSegment(){
this.segments[this.segments.length] = new Segment(this, this.rad)
}
draw(){
fill(255)
let xdiff = mouseX - this.x
let ydiff = mouseY - this.y
length = sqrt(xdiff*xdiff + ydiff*ydiff)
let movedlength = sqrt(movedX*movedX +movedY*movedY)
if (movedlength>this.speed) {
this.xdiff = xdiff/length
this.ydiff = ydiff/length
}
this.x = this.x + this.xdiff*this.speed
this.y = this.y + this.ydiff*this.speed
ellipse(this.x,this.y, this.rad)
for(let i=0;i<this.segments.length;i++){
this.segments[i].updatePos(this.xdiff/length, this.ydiff/length)
this.segments[i].draw()
}
}
}
function printScore() {
fill(color(255))
rect(margin, margin, windowWidth/2-2*margin, windowHeight/10 - 2*margin)
textAlign(RIGHT)
fill(color(255,0,0))
textSize(windowHeight/20)
text(score, windowWidth/2-2*margin, windowHeight/10-2*margin)
textAlign(LEFT)
fill(color(0))
textSize(windowHeight/30)
text('Score:', 2*margin, margin + windowHeight/20)
}
function printLives() {
fill(color(255))
rect(margin+ windowWidth/2, margin, windowWidth/2-2*margin, windowHeight/10 - 2*margin)
textAlign(RIGHT)
fill(color(255,0,0))
textSize(windowHeight/20)
text(lives, windowWidth-2*margin, windowHeight/10-2*margin)
textAlign(LEFT)
fill(color(0))
textSize(windowHeight/30)
text('Lives:', 2*margin+ windowWidth/2, margin + windowHeight/20)
}
function printPlayArea() {
let top = windowHeight/10
let left = margin
right = margin
fill(color(0))
rect(left,top,windowWidth - margin*2,windowHeight*0.9 - 2*margin)
}
let score = 0
let lives = 3
let margin = 10
let snake
function setup() {
createCanvas(windowWidth, windowHeight);
snake = new Snake()
snake.addSegment()
}
function draw() {
background(220);
printLives()
printScore()
printPlayArea()
snake.draw()
}