当前位置: 首页 > article >正文

用AI写游戏1——js实现贪吃蛇

使用模型通义千问
提示词:
用js html css 做一个贪吃蛇的动画

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Snake Game</title>
    <link rel="stylesheet" href="css/test023.css">
</head>
<body>
<div id="gameBoard"></div>
<script src="js/test023.js"></script>
</body>
</html>
body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f0f0;
    margin: 0;
}

#gameBoard {
    display: grid;
    width: 400px;
    height: 400px;
    grid-template-columns: repeat(20, 1fr);
    grid-template-rows: repeat(20, 1fr);
    border: 5px solid #333;
}

.cell {
    width: 100%;
    height: 100%;
    background-color: #ccc;
    border: 1px solid #ddd;
}

.snake {
    background-color: #28a745;
}

.food {
    background-color: #dc3545;
}
const board = document.getElementById('gameBoard');
const rows = 20, cols = 20;
let snake = [{ x: 10, y: 10 }];
let direction = { x: 0, y: -1 };
let food = createFood();
let gameOver = false;

function createBoard() {
    for (let row = 0; row < rows; row++) {
        for (let col = 0; col < cols; col++) {
            const cell = document.createElement('div');
            cell.classList.add('cell');
            board.appendChild(cell);
        }
    }
}

function updateBoard() {
    const cells = document.querySelectorAll('.cell');
    cells.forEach(cell => cell.className = 'cell');

    snake.forEach(segment => {
        const index = segment.y * cols + segment.x;
        cells[index].classList.add('snake');
    });

    const foodIndex = food.y * cols + food.x;
    cells[foodIndex].classList.add('food');
}

function createFood() {
    let newFood;
    do {
        newFood = { x: Math.floor(Math.random() * cols), y: Math.floor(Math.random() * rows) };
    } while (snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
    return newFood;
}

function moveSnake() {
    const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
    if (head.x < 0 || head.x >= cols || head.y < 0 || head.y >= rows || snake.some(segment => segment.x === head.x && segment.y === head.y)) {
        gameOver = true;
        return;
    }

    snake.unshift(head);

    if (head.x === food.x && head.y === food.y) {
        food = createFood();
    } else {
        snake.pop();
    }
}

document.addEventListener('keydown', event => {
    switch (event.key) {
        case 'ArrowUp':
            if (direction.y === 0) direction = { x: 0, y: -1 };
            break;
        case 'ArrowDown':
            if (direction.y === 0) direction = { x: 0, y: 1 };
            break;
        case 'ArrowLeft':
            if (direction.x === 0) direction = { x: -1, y: 0 };
            break;
        case 'ArrowRight':
            if (direction.x === 0) direction = { x: 1, y: 0 };
            break;
    }
});

createBoard();

const gameLoop = setInterval(() => {
    if (gameOver) {
        clearInterval(gameLoop);
        alert('Game Over!');
        return;
    }
    moveSnake();
    updateBoard();
}, 100);

这段代码创建了一个基础的贪吃蛇游戏,包括了游戏区域的渲染、蛇的移动与增长、食物的生成及蛇吃到食物后的增长逻辑。通过监听键盘事件改变蛇的方向,并使用setInterval函数控制游戏循环。请注意,这只是一个基础示例,实际开发中可能需要添加更多功能如分数统计、游戏重置等。

实现效果

在这里插入图片描述


http://www.kler.cn/a/537230.html

相关文章:

  • PHP之hyperf学习笔记
  • 设计模式.
  • 硬件工程师思考笔记02-器件的隐秘角落:磁珠与电阻噪声
  • Games104——游戏引擎Gameplay玩法系统:基础AI
  • 化学-基础知识一
  • 从零创建 Vue 3 项目
  • 2025.2.5——五、[网鼎杯 2020 青龙组]AreUSerialz 代码审计|反序列化
  • AlphaGPT获国家AIGC生成式算法备案,推动法律AI技术安全合规发展
  • Linux之kernel(7)系统调用源码分析
  • 三轴云台之加速度计篇
  • 大规模多准则决策模型构建详细方案
  • 轻量级服务器http-server
  • 仓颉编程语言:编程世界的 “文化瑰宝”
  • iOS三方登录 - Facebook登录
  • es6中关于symbol的用法,以及使用场景
  • Kotlin 2.1.0 入门教程(十)
  • TAPEX:通过神经SQL执行器学习的表格预训练
  • Ubuntu20.04 本地部署 DeepSeek-R1 及 chatbox可视化
  • TCN时间卷积神经网络多变量多步光伏功率预测(Matlab)
  • 4-redis分片集群
  • springboot配置redis
  • RTOS基础(TODO)
  • Jupyter Notebook使用指南--虚拟环境
  • 使用scoop 下载速度慢怎么办
  • Day38【AI思考】-彻底打通线性数据结构间的血脉联系
  • 位置定位与IP属地:异同解析与实际应用