Krok 7: jeszcze raz
Duchy w zamku - Gry w Pythonie - przykłady (Python)
Ostatni krok: gra od nowa bez ponownego uruchamiania. Metoda `restart(self)` ustawia wszystko jak na początku: stan, klucze, życia, czarodzieja i duchy (usunięte z planszy, lista wyczyszczona, jeden nowy). Klawisz `r` po końcu gry albo po wygranej ją wywołuje. To pełna wersja gry z przykładu Zagraj.
import random
class Game(Sprite):
def __init__(self):
self.size = 12
self.color = (99, 102, 241)
self.position = (0, 88)
self.keys = 0
self.lives = 3
self.state = "play"
def restart(self):
self.state = "play"
self.keys = 0
self.lives = 3
wizard.position = (0, 0)
for ghost in ghosts:
world.remove(ghost)
ghosts.clear()
add_ghost()
def update(self):
if self.state != "play" and world.key('r'):
self.restart()
if self.state == "play":
self.position = (0, 88)
self.text = f"Klucze: {self.keys} Życia: {self.lives}"
if self.lives <= 0:
self.state = "over"
if self.keys >= 10:
self.state = "win"
if self.state == "over":
self.position = (0, 0)
self.text = f"Koniec gry! Klucze: {self.keys}\nr = jeszcze raz"
if self.state == "win":
self.position = (0, 0)
self.text = f"Wygrana! Klucze: {self.keys}\nr = jeszcze raz"
class Wizard(Sprite):
def __init__(self):
self.image = 0
self.color = (124, 58, 237)
self.size = 22
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 Key(Sprite):
def __init__(self):
self.image = 42
self.color = (202, 138, 4)
self.size = 16
self.jump()
def jump(self):
self.position = (random.randint(-90, 90), random.randint(-90, 70))
def update(self):
if game.state != "play":
return
if self.touches(wizard):
game.keys = game.keys + 1
self.jump()
if game.keys % 3 == 0:
add_ghost()
class Ghost(Sprite):
def __init__(self):
self.image = 17
self.color = (100, 116, 139)
self.size = 22
self.rotate = False
self.corner()
def corner(self):
self.position = random.choice([(-90, -90), (90, -90), (-90, 70), (90, 70)])
def update(self):
if game.state != "play":
return
self.point_towards(wizard)
self.move(1)
if self.touches(wizard):
game.lives = game.lives - 1
wizard.position = (0, 0)
self.corner()
def add_ghost():
ghost = Ghost()
ghosts.append(ghost)
world.add(ghost)
game = Game()
wizard = Wizard()
key = Key()
ghosts = []
world.add(game)
world.add(key)
world.add(wizard)
add_ghost()
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.