Sokoban Generator

by Ben Gillbanks

HTML

<div id="content"></div>

JavaScript

class SokoGenerator {
	constructor() {
		this.levels = [];
		this.patterns = this.loadPatterns();
		this.noOfBoxes = 0;
		this.noOfLevels = 0;
		this.roomWidth = 0;
		this.roomHeight = 0;
		this.difficulty = 0;
	}

	// Load patterns (for simplicity, assuming patterns are preloaded)
	loadPatterns() {
		// You can implement a file loading logic or hardcode some pattern grids
		return [
            [
                ['W', 'W', 'W'],
                ['W', ' ', 'W'],
                ['W', 'W', 'W']
            ],
            [
                [' ', 'W', ' '],
                ['W', ' ', 'W'],
                [' ', 'W', ' ']
            ],
            // Add more patterns here...
        ];
	}

	// Generates a random number between min and max, divisible by divisor
	randomNumber(min, max, divisor = 1) {
		let number;
		do {
			number = Math.floor(Math.random() * (max - min + 1)) + min;
		} while (number % divisor !== 0);
		return number;
	}

	// Initialize the level with walls and floors
	initLevel(roomWidth, roomHeight) {
		const level = [];
		const adjustedHeight = roomHeight + 2;
		const adjustedWidth = roomWidth + 2;

		for (let y = 0; y < adjustedHeight; y++) {
			const row = [];
			for (let x = 0; x < adjustedWidth; x++) {
				if (y === 0 || y === adjustedHeight - 1 || x === 0 || x === adjustedWidth - 1) {
					row.push('W'); // Wall
				} else {
					row.push(' '); // Floor
				}
			}
			level.push(row);
		}
		return level;
	}

	// Place boxes, goals, and player
	placeGoalsAndBoxes(level, roomWidth, roomHeight, noOfBoxes) {
		// Randomly place goals and boxes
		for (let i = 0; i < noOfBoxes; i++) {
			this.placeObject(level, roomWidth, roomHeight, 'G'); // Goal
			this.placeObject(level, roomWidth, roomHeight, 'B'); // Box
		}
	}

	// Randomly place an object in the level
	placeObject(level, roomWidth, roomHeight, object) {
		let x, y;
		do {
			x = this.randomNumber(1, roomWidth);
			y =...