|
|
(не показано 10 промежуточных версий 2 участников) |
Строка 1: |
Строка 1: |
| var canvas = document.createElement("canvas");
| | $(function () { |
| canvas.width = 300;
| | var messageDiv = $('<div id="test-message">').text('Скрипт успешно загружен!'); |
| canvas.height = 300;
| | $('body').prepend(messageDiv); |
| document.body.appendChild(canvas);
| | console.log('Тестовое сообщение добавлено на страницу.'); |
| var ctx = canvas.getContext("2d");
| | }); |
| | |
| var gridSize = 10;
| |
| var snake = [{x: 50, y: 50}];
| |
| var direction = {x: gridSize, y: 0};
| |
| var food = {x: 100, y: 100};
| |
| var gameOver = false;
| |
| | |
| function draw() { | |
| ctx.clearRect(0, 0, canvas.width, canvas.height); | |
| | |
| ctx.fillStyle = "#00FF00";
| |
| snake.forEach(function(segment) {
| |
| ctx.fillRect(segment.x, segment.y, gridSize, gridSize);
| |
| });
| |
| | |
| ctx.fillStyle = "#FF0000";
| |
| ctx.fillRect(food.x, food.y, gridSize, gridSize);
| |
| | |
| if (gameOver) {
| |
| ctx.fillStyle = "#000000";
| |
| ctx.fillText("Game Over!", canvas.width / 2 - 40, canvas.height / 2);
| |
| } | |
| }
| |
| | |
| function update() {
| |
| if (gameOver) return;
| |
| | |
| var newHead = {x: snake[0].x + direction.x, y: snake[0].y + direction.y};
| |
| | |
| if (newHead.x < 0 || newHead.x >= canvas.width || newHead.y < 0 || newHead.y >= canvas.height || collision(newHead)) {
| |
| gameOver = true;
| |
| return;
| |
| }
| |
| | |
| snake.unshift(newHead);
| |
| | |
| if (newHead.x === food.x && newHead.y === food.y) { | |
| food = {x: Math.floor(Math.random() * (canvas.width / gridSize)) * gridSize, y: Math.floor(Math.random() * (canvas.height / gridSize)) * gridSize};
| |
| } else {
| |
| snake.pop();
| |
| }
| |
| }
| |
| | |
| function collision(head) {
| |
| for (var i = 1; i < snake.length; i++) {
| |
| if (head.x === snake[i].x && head.y === snake[i].y) {
| |
| return true;
| |
| }
| |
| }
| |
| return false;
| |
| }
| |
| | |
| function changeDirection(event) {
| |
| if (event.keyCode === 37 && direction.x === 0) {
| |
| direction = {x: -gridSize, y: 0};
| |
| } else if (event.keyCode === 38 && direction.y === 0) {
| |
| direction = {x: 0, y: -gridSize};
| |
| } else if (event.keyCode === 39 && direction.x === 0) {
| |
| direction = {x: gridSize, y: 0};
| |
| } else if (event.keyCode === 40 && direction.y === 0) {
| |
| direction = {x: 0, y: gridSize};
| |
| }
| |
| }
| |
| | |
| document.addEventListener("keydown", changeDirection);
| |
| | |
| function gameLoop() {
| |
| update();
| |
| draw();
| |
| if (!gameOver) {
| |
| setTimeout(gameLoop, 100);
| |
| }
| |
| }
| |
| | |
| gameLoop();
| |