Search code examples
pythonnim-game

Number of stones is inconsistent, nim game


The issue is that the number of stones the computer takes differs from the number that is displayed on the screen. I know it's cause the function is being repeated twice. But I can't find a way to store the random number generated and use that number for printing AND subtracting [Also I know this can be done without using functions but it is required]

Here is the code:

import random
stones = random.randint(15, 30)
turn = 0

while stones > 0:
    if turn == 0:
        def player_announce():
            print('There are', stones, 'stones. How many would you like?', end=' ')
        def invalid_entry():
            print('Enter a number from 1-3.')
        player_announce()
        player_stones = int(input(''))
        if player_stones > 3 or player_stones < 1:
            invalid_entry()
        else:
            stones = stones - player_stones
            turn = 1
    else:
        def draw_stones():
            computer_stones = random.randint(1, 3)
            return computer_stones
        print('There are', stones, 'stones. The computer takes', draw_stones())
        stones -= draw_stones()
        turn = 0
if turn == 0:
    print('The computer beats the player!')
else:
    print('The player beats the computer!')

Solution

  • The simple answer is to call draw_stones once and store the result:

    computers_stones = draw_stones()
    print('There are', stones, 'stones. The computer takes', computers_stones)
    stones -= computers_stones
    

    Once you've got it working, I advise you get someone to read over the whole thing for you there are a lot of things you could do better!