CTX is not showing

  • 本文关键字:showing not is CTX ctx
  • 更新时间 :
  • 英文 :


我一直试图让CTX为学校的事情工作,但当我运行它时,它甚至没有出现。我想它可能会问,因为我的老师不想帮助我。

我试着把提供的视频看了几遍,看看我做错了什么,但我不能弄清楚。我只是想制作一款简单的蛇类游戏,但这款游戏的失败让我非常抓狂。帮助。

我将尝试张贴代码,就像它应该显示,我不知道它是否会工作。



<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>

有几个小问题:

  1. 函数keypush在game_function
  2. 中声明
  3. 起始速度为0,因此snake不移动
  4. tail.lengthtail_length不相同

var x_pos = 10;
var y_pos = 10;
var x_vel = 1;
var y_vel = 0;
var tile_count = 40;
var tail=[];
var tail_length = 5;
var canvas;
var ctx;
function game_function() {
// movement
x_pos += x_vel
y_pos += y_vel
if(x_pos<0) x_pos = tile_count-1;
if(y_pos<0) y_pos = tile_count-1;
if(x_pos>= tile_count) x_pos = 0;
if(y_pos>= tile_count) y_pos = 0;

tail.push({x:x_pos, y:y_pos});
while(tail.length > tail_length) tail.shift();
// rendering
var h_scale = (canvas.width*1.0 / tile_count);
var v_scale = (canvas.height*1.0 / tile_count);

ctx.fillStyle = "black"
ctx.fillRect(0,0, canvas.width, canvas.height);
ctx.fillStyle = "lime";
for(var i=0; i < tail.length; i++)
ctx.fillRect(tail[i].x * h_scale, tail[i].y * v_scale, h_scale, v_scale);
}
function keypush(e){
switch(e.code) {
case 'ArrowUp': x_vel=0; y_vel=-1; break;
case 'ArrowDown': x_vel=0; y_vel=1; break;
case 'ArrowLeft': x_vel=-1; y_vel=0; break;
case 'ArrowRight': x_vel=+1; y_vel=0; break;
}
}
window.onload = function(){
canvas = document.getElementById("game");
ctx = canvas.getContext('2d');
document.addEventListener("keydown", keypush);
setInterval(game_function, 1000/15);
}
<canvas id="game" width="160" height="160">
</canvas>

最新更新