I tried to make a 2-player Chomp game in javascript:
const num_rows = 4;
const num_cols = 7;
var cur_player = 1;
var rows = [];
var buttons = [];
cur_player_text = document.createElement('div');
cur_player_text.innerText = "Current player: " + cur_player;
cur_player_text.id = "cur_player";
document.body.appendChild(cur_player_text);
for(var i = num_rows; i>0; i--) {
rows[i] = document.createElement('div');
rows[i].id = "row" + [i];
document.body.appendChild(rows[i]);
buttons[i] = [];
for(var j = 1; j<=num_cols; j++) {
buttons[i][j] = document.createElement('button');
buttons[i][j].className = "chocolate";
buttons[i][j].id = "button" + [i] + "," + [j];
buttons[i][j].innerText = "x";
buttons[i][j].setAttribute('onclick', 'squareClick(' + i + ', ' + j + ');');
rows[i].appendChild(buttons[i][j]);
}
}
buttons[1][1].setAttribute('disabled', '');
function squareClick(row, col) {
var i = row;
var j = col;
while(buttons[i] != undefined && buttons[i][j] != undefined && buttons[i][j].getAttribute('disabled') == null) {
while(buttons[i][j] != undefined && buttons[i][j].getAttribute('disabled') == null) {
buttons[i][j].setAttribute('disabled', '');
j++;
}
row = row+1;
i = row;
j = col;
}
if(buttons[1][2].getAttribute('disabled') == '' && buttons[2][1].getAttribute('disabled') == '') {
document.getElementById('cur_player').innerText = "Winner: " + cur_player;
}
else {
cur_player = cur_player%2 + 1;
document.getElementById('cur_player').innerText = "Current player: " + cur_player;
}
}
It seems to work but the code is very ugly. How can it be made cleaner and more elegant?