Hi I'm creating a snake game right now and I have a problem that my food is not aligned with my snake so I can't get my snake to eat it, no error messsages just can't get that working, please explain where I went wrong and how I can get this to be aligned and eaten.
Here is my code:
My Food:
function columns()
{
return floor(width / scl);
}
function rows()
{
return floor(height / scl);
}
function randomPlaceFood()
{
return createVector(floor(random(columns())), floor(random(rows())));
}
function Food()
{
this.vector = randomPlaceFood().mult(scl);
this.x = random(0, 700);
this.y = random(0, 700);
this.updateFood = function()
{
this.vector = randomPlaceFood().mult(scl);
}
this.showFood = function()
{
fill(255, 0, 10);
rect(this.x, this.y, scl, scl);
}
}
My Snake:
function Snake()
{
this.x = 0;
this.y = 0;
this.xspeed = 0;
this.yspeed = 0;
this.updateSnake = function()
{
this.x = this.x + this.xspeed * scl;
this.y = this.y + this.yspeed * scl;
this.x = constrain(this.x, 0, width - scl);
this.y = constrain(this.y, 0, height - scl);
}
this.showSnake = function()
{
fill(255);
rect(this.x, this.y, scl, scl);
}
this.direction = function(x, y)
{
this.xspeed = x;
this.yspeed = y;
}
this.eatFood = function()
{
if (this.x === food.x && this.y === food.y)
{
randomPlaceFood();
}else
{
randomPlaceFood();
}
}
this.keyPressed = function()
{
if (keyCode === 87)
{
snake.direction(0, -1);
} else if (keyCode === 83)
{
snake.direction(0, 1);
} else if (keyCode === 68)
{
snake.direction(1, 0);
} else if (keyCode === 65)
{
snake.direction(-1, 0);
}
}
}
And the main file:
var snake;
var scl = 20;
var food;
function setup()
{
//Sets the Canvas
createCanvas(700, 700);
//Creates a new object using the variable snake
snake = new Snake();
food = new Food();
frameRate(10);
}
function draw()
{
//Sets the Background, number implies the colour
background(40);
//Adds all the values set within the function to the snake
snake.updateSnake();
snake.showSnake();
snake.keyPressed();
food.showFood();
food.updateFood();
if(snake.eatFood())
{
randomPlaceFood();
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…