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

856 views Asked by At

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
2

There are 2 answers

2
John Greenfield On BEST ANSWER
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()
0
Marsilinou Zaky On

Take a look at this example below.

from random import randint


def main():
    players_count = int(input('How many players> '))
    player_dict = {}

    for pl in range(players_count):
        player_name = input(f'Player {str(pl + 1)} name> ')  # Get players name from user input
        player_dict[player_name] = 0  # Initialize all players scores to 0

    for player_name in player_dict:
        player_dict[player_name] = roll_dice(player_name)  # Update score of each player

    print(sorted(player_dict.items(), key=lambda item: item[1]))  # Display sorted scores 


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)
    return roll
main()