When creating a game or an interactive application in JavaScript, alternating turns between two or more players is a common requirement. In this blog post, we will explore different methods to achieve this functionality using JavaScript.
Maintaining a Turn Variable
The simplest way to alternate turns between players is to keep track of a variable that represents the current turn. This variable can be a boolean, which we will toggle between true and false to represent Player 1 and Player 2, respectively.
let turn = true; // Player 1's turn
function switchTurn() {
turn = !turn;
}
function performAction() {
if (turn) {
console.log("Player 1's action");
} else {
console.log("Player 2's action");
}
switchTurn();
}
performAction(); // Player 1's action
performAction(); // Player 2's action
performAction(); // Player 1's action
In this example, we have a turn variable that is initialized to true, representing Player 1’s turn. We also have a switchTurn() function that toggles the value of the turn variable. The performAction() function simulates a game action and calls switchTurn() after each action is completed.
Using an Array of Players
If there are more than two players, we can use an array to store the player information and use a counter variable to keep track of the current turn. The counter is incremented after each turn, and when it reaches the end of the array, it is reset to zero.
const players = ["Player 1", "Player 2", "Player 3"];
let currentPlayerIndex = 0;
function switchTurn() {
currentPlayerIndex = (currentPlayerIndex + 1) % players.length;
}
function performAction() {
console.log(players[currentPlayerIndex] + "'s action");
switchTurn();
}
performAction(); // Player 1's action
performAction(); // Player 2's action
performAction(); // Player 3's action
performAction(); // Player 1's action
In this example, we have an array called players containing the player’s names and a variable called currentPlayerIndex that represents the current player’s index in the array. The switchTurn() function increments the currentPlayerIndex and resets it to zero when it reaches the end of the array, ensuring that the turn cycle loops through all players.
Conclusion
Alternating turns in JavaScript is a simple and straightforward process. By using either a turn variable or an array of players, you can easily manage the flow of turns in your game or interactive application. Don’t forget to call the switchTurn() function after each action to ensure a smooth transition between turns.