0

I am working on a blackjack game to train myself. I am at the beginning. I have done all the game basically, but when the game ends, and I restart it, the numbers of the list, which are the cards, doesn't restore. I tried using copy and deepcopy, and saving it into another variable, but it won't work.

cards = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11]
saved_cards = copy.copy(cards)

def start(x, y):
    # Dealer
    cards = saved_cards

    index1 = int(random.choice(cards))  # Pesca le carte
    index2 = int(random.choice(cards))
    y = y + index1 + index2

    cards.remove(index1)  # Rimuove le carte dal mazzo
    cards.remove(index2)

    #Player

    index1 = int(random.choice(cards))
    index2 = int(random.choice(cards))
    x = x + index1 + index2

    if index1 == 9 or 10 and index2 == 1:
        index2 = 11

    cards.remove(index1)
    cards.remove(index2)

def end():
    again = input("Vuoi rigiocare? ")

    if again in ["S", "s"]:

        start(x = 0, y = 0)
    elif  again in ["N", "n"]:
        print("Grazie per aver giocato!")
        return
alex
  • 10,900
  • 15
  • 70
  • 100
Pingu
  • 3
  • 1
  • `cards = saved_cards` changes `cards` to refer to the same list. You want to make a copy here instead (e.g.: `cards = saved_cards[:]`), otherwise you modify `saved_cards` – UnholySheep Feb 25 '22 at 22:23
  • @UnholySheep Thank you really, it works! But why do i have to write it exactly like that? what does it change from before? – Pingu Feb 25 '22 at 22:26
  • You could probably also write `cards = copy.copy(saved_cards)`, I'm just more used to the `[:]` syntax – UnholySheep Feb 25 '22 at 22:32
  • Or `cards = saved_cards.copy()` – Barmar Feb 25 '22 at 22:33
  • I do not like the fact that [:] means a copy. This should be an implementation decision. [].copy() is clearer. – William Feb 25 '22 at 22:50

0 Answers0