Search code examples
pythoncomparisondicehighest

How to make the dice game compare scores between other players?


I'm creating a dice game. I'm stuck, I want the game to compare for each player's roll output roll = randint(1, 6) so the player with the highest score wins. But, I really don't know how to do that.

from random import randint

def main():
    player = int(input('How many players> ')) 
    step = 1
    player += 1
    player_dict = {}

    for pl in range(1, player, step):
        player_name = input(f'Player {str(pl)} name> ') # Get players name from user input
        player_dict[pl] = player_name

    for x in player_dict:
        roll_dice(player_dict[x])

def roll_dice(player_name):
    start_rolling = input(f'{player_name} roll dice? y/n> ')
    if start_rolling == 'y' or start_rolling == 'Y':
        roll = randint(1, 6)
        print(roll)

    return roll_dice

Solution

  • from random import randint
    
    
    def main():
        player = int(input('How many players> ')) 
        step = 1
        player += 1
        player_dict = {}
        scores_dict = {}
        
        for pl in range(1, player, step):
            player_name = input(f'Player {str(pl)} name> ') # Get players name from user input
            player_dict[pl] = player_name
    
        for x in player_dict:
            score = roll_dice(player_dict[x])
            scores_dict[player_dict[x]] = score
    
    
        highest_score = max(scores_dict, key=scores_dict.get)
        sorted_scores = {k: v for k, v in sorted(scores_dict.items(), key=lambda item: item[1], reverse=True)}
        print('----------Results------------')
        [print(f'Position {i+1}: {key} with a roll of {value}') for i, (key, value) in enumerate(sorted_scores.items())]
        print('----------Winner-------------')
        print(f'{highest_score} wins')
    
    def roll_dice(player_name):
        start_rolling = input(f'{player_name} roll dice? y/n> ')
        if start_rolling == 'y' or start_rolling == 'Y':
            roll = randint(1, 6)
            print(f'{player_name} rolls a {roll}')
            return roll
        return
    
    if __name__ == '__main__':
        main()