جواب «Step 3: Hits, Score and Lives» چالش 3 از جلسهی 12
سؤال
قدم سوم: قانونهای بازی. score = 0 و lives = 3. هر گلوله که به سنگی خورد (bullet.collidelist(rocks)): سنگ با reset_rock برگردد، گلوله حذف شود، امتیاز +۱ و صدای explosion. هر سنگی که به سفینه خورد (ship.collidelist(rocks)): سنگ برگردد، یک جان کم و صدای hit. امتیاز و جان را بالای صفحه بنویس.
راهنما
داخل حلقهی گلولهها elif بگذار: i = bullet.collidelist(rocks) و اگر -1 نبود، reset_rock(rocks[i])، bullets.remove(bullet)، score += 1. بعد از حلقهها: i = ship.collidelist(rocks).
یک جواب درست
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()
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
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()
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن