Okay, I understand! You want the line drawing to be visible in real-time as you drag the mouse, and you want a guarantee (or at least a strong attempt) that every generated level is solvable.
Here's the updated HTML code for "Forsaken Generator Simulator," incorporating real-time line rendering, robust collision detection, and a basic solvability check using a Breadth-First Search (BFS) algorithm to ensure each pair can theoretically be connected without considering other pairs' paths. While this doesn't guarantee a solution when all paths must coexist, it significantly improves the playability by preventing isolated dots.
Key Changes:
- Real-time Line Rendering: The
currentPath is now drawn in a distinct color (lime green) on mousemove events, giving immediate visual feedback.
- Improved Collision Detection:
- Lines cannot go outside the grid.
- Lines cannot cross existing completed lines.
- Lines cannot pass through other dots (only the starting dot and its matching target dot).
- Lines cannot cross themselves.
- Solvability Check: The
generateLevel function now uses a findPathBFS helper. Before displaying a level, it checks if every dot pair has at least one path between them on an empty grid. If not, it regenerates the level. This significantly reduces unsolvable random layouts.
- Grid State Management: The
grid array now correctly tracks null (empty), number (dot), or 'occupied' (completed path segment) cells.
- Path Clearing: When a line is released on an invalid spot, the temporary line instantly disappears.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forsaken Generator Simulator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 20px;
background-color: #e0e0e0;
color: #333;
}
h1 {
color: #4CAF50; /* A nice green */
}
canvas {
border: 2px solid #555;
background-color: #f8f8f8;
margin: 20px auto;
display: block;
box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}
#message {
font-size: 20px;
margin-bottom: 15px;
color: #666;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Forsaken Generator Simulator</h1>
<div id="message">Level 1 - Connect all pairs!</div>
<canvas id="gameCanvas" width="600" height="600"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const cellSize = 100; // Each cell is 100x100 pixels for a 6x6 grid
let grid = Array(6).fill().map(() => Array(6).fill(null)); // 6x6 grid: null for empty, number for dot, 'occupied' for path
let dots = []; // Array of {row, col, number}
let paths = []; // Array of completed paths, each path is an array of {row, col}
let currentPath = null; // Current path being drawn (temporary)
let startCell = null; // Starting cell of the current path
let level = 1; // Track the level
// --- Core Game Logic ---
function generateLevel() {
let solvable = false;
let attempts = 0;
const maxAttempts = 200; // Max attempts to find a solvable grid for this method
while (!solvable && attempts < maxAttempts) {
attempts++;
dots = [];
paths = [];
grid = Array(6).fill().map(() => Array(6).fill(null)); // Reset grid
const numbers = [1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8]; // Two of each number
numbers.sort(() => Math.random() - 0.5); // Shuffle numbers
// Place dots randomly
const positions = [];
while (positions.length < 16) {
const row = Math.floor(Math.random() * 6);
const col = Math.floor(Math.random() * 6);
if (!positions.some(p => p.row === row && p.col === col)) {
positions.push({row, col});
dots.push({row, col, number: numbers[positions.length - 1]});
grid[row][col] = dots[dots.length - 1].number; // Mark cell with dot number
}
}
// --- Solvability Check (BFS for each pair individually) ---
let allPairsConnectable = true;
const checkedPairs = new Set(); // To avoid redundant checks (1->2 and 2->1)
for (let i = 0; i < dots.length; i++) {
const startDot = dots[i];
// Find the other dot with the same number
const targetDot = dots.find(d => d.number === startDot.number && !(d.row === startDot.row && d.col === startDot.col));
if (!targetDot) continue; // Should not happen if numbers are paired correctly
// Create a unique key for the pair to prevent re-checking
const pairKey1 = `${startDot.row},${startDot.col}-${targetDot.row},${targetDot.col}`;
const pairKey2 = `${targetDot.row},${targetDot.col}-${startDot.row},${startDot.col}`;
if (checkedPairs.has(pairKey1) || checkedPairs.has(pairKey2)) {
continue; // Already checked this pair
}
// Perform BFS on a fresh copy of the grid (with only dots)
// The BFS will assume an empty grid, it does not account for other lines.
// This is a basic solvability check, not a full "flow puzzle" solver.
const pathFound = findPathBFS(startDot, targetDot, grid);
if (!pathFound) {
allPairsConnectable = false;
break; // This level is not solvable by this simple check
}
checkedPairs.add(pairKey1); // Mark this pair as checked
}
if (allPairsConnectable) {
solvable = true;
}
}
if (!solvable) {
console.warn("Could not generate a solvable level after max attempts. This might be rare or impossible with current constraints.");
// As a fallback, you might want to show an error or reset to a known solvable state.
// For this example, we will just proceed with the last attempted generation.
}
document.getElementById('message').textContent = `Level ${level} - Connect all pairs!`;
drawGrid();
}
/**
* Uses Breadth-First Search (BFS) to find if a path exists between two dots
* on the current grid state (excluding 'occupied' cells for other paths).
* @param {object} start - {row, col} of the starting dot.
* @param {object} end - {row, col} of the target dot.
* @param {Array<Array<any>>} currentGridState - The grid with dots.
* @returns {Array<object>|null} The path if found, or null.
*/
function findPathBFS(start, end, currentGridState) {
const queue = [{ row: start.row, col: start.col, path: [] }]; // path tracks cells to avoid self-crossing for this individual BFS
const visited = new Set();
visited.add(`${start.row},${start.col}`);
while (queue.length > 0) {
const { row, col, path } = queue.shift();
// If we reached the target, return true (path found)
if (row === end.row && col === end.col) {
return true; // We only need to know if a path exists
}
// Explore neighbors
const neighbors = [
{ r: row - 1, c: col }, // Up
{ r: row + 1, c: col }, // Down
{ r: row, c: col - 1 }, // Left
{ r: row, c: col + 1 } // Right
];
for (const neighbor of neighbors) {
const nr = neighbor.r;
const nc = neighbor.c;
// Check boundaries
if (nr < 0 || nr >= 6 || nc < 0 || nc >= 6) continue;
const visitedKey = `${nr},${nc}`;
if (visited.has(visitedKey)) continue;
const cellContent = currentGridState[nr][nc];
// A cell is valid if:
// 1. It's empty (null)
// 2. It's the target dot for this specific BFS (end.row, end.col)
// 3. It's NOT occupied by another completed path ('occupied')
// 4. It's NOT another dot's starting position (unless it's the end dot)
const isTargetDot = (nr === end.row && nc === end.col);
const isOtherDot = (cellContent !== null && typeof cellContent === 'number' && !isTargetDot);
const isOccupiedByOtherPath = (cellContent === 'occupied');
if ((cellContent === null || isTargetDot) && !isOtherDot && !isOccupiedByOtherPath) {
visited.add(visitedKey);
queue.push({ row: nr, col: nc, path: [...path, { row: nr, col: nc }] });
}
}
}
return null; // No path found
}
// --- Drawing Functions ---
function drawGrid() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw grid lines
ctx.strokeStyle = '#ccc';
ctx.lineWidth = 1;
for (let i = 0; i <= 6; i++) {
ctx.beginPath();
ctx.moveTo(0, i * cellSize);
ctx.lineTo(canvas.width, i * cellSize);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(i * cellSize, 0);
ctx.lineTo(i * cellSize, canvas.height);
ctx.stroke();
}
// Draw existing paths (completed paths)
paths.forEach(path => {
ctx.strokeStyle = 'blue';
ctx.lineCap = 'round'; // Makes lines look nicer
ctx.lineWidth = 10;
ctx.beginPath();
path.forEach((cell, index) => {
const x = cell.col * cellSize + cellSize / 2;
const y = cell.row * cellSize + cellSize / 2;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
});
// Draw current path (in-progress line)
if (currentPath) {
ctx.strokeStyle = 'lime'; // Different color for current line
ctx.lineCap = 'round';
ctx.lineWidth = 10;
ctx.beginPath();
currentPath.forEach((cell, index) => {
const x = cell.col * cellSize + cellSize / 2;
const y = cell.row * cellSize + cellSize / 2;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
}
// Draw dots (on top of everything else)
dots.forEach(dot => {
// Determine if this dot is connected (part of a completed path)
const isConnected = paths.some(path =>
(path[0].row === dot.row && path[0].col === dot.col) ||
(path[path.length - 1].row === dot.row && path[path.length - 1].col === dot.col)
);
if (!isConnected) {
ctx.fillStyle = 'red'; // Unconnected dots are red
ctx.beginPath();
ctx.arc(dot.col * cellSize + cellSize / 2, dot.row * cellSize + cellSize / 2, 20, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = 'white'; // Number color
ctx.font = '30px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(dot.number, dot.col * cellSize + cellSize / 2, dot.row * cellSize + cellSize / 2);
} else {
// Connected dots might have a slightly different appearance or no number
// For now, let's just make their outline different to show they're connected
ctx.strokeStyle = 'darkgreen'; // Green border for connected dots
ctx.lineWidth = 3;
ctx.beginPath();
ctx.arc(dot.col * cellSize + cellSize / 2, dot.row * cellSize + cellSize / 2, 20, 0, 2 * Math.PI);
ctx.stroke();
ctx.fillStyle = 'gray'; // Faded number for connected dots
ctx.font = '30px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(dot.number, dot.col * cellSize + cellSize / 2, dot.row * cellSize + cellSize / 2);
}
});
}
// --- Event Listeners ---
canvas.addEventListener('mousedown', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const col = Math.floor(x / cellSize);
const row = Math.floor(y / cellSize);
// Find if a dot exists at the clicked position and if it's not already connected
const clickedDot = dots.find(d => d.row === row && d.col === col);
if (clickedDot) {
// Check if this dot is already the start or end of a completed path
const isDotConnected = paths.some(path =>
(path[0].row === clickedDot.row && path[0].col === clickedDot.col) ||
(path[path.length - 1].row === clickedDot.row && path[path.length - 1].col === clickedDot.col)
);
if (!isDotConnected) {
startCell = {row, col, number: clickedDot.number}; // Store start dot's number
currentPath = [{row, col}]; // Start path with the clicked dot
}
}
});
canvas.addEventListener('mousemove', (e) => {
if (!currentPath || !startCell) return; // No path being drawn
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const col = Math.floor(x / cellSize);
const row = Math.floor(y / cellSize);
// Stay within grid boundaries
if (row < 0 || row >= 6 || col < 0 || col >= 6) {
// Optionally, could clear path if mouse goes out of bounds
return;
}
const lastCellInPath = currentPath[currentPath.length - 1];
// Don't add the same cell again if mouse hasn't moved to a new grid cell
if (lastCellInPath.row === row && lastCellInPath.col === col) {
return;
}
// Check if the new cell is adjacent (horizontal or vertical) to the last cell in path
if (isAdjacent(lastCellInPath, {row, col})) {
const cellContent = grid[row][col];
// Find the target dot for the current startDotNumber (the other dot of the same number)
const targetDot = dots.find(d => d.number === startCell.number && !(d.row === startCell.row && d.col === startCell.col));
// A move is valid if:
// 1. The cell is completely empty (null)
// 2. OR, the cell is the *specific* target dot for the current line
// AND it's not already part of the current path (to prevent self-crossing)
// AND it's not another dot or an already occupied path segment.
const isTargetCell = (targetDot && row === targetDot.row && col === targetDot.col);
const isCellAlreadyInCurrentPath = currentPath.some(c => c.row === row && c.col === col);
if (!isCellAlreadyInCurrentPath && (cellContent === null || isTargetCell)) {
currentPath.push({row, col});
drawGrid(); // Redraw immediately to show the in-progress line
}
}
});
canvas.addEventListener('mouseup', (e) => {
if (!currentPath || !startCell) return;
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const col = Math.floor(x / cellSize);
const row = Math.floor(y / cellSize);
const startDotNumber = startCell.number;
const targetDot = dots.find(d => d.row === row && d.col === col && d.number === startDotNumber && !(d.row === startCell.row && d.col === startCell.col));
// Check for a successful connection:
// 1. Mouse released on the correct target dot.
// 2. The path length is greater than 1 (to ensure it's not just a click on the same dot).
// 3. The last cell added to currentPath is indeed the target dot.
if (targetDot && currentPath.length > 1) {
const lastCellInPath = currentPath[currentPath.length - 1];
if (lastCellInPath.row === targetDot.row && lastCellInPath.col === targetDot.col) {
// Valid connection! Mark path cells as 'occupied' in the grid.
currentPath.forEach(cell => {
// Only mark intermediate cells as 'occupied', dots retain their number
if (!dots.some(d => d.row === cell.row && d.col === cell.col)) {
grid[cell.row][cell.col] = 'occupied';
}
});
paths.push(currentPath); // Add to completed paths
currentPath = null;
startCell = null;
drawGrid();
checkWin();
return; // Exit after successful connection
}
}
// If not a successful connection, clear the temporary path
currentPath = null;
startCell = null;
drawGrid(); // Redraw to clear the in-progress line
});
canvas.addEventListener('mouseleave', () => {
// Clear current path if mouse leaves the canvas
if (currentPath) {
currentPath = null;
startCell = null;
drawGrid();
}
});
// --- Helper Functions ---
function isAdjacent(cell1, cell2) {
const rowDiff = Math.abs(cell1.row - cell2.row);
const colDiff = Math.abs(cell1.col - cell2.col);
// Only horizontal or vertical moves allowed (not diagonal)
return (rowDiff === 1 && colDiff === 0) || (rowDiff === 0 && colDiff === 1);
}
function checkWin() {
// A level is complete when all 8 pairs are connected
if (paths.length === 8) {
level++;
setTimeout(() => { // Small delay for player to see completion
alert('Level complete! Generating next level...');
generateLevel();
}, 300);
}
}
// Start the game for the first time
generateLevel();
</script>
</body>
</html>