I've been writing some console-based games in python
and got in the habit of having a "mainloop" that looks something like this (if it were JS
):
// mainLoop would be
function mainLoop() {
while ( state === "playing" ) {
if ( turn === "player" ) {
playerTurn(table, board);
turn = "computer";
} else {
computerTurn(table, board);
turn = "player";
}
}
}
This is great as I can easily swap out computer
for player2
so the basic structure doesn't change much for AI vs 2-player games.
However, in HTML5
things get really confusing. Part of me wants to hold onto the simplicity of my mainloop
structure, but since I need the listen for events in JS, it looks like I need to completely shift paradigm.
I did actually get what I want happening using
document.addEventListener( "click", function ( event ) {
if ( event.target.matches( "#reset" ) ) {
init( );
} else if ( event.target.matches( ".cell" ) && turn === "player" ) {
playerTurn( event, table, board );
if ( hasFreeSpot( board ) ) { // don't switch player if board full (or win position?)
computerTurn( table, board );
}
}
}, false );
and updating turn
to player
or computer
within playerTurn()
and computerTurn()
It's hard to reproduce a working example of what I'm trying to do as the program is quite long. what I'm looking for here if possible is some big-picture advice on how to implement player vs computer games in HTML5
where the player move comprises of clicking on some element.
Is there a basic template I can use for this kind of thing? Is the idea of a mainloop
relevant in this context?
Is seems my current approach is a very confusing hybrid of procedural code for the computer turn and even-driven code for the player turn.
I will be happy to edit my question an include a full example if that is what you guys want here.
Thanks in advance.