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.
To refine the snake AI and make it more intelligent and strategic, we can implement several enhancements:
Here’s the refined implementation:
// ... [Previous code remains largely the same, with updates in the DijkstraPathfinder and Snake classes]
// ======================================================================
// Dijkstra's Pathfinding Algorithm (Enhanced)
// ======================================================================
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
];
}
// Enhanced pathfinding with cost considerations
findPath(start, target, obstacles, opponentHead) {
const startKey = Utils.key(start.x, start.y);
const targetKey = Utils.key(target.x, target.y);
// Dijkstra setup with priority queue
const dist = new Map();
const prev = new Map();
const pq = new PriorityQueue((a, b) => dist.get(a) - dist.get(b));
// Initialize distances
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);
}
}
dist.set(startKey, 0);
pq.enqueue(startKey, 0);
const obstacleSet = new Set(obstacles);
while (!pq.isEmpty()) {
const uKey = pq.dequeue();
const u = Utils.coordsFromKey(uKey);
if (uKey === targetKey) {
return this.reconstructPath(prev, targetKey);
}
// Explore neighbors with enhanced cost calculation
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;
}
// Calculate dynamic cost based on proximity to opponent's head
const baseCost = 1;
const dangerCost = this.calculateDangerCost(v, opponentHead);
const totalCost = baseCost + dangerCost;
const alt = dist.get(uKey) + totalCost;
if (alt < dist.get(vKey)) {
dist.set(vKey, alt);
prev.set(vKey, uKey);
pq.enqueue(vKey, alt);
}
}
}
return null; // No path found
}
calculateDangerCost(pos, opponentHead) {
if (!opponentHead) return 0;
const dx = pos.x - opponentHead.x;
const dy = pos.y - opponentHead.y;
const distance = Math.abs(dx) + Math.abs(dy);
return Math.max(0, 2 - distance); // Higher cost when closer to opponent
}
// ... [Other methods remain the same]
}
// ======================================================================
// Priority Queue Implementation
// ======================================================================
class PriorityQueue {
constructor(comparator) {
this.heap = [];
this.comparator = comparator || ((a, b) => a - b);
}
enqueue(key, priority) {
const element = { key, priority };
this.heap.push(element);
this.bubbleUp(this.heap.length - 1);
}
dequeue() {
const root = this.heap[0];
const end = this.heap.pop();
if (this.heap.length > 0) {
this.heap[0] = end;
this.bubbleDown(0);
}
return root.key;
}
isEmpty() {
return this.heap.length === 0;
}
bubbleUp(index) {
const element = this.heap[index];
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
const parent = this.heap[parentIndex];
if (this.comparator(element.priority, parent.priority) >= 0) break;
this.heap[index] = parent;
index = parentIndex;
}
this.heap[index] = element;
}
bubbleDown(index) {
const length = this.heap.length;
const element = this.heap[index];
while (true) {
let leftChildIndex = 2 * index + 1;
let rightChildIndex = 2 * index + 2;
let swapIndex = null;
if (leftChildIndex < length) {
const leftChild = this.heap[leftChildIndex];
if (this.comparator(leftChild.priority, element.priority) < 0) {
swapIndex = leftChildIndex;
}
}
if (rightChildIndex < length) {
const rightChild = this.heap[rightChildIndex];
if (
(swapIndex === null && this.comparator(rightChild.priority, element.priority) < 0) ||
(swapIndex !== null && this.comparator(rightChild.priority, this.heap[swapIndex].priority) < 0)
) {
swapIndex = rightChildIndex;
}
}
if (swapIndex === null) break;
this.heap[index] = this.heap[swapIndex];
index = swapIndex;
}
this.heap[index] = element;
}
}
// ======================================================================
// Snake Class (Enhanced)
// ======================================================================
class Snake {
constructor(id, startX, startY, bodyColor, headColor) {
// ... [Constructor remains the same]
}
calculateMove(pathfinder, food, allObstacles, opponentHead) {
if (!this.isAlive) return;
const head = this.getHead();
// Enhanced pathfinding with opponent awareness
this.path = pathfinder.findPath(head, food, allObstacles, opponentHead);
// Fallback strategy with improved logic
if (!this.path || this.path.length === 0) {
this.path = this.findStrategicFallbackMove(pathfinder, allObstacles, opponentHead);
}
}
findStrategicFallbackMove(pathfinder, obstacles, opponentHead) {
const head = this.getHead();
const safeMoves = [];
for (const dir of pathfinder.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) || obstacles.has(nextKey)) {
continue;
}
// Calculate strategic score based on multiple factors
const strategicScore = this.calculateStrategicScore(nextPos, opponentHead);
safeMoves.push({ pos: nextPos, score: strategicScore });
}
if (safeMoves.length > 0) {
safeMoves.sort((a, b) => b.score - a.score);
return [safeMoves[0].pos];
}
return null;
}
calculateStrategicScore(pos, opponentHead) {
let score = 0;
// 1. Maximize distance from opponent's head
if (opponentHead) {
const dx = pos.x - opponentHead.x;
const dy = pos.y - opponentHead.y;
const distance = Math.abs(dx) + Math.abs(dy);
score += distance * 2; // Higher score for greater distance
}
// 2. Minimize distance to center of the board
const centerX = Config.GRID_SIZE / 2;
const centerY = Config.GRID_SIZE / 2;
const centerDistance = Math.abs(pos.x - centerX) + Math.abs(pos.y - centerY);
score += (10 - centerDistance); // Higher score for being closer to center
// 3. Avoid corners
if ((pos.x === 0 || pos.x === Config.GRID_SIZE - 1) && (pos.y === 0 || pos.y === Config.GRID_SIZE - 1)) {
score -= 5; // Penalty for being in a corner
}
return score;
}
// ... [Other methods remain largely the same]
}
// ======================================================================
// Game Manager (Updated)
// ======================================================================
class Game {
constructor() {
// ... [Constructor remains the same]
}
update() {
if (!this.isRunning) return;
// Gather all current obstacles and opponent heads
const allObstacles = this.getAllOccupiedCells();
const opponentHeads = this.snakes.map(snake => snake.getHead());
// Calculate paths for both snakes with enhanced parameters
this.snakes.forEach((snake, index) => {
const opponentHead = opponentHeads.find((_, i) => i !== index);
const obstaclesForThisSnake = new Set(allObstacles);
obstaclesForThisSnake.delete(Utils.key(snake.getHead().x, snake.getHead().y));
snake.calculateMove(this.pathfinder, this.food, obstaclesForThisSnake, opponentHead);
});
// ... [Rest of the update method remains the same]
}
// ... [Other methods remain the same]
}
// ... [Rest of the code remains the same]
These improvements make the snakes more intelligent, proactive, and strategic in their decision-making, leading to more engaging and competitive gameplay.
give the full code
Here’s the full refined code with all enhancements integrated into a single HTML file. This version includes the improved AI, strategic pathfinding, and optimized fallback behaviors:
<!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 - Enhanced 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 (Enhanced Edition)</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: 600, // 30 * 20
GAME_SPEED: 100, // ms per frame
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;
}
};
// ======================================================================
// Priority Queue Implementation
// ======================================================================
class PriorityQueue {
constructor(comparator = (a, b) => a.priority - b.priority) {
this._heap = [];
this._comparator = comparator;
}
enqueue(item, priority) {
const element = { item, priority };
this._heap.push(element);
this._bubbleUp(this._heap.length - 1);
}
dequeue() {
const root = this._heap[0];
const end = this._heap.pop();
if (this._heap.length > 0) {
this._heap[0] = end;
this._bubbleDown(0);
}
return root.item;
}
isEmpty() {
return this._heap.length === 0;
}
_bubbleUp(index) {
const element = this._heap[index];
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
const parent = this._heap[parentIndex];
if (this._comparator(element, parent) >= 0) break;
this._heap[index] = parent;
index = parentIndex;
}
this._heap[index] = element;
}
_bubbleDown(index) {
const length = this._heap.length;
const element = this._heap[index];
while (true) {
let swapIndex = null;
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
if (leftChildIndex < length) {
const leftChild = this._heap[leftChildIndex];
if (this._comparator(leftChild, element) < 0) {
swapIndex = leftChildIndex;
}
}
if (rightChildIndex < length) {
const rightChild = this._heap[rightChildIndex];
if ((swapIndex === null && this._comparator(rightChild, element) < 0) ||
(swapIndex !== null && this._comparator(rightChild, this._heap[swapIndex]) < 0)) {
swapIndex = rightChildIndex;
}
}
if (swapIndex === null) break;
this._heap[index] = this._heap[swapIndex];
index = swapIndex;
}
this._heap[index] = element;
}
}
// ======================================================================
// Dijkstra's Pathfinding Algorithm (Enhanced)
// ======================================================================
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
];
}
findPath(start, target, obstacles, opponentHead) {
const startKey = Utils.key(start.x, start.y);
const targetKey = Utils.key(target.x, target.y);
const dist = new Map();
const prev = new Map();
const pq = new PriorityQueue();
dist.set(startKey, 0);
pq.enqueue(startKey, 0);
const obstacleSet = new Set(obstacles);
while (!pq.isEmpty()) {
const uKey = pq.dequeue();
const u = Utils.coordsFromKey(uKey);
if (uKey === targetKey) {
return this.reconstructPath(prev, targetKey);
}
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;
}
const baseCost = 1;
const dangerCost = this.calculateDangerCost(v, opponentHead);
const totalCost = baseCost + dangerCost;
const alt = dist.get(uKey) + totalCost;
if (!dist.has(vKey) || alt < dist.get(vKey)) {
dist.set(vKey, alt);
prev.set(vKey, uKey);
pq.enqueue(vKey, alt);
}
}
}
return null; // No path found
}
calculateDangerCost(pos, opponentHead) {
if (!opponentHead) return 0;
const dx = pos.x - opponentHead.x;
const dy = pos.y - opponentHead.y;
const distance = Math.abs(dx) + Math.abs(dy);
return Math.max(0, 3 - distance); // Higher cost when closer to opponent
}
reconstructPath(prev, targetKey) {
const path = [];
let currentKey = targetKey;
while (prev.has(currentKey)) {
path.unshift(Utils.coordsFromKey(currentKey));
currentKey = prev.get(currentKey);
}
return path.length > 0 ? [path[0]] : []; // Return only the next step
}
findSafeMove(head, obstacles, opponentHead) {
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) || obstacles.has(nextKey)) {
continue;
}
const strategicScore = this.calculateStrategicScore(nextPos, opponentHead);
safeMoves.push({ pos: nextPos, score: strategicScore });
}
if (safeMoves.length > 0) {
safeMoves.sort((a, b) => b.score - a.score);
return [safeMoves[0].pos];
}
return null; // No safe move found
}
calculateStrategicScore(pos, opponentHead) {
let score = 0;
// Maximize distance from opponent's head
if (opponentHead) {
const dx = pos.x - opponentHead.x;
const dy = pos.y - opponentHead.y;
const distance = Math.abs(dx) + Math.abs(dy);
score += distance * 2;
}
// Minimize distance to center
const centerX = Config.GRID_SIZE / 2;
const centerY = Config.GRID_SIZE / 2;
const centerDistance = Math.abs(pos.x - centerX) + Math.abs(pos.y - centerY);
score += 10 - centerDistance;
// Avoid corners
if ((pos.x === 0 || pos.x === Config.GRID_SIZE - 1) && (pos.y === 0 || pos.y === Config.GRID_SIZE - 1)) {
score -= 5;
}
return score;
}
}
// ======================================================================
// Snake Class (Enhanced)
// ======================================================================
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;
}
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, opponentHead) {
const head = this.getHead();
this.path = pathfinder.findPath(head, food, allObstacles, opponentHead);
if (!this.path || this.path.length === 0) {
this.path = pathfinder.findSafeMove(head, allObstacles, opponentHead);
}
}
move(food, game) {
if (!this.isAlive || !this.path || this.path.length === 0) return;
const nextStep = this.path.shift();
this.body.unshift(nextStep);
if (nextStep.x === food.x && nextStep.y === food.y) {
this.score++;
game.spawnFood();
} else {
this.body.pop();
}
}
checkCollisions(otherSnake) {
const head = this.getHead();
if (Utils.isOutOfBounds(head.x, head.y)) {
this.die(`Snake ${this.id} hit a wall!`);
return;
}
const selfBodyKeys = this.getBodyKeys(false);
if (selfBodyKeys.includes(Utils.key(head.x, head.y))) {
this.die(`Snake ${this.id} collided with itself!`);
return;
}
if (otherSnake.isAlive) {
const otherSnakeKeys = otherSnake.getBodyKeys();
if (otherSnakeKeys.includes(Utils.key(head.x, head.y))) {
this.die(`Snake ${this.id} collided with Snake ${otherSnake.id}!`);
otherSnake.die(`Snake ${otherSnake.id} collided with Snake ${this.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
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 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();
}
}
// ======================================================================
// Game Manager
// ======================================================================
class Game {
constructor() {
this.canvas = document.getElementById('gameCanvas');
this.ctx = this.canvas.getContext('2d');
this.canvas.width = Config.CANVAS_SIZE;
this.canvas.height = Config.CANVAS_SIZE;
this.statusElement = document.getElementById('status');
this.score1Element = document.getElementById('score1');
this.score2Element = document.getElementById('score2');
this.pathfinder = new DijkstraPathfinder(Config.GRID_SIZE);
this.isRunning = false;
this.food = { x: 0, y: 0 };
this.snakes = [];
this.gameLoopTimeout = null;
this.init();
}
init() {
this.snake1 = new Snake(1, 5, Math.floor(Config.GRID_SIZE / 2), Config.COLORS.SNAKE1, Config.COLORS.SNAKE1_HEAD);
this.snake2 = new Snake(2, Config.GRID_SIZE - 6, Math.floor(Config.GRID_SIZE / 2), Config.COLORS.SNAKE2, Config.COLORS.SNAKE2_HEAD);
this.snakes = [this.snake1, this.snake2];
this.spawnFood();
this.isRunning = true;
this.updateStatus("Game Running...");
this.gameLoop();
}
getAllOccupiedCells() {
const occupied = new Set();
this.snakes.forEach(snake => {
if (snake.isAlive) {
snake.getBodyKeys().forEach(key => occupied.add(key));
}
});
return occupied;
}
spawnFood() {
const occupied = this.getAllOccupiedCells();
let newFoodPos;
do {
newFoodPos = {
x: Utils.getRandomInt(Config.GRID_SIZE),
y: Utils.getRandomInt(Config.GRID_SIZE)
};
} while (occupied.has(Utils.key(newFoodPos.x, newFoodPos.y)));
this.food = newFoodPos;
}
update() {
if (!this.isRunning) return;
const allObstacles = this.getAllOccupiedCells();
const opponentHeads = this.snakes.map(snake => snake.getHead());
this.snakes.forEach((snake, index) => {
const opponentHead = opponentHeads.find((_, i) => i !== index);
const obstaclesForThisSnake = new Set(allObstacles);
obstaclesForThisSnake.delete(Utils.key(snake.getHead().x, snake.getHead().y));
snake.calculateMove(this.pathfinder, this.food, obstaclesForThisSnake, opponentHead);
});
this.snakes.forEach(snake => snake.move(this.food, this));
this.snakes[0].checkCollisions(this.snakes[1]);
this.snakes[1].checkCollisions(this.snakes[0]);
this.checkGameOver();
this.updateScores();
}
draw() {
const ctx = this.ctx;
const CS = Config.CELL_SIZE;
// Clear canvas
ctx.fillStyle = Config.COLORS.BACKGROUND;
ctx.fillRect(0, 0, Config.CANVAS_SIZE, Config.CANVAS_SIZE);
// Draw grid lines
ctx.strokeStyle = Config.COLORS.GRID_LINES;
ctx.lineWidth = 0.5;
for (let i = 0; i <= Config.GRID_SIZE; i++) {
ctx.beginPath();
ctx.moveTo(i * CS, 0);
ctx.lineTo(i * CS, Config.CANVAS_SIZE);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, i * CS);
ctx.lineTo(Config.CANVAS_SIZE, i * CS);
ctx.stroke();
}
// Draw food
ctx.fillStyle = Config.COLORS.FOOD;
ctx.beginPath();
ctx.arc(this.food.x * CS + CS / 2, this.food.y * CS + CS / 2, CS / 2 - 2, 0, Math.PI * 2);
ctx.fill();
// Draw snakes
this.snakes.forEach(snake => snake.draw(ctx));
}
gameLoop() {
if (!this.isRunning) return;
this.update();
this.draw();
this.gameLoopTimeout = setTimeout(() => this.gameLoop(), Config.GAME_SPEED);
}
updateScores() {
this.score1Element.textContent = `Snake 1 (Red): ${this.snake1.score}`;
this.score2Element.textContent = `Snake 2 (Blue): ${this.snake2.score}`;
}
updateStatus(message) {
this.statusElement.textContent = message;
}
checkGameOver() {
const aliveSnakes = this.snakes.filter(s => s.isAlive).length;
if (aliveSnakes < 2) {
this.isRunning = false;
clearTimeout(this.gameLoopTimeout);
let message = "Game Over! ";
if (this.snake1.isAlive) {
message += "Snake 1 (Red) Wins!";
} else if (this.snake2.isAlive) {
message += "Snake 2 (Blue) Wins!";
} else {
message += "It's a draw!";
}
this.updateStatus(message + " Refresh to restart.");
}
}
}
// Initialize the game
window.onload = () => {
new Game();
};
</script>
</body>
</html>
This version of the game provides a more engaging and competitive experience, with snakes making smarter decisions based on their environment and opponent's position.