貪吃蛇是一款經典的游戲,現在可以用HTML和JavaScript來編寫貪吃蛇代碼。HTML用于創建游戲畫面,JavaScript用于實現游戲邏輯。
<canvas id="canvas" width="400" height="400"></canvas> <script> // 定義常量 const COLS = 20; // 列數 const ROWS = 20; // 行數 const SNAKE_SIZE = 20; // 蛇塊大小 // 定義變量 var canvas, ctx, snake; // 初始化函數 function init() { canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); snake = new Snake(); } // 繪制函數 function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); snake.move(); snake.draw(); setTimeout(draw, 100); } // 蛇類 function Snake() { this.body = [{ x: 10, y: 10 }, { x: 9, y: 10 }, { x: 8, y: 10 }]; this.direction = "right"; this.draw = function() { ctx.fillStyle = "green"; for (var i = 0; i< this.body.length; i++) { var bodyPart = this.body[i]; ctx.fillRect(bodyPart.x * SNAKE_SIZE, bodyPart.y * SNAKE_SIZE, SNAKE_SIZE, SNAKE_SIZE); } }; this.move = function() { var newHead = { x: this.body[0].x, y: this.body[0].y }; if (this.direction === "right") { newHead.x++; } else if (this.direction === "left") { newHead.x--; } else if (this.direction === "up") { newHead.y--; } else if (this.direction === "down") { newHead.y++; } this.body.unshift(newHead); this.body.pop(); }; } // 監聽鍵盤事件 document.addEventListener("keydown", function(event) { if (event.key === "ArrowRight") { snake.direction = "right"; } else if (event.key === "ArrowLeft") { snake.direction = "left"; } else if (event.key === "ArrowUp") { snake.direction = "up"; } else if (event.key === "ArrowDown") { snake.direction = "down"; } }); // 初始化并開始游戲 init(); draw(); </script>
以上是一個簡單的貪吃蛇代碼示例,其中創建了一個Snake類,用于表示貪吃蛇,包含了蛇的身體、方向、移動、繪制等屬性和方法。監聽了鍵盤事件,用于改變蛇的方向。通過不斷調用繪制函數,實現了蛇的不斷運動和重新繪制。
上一篇html 漂亮表格代碼