לחצו על R כדי לשחק שוב
חלק מהיחידה חוקי המשחק במסלול ה-Pygame של Coddy. שיעור 3 מתוך 30.
כשהמשחק מסתיים, השחקן רוצה לשחק שוב בלי להפעיל מחדש את התוכנית. הוסיפו שורה למסך סיום המשחק ומקש שמתחיל משחק חדש:
if event.key == pygame.K_r and state == "over":
player.x = 220
rock.y = -24
rock.x = random.randint(0, 456)
state = "play"החזרת המצב ל־"play" אינה מספיקה. הסלע עדיין נוגע בשחקן, ולכן הפריים הבא יסיים שוב את המשחק. החזירו את האובייקטים שהזזו למקומות שבהם הם מתחילים במשחק חדש.
זהו אותו דפוס כמו בתפריט: מקש, בדיקה של המצב הנוכחי ומצב חדש.
אתגר
קלאפשר לשחק שוב לאחר סיום המשחק.
- מתחת ל־
Game over, הציגו אתPress R to play againבמרכז בנקודה (240, 200). - כשלוחצים על R והמצב הוא
"over": החזירו את השחקן למיקום x 220, החזירו את הסלע למיקום y -24 עם ערך x אקראי בין 0 ל־456, והגדירו את המצב ל־"play".
לחצו על "שחק", הפסידו ואז לחצו על R: משחק חדש מתחיל. לאחר מכן לחצו על "בדיקה".
נסו בעצמכם
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Meteor Dodge")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)
player = pygame.Rect(220, 300, 40, 40)
rock = pygame.Rect(random.randint(0, 456), -24, 24, 24)
score = 0
state = "menu"
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN and state == "menu":
state = "play"
if state == "play":
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.x -= 6
if keys[pygame.K_RIGHT]:
player.x += 6
player.clamp_ip(screen.get_rect())
rock.y += 4
if rock.top > 360:
rock.y = -24
rock.x = random.randint(0, 456)
score += 1
if rock.colliderect(player):
state = "over"
screen.fill((30, 30, 46))
if state == "menu":
title = font.render("Meteor Dodge", True, (240, 240, 240))
screen.blit(title, title.get_rect(center=(240, 140)))
hint = font.render("Press Enter to play", True, (240, 240, 240))
screen.blit(hint, hint.get_rect(center=(240, 200)))
else:
pygame.draw.rect(screen, (255, 196, 0), player)
pygame.draw.rect(screen, (235, 80, 80), rock)
score_text = font.render(f"Score: {score}", True, (240, 240, 240))
screen.blit(score_text, (10, 10))
if state == "over":
message = font.render("Game over", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))
pygame.display.flip()
clock.tick(60)
pygame.quit()
כל השיעורים ביחידה חוקי המשחק
תרגלו בעצמכם: Pygame אונליין