snake: make game resizable by user

This commit is contained in:
Trianta 2024-11-25 15:20:56 -06:00
parent 47fd5c7458
commit 343af77bd1
2 changed files with 22 additions and 1 deletions

View File

@ -34,6 +34,12 @@
<canvas width="625" height="375" id="snake"></canvas>
<script src="public/snake.js"></script>
</div>
<p class="cardStats">
Adjust game size -- Width:
<input class="cardStats" id="snakeWidth" type="number" min="2" max="31" value="25">
Height:
<input class="cardStats" id="snakeHeight" type="number" min="2" max="24" value="15">
</p>
<p class="cardStats">Snake Head Location: <span id="snakeHead"></span></p>
<p class="cardStats">Food Location: <span id="snakeFood"></span></p>
<a class="navItem" href="https://lab.trianta.dev/Trianta/trianta.dev/src/branch/main/src/snake.ts">View Code</a>

View File

@ -169,6 +169,21 @@ class SnakeCore {
document.getElementById("snakeHead").innerHTML = "x: " + this.body[this.body.length - 1].x + " y: " + this.body[this.body.length - 1].y;
document.getElementById("snakeFood").innerHTML = "x: " + this.food.x + " y: " + this.food.y ;
}
// Update width and height from page to match game
getPageNumbers() {
let specifiedWidth = parseInt((document.getElementById("snakeWidth") as HTMLInputElement).value);
let specifiedHeight = parseInt((document.getElementById("snakeHeight") as HTMLInputElement).value);
if (this.width == specifiedWidth && this.height == specifiedHeight)
return false;
this.width = specifiedWidth;
this.height = specifiedHeight;
while (this.height > this.board.length)
this.board.push(new Array(this.width));
this.canvas.setAttribute("width", String(specifiedWidth * this.grid));
this.canvas.setAttribute("height", String(specifiedHeight * this.grid));
return true;
}
}
class Bot {
@ -270,7 +285,7 @@ const g_snakebot: Bot = new Bot();
// game loop
function snakeloop() {
// Reset of needed
if (g_snake.gameover)
if (g_snake.gameover || g_snake.getPageNumbers())
g_snake.reset();
// Simulate movement of snake