Krok 4: czas gry

Kryształowa jaskinia - Gry w Pythonie - przykłady (Python)

Gra dostaje czas i stany. `Game` liczy ticki (30 na sekundę) i pozostałe sekundy: `left = 30 - self.ticks // 30`. Pole `state` mówi, co się dzieje: `"play"` to gra, `"over"` to koniec czasu. Czarodziej i kryształ na początku `update` sprawdzają `if game.state != "play": return`, więc po końcu gry stoją.

import random

class Game(Sprite):
  def __init__(self):
    self.size = 14
    self.color = (99, 102, 241)
    self.position = (0, 88)
    self.points = 0
    self.ticks = 0
    self.state = "play"

  def update(self):
    if self.state == "play":
      self.ticks = self.ticks + 1
      left = 30 - self.ticks // 30
      self.text = f"Kryształy: {self.points}  Czas: {left}"
      if left <= 0:
        self.state = "over"
    if self.state == "over":
      self.text = f"Koniec czasu! Kryształy: {self.points}"

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

  def update(self):
    if game.state != "play":
      return
    if world.key('right'):
      self.x = self.x + 3
    if world.key('left'):
      self.x = self.x - 3
    if world.key('up'):
      self.y = self.y + 3
    if world.key('down'):
      self.y = self.y - 3

class Crystal(Sprite):
  def __init__(self):
    self.image = 43
    self.color = (14, 165, 233)
    self.size = 18
    self.position = (random.randint(-85, 85), random.randint(-85, 70))

  def update(self):
    if game.state != "play":
      return
    if self.touches(player):
      game.points = game.points + 1
      self.position = (random.randint(-85, 85), random.randint(-85, 70))

game = Game()
player = Player()
crystal = Crystal()
world.add(game)
world.add(player)
world.add(crystal)
world.start()

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

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