How to create variables in a loop without knowing the number of variables needed in advance?

I am currently doing a student project in Python.

The game itself:

  • The user chooses the number of players who want to play (Minimum 1)

  • The user assigns a number of tokens to be applied for each player (Like a life system)

  • Then, the first player will "throw" 3 dice from 1 - 6.

  • The total score of the 3 dice is calculated and then we ask if the player wants to roll 1, 2 or 3 dice again. (The goal is to get as close as possible or to be equal to 21).

  • It is possible to throw the dice several times in a row. (The other throws are added to the total)

  • The player loses a token if his total score is higher than 21.

  • The player can stop his turn by indicating 0.

The loop does its work by passing the hand to the second player.

When the players have finished playing, we look at the scores. The player being at 21 or the closest wins this round, the others must give a token to the "bank". (So the player having exceeded 21 will automatically lose 2 tokens for this round).

The game stops when only one player has a token left.


My Problem

I can't see how to store in variables the total score of players and their respective tokens. As the user decides the number of players, I can't predict variables.

My Code

#Programme : Blackjack
#Auteur : Antoine Bauduffe MP

#Import
from random import randrange

#Variable(s) :
verifJoueur = False;
verifJeton = False;
verifRelance = False;
i = 1;
n = 1;
y = 1;
relance = 1;
scoreTotal = 0;
DN = 0;
ScoreJoueur = [];

#Interface :
print("\n");
print("<------------------------------------------------------------------->");
print("<---------------------------- BLACKJACK ---------------------------->");
print("<------------------------------------------------------------------->");

#Boucle demandant le nombre de joueur
while verifJoueur == False:
    try:
        nbJoueur = int(input("Veuillez indiquer le nombre de joueur : "));
        int(nbJoueur);
        if nbJoueur >= 1:
            verifJoueur = True;
        else:
            print("\n")
            print("[Un joueur est requis pour lancer une partie !]")
    except ValueError:
        print("\n")
        print("[Indiquer un nombre de joueur correct !]");
        
#Boucle demandant le nombre de jeton par joueur
while verifJeton == False:
    try:
        nbJetonsParJoueur = int(input("Veuillez indiquer le nombre de jeton par joueur (Pas plus de 10) : "));
        int(nbJetonsParJoueur);
        if nbJetonsParJoueur >= 1 and nbJetonsParJoueur <= 10:
            verifJeton = True;
        else:
            print("\n")
            print("[Les joueurs ne peuvent pas avoir moins de 1 jeton ni plus de 10 jetons !]")
    except ValueError:
        print("\n")
        print("[Indiquer un nombre de jeton correct !]");

#Résumé des paramètres
print("\n");
print("<------------------------------------------------------------------->");
print("Lancement d'une partie pour " + str(nbJoueur) + " joueur(s), possedant chacun " + str(nbJetonsParJoueur) + " jeton(s).");
print("<------------------------------------------------------------------->");
print("\n")

#Boucle des joueurs
while i <= nbJoueur:
    print("<----------------------- Tour du joueur " +  str(i) + " : ------------------------>");

    print(str(n) + "°) Lancement de dés : ");
    for x in range(0, 3):
        DN = randrange(1, 7);
        print("--> " + str(DN));
        scoreTotal = scoreTotal + DN;
    print("Total : " + str(scoreTotal));
    
    #Boucle qui vérifié les relances ou non
    while verifRelance == False:
        try:
            if scoreTotal > 21:
                verifRelance = True;
                print('\n')
                print("<------------------------------------------------------------------->");
                print("Votre score dépasse 21 ! Vous perdez un jeton !")
                print("<------------------------------------------------------------------->");
                print('\n');
                print("<---------------- Fin du tour pour le joueur " +  str(i) + " ---------------->");
                print("<---------------- Score du joueur " +  str(i) + " : " + str(scoreTotal) + " ---------------->");
                print("\n");
                break;
            else:
                relance = int(input("Relancer ? Indiquer le nombre de dés à relancer [0 pour ne pas relancer] : "));
                int(relance);
                if relance >= 0 and relance <= 3:
                    if relance == 0:
                        verifRelance = True;
                        print('\n');
                        print("<---------------- Fin du tour pour le joueur " +  str(i) + " ---------------->");
                        print("<---------------- Score du joueur " +  str(i) + " : " + str(scoreTotal) + " ---------------->");
                        print("\n");
                        break;
                    if relance == 1:
                        print("\n");
                        n = n + 1;
                        print(str(n) + "°) Lancement de dés : ");
                        DN = randrange(1, 7);
                        print("--> " + str(DN));
                        scoreTotal = scoreTotal + DN;
                        print("Total : " + str(scoreTotal));
                    if relance == 2:
                        print("\n");
                        n = n + 1;
                        print(str(n) + "°) Lancement de dés : ");
                        for x in range(0, 2):
                            DN = randrange(1, 7);
                            print("--> " + str(DN));
                            scoreTotal = scoreTotal + DN;
                        print("Total : " + str(scoreTotal));
                    if relance == 3:
                        print("\n");
                        n = n + 1;
                        print(str(n) + "°) Lancement de dés : ");
                        for x in range(0, 3):
                            DN = randrange(1, 7);
                            print("--> " + str(DN));
                            scoreTotal = scoreTotal + DN;
                        print("Total : " + str(scoreTotal));
                else:
                    print("\n")
                    print("[Indiquer un nombre compris entre [0 - 3] !]")
        except ValueError:
            print("\n")
            print("[Indiquer un nombre de dés valide !]");
            
    # Réinitialisation pour le joueur suivant
    n = 1
    verifRelance = False;
    scoreTotal = 0
    i = i + 1;

#Résultat de la manche
print("\n");
print("<------------------------------------------------------------------->");
print("Chaque joueur à terminé son tour ...")
print("Voyons qui gagne cette manche !")
print("<------------------------------------------------------------------->");

As you can see, in my code I don't manage tokens and total score at all but there is the general aspect of the program.

Thank you for your help in advance.


Solution 1:

As you know how many players will be playing, you can create a dictionary for each player to store the info needed.

num_players = 5 # <- user input
tokens = 3 # <- user input
players = {}

for i in range(1, num_players + 1):
    players[i] = {
        'tokens': tokens,
        'score': 0
    }

print(players)
# {1: {'tokens': 3, 'score': 0}, 2: {'tokens': 3, 'score': 0}, 3: {'tokens': 3, 'score': 0}, 4: {'tokens': 3, 'score': 0}, 5: {'tokens': 3, 'score': 0}}

You can remove a token and add the dice result of player 2 as this:

dice_result = 8 # <- calculate
players[2]['tokens'] = players[2]['tokens'] -1
players[2]['score'] = players[2]['score'] + dice_result