Level code generator

by Ben Gillbanks

JavaScript

// Secret key for generating codes (you can make this any random string)
const secretKey = "benIsAwesome";
const codeLength = 4;


// Simple hash function to make the code more unique and deterministic
function hashString(input) {
input = btoa(input);
//return input;
	let hash = 0;
	let result = '';
	for (let i = 0; i < input.length; i++) {
		hash = (hash << 5) - hash + input.charCodeAt(i);
		hash = hash & hash; // Convert to 32bit integer
	}

	// Loop to extend the length of the result by rehashing
	for (let j = 0; j < 5; j++) { // Adjust to control string length
		hash = (hash << 5) - hash + secretKey.charCodeAt(j % secretKey.length);
		result += Math.abs(hash).toString(36); // Append base-36 to the result
	}
    
    console.log(result);

	return result;
}

// Function to generate the code
function getCode(id) {
	const combined = id + secretKey; // Combine the id and secret key for uniqueness
	let hashedString = hashString(combined); // Generate hash of the combined string
	hashedString = hashedString.replace(/[^a-zA-Z]/g, ''); // Remove any non-letter characters
	hashedString = hashedString.toUpperCase(); // Convert to uppercase
	//console.log('Hashed string:', hashedString); // Log for debugging
	return hashedString.substring(0, codeLength); // Return the first 'codeLength' characters
}

// Function to check if the entered code is valid
function checkCode(id, code) {
	const generatedCode = getCode(id); // Get the correct code for the given id
	return generatedCode === code; // Compare the entered code with the correct one
}

// Example usage
for (let i = 0; i < 20; i++) {
	// Log generated codes for levels 0 to 19
	console.log(`Level ${i}: Code = ${getCode(i)}`);
}