Auto tetris
HTML
<div class="description">
Test UI for tetris algorithm. Just 2 figures: 1x4 and 2x2. Just implement function getColumnNumberForLeftFigureSquare() that finds the best place for current figure (column number for left square). And wait for the results. Size of tetris: 10 x 20.
</div>
<div id="auto-tetris"></div>
<div class="results">
Squares left: <span id="left">200</span>
</div>
CSS
.description {
width: 100%;
}
.results {
padding: 20px
}
#auto-tetris {
float: left;
width: 200px;
height: 400px;
position: relative;
border: 1px solid #666;
}
.fig {
background: #d14;
position: absolute;
}
.fig.top {
top: 0;
left: 50%;
}
.fig-1-1 {
width: 80px;
height: 20px;
}
.fig-1-1.top {
margin-left: -40px;
}
.fig-1-2 {
width: 20px;
height: 80px;
}
.fig-1-2.top {
margin-left: -10px;
}
.fig-2-1, .fig-2-2 {
width: 40px;
height: 40px;
}
.fig-2-1.top, .fig-2-2.top {
margin-left: -20px;
}
JavaScript
// Function should return integer from 1 to 10. It is a number of column in which will be left square of figure.
function getColumnNumberForLeftFigureSquare(w, h) {
// You can use 3 vars: w, h (size of figure), cols
//return getRandomInt(1, 6);
//naive algorythm - put them as low as possible
//me knows no js, very copy-paste part for arrays
var starts = [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1], //contains the beginnings of straight levels
heights = [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1], // contains straight levels heights
lengths = [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]; //contains straight levels lengths
var currentCol = 0;
starts[currentCol] = currentCol;
heights[currentCol] = cols[0];
lengths[currentCol] = 1;
//index all straight sequences of heigths, where they start,
//how high they are & how long they are
for (var i=1; i < 10; i++)
{
if (cols[i-1] == cols[i])
{
lengths[currentCol]++;
}
else
{
currentCol++;
starts [currentCol] = i;
heights[currentCol] = cols[i];
lengths[currentCol] = 1;
}
}
//find minimal height wide enough for the figure
var minH = heights[0],
minCol = 0;
for (var i=1; i < 10 || starts[i] > 0; i++)
{
if (heights[i] < minH && lengths[i] >= w)
{
minH = heights[i];
minCol = i;
}
}
//return the starting column number for the found minimal height
return (starts[minCol]+1);
}
var interval,
cols = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // contains filled height for each column (10 columns)
left = 200; // Score
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function createRandomFigure() {
var t = document.getElementById('auto-tetris'),
l = document.getElementById('left'),
f = getRandomInt(1, 3), // 1...