Star Catcher: תופסים כוכביםStar Catcher
Rect, מקלדת, התנגשויות, טקסט, מצבי משחק ושיא בקובץ.
Rect, keyboard, collisions, text, game states and a saved high score.
הגבלה לטווחClamping
תזכורת: מה ביקשוReminder: the task
כתבו clamp(value, low, high) שמחזירה את הערך אם הוא בטווח, אחרת את הגבול הקרוב, ו-move_player(x, keys, speed, width, player_w) שמקבלת קבוצת מקשים לחוצים ({"left"}, {"right"}...) ומחזירה את x החדש בתוך המסך. שני החיצים יחד מבטלים זה את זה.
Write clamp(value, low, high) returning the value if in range, otherwise the nearest bound, and move_player(x, keys, speed, width, player_w) taking a set of pressed keys ({"left"}, {"right"}...) and returning the new on-screen x. Both arrows together cancel out.
הפתרון המלא והפלט שלוFull solution and its output
def clamp(value, low, high):
return max(low, min(high, value))
def move_player(x, keys, speed, width, player_w):
direction = ("right" in keys) - ("left" in keys)
return clamp(x + direction * speed, 0, width - player_w)
print(move_player(395, {"right"}, 10, 480, 80), move_player(5, {"left"}, 10, 480, 80), move_player(100, {"left", "right"}, 10, 480, 80))400 0 100
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
חפיפת מלבניםRectangle overlap
תזכורת: מה ביקשוReminder: the task
בלי pygame: כתבו overlap(a, b) לשני מלבנים כטאפלים (x, y, w, h) שמחזירה True אם הם חופפים (נגיעה בקצה בלבד אינה חפיפה, בדיוק כמו ב-pygame).
Without pygame: write overlap(a, b) for two rects as tuples (x, y, w, h) returning True if they overlap (merely touching edges isn't overlap, exactly as in pygame).
הפתרון המלא והפלט שלוFull solution and its output
def overlap(a, b):
ax, ay, aw, ah = a
bx, by, bw, bh = b
return ax < bx + bw and bx < ax + aw and ay < by + bh and by < ay + ah
print(overlap((0, 0, 10, 10), (5, 5, 10, 10)), overlap((0, 0, 10, 10), (10, 0, 5, 5)), overlap((0, 0, 10, 10), (2, 2, 3, 3)))True False True
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
כוכבים נופליםFalling stars
תזכורת: מה ביקשוReminder: the task
כתבו update_stars(stars, basket, speed, height) שמקבלת רשימת כוכבים (רשימות [x, y] של 16×16) וסל (x, y, w, h). היא מזיזה כל כוכב ב-speed למטה, ומחזירה (stars_left, caught, missed): נתפס = חופף לסל, הוחמץ = y גדול מ-height.
Write update_stars(stars, basket, speed, height) taking a list of stars ([x, y] lists, 16×16) and a basket (x, y, w, h). It moves every star down by speed and returns (stars_left, caught, missed): caught = overlaps the basket, missed = y greater than height.
הפתרון המלא והפלט שלוFull solution and its output
def overlap(a, b):
ax, ay, aw, ah = a
bx, by, bw, bh = b
return ax < bx + bw and bx < ax + aw and ay < by + bh and by < ay + ah
def update_stars(stars, basket, speed, height):
left, caught, missed = [], 0, 0
for x, y in stars:
y += speed
if overlap((x, y, 16, 16), basket):
caught += 1
elif y > height:
missed += 1
else:
left.append([x, y])
return left, caught, missed
print(update_stars([[210, 280], [10, 318], [300, 100]], (200, 290, 80, 16), 5, 320))([[300, 105]], 1, 1)
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
טקסט במרכזCentred text
תזכורת: מה ביקשוReminder: the task
בעזרת pygame: צרו חלון 300×120, כתבו GAME OVER בגופן ברירת המחדל בגודל 48 כך שהמרכז של הטקסט יהיה במרכז החלון, והדפיסו את מרכז ה-rect של הטקסט ואם הוא נכנס כולו בחלון.
With pygame: create a 300×120 window, write GAME OVER in the default font at size 48 so the text's centre is the window's centre, and print the text rect's centre and whether it fits entirely in the window.
הפתרון המלא והפלט שלוFull solution and its output
import pygame
pygame.init()
screen = pygame.display.set_mode((300, 120))
font = pygame.font.Font(None, 48)
text = font.render("GAME OVER", True, (255, 90, 110))
rect = text.get_rect(center=screen.get_rect().center)
screen.blit(text, rect)
print(rect.center, screen.get_rect().contains(rect))
pygame.quit()(150, 60) True
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
Star Catcher: לוגיקת המשחקStar Catcher: game logic
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה Game(width, height) עם סל basket = [x, y, 80, 16] בתחתית במרכז, רשימת stars, score, lives = 3 ו-state = "playing". spawn(x) מוסיפה כוכב ב-[x, -16]. tick(keys) (במצב playing בלבד): מזיזה את הסל 6 פיקסלים לפי המקשים (בתוך המסך), מזיזה כוכבים 4 למטה, תפיסה = נקודה, פספוס = חיים, ובאפס חיים state = "over".
Write a Game(width, height) class with a basket = [x, y, 80, 16] centred at the bottom, a stars list, score, lives = 3 and state = "playing". spawn(x) adds a star at [x, -16]. tick(keys) (only while playing): moves the basket 6 pixels by the keys (within the screen), moves stars 4 down, a catch = a point, a miss = a life, and at zero lives state = "over".
הפתרון המלא והפלט שלוFull solution and its output
def overlap(a, b):
return a[0] < b[0] + b[2] and b[0] < a[0] + a[2] and a[1] < b[1] + b[3] and b[1] < a[1] + a[3]
class Game:
def __init__(self, width, height):
self.w, self.h = width, height
self.basket = [(width - 80) // 2, height - 30, 80, 16]
self.stars, self.score, self.lives, self.state = [], 0, 3, "playing"
def spawn(self, x):
self.stars.append([x, -16])
def tick(self, keys):
if self.state != "playing":
return
d = ("right" in keys) - ("left" in keys)
self.basket[0] = max(0, min(self.w - 80, self.basket[0] + 6 * d))
left = []
for x, y in self.stars:
y += 4
if overlap((x, y, 16, 16), self.basket):
self.score += 1
elif y > self.h:
self.lives -= 1
else:
left.append([x, y])
self.stars = left
if self.lives <= 0:
self.state = "over"
g = Game(480, 320)
g.spawn(230)
g.spawn(10)
for _ in range(90):
g.tick(set())
print(g.score, g.lives, g.state, g.basket[:2])1 2 playing [200, 290]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
קושי עולהRising difficulty
תזכורת: מה ביקשוReminder: the task
כתבו difficulty(score) שמחזירה (fall_speed, spawn_every): מתחילים ב-(3, 40), כל 5 נקודות המהירות עולה ב-1 וזמן ההופעה יורד ב-4 פריימים, עד מקסימום מהירות 10 ומינימום 12 פריימים. ואז simulate(catches) שמקבלת רשימת True/False (תפיסה/פספוס) לכל כוכב לפי הסדר ומחזירה את הניקוד ואת הקושי בסוף, ועוצרת בשלוש פספוסים.
Write difficulty(score) returning (fall_speed, spawn_every): start at (3, 40), every 5 points speed goes up by 1 and spawn time down by 4 frames, up to a max speed of 10 and a min of 12 frames. Then simulate(catches) taking True/False (catch/miss) per star in order and returning the score and the final difficulty, stopping at three misses.
הפתרון המלא והפלט שלוFull solution and its output
def difficulty(score):
level = score // 5
return min(10, 3 + level), max(12, 40 - 4 * level)
def simulate(catches):
score, misses = 0, 0
for caught in catches:
if caught:
score += 1
else:
misses += 1
if misses == 3:
break
return score, difficulty(score)
print(difficulty(0), difficulty(12), difficulty(100))
print(simulate([True] * 7 + [False, True, False, False, True]))(3, 40) (5, 32) (10, 12) (8, (4, 36))
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
טבלת שיאיםA high-score table
תזכורת: מה ביקשוReminder: the task
כתבו add_score(table, name, score, size=5) שמכניסה שיא לטבלה (רשימת זוגות (name, score) ממוינת מהגבוה), שומרת רק size הטובים, ובשוויון השיא הוותיק נשאר לפני החדש. מחזירה את המקום (1 ומעלה) או None אם לא נכנס. ואז to_text(table) שמחזירה שורות 1. Noa ....... 42 ברוחב 20 (שם משמאל, ניקוד מימין, נקודות באמצע).
Write add_score(table, name, score, size=5) inserting a score into a table (a list of (name, score) pairs sorted high to low), keeping only the best size, and on a tie the older score stays ahead of the new one. Return the place (1 and up) or None if it didn't make it. Then to_text(table) returning lines like 1. Noa ....... 42 at width 20 (name on the left, score on the right, dots between).
הפתרון המלא והפלט שלוFull solution and its output
def add_score(table, name, score, size=5):
i = next((k for k, (_, s) in enumerate(table) if s < score), len(table))
if i >= size:
return None
table.insert(i, (name, score))
del table[size:]
return i + 1
def to_text(table):
lines = []
for place, (name, score) in enumerate(table, 1):
left, right = f"{place}. {name}", str(score)
lines.append(f"{left} {'.' * (20 - len(left) - len(right) - 2)} {right}")
return "\n".join(lines)
table = [("Dana", 40), ("Avi", 30)]
print(add_score(table, "Noa", 42), add_score(table, "Tal", 30), add_score(table, "Ido", 5, size=4), add_score(table, "Bo", 1, size=4))
print(to_text(table))1 4 None None 1. Noa .......... 42 2. Dana ......... 40 3. Avi .......... 30 4. Tal .......... 30
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.