为了给贪吃蛇更多的自由度,它需要能够在合理的情况下尝试不同的方向,而不仅仅像在示例中那样因受限机制的影响总是固定不变地移动。我们要确保AI能够考虑各个方向,并且在需要时允许转向。以下是一些调整,帮助创建设计更智能的AI来玩贪吃蛇:
- 移除固定方向的限制: 去掉对蛇不能180度掉头的限制,确保模型可以探索所有方向。
- 奖励和探索机制的改进: 更新奖励机制和探索策略,使AI通过尝试不同移动找到更多食物并避免自我撞击。
以下是更新后的代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇游戏与AI</title>
<style>
canvas {
border: 1px solid black;
display: block;
margin: 10px auto;
}
#controls {
text-align: center;
margin-top: 10px;
}
#score, #iteration {
text-align: center;
font-size: 20px;
margin-top: 10px;
}
#nn-structure {
text-align: center;
font-size: 16px;
margin-top: 10px;
}
.neural-network {
display: flex;
justify-content: center;
align-items: center;
margin: 20px;
}
.layer {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin: 0 10px;
}
.node {
width: 30px;
height: 30px;
margin: 2px 0;
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
transition: background-color 0.2s;
cursor: pointer;
}
.node span {
display: none;
font-size: 10px;
}
.node:hover span {
display: block;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
</head>
<body>
<div id="score">分数: 0</div>
<div id="iteration">迭代: 0</div>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<div id="nn-structure">神经网络结构可视化</div>
<div class="neural-network" id="neural-network"></div>
<div id="controls">
<button onclick="toggleGame()">开始/暂停</button>
<button onclick="changeSpeed(-50)">加速</button>
<button onclick="changeSpeed(50)">减速</button>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const box = 20;
let snake, food, direction, score, reward;
let game, iteration = 0;
let speed = 200;
let running = false;
const directions = ['UP', 'DOWN', 'LEFT', 'RIGHT'];
function initializeGame() {
snake = [{x: 9 * box, y: 10 * box}];
food = {
x: Math.floor(Math.random() * 19 + 1) * box,
y: Math.floor(Math.random() * 19 + 1) * box
};
direction = 'RIGHT';
score = 0;
reward = 0;
iteration = 0;
document.getElementById('score').innerHTML = '分数: ' + score;
document.getElementById('iteration').innerHTML = '迭代: ' + iteration;
}
function toggleGame() {
running = !running;
if (running) {
game = setInterval(gameStep, speed);
} else {
clearInterval(game);
}
}
function changeSpeed(delta) {
speed = Math.max(50, speed + delta);
if (running) {
clearInterval(game);
game = setInterval(gameStep, speed);
}
}
function createModel() {
const model = tf.sequential();
model.add(tf.layers.dense({units: 8, inputShape: [5], activation: 'relu'}));
model.add(tf.layers.dense({units: 8, activation: 'relu'}));
model.add(tf.layers.dense({units: 8, activation: 'relu'}));
model.add(tf.layers.dense({units: 4}));
model.compile({
optimizer: tf.train.adam(0.001),
loss: 'meanSquaredError'
});
return model;
}
const model = createModel();
function draw() {
ctx.fillStyle = 'lightgrey';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? 'green' : 'white';
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = 'black';
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, box, box);
}
function drawNetworkStructure(outputArray) {
const nnContainer = document.getElementById('neural-network');
nnContainer.innerHTML = '';
const layerSizes = [5, 8, 8, 8, 4];
layerSizes.forEach((size, layerIndex) => {
const layerDiv = document.createElement('div');
layerDiv.className = 'layer';
for (let i = 0; i < size; i++) {
const nodeDiv = document.createElement('div');
nodeDiv.className = 'node';
let value = (layerIndex === layerSizes.length - 1 && outputArray) ? outputArray[i] : Math.random() * 2 - 1;
const colorIntensity = Math.floor((value + 1) * 127.5);
nodeDiv.style.backgroundColor = `rgb(${255-colorIntensity}, ${255-colorIntensity}, 255)`;
const span = document.createElement('span');
span.textContent = value.toFixed(2);
nodeDiv.appendChild(span);
layerDiv.appendChild(nodeDiv);
}
nnContainer.appendChild(layerDiv);
});
}
function gameStep() {
iteration++;
const inputTensor = tf.tensor2d([[snake[0].x / canvas.width, snake[0].y / canvas.height, food.x / canvas.width, food.y / canvas.height, Math.random()]]);
const prediction = model.predict(inputTensor);
const directionIndex = prediction.argMax(-1).dataSync()[0];
const outputArray = Array.from(prediction.dataSync());
document.getElementById('nn-structure').innerHTML = '神经网络输出 (归一化): ' + JSON.stringify(outputArray.map(v => v.toFixed(2)));
drawNetworkStructure(outputArray);
direction = directions[directionIndex];
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (direction === 'LEFT') snakeX -= box;
if (direction === 'UP') snakeY -= box;
if (direction === 'RIGHT') snakeX += box;
if (direction === 'DOWN') snakeY += box;
if (snakeX === food.x && snakeY === food.y) {
score++;
reward = 10;
food = {
x: Math.floor(Math.random() * 19 + 1) * box,
y: Math.floor(Math.random() * 19 + 1) * box
};
} else {
snake.pop();
reward = -0.1;
}
const newHead = {x: snakeX, y: snakeY};
if (snakeX < 0 || snakeX >= canvas.width || snakeY < 0 || snakeY >= canvas.height || collision(newHead, snake)) {
reward = -10;
initializeGame();
if (running) toggleGame();
} else {
snake.unshift(newHead);
}
const targetTensor = tf.tensor2d([Array.from({ length: 4 }, (_, index) => index === directionIndex ? reward : 0)]);
model.fit(inputTensor, targetTensor, {epochs: 1}).then(() => {
console.log("训练完成每一步");
});
document.getElementById('score').innerHTML = '分数: ' + score;
document.getElementById('iteration').innerHTML = '迭代: ' + iteration;
draw();
}
function collision(head, array) {
return array.some(segment => head.x === segment.x && head.y === segment.y);
}
initializeGame();
drawNetworkStructure([]);
</script>
</body>
</html>
变化与解释
-
自由方向选择:
- 去掉了对“只能在当前方向基础上选择下一步方向”的限制。这里通过引入
directions数组,我们可以让AI在每次的方向预测中选择任意一个方向('UP', 'DOWN', 'LEFT', 'RIGHT')。
-
奖励机制和训练:
- 奖励和训练步骤做出适宜调整。在每个游戏步骤中,预测AI选择的状态动作对模型进行梯度更新。
-
模型使用:
- 这个示意模型没有真正复杂的学习能力,但通过上面的调整,我们展示了如何处理更灵活的方向选择,这样可以完善AI在尝试不同行动策略时如何进行强化学习。
真正的强化学习算法(例如Q-learning或Deep Q-learning)会使用一个Q-table或神经网络来存储状态动作值,并根据复杂的策略进行学习和反向传播。在实际游戏应用中,这更需要大量的数据训练来逼近最优策略。