前端实现贪吃蛇小游戏(jquery)
以下是使用jQuery实现贪吃蛇游戏的核心函数示例:
$(document).ready(function() {
var gameOver = false;
var direction = 'right';
var snake = [{ x: 4, y: 4 }, { x: 4, y: 5 }, { x: 4, y: 6 }];
var food = { x: 7, y: 7 };
function draw() {
// 清除背景
$('#game-board').empty();
// 绘制食物
$('#game-board').append($('<div>').attr('class', 'food').css({
top: food.y * 20,
left: food.x * 20
}));
// 绘制蛇
$.each(snake, function(index, position) {
$('#game-board').append($('<div>').attr('class', 'snake-segment').css({
top: position.y * 20,
left: position.x * 20
}));
});
}
function moveSnake() {
// 移动蛇的头部
var newHead = { x: snake[0].x, y: snake[0].y };
switch (direction) {
case 'right':
newHead.x += 1;
break;
case 'left':
newHead.x -= 1;
break;
case 'up':
newHead.y -= 1;
break;
case 'down':
newHead.y += 1;
break;
}
// 如果吃到食物,则不移动蛇的尾部
if (newHead.x === food.x && newHead.y === food.y) {
food = { x: Math.floor(Math.random() * 10 + 1), y: Math.floor(Math.random() * 10 + 1) };
} else {
snake.pop(); // 移除蛇的尾部
}
// 将新的头部加入蛇的数组
snake.unshift(newHead);
// 检查游戏结束条件
if (newHead.x < 1 || newHead.x > 10 || newHead.y < 1 || newHead.y > 10 || $.inArray({ x: newHead.x, y: newHead.y }, snake) !== -1) {
gameOver = true;
}
draw();
if (gameOver) {
alert('Game Over!');
}
}
// 键盘按键事件处理
$(document).keydown(function(event) {
var keyCode = event.which;
switch (keyCode) {
case 37: // 左
if (direction !== 'right') {
direction = 'left';
}
break;
case 38: // 上
if (direction !== 'down') {
direction = 'up';
评论已关闭