rlunde
rlunde

Reputation: 73

Iteratively searching through a looped list

I'm currently in the process of learning how to use Python, and i'm trying to build a Monopoly simulator (for starters, I just want to simulate how one player moves about on the board).

How do i iteratively go through the list of board positions: eg. range(0, 39)? So, if the player is currently in position 35, and rolls a 6, he ends up in position 1.

Hopefully you're able to help! All the best :)

Upvotes: 2

Views: 66

Answers (4)

Brendan.Sherman
Brendan.Sherman

Reputation: 21

You can just subtract the number rolled from distance from the player to the end of the board.

if the difference is less than 0, send the player back to the start of the board and add the absolute value of the difference to the player's position.

Upvotes: 1

David542
David542

Reputation: 110380

You can use the % operator as the above answer describes. For example --

Position        Place
0               Go
1               Mediterranean Avenue
...
35              Short Line
36              Chance
37              Park Place
38              Luxury Tax
39              Boardwalk

Now, if a user is on Position 35 (Short Line) and rolls a 6, their new position will be:

Old_Position = 35
Roll         = 6
New_Position = (35 + 6) % 40 = 1

So they will now be on position 1, or Mediterranean Avenue.

Upvotes: 3

rlunde
rlunde

Reputation: 73

Nevermind, I found the answer myself. I must have been nodding off. Taking the current field, doing the modulo of it, gives the answer.

playerField = ((playerField + random.choice(diceRoll)%40)

Works.

Upvotes: 1

Jacob G.
Jacob G.

Reputation: 29710

You'll want to look into the modulus/remainder operator, %.

https://en.wikipedia.org/wiki/Modulo_operation

For example, the expression "5 mod 2" would evaluate to 1 because 5 divided by 2 leaves a quotient of 2 and a remainder of 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 has a quotient of 3 and leaves a remainder of 0; there is nothing to subtract from 9 after multiplying 3 times 3.

You can use this to automatically handle when the user "wraps around" the board.

Upvotes: 3

Related Questions