i have been trying to get the ctx to work for a school thing, but it is not even showing up when i run it. i figured it might ask here due to the fact my teacher does not want to help me.
i have tried going over the video provided several times in order to see what i did wrong, but i could not figure it out. i'm just trying to make a simple snake game, and the fact this isn't working is driving me up the wall. help.
i am going to try to post the code like it should show, i don't know if it will work.
<script>
window.onload = function(){
canvas = document.getElementById("game");
ctx = canvas.getContext('2d');
document.addEventListener("keydown", keypush);
setInterval(game_function, 1000/15);
}
x_pos =10; // start lol
y_pos =10;
x_vel = 0;
y_vel = 0;
grid_size = 40; //the grid, ye idjut
tile_count = 40;
apple_x =15;
apple_y =15;
trail=[]; //has tail positions
tail_length = 5;
function game_function() {
//velocity based postion lol
x_pos = x_pos + x_vel
y_pos = y_pos + y_vel
// wrap, but not the kind you eat
if(x_pos<0) {
x_pos = tile_count-1;
}
if(y_pos<0) {
y_pos = tile_count-1;
}
if(x_pos> tile_count -1) {
x_pos = 0;
}
if(y_pos> tile_count -1) {
y_pos = 0;
}
function keypush(){
}
//background color
ctx.fillStyle = "black"
ctx.fillRect(0,0, canvas.width, canvas.height);
//snake color
ctx.fillStyle = "lime";
// segment coloring junk
for(var i=0; i < trail.length; i++)
{
ctx.fillRect(trail[i].x * grid_size, trail[i].y * grid_size, grid_size -1, grid_size -1);
}
//move
trail.push({x:x_pos, y:y_pos});
//delete the previous position
while(trail.length > tail.length) {
trail.shift();
}
}
</script>
There are several small problems:
tail.lengthis not the same astail_length