Let's say that both players start with 10 dollars. We can represent the game state with a list:
start = {10, 10};
Create a function which plays one round of the game. There are only two possible outcomes, we can use RandomChoice
to pick randomly between them:
oneRound[{x_, y_}] := RandomChoice[{{x + 1, y - 1}, {x - 1, y + 1}}]
For example oneRound[start]
will give either {9, 11}
or {11, 9}
with equal probability. By repeatedly applying the oneRound
function to the list we can simulate the game. But we also need to stop the game when one player runs out of money. So we create another function which returns True
if the game can continue and False
otherwise. The condition for the game to continue is that both players have more than zero dollars:
gameContinues[{x_, y_}] := x > 0 && y > 0
To simulate a full game we need some code which starts with the list start
and repeatedly applies the function oneRound
as long as gameContinues
returns True
. As Andre suggested, we can use NestWhileList
for this:
result = NestWhileList[oneRound, start, gameContinues]
{{10, 10}, {11, 9}, {12, 8}, {11, 9}, ..., {18, 2}, {19, 1}, {20, 0}}
To visualise the game:
ListLinePlot[Transpose[result], PlotLegends -> {"Player 1", "Player 2"}]

f[x_] := x + RandomChoice[{-1, 1}]; testQ[y_] := (y > 0); NestWhileList[f, 10, testQ]
? $\endgroup$