xxxxxxxxxx
144
//Code Credit: 1. Snake game: https://www.skillshare.com/classes/Snake-Make-A-Classic-Game-using-Javascript-P5-js-Framework/230116486/projects
var numOfBlocks = 30;
var blockSize = 20;
var headX = 0;
var headY = 0;
var speadX = 0;
var speadY = 0;
var tailLength = 3;
var tailBlocks = [];
var appleX = 0;
var appleY = 0;
var score = 0;
function setup() {
createCanvas(600, 600);
frameRate(10);
//start at the center
headX = 300;
headY = 0;
//苹果!!apple
apple();
}
function draw() {
background(30,28,29);
scorePage();
// add a new tail 尾巴
tailBlocks.push({x: headX, y: headY})
//变短
while(tailBlocks.length > tailLength){
tailBlocks.shift()
}
//tailBlocks;
for(let i = 0; i < tailBlocks.length; i++){
fill(255,100)
rect(tailBlocks[i].x * blockSize,
tailBlocks[i].y * blockSize,
blockSize,
blockSize);
}
//anmation of snake蛇头动态
headX = headX + speadX;
headY = headY + speadY;
//loop the snake back to the edge!! 蛇头回归
if(headX < 0){
headX = numOfBlocks - 1;
}
if(headX > numOfBlocks -1){
headX = 0;
}
if(headY < 0){
headY = numOfBlocks - 1;
}
if(headY > numOfBlocks -1){
headY = 0;
}
//苹果!!
//吃苹果! eat apple
if(headX === appleX && headY === appleY){
apple();
//加尾巴
tailLength++;
//加分
score++;
print(score);
}
//draw 苹果
fill(255,0,0,180);
rect(appleX * blockSize,
appleY * blockSize,
blockSize, blockSize);
//蛇头块 snake head
fill(255,180);
rect(headX * blockSize,
headY * blockSize,
blockSize,blockSize);
// drawCoordinate();
}
function keyPressed(){
if(key == 'w'){
speadX = 0;
speadY = -1;
}else if(key == 's'){
speadX = 0;
speadY = 1;
}else if(key == 'a'){
speadX = -1;
speadY = 0;
}else if(key == 'd') {
speadX = 1;
speadY = 0;
}
}
function apple(){
appleX = floor(random(0, numOfBlocks));
appleY = floor(random(0, numOfBlocks));
}
function scorePage(){
fill(0);
textSize(20);
text('Score:' + score, 521,586);
}
/*function drawCoordinate(){
strokeWeight(0);
fill(0);
text("X: "+mouseX, 0, 50);
text("Y: "+mouseY, 0, 30);
}*/