xxxxxxxxxx
162
let snake;
let resolution = 30;
let food;
let w, h;
let score = 0;
let specialFood = null;
let specialFoodChance = 0.1;
let specialFoodValue = 3;
const bgColor = 0;
const snakeColor = '#8FBC8F';
const foodColor = '#ADFF2F';
const specialFoodColor = '#FFD700';
function setup() {
createCanvas(windowWidth, windowHeight);
background(bgColor);
w = width / resolution;
h = height / resolution;
frameRate(10);
snake = new Snake(snakeColor);
addFood();
}
function draw() {
background(bgColor);
fill(foodColor);
rect(food.x * resolution, food.y * resolution, resolution, resolution);
if (specialFood) {
fill(specialFoodColor);
rect(specialFood.x * resolution, specialFood.y * resolution, resolution, resolution);
}
if (snake.eat(food)) {
addFood();
score++;
}
if (specialFood && snake.eat(specialFood, specialFoodValue)) {
specialFood = null;
score += specialFoodValue;
}
snake.update();
snake.show();
if (snake.endGame()) {
print("GAME OVER!");
background('#FF0000');
noLoop();
}
//Score
fill(255);
textSize(20);
text("Score: " + score, 10, 30);
}
function keyPressed() {
if (keyCode === LEFT_ARROW && snake.dir.x !== 1)
snake.setDir(-1, 0);
else if (keyCode === RIGHT_ARROW && snake.dir.x !== -1)
snake.setDir(1, 0);
else if (keyCode === DOWN_ARROW && snake.dir.y !== -1)
snake.setDir(0, 1);
else if (keyCode === UP_ARROW && snake.dir.y !== 1)
snake.setDir(0, -1);
}
function addFood() {
let x = floor(random(w));
let y = floor(random(h));
food = createVector(x, y);
if(!specialFood) {
if (random(1) < specialFoodChance)
specialFood = createVector(floor(random(w)), floor(random(h)));
else specialFood = null;
}
}
class Snake {
constructor(snakeColor) {
this.body = [];
this.body[0] = createVector(floor(w / 2), floor(h / 2));
this.dir = createVector(0, 0);
this.len = 1;
this.snakeColor = snakeColor;
}
update() {
let head = this.body[this.body.length - 1].copy();
this.body.shift();
head.x += this.dir.x;
head.y += this.dir.y;
if (head.x >= w) {
head.x = 0;
}
else if (head.x < 0) {
head.x = w - 1;
}
if (head.y >= h) {
head.y = 0;
}
else if (head.y < 0) {
head.y = h - 1;
}
this.body.push(head);
}
show() {
fill(this.snakeColor);
for (let i = 0; i < this.body.length; i++) {
rect(this.body[i].x * resolution, this.body[i].y * resolution, resolution, resolution);
}
}
setDir(x, y) {
this.dir.x = x;
this.dir.y = y;
}
eat(pos, growAmount = 1) {
let head = this.body[this.body.length - 1];
let distance = dist(head.x, head.y, pos.x, pos.y);
let collisionThreshold = 0.8;
if (distance < collisionThreshold) {
for (let i = 0; i < growAmount; i++) {
this.body.unshift(createVector(this.body[0].x - this.dir.x, this.body[0].y - this.dir.y));
this.len++;
}
return true;
}
return false;
}
endGame() {
let x = this.body[this.body.length - 1].x;
let y = this.body[this.body.length - 1].y;
for (let i = 0; i < this.body.length - 1; i++) {
let part = this.body[i];
if (part.x === x && part.y === y) {
return true;
}
}
return false;
}
}