Krok 7: chmury w tle
Żabi skok - Gry w Pythonie - przykłady (Python)
Chmury w tle: lista `clouds` z trzema chmurami tworzona pętlą. Chmury są dodane na planszę PRZED innymi obiektami, więc rysują się pod nimi, i płyną zawsze, także po końcu gry.
import random
class Game(Sprite):
def __init__(self):
self.size = 12
self.color = (99, 102, 241)
self.position = (0, 88)
self.points = 0
self.speed = 3
self.state = "play"
def update(self):
if self.state == "play":
self.speed = 3 + self.points // 5
self.text = f"Punkty: {self.points}"
if self.state == "over":
self.text = f"Koniec gry! Punkty: {self.points}"
class Frog(Sprite):
def __init__(self):
self.image = 22
self.color = (34, 197, 94)
self.size = 20
self.rotate = False
self.position = (-60, -70)
self.vy = 0
def update(self):
if game.state != "play":
return
if world.key('space') and self.y == -70:
self.vy = 8
self.y = self.y + self.vy
self.vy = self.vy - 0.5
if self.y <= -70:
self.y = -70
self.vy = 0
class Mushroom(Sprite):
def __init__(self):
self.image = 29
self.color = (220, 38, 38)
self.size = 20
self.position = (100, -70)
self.wait = 0
def update(self):
if game.state != "play":
return
if self.wait > 0:
self.wait = self.wait - 1
return
self.x = self.x - game.speed
if self.x <= -100:
self.x = 100
game.points = game.points + 1
self.wait = random.randint(0, 40)
if self.touches(frog):
game.state = "over"
class Coin(Sprite):
def __init__(self):
self.image = 48
self.color = (234, 179, 8)
self.size = 14
self.reset()
def reset(self):
self.position = (100, random.randint(-40, 0))
def update(self):
if game.state != "play":
return
self.x = self.x - game.speed
if self.touches(frog):
game.points = game.points + 3
self.reset()
if self.x <= -100:
self.reset()
class Cloud(Sprite):
def __init__(self):
self.image = 35
self.color = (226, 232, 240)
self.size = 30
self.position = (random.randint(-100, 100), random.randint(30, 75))
def update(self):
self.x = self.x - 1
if self.x <= -100:
self.position = (100, random.randint(30, 75))
clouds = []
for i in range(3):
clouds.append(Cloud())
for cloud in clouds:
world.add(cloud)
game = Game()
frog = Frog()
mushroom = Mushroom()
coin = Coin()
world.add(game)
world.add(frog)
world.add(mushroom)
world.add(coin)
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.