snake: implement input buffer

Hunter
Thursday, July 24th, 2025 at 1:04 PM

pages/snake/index.html+19-10

pages/snake/index.html
234  		let board = [];
235  		let snake = [{x: 10, y: 10}];
236  		let direction = {x: 0, y: -1};
    -		let nextDirection = {x: 0, y: -1};
237 +		let inputBuffer = [];
238 +		const MAX_INPUT_BUFFER_SIZE = 3;
239  		let apple = {x: 5, y: 5};
240  		let score = 0;
241  		let highScore = 0;

343  		function moveSnake() {
344  			if (!gameRunning) return;
345  			
    -			// Use the next direction for movement
    -			direction = nextDirection;
346 +			// Process next direction from input buffer if available
347 +			if (inputBuffer.length > 0) {
348 +				direction = inputBuffer.shift();
349 +			}
350  			
351  			const head = {
352  				x: snake[0].x + direction.x,

408  			// Reset game state first
409  			snake = [{x: 10, y: 10}];
410  			direction = {x: 0, y: -1};
    -			nextDirection = {x: 0, y: -1};
411 +			inputBuffer = [];
412  			score = 0;
413  			gameSpeed = 200;
414  			document.getElementById('score').textContent = `Score: ${score}`;

473  		function setDirection(newDirection) {
474  			if (!gameRunning) return;
475  			
476 +			// Don't add if buffer is full
477 +			if (inputBuffer.length >= MAX_INPUT_BUFFER_SIZE) return;
478 +			
479 +			// Get the most recent direction (either from buffer or current direction)
480 +			const lastDirection = inputBuffer.length > 0 ? inputBuffer[inputBuffer.length - 1] : direction;
481 +			
482  			// Allow any direction when snake is only 1 segment long
483  			if (snake.length === 1) {
    -				nextDirection = newDirection;
484 +				inputBuffer.push(newDirection);
485  				return;
486  			}
487  			
    -			// Prevent reversing into self by checking current direction
    -			if (newDirection.x !== 0 && direction.x !== -newDirection.x) {
    -				nextDirection = newDirection;
    -			} else if (newDirection.y !== 0 && direction.y !== -newDirection.y) {
    -				nextDirection = newDirection;
488 +			// Prevent reversing into self by checking the last direction
489 +			if (newDirection.x !== 0 && lastDirection.x !== -newDirection.x) {
490 +				inputBuffer.push(newDirection);
491 +			} else if (newDirection.y !== 0 && lastDirection.y !== -newDirection.y) {
492 +				inputBuffer.push(newDirection);
493  			}
494  		}
495