xxxxxxxxxx
170
const size_=10;
const RIGHT_ = {x:size_,y:0};
const LEFT_ = {x:-size_,y:0};
const UP_ = {x:0,y:-size_};
const DOWN_ = {x:0,y:size_};
const bugs = ['🦋','🐞','🦀','🦐','🦂','🐛','🐝','🐙','🐡','🦞','🐌'];
let food_loc;
let food;
const W=800;
const H=600;
let game_over = false;
let start =false;
const title = "SNAKE GAME";
const score_label ="Score: ";
const speed_label ="Speed: ";
let score=0;
let speed =5;
function setup() {
createCanvas(W, H);
S= new Snake(Math.floor(W/2),Math.floor(H/2),10);
textSize(10);
food_loc = {x:random(10,W-10),y:random(60,H-10)};
food = bugs[Math.floor(Math.random() * bugs.length)];
}
function draw() {
background(0);
frameRate(speed);
wall_setup();
push()
fill('yellow');
textSize(18);
text(score_label,W/10,30);
fill('green');
text(score,W/5,30);
fill('magenta');
textSize(26);
text(title,W/2-title.length/2,30);
fill('cyan');
textSize(18);
text(speed_label,W-W/5,30);
fill('orange');
text(speed,W-W/10,30);
pop()
S.show();
if (start){
S.go();
text(food,food_loc.x,food_loc.y);
}
if (edist(S.head,food_loc)<10){
S.body.unshift({x:S.head.x,y:S.head.y});
S.content.unshift(food);
food_loc = {x:random(10,W-10),y:random(60,H-10)};
food = bugs[Math.floor(Math.random() * bugs.length)];
score+=10
speed+=1;
}
else if ((S.bit_itself()) || (S.head.x <10) || (S.head.x >W-20) || (S.head.y<60) || (S.head.y>H-10)){
game_over = true;
noLoop();
}
}
function edist(p1,p2){
return dist(p1.x,p1.y,p2.x,p2.y);
}
function wall_setup(){
for (let i=20;i<50;i=i+8){
text('◼︎',W/3,i);
text('◼︎',2*W/3,i);
}
for (let i=20;i<50;i=i+8){
text('◼︎',0,i);
text('◼︎',W-10,i);
}
for (let i=0;i<W;i=i+8){
text('◼︎',i,10);
}
for (let i=50;i<H;i=i+8){
text('▫️',0,i);
text('▫️',W-10,i);
}
for (let i=0;i<W;i=i+8){
text('▫️',i,50);
text('▫️',i,H);
}
}
function keyPressed(){
if (keyCode === LEFT_ARROW){
S.direction=LEFT_;
}
else if(keyCode === RIGHT_ARROW){
S.direction=RIGHT_;
}
else if(keyCode === DOWN_ARROW){
S.direction=DOWN_;
}
else if(keyCode === UP_ARROW){
S.direction=UP_;
}
else if (keyCode === ENTER){
start=true;
}
}
function Snake(x,y,size){
this.size=size;
this.body = [{x:x-size,y:y}];
this.head={x:x,y:y};
this.content= ['◻️'];
this.head={x:x,y:y};
this.head={x:x,y:y};
this.direction = RIGHT_
this.show = function(){
fill('red');
text('🔴',this.head.x,this.head.y);
fill('white');
textSize(this.size);
let i=0;
for(let b of this.body){
text(this.content[i],b.x,b.y);
i++;
}
}
this.go = function(){
const shead = {this.head};
this.head.x += this.direction.x;
this.head.y += this.direction.y;
this.body.unshift(shead);
this.body.pop();
}
this.bit_itself = function(){
for(let b of this.body){
if(edist(this.head,b)<10){
return true;
}
}
return false;
}
};