Brick Breaker: שובר לבניםBrick Breaker
מחלקות במשחק, שלבים מנתוני טקסט, power-ups ומטמון תמונות.
Classes in a game, levels from text data, power-ups and an image cache.
ספירת לבניםCounting bricks
תזכורת: מה ביקשוReminder: the task
כתבו parse_level(rows, cell_w, cell_h, top) שמחזירה רשימת (x, y, ch) לכל תו שאינו ., כש-x = עמודה × cell_w ו-y = top + שורה × cell_h, ו-count_by_type(rows) שמחזירה מילון תו → כמות.
Write parse_level(rows, cell_w, cell_h, top) returning (x, y, ch) for every non-. character, where x = column × cell_w and y = top + row × cell_h, and count_by_type(rows) returning a dict character → count.
הפתרון המלא והפלט שלוFull solution and its output
from collections import Counter
def parse_level(rows, cell_w, cell_h, top):
return [(c * cell_w, top + r * cell_h, ch) for r, row in enumerate(rows) for c, ch in enumerate(row) if ch != "."]
def count_by_type(rows):
return dict(Counter("".join(rows).replace(".", "")))
level = ["RR.R", ".OO."]
print(parse_level(level, 40, 15, 30))
print(count_by_type(level))[(0, 30, 'R'), (40, 30, 'R'), (120, 30, 'R'), (40, 45, 'O'), (80, 45, 'O')]
{'R': 3, 'O': 2}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
פגיעה לפי צדA hit by side
תזכורת: מה ביקשוReminder: the task
בלי pygame: כתבו move(ball, vx, vy, bricks) כשהכדור והלבנים הם רשימות [x, y, w, h]. מזיזים ב-x, אם יש חפיפה עם לבנה מוחקים אותה והופכים vx (ומחזירים את x אחורה); ואז אותו דבר ב-y. מחזירה (vx, vy, removed) כש-removed הוא מספר הלבנים שנמחקו.
Without pygame: write move(ball, vx, vy, bricks) where the ball and bricks are [x, y, w, h] lists. Move along x; if it overlaps a brick, remove it and flip vx (and move x back); then the same on y. Return (vx, vy, removed) where removed is the number of bricks removed.
הפתרון המלא והפלט שלו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]
def first_hit(ball, bricks):
return next((i for i, b in enumerate(bricks) if overlap(ball, b)), -1)
def move(ball, vx, vy, bricks):
removed = 0
ball[0] += vx
i = first_hit(ball, bricks)
if i >= 0:
bricks.pop(i)
vx, removed = -vx, removed + 1
ball[0] += vx
ball[1] += vy
i = first_hit(ball, bricks)
if i >= 0:
bricks.pop(i)
vy, removed = -vy, removed + 1
ball[1] += vy
return vx, vy, removed
bricks = [[100, 50, 40, 14]]
print(move([110, 66, 10, 10], 0, -4, bricks), bricks)(0, 4, 1) []
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
זמני אפקטEffect timers
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה Effects() עם add(name, frames) שמפעילה אפקט (ואם כבר פעיל, מאריכה ל-max בין הנותר לחדש), tick() שמורידה 1 מכל אפקט ומוחקת את מה שהגיע ל-0, ו-active(name).
Write an Effects() class with add(name, frames) turning an effect on (and if already active, extending it to the max of what's left and the new value), tick() reducing every effect by 1 and removing those at 0, and active(name).
הפתרון המלא והפלט שלוFull solution and its output
class Effects:
def __init__(self):
self.left = {}
def add(self, name, frames):
self.left[name] = max(frames, self.left.get(name, 0))
def tick(self):
self.left = {k: v - 1 for k, v in self.left.items() if v > 1}
def active(self, name):
return name in self.left
e = Effects()
e.add("wide", 3)
e.add("slow", 1)
e.tick()
e.add("wide", 1)
print(e.active("wide"), e.active("slow"), e.left)
e.tick(); e.tick()
print(e.active("wide"))True False {'wide': 2}
Falseיש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
חיזוק אקראיA random drop
תזכורת: מה ביקשוReminder: the task
כתבו drops(n_bricks, chance, seed) שמחזירה רשימת אינדקסים של לבנים (מתוך n_bricks שנשברות לפי הסדר) שהפילו חיזוק, כשכל אחת מפילה בהסתברות chance לפי random.Random(seed).random() < chance. בנוסף, אסור שני חיזוקים ברצף: אם הלבנה הקודמת הפילה, הנוכחית לא.
Write drops(n_bricks, chance, seed) returning the indexes of bricks (of n_bricks broken in order) that dropped a power-up, each dropping with probability chance via random.Random(seed).random() < chance. Also no two drops in a row: if the previous brick dropped, this one doesn't.
הפתרון המלא והפלט שלוFull solution and its output
import random
def drops(n_bricks, chance, seed):
rng = random.Random(seed)
out = []
for i in range(n_bricks):
roll = rng.random()
if roll < chance and (not out or out[-1] != i - 1):
out.append(i)
return out
print(drops(20, 0.3, 1), drops(10, 1.0, 0), drops(5, 0.0, 0))[0, 3, 8, 13, 16, 19] [0, 2, 4, 6, 8] []
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
Brick Breaker: מנועBrick Breaker: the engine
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה Breaker(level, w=480, h=320) שבונה לבנים מהמפה ([x, y, 44, 14], x = 8 + c × 46, y = 30 + r × 18), מחבט [w // 2 - 40, h - 22, 80, 10], כדור [w // 2 - 5, h - 60, 10, 10] עם vx=3, vy=-4, score, lives=3, state. step(paddle_x): ממקם את המחבט (מוגבל), מזיז את הכדור בהפרדת צירים מול הלבנים (10 נקודות ללבנה), קירות ותקרה, החזרה מהמחבט עם זווית, נפילה = חיים והגשה, אין לבנים = "won".
Write a Breaker(level, w=480, h=320) class building bricks from the map ([x, y, 44, 14], x = 8 + c × 46, y = 30 + r × 18), a paddle [w // 2 - 40, h - 22, 80, 10], a ball [w // 2 - 5, h - 60, 10, 10] with vx=3, vy=-4, score, lives=3, state. step(paddle_x): places the paddle (clamped), moves the ball with axis separation against bricks (10 points a brick), walls and ceiling, a paddle return with an angle, a fall = a life and a re-serve, no bricks = "won".
הפתרון המלא והפלט שלו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 Breaker:
def __init__(self, level, w=480, h=320):
self.w, self.h = w, h
self.bricks = [[8 + c * 46, 30 + r * 18, 44, 14] for r, row in enumerate(level) for c, ch in enumerate(row) if ch != "."]
self.paddle = [w // 2 - 40, h - 22, 80, 10]
self.score, self.lives, self.state = 0, 3, "playing"
self.serve()
def serve(self):
self.ball, self.vx, self.vy = [self.w // 2 - 5, self.h - 60, 10, 10], 3, -4
def _hit(self):
i = next((k for k, b in enumerate(self.bricks) if overlap(self.ball, b)), -1)
if i >= 0:
self.bricks.pop(i)
self.score += 10
return i >= 0
def step(self, paddle_x):
if self.state != "playing":
return
self.paddle[0] = max(0, min(self.w - 80, paddle_x))
b = self.ball
b[0] += self.vx
if self._hit() or b[0] < 0 or b[0] + 10 > self.w:
self.vx = -self.vx
b[0] += self.vx
b[1] += self.vy
if self._hit() or b[1] < 0:
self.vy = -self.vy
b[1] += self.vy
if self.vy > 0 and overlap(b, self.paddle):
self.vx, self.vy = (b[0] + 5 - (self.paddle[0] + 40)) / 40 * 5, -abs(self.vy)
if b[1] > self.h:
self.lives -= 1
self.state = "over" if self.lives == 0 else "playing"
self.serve()
if not self.bricks:
self.state = "won"
g = Breaker(["RR.R", "OOOO"])
for _ in range(800):
g.step(g.ball[0] - 35)
print(g.state, g.score, g.lives, len(g.bricks))playing 0 3 7
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
לבנים חזקותStrong bricks
תזכורת: מה ביקשוReminder: the task
הרחיבו את מפת השלבים: ספרה 1–3 היא לבנה שצריך לפגוע בה כך וכך פעמים, ו-# היא לבנה בלתי שבירה. כתבו build(level) שמחזירה רשימת מילונים {x, y, hp} (hp=None לבלתי שבירה, x = c × 46, y = r × 18), ו-hit(bricks, i) שמורידה hp, מוחקת לבנה שהגיעה ל-0, ומחזירה ניקוד: 10 לשבירה, 2 לפגיעה בלי שבירה, 0 לבלתי שבירה.
Extend the level maps: a digit 1–3 is a brick needing that many hits, and # is an unbreakable brick. Write build(level) returning dicts {x, y, hp} (hp=None for unbreakable, x = c × 46, y = r × 18), and hit(bricks, i) lowering hp, removing a brick at 0, and returning points: 10 for breaking, 2 for a hit without breaking, 0 for unbreakable.
הפתרון המלא והפלט שלוFull solution and its output
def build(level):
return [{"x": c * 46, "y": r * 18, "hp": None if ch == "#" else int(ch)}
for r, row in enumerate(level) for c, ch in enumerate(row) if ch != "."]
def hit(bricks, i):
b = bricks[i]
if b["hp"] is None:
return 0
b["hp"] -= 1
if b["hp"] == 0:
bricks.pop(i)
return 10
return 2
bricks = build(["3#1", ".2."])
print([hit(bricks, 0) for _ in range(3)], len(bricks), [b["hp"] for b in bricks])[2, 2, 10] 3 [None, 1, 2]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
עורך שלביםA level editor
תזכורת: מה ביקשוReminder: the task
כתבו validate(level) שבודקת מפה ומחזירה רשימת בעיות: "empty" אם אין לבנים שבירות, "ragged" אם השורות באורך שונה, "bad char X" לכל תו לא חוקי (מותר .#123RGBOY, פעם אחת לכל תו, ממוין), ו-"too wide" אם יש יותר מ-10 עמודות. ואז mirror(level) שמחזירה מפה סימטרית: חצי שמאלי של כל שורה + ההיפוך שלו.
Write validate(level) checking a map and returning a list of problems: "empty" if there are no breakable bricks, "ragged" if rows differ in length, "bad char X" for each invalid character (allowed .#123RGBOY, once per character, sorted), and "too wide" with more than 10 columns. Then mirror(level) returning a symmetric map: each row's left half + its reverse.
הפתרון המלא והפלט שלוFull solution and its output
ALLOWED = ".#123RGBOY"
def validate(level):
problems = []
text = "".join(level)
if not any(ch not in ".#" for ch in text):
problems.append("empty")
if len({len(r) for r in level}) > 1:
problems.append("ragged")
problems += [f"bad char {ch}" for ch in sorted(set(text) - set(ALLOWED))]
if any(len(r) > 10 for r in level):
problems.append("too wide")
return problems
def mirror(level):
return [row[: len(row) // 2] + row[: len(row) // 2][::-1] for row in level]
print(validate(["RR", "R"]), validate(["#.#"]), validate(["RxRz", "zzzz"]))
print(mirror(["RGB.", "1#..", "OOYY"]))['ragged'] ['empty'] ['bad char x', 'bad char z'] ['RGGR', '1##1', 'OOOO']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.