Lista i len: ile zostało?

Wiele obiektów i losowość - Gry w Pythonie - wstęp (Python)

Monety trzymamy na liście `coins`. Zebrana moneta usuwa się z planszy i z listy (`coins.remove(self)`), więc `len(coins)` mówi, ile jeszcze zostało. Gdy lista jest pusta, napis ogłasza wygraną.

import random

class Player(Sprite):
  def __init__(self):
    self.image = 0
    self.color = (124, 58, 237)
    self.size = 35

  def update(self):
    self.position = world.mouse.position

class Coin(Sprite):
  def __init__(self):
    self.image = 48
    self.color = (234, 179, 8)
    self.size = 18
    self.position = (random.randint(-90, 90), random.randint(-80, 70))

  def update(self):
    if self.touches(player):
      coins.remove(self)
      self.remove()

class Counter(Sprite):
  def __init__(self):
    self.size = 12
    self.color = (99, 102, 241)
    self.position = (0, 88)

  def update(self):
    if len(coins) == 0:
      self.text = "Wygrana!"
    else:
      self.text = f"Zostało: {len(coins)}"

player = Player()
world.add(player)
world.add(Counter())
coins = []
for i in range(8):
  coin = Coin()
  coins.append(coin)
  world.add(coin)

world.start()

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu Gry w Pythonie - wstęp·Zaloguj się, aby zapisać postęp na koncie.