gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
почему ивент нажатия клавиши не работает? <html> <head> <meta charset="utf-8">…
- User
почему ивент нажатия клавиши не работает?
var canvasSize = 600; var floorSize = 40; var tileSize = canvasSize / floorSize; var chessboard = true; var score = 0; var maxScore = 0; var snake = [780] var food = getRandomInt(floorSize*floorSize) var canvas var ctx function main() { setInterval(render, 100); setInterval(physics, 100); } // Функция для получения индекса тайла из направления function getMovedTile(index, direction) { const moves = { up: -floorSize, down: floorSize, left: -1, right: 1 }; if (!moves.hasOwnProperty(direction)) return false; const newIndex = index + moves[direction]; if (newIndex < 0 || newIndex >= floorSize * floorSize) return false; // ню индекс аут оф баундс if (direction === 'left' && index % floorSize === 0 || direction === 'right' && (index + 1) % floorSize === 0) return false; //ню индекс аут оф горизонтальных баундс return newIndex; } function getRandomInt(max) { return Math.floor(Math.random() * max); } // функция для проверки "шахматности" тайла по индексу function isChessTile(index) { return (Math.floor(index / floorSize) + (index % floorSize)) % 2 == 0; } // функция для рендера тайла по индексу function renderTile(index, color) { let fillStyle = ctx.fillStyle; if (color) ctx.fillStyle = color; let x = (index % floorSize) * tileSize; let y = Math.floor(index / floorSize) * tileSize; ctx.fillRect(x, y, tileSize, tileSize); ctx.fillStyle = fillStyle } function render() { canvas = document.getElementById("mainCamera"); canvas.width = canvasSize; canvas.height = canvasSize; ctx = canvas.getContext("2d") ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = "#ff70ff"; // светлый оттенок пурпурного ctx.fillRect(0, 0, canvas.width, canvas.height); // отрисовка фона // игра еще ни разу не начиналась if (gamestate == -1) { ctx.fillStyle = "#FFFF"; ctx.font = "bold 30pt Arial"; ctx.textAlign = "center" ctx.fillText("добро пожаловать! :3", 300, 295); ctx.font = "15pt Arial"; ctx.fillText("нажмите пробел чтобы начать игру", 300, 295+25); } // игра проиграна if (gamestate == 0) { ctx.fillStyle = "#FFFF"; ctx.font = "bold 30pt Arial"; ctx.textAlign = "center" ctx.fillText("ви проебалі :(", 300, 275); ctx.font = "15pt Arial"; ctx.fillText("счет: " + score + " рекорд: " + maxScore, 300, 275+30); ctx.fillText("нажмите пробел чтобы продолжить игру!", 300, 275+75); } // игра идет if (gamestate == 1) { // отрисовка шахматного поля if (chessboard) { for (let i = 0; i < floorSize * floorSize; i++) { if (isChessTile(i)) {renderTile(i, "#ff78ff"); } } } // отрисовка еды renderTile(food, "#ffee00"); // отрисовка змеи for (let i = 0; i < snake.length; i++) { renderTile(snake[i], "#800080"); } } } function physics(){ canvas.addEventListener("keydown", function (event) { ctx.fillStyle = "#FFFF"; ctx.font = "bold 30pt Arial"; ctx.textAlign = "center" ctx.fillText("нажата " + event.key, 300, 295); }) let lastElement = snake.pop(); let modifiedElement = getMovedTile(lastElement, 'left') snake.unshift(modifiedElement); } </script> <style type="text/css"> canvas { /* выравнивание полотна по центру экрана */ position: absolute; top:-50; bottom: 0; left: 0; right: 0; margin:auto; /* контур вокруг полотна */ border: 2px solid black; } </style> </head> <body> <canvas id="mainCamera" width="150" height="150"> kril yourshelf </canvas> <script>main();</script> </body> - Assistant