# Thread: Programming a Nim game in Python (MATH HELP!!)

Join Date
Jun 2008
Posts
128

## Programming a Nim game in Python (MATH HELP!!)

Hi,

I'm trying to program a Nim game for Python but I'm stuck with the mathematical logic. I have no problem in the language itself but I have trouble with the mathematical aspect.

The game starts from n = 10-100 marbles (random). Player or the computer has to pick from 1 - n/2 marbles. Whoever has the last marble left loses the game.

The problem I'm having now is to find a way to get to 1 less the power 2.

For example, if the pile size is 100, the computer will need to take away 37 marbles so that there are 63 left. If the pile size is 52, then the computer needs to take away 37 marbles to get to 15.

So how do i manipulate the math so I can get the following number from n:
3, 7, 15, 31 or 63

2. Web Hosting Master
Join Date
May 2009
Posts
766
Smells like homework...

Join Date
Jun 2008
Posts
128
I think I kind of figured it out:

if n > 63:
ai_choice = n-63

if 31 > n > 63:
ai_choice = n-31

if 15 > n > 31:
ai_choice = n-15

if 7 > n > 15:
ai_choice = n-7

if 3 > n > 7:
ai_choice = n-3

if n == 63 or n == 31 or n == 15 or n == 7 or n == 3:
ai_choice = random.randint(1,n/2)

Join Date
Jun 2008
Posts
128
oops this is more like it:

if n > 63:
ai_choice = n-63
n = n - ai_choice
print_choice = 1

elif 31 < n < 63:
ai_choice = n-31
n = n - ai_choice
print_choice = 1

elif 15 < n < 31:
ai_choice = n-15
n = n - ai_choice
print_choice = 1

elif 7 < n < 15:
ai_choice = n-7
n = n - ai_choice
print_choice = 1

elif 3 < n < 7:
ai_choice = n-3
n = n - ai_choice
print_choice = 1

elif 1 < n < 3:
ai_choice = 1
n = n - ai_choice
print_choice = 1

Join Date
Jun 2008
Posts
128
Originally Posted by mattle
Smells like homework...
Well it's homework but what I was asking was pure mathematical logic which has nothing to do with python.

6. Web Hosting Master
Join Date
May 2009
Posts
766
Seems to me that's the whole point of a programming course anyway...learning the fundamental concepts and logical flows. Learning the syntax is not nearly as important...

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•