I have a small function for an AI player in Tic-Tac-Toe, but I dont want it to run at all if the player selects the "2 Player" version of the game.
function computerPlayer(){
let computerPlayer = true;
chooseRandomSpace();
winCheck();
}
function chooseRandomSpace() {
let n = Math.floor(Math.random() * 9);
if (game.entries[n] === null) {
game.entries[n] = "O";
return (document.getElementById(`space${n}`).innerText = "O");
} else {
chooseRandomSpace();
}
}
and this is the function that runs on 2 player button click:
function twoPlayerGame(){
document.getElementById("playerNames1").style.display = "block";
document.getElementById("playerNames2").style.display = "block";
document.getElementById("numOfPlayers1").style.display = "none";
document.getElementById("numOfPlayers2").style.display = "none";
}
CodePudding user response:
well as already commented on, if you don't want to run the function don't call it. If you have an inline click event you could create a global variable twoPlayer and set it equal to false. Inside function twoPlayerGame() add if (!twoPlayer) return
elsewhere, when you select 2 person game set twoPlayer to true
CodePudding user response:
Your post is currently missing some info we'll need to tackle your problem, but I think I can still sketch what you need.
You've got a game "loop" in which the human player acts, and then the game reacts by making the computer player act, and then the game waits for the human player to act again. What you're asking for help with is "disengaging" the computer player, so that the game loop will simply alternate between human actors.
The way to handle that is simple: you need a shared piece of state, a flag that tells the game loop whether the second-player action comes from a human or the computer player. This is precisely what @DCR suggested.
Your game loop code is incomplete, and the naming is confusing. Based on what I see, computerPlayer
should be named beginOnePlayerGame()
, because that's what it does. A function named "computerPlayer" should be responsible for selecting a single move on behalf of the computer player.
Right now your core game loop appears to be the "chooseRandomSpace" function. I suspect that the major problem you're facing is that this function tries to do too much. The core game loop should just be a "traffic cop": it should decide whose turn it is, and then "ask" the current player for their move.
if the current player is human, "asking" them for their move may involve things like enabling click-handlers on the game UI, and updating other display UI to signal to a human that they can act; the game loop then needs to wait -- possibly forever -- for the human player to act
if the current player is a computer, "asking" it for its move may be as simple as calling a "getRandomMove" function that selects any available space