1

I have a game with 2 players. They are called p1 and p2. Each turn I have to switch between them. This is what I do now

var currentPlayer = "p1";
var nextPlayer = (currentPlayer === "p1") ? "p2" : "p1";

But is seems not elegant. Is there a way to just get "the other one" out of 2 predefined values.

ilyo
  • 35,851
  • 46
  • 106
  • 159
  • 1
    I think your method is fine. It's certainly easy to understand. – Parris Varney Oct 21 '15 at 11:08
  • 1
    _simplest way_? `(currentPlayer === "p1") ? "p2" : "p1";` is the simplest, redable way – Tushar Oct 21 '15 at 11:08
  • 3
    Possible Duplicate [Is there a better way of writing v = (v == 0 ? 1 : 0);](http://stackoverflow.com/questions/6911235/is-there-a-better-way-of-writing-v-v-0-1-0) – Tushar Oct 21 '15 at 11:10
  • Title should be changed to _What are possible ways to get “the other value” from 2 static values?_ – Tushar Oct 21 '15 at 11:24

1 Answers1

1

What you're doing is a very common approach, so it's fine. But if you want something more elegant, you can do:

var players = ["p1", "p2"];
var playerNum = 0;
var currentPlayer = players[playerNum];
var nextPlayerNum = (playerNum + 1) % players.length;
var nextPlayer = players[nextPlayerNum];

This is probably overkill for just two players. But it generalizes to an arbitrary number of players easily -- just add more elements to the players array.

players could also be an array of objects that contain all the state of the players, not just their names.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 4
    2x the code, and 1/2 as understandable isn't more elegant. – Parris Varney Oct 21 '15 at 11:10
  • It's more modular, because it doesn't require hard-coding the player names throughout the code. – Barmar Oct 21 '15 at 11:12
  • @Barmar I don't agree, `var player1 = 'p1', player2 = 'p2'; var nextPlayer = (currentPlayer === player1) ? player2 : player1;` Isn't this _modular_ – Tushar Oct 21 '15 at 11:14
  • I like this answer as it will work for three, four ... players as well and you only have to change the players array, you could now even fetch that array from a server.... – rene Oct 21 '15 at 11:18
  • @rene OP is interested in only two players. And this will give you _next_ player in chain, not the other – Tushar Oct 21 '15 at 11:22
  • Sure, that is all true. My comment stands. – rene Oct 21 '15 at 11:24