Exercici funcions i arrays (solució funció)
by xxjcaxx
HTML
<div id="board">
</div>
CSS
.chess {
width: 100%;
height: 100%;
display: block;
background: #eee;
margin: 0;
padding: 0;
overflow: overlay;
}
.chess td {
width: 20px;
height: 20px;
text-align: center;
}
.chess tr:nth-child(odd) td:nth-child(even), .chess tr:nth-child(even) td:nth-child(odd){
background-color: #111;
color: #fff;
}
JavaScript
function createBoard() {
let row = new Array(8).fill(null);
return new Array(8).fill([...row]);
}
function createCell(cell) {
return `<td></td>`;
}
function createRow(row) {
return `<tr>${row.map(createCell).join(' ')}</tr>`;
}
function drawBoard(board) {
let tableBoard = document.createElement('table');
tableBoard.classList.add('chess');
tableBoard.innerHTML = board.map(createRow).join(' ');
return tableBoard;
}
function fillBoard(tableBoard) {
const chessBoard = [
['♜', '♞', '♝', '♛', '♚', '♝', '♞', '♜'],
['♟', '♟', '♟', '♟', '♟', '♟', '♟', '♟'],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
['♙', '♙', '♙', '♙', '♙', '♙', '♙', '♙'],
['♖', '♘', '♗', '♕', '♔', '♗', '♘', '♖'],
];
[...tableBoard.querySelectorAll('tr')].forEach((tr,i) => {
[...tr.querySelectorAll('td')].forEach((td,j)=> {
td.innerText = chessBoard[i][j];
});
}
);
return tableBoard;
}
// Crea una funció que plene el tauler amb les fitxes unicode de l'escacs. Crida-la en el moment adequat
document.querySelector('#board').append(fillBoard(drawBoard(createBoard())));