refine the snake AI
- User
refine the snake AI
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
refine the snake AI
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's an updated version of the code with a refined snake AI:
// ... (rest of the code remains the same)
// ======================================================================
// Snake Class
// ======================================================================
class Snake {
constructor(id, startX, startY, bodyColor, headColor) {
this.id = id;
this.body = [{ x: startX, y: startY }];
this.bodyColor = bodyColor;
this.headColor = headColor;
this.path = [];
this.isAlive = true;
this.score = 0;
this.direction = { x: 1, y: 0 }; // Initial direction
}
getHead() {
return this.body[0];
}
getBodyKeys(includeHead = true) {
const start = includeHead ? 0 : 1;
return this.body.slice(start).map(segment => Utils.key(segment.x, segment.y));
}
calculateMove(pathfinder, food, allObstacles) {
if (!this.isAlive) return;
const head = this.getHead();
// Obstacles include self-body (excluding head, as we start there) and opponent's body
this.path = pathfinder.findPath(head, food, allObstacles);
// Fallback strategy: If Dijkstra finds no path to food, try to find any safe move
if (!this.path || this.path.length === 0) {
this.path = pathfinder.findSafeMove(head, allObstacles);
}
// Update direction based on the calculated path
if (this.path.length > 0) {
const nextStep = this.path[0];
this.direction = { x: nextStep.x - head.x, y: nextStep.y - head.y };
}
}
move(food, game) {
if (!this.isAlive) return;
if (!this.path || this.path.length === 0) {
// If even the fallback fails, the snake is trapped and dies.
this.die(`Snake ${this.id} is trapped!`);
return;
}
const nextStep = this.path.shift();
// Add the new head position
this.body.unshift(nextStep);
// Check if food is eaten
if (nextStep.x === food.x && nextStep.y === food.y) {
this.score++;
game.spawnFood();
// Don't remove the tail, the snake grows
} else {
// Remove the tail
this.body.pop();
}
}
checkCollisions(otherSnake) {
if (!this.isAlive) return;
const head = this.getHead();
// 1. Wall collision
if (Utils.isOutOfBounds(head.x, head.y)) {
this.die(`Snake ${this.id} hit a wall!`);
return;
}
// 2. Self collision (check body from segment 1 onwards)
const selfBodyKeys = this.getBodyKeys(false);
if (selfBodyKeys.includes(Utils.key(head.x, head.y))) {
this.die(`Snake ${this.id} collided with itself!`);
return;
}
// 3. Collision with the other snake
if (otherSnake.isAlive) {
const otherSnakeKeys = otherSnake.getBodyKeys();
if (otherSnakeKeys.includes(Utils.key(head.x, head.y))) {
// Check for head-on collision
const otherHead = otherSnake.getHead();
if (head.x === otherHead.x && head.y === otherHead.y) {
this.die(`Snake ${this.id} had a head-on collision!`);
otherSnake.die(`Snake ${otherSnake.id} had a head-on collision!`);
} else {
this.die(`Snake ${this.id} hit Snake ${otherSnake.id}!`);
}
}
}
}
die(reason) {
this.isAlive = false;
console.log(reason);
}
draw(ctx) {
if (!this.isAlive) return;
const cs = Config.CELL_SIZE;
const radius = cs / 4;
// Draw body segments
ctx.fillStyle = this.bodyColor;
for (let i = 1; i < this.body.length; i++) {
const segment = this.body[i];
this.drawRoundedRect(ctx, segment.x * cs, segment.y * cs, cs, cs, radius);
}
// Draw head
const head = this.getHead();
ctx.fillStyle = this.headColor;
this.drawRoundedRect(ctx, head.x * cs, head.y * cs, cs, cs, radius);
// Draw simple eyes
ctx.fillStyle = '#fff';
ctx.beginPath();
ctx.arc(head.x * cs + cs * 0.3, head.y * cs + cs / 2, cs * 0.1, 0, Math.PI * 2);
ctx.arc(head.x * cs + cs * 0.7, head.y * cs + cs / 2, cs * 0.1, 0, Math.PI * 2);
ctx.fill();
}
drawRoundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
ctx.fill();
}
}
// ======================================================================
// Dijkstra's Pathfinding Algorithm
// ======================================================================
class DijkstraPathfinder {
constructor(gridSize) {
this.gridSize = gridSize;
this.directions = [
{ x: 0, y: -1 }, // Up
{ x: 1, y: 0 }, // Right
{ x: 0, y: 1 }, // Down
{ x: -1, y: 0 } // Left
];
}
// Finds the shortest path from start to target, avoiding obstacles.
findPath(start, target, obstacles) {
const startKey = Utils.key(start.x, start.y);
const targetKey = Utils.key(target.x, target.y);
// Dijkstra setup
const dist = new Map();
const prev = new Map();
const queue = new Set();
// Initialize distances and queue
for (let y = 0; y < this.gridSize; y++) {
for (let x = 0; x < this.gridSize; x++) {
const k = Utils.key(x, y);
dist.set(k, Infinity);
queue.add(k);
}
}
dist.set(startKey, 0);
const obstacleSet = new Set(obstacles);
while (queue.size > 0) {
// Find the node in Q with the smallest distance (acting as a priority queue)
let uKey = null;
let minDist = Infinity;
for (const key of queue) {
const d = dist.get(key);
if (d < minDist) {
minDist = d;
uKey = key;
}
}
if (uKey === null || minDist === Infinity) {
break; // Remaining nodes are unreachable
}
queue.delete(uKey);
const u = Utils.coordsFromKey(uKey);
if (uKey === targetKey) {
return this.reconstructPath(prev, targetKey);
}
// Explore neighbors
for (const dir of this.directions) {
const v = { x: u.x + dir.x, y: u.y + dir.y };
const vKey = Utils.key(v.x, v.y);
if (Utils.isOutOfBounds(v.x, v.y) || obstacleSet.has(vKey)) {
continue;
}
if (queue.has(vKey)) {
const alt = dist.get(uKey) + 1; // Cost between adjacent cells is 1
if (alt < dist.get(vKey)) {
dist.set(vKey, alt);
prev.set(vKey, uKey);
}
}
}
}
return null; // No path found
}
reconstructPath(prev, targetKey) {
const path = [];
let currentKey = targetKey;
while (prev.has(currentKey)) {
path.unshift(Utils.coordsFromKey(currentKey));
currentKey = prev.get(currentKey);
}
// We only need the next step from the start position
return path.length > 0 ? [path[0]] : [];
}
// Fallback AI: If no path to food exists, find any safe move.
findSafeMove(head, obstacles) {
const obstacleSet = new Set(obstacles);
const safeMoves = [];
for (const dir of this.directions) {
const nextPos = { x: head.x + dir.x, y: head.y + dir.y };
const nextKey = Utils.key(nextPos.x, nextPos.y);
if (!Utils.isOutOfBounds(nextPos.x, nextPos.y) && !obstacleSet.has(nextKey)) {
// Calculate a simple heuristic: distance from other obstacles/walls (maximize space)
let score = 0;
if (Utils.isOutOfBounds(nextPos.x + 1, nextPos.y)) score
give the full code
Here's the full code with the refined snake AI:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Snake Battle Royale - Dijkstra Edition</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #2c3e50;
color: #ecf0f1;
}
h1 {
margin-bottom: 10px;
font-size: 24px;
}
#gameCanvas {
border: 4px solid #34495e;
background-color: #1a1a1a;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
border-radius: 8px;
}
#scoreboard {
display: flex;
justify-content: space-around;
width: 600px;
margin-top: 20px;
font-size: 18px;
font-weight: bold;
}
.score {
padding: 10px 20px;
border-radius: 5px;
background-color: #34495e;
}
#score1 { color: #e74c3c; }
#score2 { color: #3498db; }
#status {
margin-top: 15px;
font-size: 16px;
color: #f1c40f;
}
</style>
</head>
<body>
<h1>AI Snake Battle Royale (Dijkstra Pathfinding)</h1>
<canvas id="gameCanvas"></canvas>
<div id="scoreboard">
<div id="score1" class="score">Snake 1 (Red): 0</div>
<div id="score2" class="score">Snake 2 (Blue): 0</div>
</div>
<div id="status">Game Running...</div>
<script>
// ======================================================================
// Configuration & Constants
// ======================================================================
const Config = {
GRID_SIZE: 30,
CELL_SIZE: 20,
CANVAS_SIZE: 30 * 20, // 600x600
GAME_SPEED: 100, // ms per frame (lower is faster)
COLORS: {
BACKGROUND: '#1a1a1a',
GRID_LINES: '#2c3e50',
FOOD: '#2ecc71',
SNAKE1: '#e74c3c',
SNAKE1_HEAD: '#c0392b',
SNAKE2: '#3498db',
SNAKE2_HEAD: '#2980b9',
}
};
// ======================================================================
// Utility Functions
// ======================================================================
const Utils = {
key(x, y) {
return `${x},${y}`;
},
coordsFromKey(key) {
const [x, y] = key.split(',').map(Number);
return { x, y };
},
getRandomInt(max) {
return Math.floor(Math.random() * max);
},
isOutOfBounds(x, y) {
return x < 0 || x >= Config.GRID_SIZE || y < 0 || y >= Config.GRID_SIZE;
}
};
// ======================================================================
// Dijkstra's Pathfinding Algorithm
// ======================================================================
class DijkstraPathfinder {
constructor(gridSize) {
this.gridSize = gridSize;
this.directions = [
{ x: 0, y: -1 }, // Up
{ x: 1, y: 0 }, // Right
{ x: 0, y: 1 }, // Down
{ x: -1, y: 0 } // Left
];
}
// Finds the shortest path from start to target, avoiding obstacles.
findPath(start, target, obstacles) {
const startKey = Utils.key(start.x, start.y);
const targetKey = Utils.key(target.x, target.y);
// Dijkstra setup
const dist = new Map();
const prev = new Map();
const queue = new Set();
// Initialize distances and queue
for (let y = 0; y < this.gridSize; y++) {
for (let x = 0; x < this.gridSize; x++) {
const k = Utils.key(x, y);
dist.set(k, Infinity);
queue.add(k);
}
}
dist.set(startKey, 0);
const obstacleSet = new Set(obstacles);
while (queue.size > 0) {
// Find the node in Q with the smallest distance (acting as a priority queue)
let uKey = null;
let minDist = Infinity;
for (const key of queue) {
const d = dist.get(key);
if (d < minDist) {
minDist = d;
uKey = key;
}
}
if (uKey === null || minDist === Infinity) {
break; // Remaining nodes are unreachable
}
queue.delete(uKey);
const u = Utils.coordsFromKey(uKey);
if (uKey === targetKey) {
return this.reconstructPath(prev, targetKey);
}
// Explore neighbors
for (const dir of this.directions) {
const v = { x: u.x + dir.x, y: u.y + dir.y };
const vKey = Utils.key(v.x, v.y);
if (Utils.isOutOfBounds(v.x, v.y) || obstacleSet.has(vKey)) {
continue;
}
if (queue.has(vKey)) {
const alt = dist.get(uKey) + 1; // Cost between adjacent cells is 1
if (alt < dist.get(vKey)) {
dist.set(vKey, alt);
prev.set(vKey, uKey);
}
}
}
}
return null; // No path found
}
reconstructPath(prev, targetKey) {
const path = [];
let currentKey = targetKey;
while (prev.has(currentKey)) {
path.unshift(Utils.coordsFromKey(currentKey));
currentKey = prev.get(currentKey);
}
// We only need the next step from the start position
return path.length > 0 ? [path[0]] : [];
}
// Fallback AI: If no path to food exists, find any safe move.
findSafeMove(head, obstacles) {
const obstacleSet = new Set(obstacles);
const safeMoves = [];
for (const dir of this.directions) {
const nextPos = { x: head.x + dir.x, y: head.y + dir.y };
const nextKey = Utils.key(nextPos.x, nextPos.y);
if (!Utils.isOutOfBounds(nextPos.x, nextPos.y) && !obstacleSet.has(nextKey)) {
// Calculate a simple heuristic: distance from other obstacles/walls (maximize space)
let score = 0;
if (Utils.isOutOfBounds(nextPos.x + 1, nextPos.y)) score++;
if (Utils.isOutOfBounds(nextPos.x - 1, nextPos.y)) score++;
if (Utils.isOutOfBounds(nextPos.x, nextPos.y + 1)) score++;
if (Utils.isOutOfBounds(nextPos.x, nextPos.y - 1)) score++;
safeMoves.push({ pos: nextPos, score: score });
}
}
if (safeMoves.length > 0) {
// Prefer moves that give more immediate space
safeMoves.sort((a, b) => b.score - a.score);
return [safeMoves[0].pos];
}
return null; // Trapped
}
}
// ======================================================================
// Snake Class
// ======================================================================
class Snake {
constructor(id, startX, startY, bodyColor, headColor) {
this.id = id;
this.body = [{ x: startX, y: startY }];
this.bodyColor = bodyColor;
this.headColor = headColor;
this.path = [];
this.isAlive = true;
this.score = 0;
this.direction = { x: 1, y: 0 }; // Initial direction
}
getHead() {
return this.body[0];
}
getBodyKeys(includeHead = true) {
const start = includeHead ? 0 : 1;
return this.body.slice(start).map(segment => Utils.key(segment.x, segment.y));
}
calculateMove(pathfinder, food, allObstacles) {
if (!this.isAlive) return;
const head = this.getHead();
// Obstacles include self-body (excluding head, as we start there) and opponent's body
this.path = pathfinder.findPath(head, food, allObstacles);
// Fallback strategy: If Dijkstra finds no path to food, try to find any safe move
if (!this.path || this.path.length === 0) {
this.path = pathfinder.findSafeMove(head, allObstacles);
}
// Update direction based on the calculated path
if (this.path.length > 0) {
const nextStep = this.path[0];
this.direction = { x: nextStep