implemented win condition check

This commit is contained in:
Baipyrus 2023-08-04 19:26:32 +00:00
parent b7991ed273
commit 3471e230f8

View File

@ -130,6 +130,49 @@
reveal(cell);
}
function NodeListToArray(list: NodeListOf<Element>): Element[] {
return Array.prototype.slice.call(list);
}
async function checkWinCondition() {
// Get all HTML Table Cell Elements
const cells = document.querySelectorAll('td') as NodeListOf<HTMLTableCellElement>;
const array = NodeListToArray(cells) as HTMLTableCellElement[];
// Convert all HTML Table Cell Elements to Cells
const mines = array.filter(e => e.dataset.marked).map(e => {
// Get id from cell
if (e.dataset.id === undefined) return null;
const index: number = parseInt(e.dataset.id);
// Calculate coordinates from index
const { x, y } = toCoords(index);
return { x, y } as Cell;
}).filter(e => e !== null) as Cell[];
// Prepare URL serach param for cell array
const params: URLSearchParams = new URLSearchParams();
params.set('mines', JSON.stringify(mines));
// Send get-request to verify marked as mines
const response: Response = await fetch('/checkMarked?' + params.toString());
// Parse response to JSON
const data: RawResponse = await response.json();
// Get status for error handling and cells in case it works
const { success, message, done } = data;
if (done === undefined || !success)
throw new Error(`Couldn't verify marked cells!\n${message}`);
console.log(message);
// If all marked cells have been verified as mines
if (done) {
// Display an event message, reset matrix on click
const elements = getElements();
const onClickFunc = () => { updateMatrix(false); };
displayMessage(elements, 'You won!', 'white', 'black', onClickFunc);
}
}
async function reveal(cell: HTMLTableCellElement) {
if (cell.dataset.clicked) return;
// Get id from cell
@ -176,6 +219,9 @@
// Display the reveal
displayChange(element, 'lightgrey', neighbors);
}
// Check whether winning condition is met
checkWinCondition();
}
// Handle reveal logic on right click MouseEvent
@ -205,6 +251,9 @@
// Remember cell for auto-reset
changed.push(cell);
// Check whether winning condition is met
checkWinCondition();
}
// Handle reveal logic on double click MouseEvent