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

جواب «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() را صدا بزن.

راهنما

داخل restart همه‌ی متغیرها را به مقدار اول برگردان (یادت نرود global). در on_key_down: if state == "over" and key == keys.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
    lives = 3
    score = 0
    bomb.pos = (random.randint(30, 470), 0)
    hero.pos = (250, 360)
    state = "playing"

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")
        screen.draw.text("Press SPACE to play again", center=(250, 250), fontsize=30)

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):
    if state == "over" and key == keys.SPACE:
        restart()

pgzrun.go()

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن