I've hit a roadblock while working on my JavaScript rendition of the classic game Battleship for a school project. I'm currently stuck on devising an AI for the opponent player. I have set up an event listener for when a cell is clicked on the playing grid:
function addListener(evt) {
evt.addEventListener('click', function(){
//lots of code
});
}
Each time I generate a new cell in the grid using a nested loop, I invoke the addListener
function as follows:
yourCell.setAttribute('id', evt + String(a) + String(b));
addListener(yourCell);
My next objective is to trigger this click event for the opponent once I have taken my turn. To test the fireEvent
function, I crafted a simple enemyTurn
function:
function enemyTurn() {
document.getElementById('yourGrid00').fireEvent('onclick');
}
As per the provided example, I assigned the ID for the cell as 'yourGrid00'
, which I have verified by inspecting the HTML output post-JavaScript execution. Note that the enemyTurn()
function is scheduled to execute only after creating and assigning IDs to all cells.
However, I encountered an error on the line containing fireEvent
:
Uncaught TypeError: undefined is not a function.
Could someone please point out what I might be overlooking here?