بتل کد Battle Codeدارد باز می‌شود…

Step 4: Start, Game Over, Levels چالش 4 از جلسه‌ی 12، سخت

قدم آخر: بازی کامل. state از "start" شروع می‌شود و صفحه‌ی عنوان با Press SPACE نشان می‌دهد. space با تابع restart() همه‌چیز را از نو می‌کند و state را "playing". وقتی lives صفر شد، state = "over" با صدای lose و نوشته‌ی GAME OVER و باز هم space برای شروع دوباره. level از ۱ شروع می‌شود و هر ۱۰ امتیاز level و speed یکی بالا می‌روند. مرحله را هم نشان بده. در حالت‌های start و over هیچ‌چیز حرکت نکند.

import pgzrun
import random

WIDTH = 500
HEIGHT = 500
TITLE = "Space Shooter"
ship = Actor("ship", (250, 450))
stars = []
for i in range(20):
    stars.append((random.randint(0, 500), random.randint(0, 500)))
rocks = []
for i in range(6):
    rocks.append(Actor("rock", (random.randint(30, 470), random.randint(-500, 0))))
bullets = []
speed = 3
score = 0
lives = 3
level = 1
state = "start"

def reset_rock(rock):
    rock.x = random.randint(30, 470)
    rock.y = -30

def restart():
    global score, lives, level, speed, state

def draw():
    screen.fill("black")
    for star in stars:
        screen.draw.filled_circle(star, 2, "white")
    for rock in rocks:
        rock.draw()
    for bullet in bullets:
        bullet.draw()
    ship.draw()
    screen.draw.text("Score: " + str(score), topleft=(10, 10), fontsize=30)
    screen.draw.text("Lives: " + str(lives), topright=(490, 10), fontsize=30)

def update():
    global score, lives, level, speed, state
    if keyboard.left and ship.left > 0:
        ship.x -= 6
    if keyboard.right and ship.right < WIDTH:
        ship.x += 6
    for rock in rocks:
        rock.y += speed
        if rock.top > HEIGHT:
            reset_rock(rock)
    for bullet in bullets[:]:
        bullet.y -= 10
        i = bullet.collidelist(rocks)
        if bullet.bottom < 0:
            bullets.remove(bullet)
        elif i != -1:
            reset_rock(rocks[i])
            bullets.remove(bullet)
            score += 1
            sounds.explosion.play()
    i = ship.collidelist(rocks)
    if i != -1:
        reset_rock(rocks[i])
        lives -= 1
        sounds.hit.play()

def on_key_down(key):
    if key == keys.SPACE:
        bullets.append(Actor("bullet", ship.pos))
        sounds.shoot.play()

pgzrun.go()

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 12: پروژه: بازی خودم

بیشتر بخوان: بازی‌سازی با پایتون و Pygame Zero