When developing canvas games for mobile devices, visual blurring often occurs due to the difference between CSS dimensions and physical screen pixels. The devicePixelRatio property addresses this scaling requirement. Consider this implementation:
function setupCanvasResolution(canvasElement) {
const pixelRatio = window.devicePixelRatio || 1;
const displayWidth = canvasElement.clientWidth;
const displayHeight = canvasElement.clientHeight;
canvasElement.width = displayWidth * pixelRatio;
canvasElement.height = displayHeight * pixelRatio;
canvasElement.style.width = displayWidth + "px";
canvasElement.style.height = displayHeight + "px";
const ctx = canvasElement.getContext('2d');
ctx.scale(pixelRatio, pixelRatio);
}
Pathfinding Implementation
The core challenge involves implementing pathfinding for the wolf to track the moving sheep. The solution utilizes a grid-based breadth-first search algorithm:
class NavigationGrid {
constructor(mapData, destination) {
this.grid = mapData;
this.target = destination;
this.gridWidth = this.grid[0].length;
this.gridHeight = this.grid.length;
}
findRoute(startPosition) {
const visited = new Set();
const queue = [[startPosition]];
while (queue.length > 0) {
const currentPath = queue.shift();
const [x, y] = currentPath[currentPath.length - 1];
if (x === this.target.x && y === this.target.y) {
return currentPath;
}
const neighbors = this.getValidNeighbors(x, y);
for (const [nx, ny] of neighbors) {
const positionKey = `${nx},${ny}`;
if (!visited.has(positionKey)) {
visited.add(positionKey);
queue.push([...currentPath, [nx, ny]]);
}
}
}
return null;
}
getValidNeighbors(x, y) {
const directions = [[0,1], [1,0], [0,-1], [-1,0]];
return directions
.map(([dx, dy]) => [x + dx, y + dy])
.filter(([nx, ny]) =>
nx >= 0 && nx < this.gridWidth &&
ny >= 0 && ny < this.gridHeight &&
this.grid[ny][nx] !== 1
);
}
}
Mobile Control Considerations
During testing, virtual joystick libraries like nipplejs were evaluated for mobile controls. However, directional button controls proved more precise for grid-based movement, as joysticks often resulted in overshooting target positions by 1-2 grid cells. The game utilizes SweetAlert for dialog management due to its simplicity and zero dependencies.
For comprehensive pathfinding cocnepts, refer to: https://www.redblobgames.com/pathfinding/a-star/introduction.html