Last active
October 16, 2015 10:26
-
-
Save adambowles/7958172f266c9d7ecff6 to your computer and use it in GitHub Desktop.
Tetris sequence generator. Live demo: http://jsfiddle.net/8zsrwm36/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var pieces = 'OISZLJT'; | |
function tetrisGenerator(length) { | |
var piecesArray = pieces.split(''); | |
var output = ''; | |
while (output.length < length) { | |
// Shuffle the pieces (Fisher-Yates/Knuth shuffle: http://stackoverflow.com/a/2450976/3690621) | |
var current = piecesArray.length, temp, random; | |
while (current !== 0) { | |
random = Math.floor(Math.random() * current); | |
current -= 1; | |
temp = piecesArray[current]; | |
piecesArray[current] = piecesArray[random]; | |
piecesArray[random] = temp; | |
} | |
// Append shuffled pieces | |
output += piecesArray.join(''); | |
} | |
// Return string trimmed to requested length | |
return output.substring(0, length); | |
} | |
function validate(tetris) { | |
// Number of tetris sections, disregarding remainders; e.g. 50 -> 7 | |
var sections = (tetris.length - (tetris.length % pieces.length)) / pieces.length; | |
// Test each section | |
for (var i = 0, validSection = false; i < sections; i++) { | |
validSection = testSection(tetris.substring(i * pieces.length, (i + 1) * pieces.length)); | |
if (!validSection) { | |
return false; | |
} | |
} | |
// Then test the remainder (if it exists) | |
var remainder = tetris.substring(tetris.length - (tetris.length % pieces.length), tetris.length); | |
if (remainder.length > 0) { | |
return testSection(remainder); | |
} | |
return true; | |
// Test a tetromino section | |
function testSection(section) { | |
switch (section.length) { | |
case 1: | |
return pieces.indexOf(section) >= 0; | |
case 7: | |
return pieces.split('').sort().join('').indexOf(section.split('').sort().join('')) >= 0; | |
default: // length: 0, 2-6, 8+ | |
if (section.length < 1 || section.length > 7) return false; | |
for (var i = 0; i < section.length; i++) { | |
if (section.charAt(i) == section.charAt(i+1)) { | |
console.log('dupe'); | |
return false; // There's a duplicated entry | |
} | |
if (pieces.indexOf(section.charAt(i)) < 0) { | |
return false; // Item is not a valid tetromino | |
} | |
} | |
// Can't find any faults | |
return true; | |
} | |
} | |
} | |
var tetrisString = tetrisGenerator(50); | |
console.log("'" + tetrisString + "' is" + (validate(tetrisString) ? '' : ' not') + ' valid'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment