diff --git a/game/贪吃蛇/snake_game.html b/game/贪吃蛇/snake_game.html index 18e7bc1..0c74f30 100644 --- a/game/贪吃蛇/snake_game.html +++ b/game/贪吃蛇/snake_game.html @@ -32,6 +32,10 @@ } #snake-canvas-container { + /* === 修改点 1:显式设置宽度和高度,使其与 canvas 元素尺寸一致 === */ + width: 600px; /* 与 JavaScript 中 CANVAS_WIDTH 匹配 */ + height: 400px; /* 与 JavaScript 中 CANVAS_HEIGHT 匹配 */ + position: relative; border: 5px solid #00f2fe; box-shadow: 0 0 20px #00f2fe, 0 0 40px #00f2fe; @@ -43,6 +47,9 @@ #snakeCanvas { background-color: #333; display: block; + /* === 修改点 1:确保 canvas 实际宽度和高度与容器一致 === */ + width: 100%; + height: 100%; } #game-info-panel { @@ -697,31 +704,69 @@ } function generateFood() { + // 计算可用的网格单元数量 + const numCols = CANVAS_WIDTH / GRID_SIZE; + const numRows = CANVAS_HEIGHT / GRID_SIZE; + + // 循环直到找到一个不在蛇身体上的食物位置 + let newFoodX, newFoodY; + do { + newFoodX = Math.floor(Math.random() * numCols); + newFoodY = Math.floor(Math.random() * numRows); + } while (isFoodOnSnake(newFoodX, newFoodY)); // 检查是否与蛇重叠 + food = { - x: Math.floor(Math.random() * (CANVAS_WIDTH / GRID_SIZE)), - y: Math.floor(Math.random() * (CANVAS_HEIGHT / GRID_SIZE)) + x: newFoodX, + y: newFoodY }; - // 确保食物不生成在蛇的身体上 + } + + // 辅助函数:检查给定坐标是否在蛇的身体上 + function isFoodOnSnake(x, y) { for (let i = 0; i < snake.length; i++) { - if (food.x === snake[i].x && food.y === snake[i].y) { - generateFood(); // 重新生成 + if (x === snake[i].x && y === snake[i].y) { + return true; } } + return false; } function drawGame() { // 清空 snakeCanvas snakeCtx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); + // === 修改点 2:绘制网格线 (增强视觉效果) === + snakeCtx.strokeStyle = '#444'; // 深灰色网格线 + snakeCtx.lineWidth = 0.5; // 网格线细一点 + for (let x = 0; x < CANVAS_WIDTH; x += GRID_SIZE) { + snakeCtx.beginPath(); + snakeCtx.moveTo(x, 0); + snakeCtx.lineTo(x, CANVAS_HEIGHT); + snakeCtx.stroke(); + } + for (let y = 0; y < CANVAS_HEIGHT; y += GRID_SIZE) { + snakeCtx.beginPath(); + snakeCtx.moveTo(0, y); + snakeCtx.lineTo(CANVAS_WIDTH, y); + snakeCtx.stroke(); + } + // 绘制食物 - snakeCtx.fillStyle = '#ff3333'; // 红色 + snakeCtx.fillStyle = '#ff4444'; // 更鲜艳的红色 snakeCtx.fillRect(food.x * GRID_SIZE, food.y * GRID_SIZE, GRID_SIZE, GRID_SIZE); + snakeCtx.strokeStyle = '#ff0000'; // 食物边框 + snakeCtx.lineWidth = 2; // 微粗边框 + snakeCtx.strokeRect(food.x * GRID_SIZE, food.y * GRID_SIZE, GRID_SIZE, GRID_SIZE); + // 绘制蛇 for (let i = 0; i < snake.length; i++) { - snakeCtx.fillStyle = (i === 0) ? '#00cc00' : '#009900'; // 蛇头绿色,身体深绿 + snakeCtx.fillStyle = (i === 0) ? '#33ff33' : '#00cc00'; // 蛇头亮绿色,身体普通绿色 snakeCtx.fillRect(snake[i].x * GRID_SIZE, snake[i].y * GRID_SIZE, GRID_SIZE, GRID_SIZE); - snakeCtx.strokeStyle = '#222'; // 边框 + + // === 修改点 2:增强蛇身的方格显示效果:添加描边 === + snakeCtx.strokeStyle = '#006600'; // 深绿色描边 + snakeCtx.lineWidth = 1.5; // 描边宽度 snakeCtx.strokeRect(snake[i].x * GRID_SIZE, snake[i].y * GRID_SIZE, GRID_SIZE, GRID_SIZE); }