Search code examples
pythonrandompygamedice

How could I modfiy this game to where I"m playing agains the computer instead of another user?


I found this code for The Dice Game of Pig, and you input for both players. I would like to modify it to where player 1 would be a computer and roll automatically. How would I go about doing this?

from random import randint

playercount = 2
maxscore = 100
safescore = [0] * playercount
player = 0
score=0

while max(safescore) < maxscore:
    rolling = input("Player %i: (%i, %i) Rolling? (Y) "
                % (player, safescore[player], score)).strip().lower() in {'yes', 'y', ''}
    if rolling:
        rolled = randint(1, 6)
        print('  Rolled %i' % rolled)
        if rolled == 1:
            print('  Bust! you lose %i but still keep your previous %i'
                  % (score, safescore[player]))
            score, player = 0, (player + 1) % playercount
        else:
            score += rolled
    else:
        safescore[player] += score
        if safescore[player] >= maxscore:
            break
        print('  Sticking with %i' % safescore[player])
        score, player = 0, (player + 1) % playercount

print('\nPlayer %i wins with a score of %i' %(player, safescore[player]))

Solution

  • from random import randint
    
    playercount = 2
    maxscore = 100
    safescore = [0] * playercount
    player = 0
    score=0
    
    while max(safescore) < maxscore:
        if player == 0:
            rolling = 0
            if score < 17 and score + safescore[player] < maxscore:
                rolling = 1
        else:
            rolling = input("Player %i: (%i, %i) Rolling? (Y) "
                % (player, safescore[player], score)).strip().lower() in {'yes', 'y', ''}
        if rolling:
            rolled = randint(1, 6)
            print('  Rolled %i' % rolled)
            if rolled == 1:
                print('  Bust! you lose %i but still keep your previous %i'
                      % (score, safescore[player]))
                score, player = 0, (player + 1) % playercount
            else:
                score += rolled
        else:
            safescore[player] += score
            if safescore[player] >= maxscore:
                break
            print('  Sticking with %i' % safescore[player])
            score, player = 0, (player + 1) % playercount
    
    print('\nPlayer %i wins with a score of %i' %(player, safescore[player]))