اربح أو اخسر
الدرس 15 من 41 في دورة اصنع ألعابًا باستخدام Pygame على Coddy.
تنتهي اللعبة. تخسر هنا عندما يصل عدد الأرواح إلى 0، وتفوز عندما تصل النتيجة إلى 10. ما دام أيٌّ من الأمرين لم يحدث، تستمر اللعبة.
ضع كل ما يتحرك تحت شرط واحد، لكي يتوقف عند انتهاء اللعبة:
if lives > 0 and score < 10:
# المفاتيح، السلة، الكتلة، حالات الالتقاط والإخفاقيبقى الرسم خارج ذلك الشرط if: تظل الشاشة تعرض الإطار الأخير، وفوقه النتيجة.
if lives == 0:
message = font.render("Game over", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))message.get_rect(center=(240, 160)) هو Rect لصورة النص، موضوعًا بحيث يكون وسطه عند (240, 160). عند الرسم باستخدام Rect، تُستخدم زاويته العلوية اليسرى، لذا يكون النص في المنتصف.
التحدي
متوسطأنه اللعبة بالفوز أو الخسارة.
- أزِح كل ما يتحرك (المفاتيح والسلة والكتلة والالتقاطات والإخفاقات) إلى الداخل تحت
if lives > 0 and score < 10:. - بعد النتيجة والأرواح، اعرض
Game overعندما تكونlives == 0، أوYou win!عندما تكونscore == 10، في المنتصف عند(240, 160).
اضغط «العب» وأخفِق في التقاط ثلاث كتل: ستظهر Game over وتتوقف اللعبة. ثم اضغط «تحقق».
جرّب بنفسك
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Catch the Blocks")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)
basket = pygame.Rect(200, 330, 80, 16)
block = pygame.Rect(220, 0, 20, 20)
score = 0
lives = 3
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
basket.x -= 8
if keys[pygame.K_RIGHT]:
basket.x += 8
basket.clamp_ip(screen.get_rect())
block.y += 3
if block.top > 360:
block.y = -20
block.x = random.randint(0, 460)
lives -= 1
if block.colliderect(basket):
block.y = -20
block.x = random.randint(0, 460)
score += 1
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), basket)
pygame.draw.rect(screen, (235, 80, 80), block)
score_text = font.render(f"Score: {score}", True, (240, 240, 240))
screen.blit(score_text, (10, 10))
lives_text = font.render(f"Lives: {lives}", True, (240, 240, 240))
screen.blit(lives_text, (370, 10))
pygame.display.flip()
clock.tick(60)
pygame.quit()
جميع دروس اصنع ألعابًا باستخدام Pygame
تدرّب بنفسك: Playground لـ Pygame