Play Again چالش 7 از جلسهی 11، سخت
به بازی بمب و جان، دکمهی شروع دوباره اضافه کن: در حالت "over" زیر GAME OVER بنویس Press SPACE to play again. یک تابع restart() بنویس که lives را ۳، score را ۰، بمب را به بالا، قهرمان را به (250, 360) و state را "playing" کند. در on_key_down، اگر state == "over" و space فشرده شد، restart() را صدا بزن.
import pgzrun
import random
WIDTH = 500
HEIGHT = 400
hero = Actor("hero", (250, 360))
bomb = Actor("bomb", (250, 0))
lives = 3
score = 0
state = "playing"
def restart():
global lives, score, state
def draw():
screen.fill("black")
hero.draw()
bomb.draw()
screen.draw.text("Score: " + str(score), topleft=(10, 10), fontsize=30)
screen.draw.text("Lives: " + str(lives), topright=(490, 10), fontsize=30)
if state == "over":
screen.draw.text("GAME OVER", center=(250, 180), fontsize=70, color="red")
def update():
global lives, score, state
if state != "playing":
return
if keyboard.right:
hero.x += 5
if keyboard.left:
hero.x -= 5
bomb.y += 4
if bomb.top > HEIGHT:
score += 1
bomb.y = 0
bomb.x = random.randint(30, 470)
if bomb.colliderect(hero):
lives -= 1
sounds.hit.play()
bomb.y = 0
bomb.x = random.randint(30, 470)
if lives == 0:
state = "over"
sounds.lose.play()
def on_key_down(key):
pass
pgzrun.go()
راهنما و جواب این چالش · برگشت به درس جلسهی 11: پایان بازی، صدا و مرحله · چالش بعدی: The Whole Loop
بیشتر بخوان: بازیسازی با پایتون و Pygame Zero