我第一次用画布做实验,有一个小游戏,障碍物从右边随机飞到左边,左边的玩家可以上下移动来躲避它们,每一次躲避都会得分,它会存储高分.
我需要使用for循环手动将障碍物添加到数组中,以将它们添加到画布中的任意x,y位置:
function ChooseRandom(min, max) { // random generator function
return Math.random() * (max - min) + min;
}
const obstacles = [ // array of obstacles to create using randomly generated positions
{
x: ChooseRandom(500, 2500),
y: ChooseRandom(0, 500),
width: 50,
height: 50
},
{
x: ChooseRandom(500, 2500),
y: ChooseRandom(0, 500),
width: 50,
height: 50
},
{
x: ChooseRandom(500, 2500),
y: ChooseRandom(0, 500),
width: 50,
height: 50
}
]
for (let i = 0; i < obstacles.length; i++) { // loop creating the obstacles using array
const obstacle = obstacles[i];
ctx.fillRect( // create obstacle
obstacle.x,
obstacle.y,
obstacle.width,
obstacle.height
);
}
数组中的项越多,它就变得越困难(因为需要避免更多的派生).因为每一项都使用相同的代码,有没有一种方法只需输入/设置一个数字,然后它就可以用这么多障碍项填充数组?
显然,这将节省代码大小,但我也在考虑添加一个难度 Select 字段,所以如果 Select 了Easy,它在任何时候只会在屏幕上添加6个障碍(数组中的6个项)、Medium 12、Hard 24等.所以如果有办法用从不同集合编号生成的大量重复项填充数组,在这种情况下会有所帮助.