Exercici funcions i arrays (solució))
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
// modifiquem createBoard per ficar les fitxes:
function createBoard() {
const chessPieces = [
['♜', '♞', '♝', '♛', '♚', '♝', '♞', '♜'],
['♟', '♟', '♟', '♟', '♟', '♟', '♟', '♟'],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
['♙', '♙', '♙', '♙', '♙', '♙', '♙', '♙'],
['♖', '♘', '♗', '♕', '♔', '♗', '♘', '♖'],
];
return chessPieces;
}
// Modifiquem la funció create cell per afegir la fitxa.
function createCell(cell) {
return `<td>${cell}</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;
}
// Crea una funció que plene el tauler amb les fitxes unicode de l'escacs. Crida-la en el moment adequat
document.querySelector('#board').append(drawBoard(createBoard()))