This was a code test I was asked to complete by employer, and since they rejected me, I wonder what should I have done differently.
var w = 7, h = 6;
var currentPlayer = 1;
var animationInProgress = 0;
var winner = 0;
var map = new Array(h);
var mapHtml = "";
for (var i = 0; i < w; i++) {
map[i] = new Array(h);
mapHtml = mapHtml + "<div class='col' id='col"+i+"' onclick='makeTurn("+i+")'><span class='ball next-ball player1'></span>";
for (var j = 0; j < h; j++) {
map[i][j] = 0;
mapHtml = mapHtml + "<div></div>";
}
mapHtml = mapHtml + "</div>";
}
$("#map").html(mapHtml);
function makeTurn(col) {
if (animationInProgress == 0 && winner == 0) {
for (var i = h-1; i >= 0; i--) {
if (map[col][i] == 0) {
map[col][i] = currentPlayer;
animateTurn(col, i);
checkForWin(col, i);
currentPlayer = 3 - currentPlayer;
break;
}
}
}
}
function animateTurn(col, row) {
animationInProgress = 1;
$("#map #col"+col+" .next-ball").addClass("animation-in-progress");
$("#map #col"+col+" .next-ball").animate({
top: '+='+(52*(row+1)-1)
}, {
duration: Math.round((row+1)*500/h),
complete: function() {
$("#map #col"+col+" div:nth-child("+(row+2)+")").html("<span class='ball player"+(3-currentPlayer)+"'></span>");
$("#map #col"+col+" .next-ball").css("top", "0px");
$("#map .animation-in-progress").removeClass("animation-in-progress");
$("#map .next-ball").removeClass("player"+(3-currentPlayer));
$("#map .next-ball").addClass("player"+currentPlayer);
animationInProgress = 0;
}
});
}
function checkForWin(x, y) {
var delta, dx, dy, n = 0;
//horizontal win
for (i = 0; i < w; i++) {
if (map[i][y] == currentPlayer) {
n++;
if (n == 4) win(currentPlayer);
} else {
n = 0;
}
}
//vertical win
n = 0;
for (i = 0; i < h; i++) {
if (map[x][i] == currentPlayer) {
n++;
if (n == 4) win(currentPlayer);
} else {
n = 0;
}
}
//diagonal / win
n = 0;
delta = Math.min(x, h-y-1);
for (dx = x-delta, dy = y+delta; dx < w && dy > 0; dx++, dy--) {
if (map[dx][dy] == currentPlayer) {
n++;
if (n == 4) win(currentPlayer);
} else {
n = 0;
}
}
//diagonal \ win
n = 0;
delta = Math.min(x, y);
for (dx = x-delta, dy = y-delta; dx < w && dy < h; dx++, dy++) {
if (map[dx][dy] == currentPlayer) {
n++;
if (n == 4) win(currentPlayer);
} else {
n = 0;
}
}
}
function win(player) {
alert('Win by player '+player+'. Refresh page to restart');
winner = 1;
}
What are the problems with this code?
- Non-descriptive variable names?
- Too many constants in code?
- Not using comments?