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

Step 3: Hits, Score and Lives چالش 3 از جلسه‌ی 12، متوسط

قدم سوم: قانون‌های بازی. score = 0 و lives = 3. هر گلوله که به سنگی خورد (bullet.collidelist(rocks)): سنگ با reset_rock برگردد، گلوله حذف شود، امتیاز +۱ و صدای explosion. هر سنگی که به سفینه خورد (ship.collidelist(rocks)): سنگ برگردد، یک جان کم و صدای hit. امتیاز و جان را بالای صفحه بنویس.

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

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

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()
    # score and lives

def update():
    global score, lives
    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
        if bullet.bottom < 0:
            bullets.remove(bullet)
        # bullet hits a rock?
    # rock hits the ship?

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

pgzrun.go()

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 12: پروژه: بازی خودم · چالش بعدی: Step 4: Start, Game Over, Levels

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