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

جواب «Eat the Apple» چالش 3 از جلسه‌ی 8

سؤال

قهرمان با چهار کلید جهت حرکت می‌کند. برنامه را کامل کن: وقتی قهرمان به سیب می‌خورد، یک امتیاز بگیرد و سیب به جای تصادفی تازه‌ای برود (x بین ۳۰ تا ۴۷۰، y بین ۳۰ تا ۳۷۰).

راهنما

if hero.colliderect(apple): و زیرش امتیاز را زیاد کن و apple.x و apple.y را با random.randint عوض کن.

یک جواب درست

import pgzrun
import random

WIDTH = 500
HEIGHT = 400
hero = Actor("hero", (250, 200))
apple = Actor("apple", (400, 100))
score = 0

def draw():
    screen.fill("darkgreen")
    hero.draw()
    apple.draw()
    screen.draw.text("Score: " + str(score), topleft=(10, 10), fontsize=30)

def update():
    global score
    if keyboard.right:
        hero.x += 4
    if keyboard.left:
        hero.x -= 4
    if keyboard.up:
        hero.y -= 4
    if keyboard.down:
        hero.y += 4
    if hero.colliderect(apple):
        score += 1
        apple.x = random.randint(30, 470)
        apple.y = random.randint(30, 370)

pgzrun.go()

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