diff --git a/levels/2.json b/levels/2.json index b656af7..9a5163e 100644 --- a/levels/2.json +++ b/levels/2.json @@ -4,6 +4,7 @@ "walls": [ [5,5], [5,6], [5,7], [5,8], [40, 35], [38, 35], [23, 35] ], + "randWallFreq": 5000, "food": [ [10,10], [11,10], @@ -13,6 +14,7 @@ [20, 23], [20, 21] ], + "randFoodFreq": 2000, "snake": [ [4,2], [4,1], [3,1], [2,1] ], diff --git a/script.js b/script.js index c4eb6b5..03e5ce6 100644 --- a/script.js +++ b/script.js @@ -41,6 +41,16 @@ function drawLine(ctx, x1, y1, x2, y2) { ctx.stroke(); } +/** + * Generate a random number + * + * @param {Number} min Minimum value + * @param {Number} max Maximum value + */ +function randInt(min, max) { + return Math.floor((Math.random()*max) + min) +} + // Get elements const startScreen = byId("startScreen") const gameScreen = byId("gameScreen") @@ -267,6 +277,32 @@ async function startGame(gameID) { if(["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(ev.key)) key = ev.key; }); + + // Automatically generate new map element if required + if(level.randWallFreq) { + const int = setInterval(() => { + if(!canvas.isConnected) + clearInterval(int); + else { + const pos = [randInt(0, map.length), randInt(0, map[0].length)] + if(map[pos[0]][pos[1]] == EMPTY) + map[pos[0]][pos[1]] = WALL; + } + }, level.randWallFreq); + } + + // Automatically generate new map element if required + if(level.randFoodFreq) { + const int = setInterval(() => { + if(!canvas.isConnected) + clearInterval(int); + else { + const pos = [randInt(0, map.length), randInt(0, map[0].length)] + if(map[pos[0]][pos[1]] == EMPTY) + map[pos[0]][pos[1]] = FOOD; + } + }, level.randFoodFreq); + } } /**