Sure! Below is an HTML file that implements a simple 2D grid-based RPG game. In this game, a hero navigates a grid using the A* pathfinding algorithm to fight enemies and collect items to improve their stats. The entire game logic is controlled by AI, and it runs automatically when you open the HTML file in a web browser.
To use it, simply copy the code into a file with an .html extension (e.g., ai_rpg_game.html) and open it in your browser.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AI-Driven 2D Grid RPG Game</title>
<style>
canvas {
border: 1px solid #000;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="600" height="600"></canvas>
<script>
// Game configuration
const gridSize = 20; // Number of cells in one row/column
const cellSize = 30; // Size of each cell in pixels
const canvasSize = gridSize * cellSize;
// Canvas setup
const canvas = document.getElementById('gameCanvas');
canvas.width = canvasSize;
canvas.height = canvasSize;
const ctx = canvas.getContext('2d');
// Game entities
let gameMap = [];
let hero = {};
let enemies = [];
let items = [];
// Initialize the game
function initGame() {
// Create an empty map
for (let y = 0; y < gridSize; y++) {
gameMap[y] = [];
for (let x = 0; x < gridSize; x++) {
gameMap[y][x] = 0; // 0: empty
}
}
// Place the hero
hero = {
x: 0,
y: 0,
hp: 100,
attack: 10,
experience: 0
};
gameMap[hero.y][hero.x] = 'H';
// Place enemies
for (let i = 0; i < 10; i++) {
let enemy = placeRandomly('E');
enemy.hp = 30;
enemy.attack = 5;
enemies.push(enemy);
}
// Place items
for (let i = 0; i < 10; i++) {
let item = placeRandomly('I');
items.push(item);
}
drawGame();
}
// Place an entity at a random empty position
function placeRandomly(symbol) {
let position;
do {
position = {
x: Math.floor(Math.random() * gridSize),
y: Math.floor(Math.random() * gridSize)
};
} while (gameMap[position.y][position.x] !== 0);
gameMap[position.y][position.x] = symbol;
return position;
}
// Draw the game
function drawGame() {
ctx.clearRect(0, 0, canvasSize, canvasSize);
// Draw the grid
for (let y = 0; y < gridSize; y++) {
for (let x = 0; x < gridSize; x++) {
ctx.strokeStyle = '#ccc';
ctx.strokeRect(x * cellSize, y * cellSize, cellSize, cellSize);
switch (gameMap[y][x]) {
case 'H':
ctx.fillStyle = 'blue';
ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
break;
case 'E':
ctx.fillStyle = 'red';
ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
break;
case 'I':
ctx.fillStyle = 'gold';
ctx.beginPath();
ctx.arc(x * cellSize + cellSize / 2, y * cellSize + cellSize / 2, cellSize / 4, 0, 2 * Math.PI);
ctx.fill();
break;
}
}
}
}
// Game loop
function gameLoop() {
if (hero.hp <= 0 || enemies.length === 0) {
alert(hero.hp <= 0 ? 'Hero has been defeated!' : 'All enemies have been defeated!');
return;
}
const target = findNearestTarget();
if (target) {
const path = findPath(hero, target);
if (path && path.length > 1) {
moveHero(path[1]);
}
}
drawGame();
setTimeout(gameLoop, 500);
}
// Find the nearest target (enemy or item)
function findNearestTarget() {
const targets = enemies.concat(items);
let minDist = Infinity;
let nearest = null;
for (let target of targets) {
const dist = Math.abs(hero.x - target.x) + Math.abs(hero.y - target.y);
if (dist < minDist) {
minDist = dist;
nearest = target;
}
}
return nearest;
}
// Move the hero to the next position
function moveHero(nextPosition) {
// Remove hero from current position
gameMap[hero.y][hero.x] = 0;
// Update hero position
hero.x = nextPosition.x;
hero.y = nextPosition.y;
// Check for encounters
const cellContent = gameMap[hero.y][hero.x];
if (cellContent === 'E') {
const enemyIndex = enemies.findIndex(e => e.x === hero.x && e.y === hero.y);
if (enemyIndex !== -1) {
battle(enemies[enemyIndex]);
if (enemies[enemyIndex].hp <= 0) {
enemies.splice(enemyIndex, 1);
}
}
} else if (cellContent === 'I') {
collectItem(hero.x, hero.y);
}
// Place hero in new position
gameMap[hero.y][hero.x] = 'H';
}
// Battle with an enemy
function battle(enemy) {
// Simple battle logic
enemy.hp -= hero.attack;
if (enemy.hp > 0) {
hero.hp -= enemy.attack;
} else {
hero.experience += 10;
improveStats();
// Remove enemy from map
gameMap[enemy.y][enemy.x] = 0;
}
}
// Collect an item
function collectItem(x, y) {
// Remove item from items array
const itemIndex = items.findIndex(i => i.x === x && i.y === y);
if (itemIndex !== -1) {
items.splice(itemIndex, 1);
// Improve hero stats
hero.attack += 2;
hero.hp += 20;
// Remove item from map
gameMap[y][x] = 0;
}
}
// Improve hero stats based on experience
function improveStats() {
if (hero.experience >= 30) {
hero.attack += 5;
hero.hp += 50;
hero.experience = 0;
}
}
// A* Pathfinding Algorithm
function findPath(start, end) {
let openSet = [];
let closedSet = [];
let cameFrom = {};
function node(x, y, g, h) {
return { x, y, g, h, f: g + h };
}
openSet.push(node(start.x, start.y, 0, heuristic(start, end)));
while (openSet.length > 0) {
// Get the node with the lowest f score
openSet.sort((a, b) => a.f - b.f);
let current = openSet.shift();
// Check if we have reached the end
if (current.x === end.x && current.y === end.y) {
let path = [];
while (current) {
path.push({ x: current.x, y: current.y });
current = cameFrom[`${current.x},${current.y}`];
}
return path.reverse();
}
closedSet.push(current);
// Check neighbors
let neighbors = getNeighbors(current);
for (let neighbor of neighbors) {
if (closedSet.find(n => n.x === neighbor.x && n.y === neighbor.y)) {
continue;
}
neighbor.g = current.g + 1;
neighbor.h = heuristic(neighbor, end);
neighbor.f = neighbor.g + neighbor.h;
let existingNode = openSet.find(n => n.x === neighbor.x && n.y === neighbor.y);
if (!existingNode || neighbor.g < existingNode.g) {
cameFrom[`${neighbor.x},${neighbor.y}`] = current;
if (!existingNode) {
openSet.push(neighbor);
}
}
}
}
// No path found
return null;
}
// Heuristic function for A* (Manhattan distance)
function heuristic(a, b) {
return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
}
// Get walkable neighbors
function getNeighbors(node) {
let neighbors = [];
let directions = [
{ x: -1, y: 0 },
{ x: 1, y: 0 },
{ x: 0, y: -1 },
{ x: 0, y: 1 }
];
for (let dir of directions) {
let x = node.x + dir.x;
let y = node.y + dir.y;
if (x >= 0 && x < gridSize && y >= 0 && y < gridSize) {
let cellContent = gameMap[y][x];
if (cellContent === 0 || cellContent === 'E' || cellContent === 'I' || (x === end.x && y === end.y)) {
neighbors.push({ x, y });
}
}
}
return neighbors;
}
// Start the game
initGame();
gameLoop();
</script>
</body>
</html>
Explanation:
-
Game Configuration:
- The game grid is a 20x20 grid (
gridSize), and each cell is 30 pixels (cellSize).
- The canvas size is calculated based on the grid size and cell size.
-
Game Initialization (initGame function):
- An empty map is created, represented as a 2D array (
gameMap).
- The hero is placed at position
(0, 0) with initial stats.
- Enemies and items are placed randomly on the map using the
placeRandomly function. Enemies are represented by 'E' and items by 'I'.
-
Drawing the Game (drawGame function):
- The canvas is cleared, and the grid is drawn.
- Entities are drawn with different colors:
- Hero: Blue square.
- Enemies: Red square.
- Items: Gold circle.
-
Game Loop (gameLoop function):
- The game continues until the hero's HP drops to 0 or all enemies are defeated.
- The hero searches for the nearest target (enemy or item) using
findNearestTarget.
- The path to the target is calculated using the A* algorithm (
findPath function).
- The hero moves towards the target by taking the next step in the path (
moveHero function).
- If the hero encounters an enemy, a battle ensues (
battle function).
- If the hero moves onto an item, the item is collected, and the hero's stats improve (
collectItem function).
- The
improveStats function increases the hero's stats based on experience.
-
Pathfinding (A Algorithm):*
- The A* algorithm calculates the shortest path from the hero's current position to the target.
- The heuristic used is the Manhattan distance.
How to Run the Game:
-
Save the Code:
- Copy the entire code into a text editor.
- Save the file with an
.html extension (e.g., ai_rpg_game.html).
-
Open in Browser:
- Open the saved HTML file with any modern web browser (e.g., Chrome, Firefox, Edge).
-
Watch the Game:
- The game will start automatically.
- You can watch the hero as it navigates the grid, fights enemies, and collects items.
Notes:
- This is a simplified example to demonstrate basic AI movement and interaction in a grid-based game.
- The game does not include advanced combat mechanics, enemy AI, or animations.
- For a more complex game, you might consider adding features like enemy movement, different types of items, obstacles, and a more sophisticated battle system.
Feel free to customize and expand upon this code to enhance the game's features and complexity!