Current_space = start point(space 0)
Player1 rolls dice. New_space = Current_space + Dice_roll.
When Player1 rolls again. How do you get New_space equal to the first New_space + 2nd Dice_roll
and so on?
Current_space = start point(space 0)
Player1 rolls dice. New_space = Current_space + Dice_roll.
When Player1 rolls again. How do you get New_space equal to the first New_space + 2nd Dice_roll
and so on?
I would have a player object that maintains its own state, like board position. Then, a method could be used to move the player X spaces.
var playerOne = player();
playerOne.move(Dice.roll())
Internally, you’re just updating a field:
function Player() {
//... stuff
position: 0,
move: function(spaces) {
this.position += spaces
}
//...
}
Sorry. I’m really new to this. Is there a name for this type of operation? Bouncing back and forth between two variables, updating their values?
The concept that I described is called encapsulation, and it’s a more advanced, object oriented principle. It’s something that you’ll just “get” after you read and consume other people’s code more.
I would advise you to avoid having more than one variable if they both mean the same thing. If you need to update current_space
, then update current_space
. new_space
is just an unnecessary step. Here’s how you’d have to do it with your code:
current_space = STARTING_SPACE # 0
new_space = current_space + dice_roll
current_space = new_space
But this can be shortened:
current_space = STARTING_SPACE # 0
current_space += dice_roll
As your application grows, having global variables like current_space
can cause lots of problems, and these problems grow as you add more variables. This is why I suggested the player object (or player class, as your code style implies that you’re writing Python or Ruby), which would encapsulate that information in useful ways.
Thank you very much for the reply. That was easy to understand. I will make sure to lookup and learn more about encapsulation and making objects.