1
if (playerturn == 1) {
     currentpos1 = startpos1 + dicetotal;
     prevpos1 = currentpos1 - dicetotal;
 } else {
     currentpos2 = startpos2 + dicetotal;
     prevpos2 = currentpos2 - dicetotal;
 }

I know this is a slight duplicate of other questions, but I still didn't understand the answers. This is for a monopoly board game, which can have upto 6 players. I want to clean up the code, because the only thing that changes is the last part of the variable.

Currentpos(i), Prevpos(i), Startpos(i) are variable names. So how would I concatenate a variable into a variable name?

Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68
Elton Frederik
  • 259
  • 1
  • 3
  • 12

1 Answers1

2

You can use object instead of variables.

var players = {
      playername : { 
          currpos:'val',
          prevpos:'val',
          startpos:'val',
          ....
      },
      ....

  }

Adding new player

players['playername1'] = { 
          currpos:'val',
          prevpos:'val',
          startpos:'val',
          ....
      }

And usage is players['playername'].currpos so in yur case jus players['playername'+playerturn].currpos = players['playername'+playerturn].startpos + dicetotal;

or array

var players = [
    { 
        currpos:'val',
        prevpos:'val',
        startpos:'val',
        ....
    },
    { 
        currpos:'val',
        prevpos:'val',
        startpos:'val',
        ....
    }
];

Adding new player:

 players.push({ 
        currpos:'val',
        prevpos:'val',
        startpos:'val',
        ....
    });

And usage is players[0].currpos so in your case players[playerturn].currpos = players[playerturn].startpos + dicetotal

nzn
  • 828
  • 5
  • 12