Space Shooter: יורה חללSpace Shooter
pygame.sprite, Groups, Mask, ירושה, גלים ובוס.
pygame.sprite, Groups, Mask, inheritance, waves and a boss.
נשק עם המתנהA gun with a cooldown
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה Gun(delay) עם tick() שמורידה את המונה (לא מתחת ל-0) ו-fire() שמחזירה True ומאפסת את המונה ל-delay אם מוכן, אחרת False. ואז shots_in(frames, delay) שמחזירה כמה יריות יוצאות כשמחזיקים ירי frames פריימים (קודם tick, אחר כך fire).
Write a Gun(delay) class with tick() lowering the counter (not below 0) and fire() returning True and resetting the counter to delay if ready, otherwise False. Then shots_in(frames, delay) returning how many shots fire when holding fire for frames frames (tick first, then fire).
הפתרון המלא והפלט שלוFull solution and its output
class Gun:
def __init__(self, delay):
self.delay, self.wait = delay, 0
def tick(self):
self.wait = max(0, self.wait - 1)
def fire(self):
if self.wait == 0:
self.wait = self.delay
return True
return False
def shots_in(frames, delay):
g = Gun(delay)
count = 0
for _ in range(frames):
g.tick()
count += g.fire()
return count
print(shots_in(60, 12), shots_in(60, 1), shots_in(5, 100))5 60 1
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מי פגע במיWho hit whom
תזכורת: מה ביקשוReminder: the task
בלי pygame: כתבו group_hits(enemies, bullets) כששני המילונים ממפים שם → מלבן (x, y, w, h). מחזירה מילון אויב → רשימה ממוינת של היריות שפגעו בו, ומוחקת מהמילונים את האויבים שנפגעו ואת היריות שפגעו (כמו groupcollide(..., True, True)).
Without pygame: write group_hits(enemies, bullets) where both dicts map name → rect (x, y, w, h). Return a dict enemy → sorted list of the bullets that hit it, and remove the hit enemies and the hitting bullets from the dicts (like groupcollide(..., True, True)).
הפתרון המלא והפלט שלו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 group_hits(enemies, bullets):
hits = {}
for e, er in enemies.items():
who = sorted(b for b, br in bullets.items() if overlap(er, br))
if who:
hits[e] = who
for e, who in hits.items():
enemies.pop(e)
for b in who:
bullets.pop(b, None)
return hits
enemies = {"e1": (0, 0, 20, 20), "e2": (50, 0, 20, 20)}
bullets = {"b1": (5, 10, 4, 10), "b2": (8, 12, 4, 10), "b3": (200, 0, 4, 10)}
print(group_hits(enemies, bullets), list(enemies), list(bullets)){'e1': ['b1', 'b2']} ['e2'] ['b3']יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צעידת הגלThe wave's march
תזכורת: מה ביקשוReminder: the task
כתבו march(enemies, dx, width, margin=10, drop=10) שמקבלת רשימת מיקומי x,y. אם צעד של dx יוציא אויב כלשהו מהטווח [margin, width - margin], כולם יורדים drop והכיוון מתהפך; אחרת כולם זזים dx. מחזירה (new_enemies, new_dx).
Write march(enemies, dx, width, margin=10, drop=10) taking a list of x,y positions. If a step of dx would take any enemy outside [margin, width - margin], all drop by drop and the direction flips; otherwise all move by dx. Return (new_enemies, new_dx).
הפתרון המלא והפלט שלוFull solution and its output
def march(enemies, dx, width, margin=10, drop=10):
if any(not margin <= x + dx <= width - margin for x, _ in enemies):
return [[x, y + drop] for x, y in enemies], -dx
return [[x + dx, y] for x, y in enemies], dx
e, dx = [[450, 40], [400, 40]], 8
for _ in range(4):
e, dx = march(e, dx, 480)
print(e, dx)[[458, 50], [408, 50]] -8
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
פיצוץAn explosion
תזכורת: מה ביקשוReminder: the task
כתבו explode(x, y, n, rng, speed=3, life=20) שמחזירה n חלקיקים [x, y, vx, vy, life] עם מהירות אקראית בתוך [-speed, speed] לכל ציר (rng.uniform), ו-update(particles) שמזיזה, מורידה life ב-1, ומחזירה רשימה רק של החיים (life > 0).
Write explode(x, y, n, rng, speed=3, life=20) returning n particles [x, y, vx, vy, life] with a random velocity within [-speed, speed] per axis (rng.uniform), and update(particles) moving them, lowering life by 1, and returning only the living ones (life > 0).
הפתרון המלא והפלט שלוFull solution and its output
import random
def explode(x, y, n, rng, speed=3, life=20):
return [[x, y, rng.uniform(-speed, speed), rng.uniform(-speed, speed), life] for _ in range(n)]
def update(particles):
out = []
for x, y, vx, vy, life in particles:
if life - 1 > 0:
out.append([x + vx, y + vy, vx, vy, life - 1])
return out
ps = explode(100, 100, 12, random.Random(1), life=3)
sizes = []
for _ in range(4):
ps = update(ps)
sizes.append(len(ps))
print(sizes, all(abs(v) <= 3 for p in explode(0, 0, 50, random.Random(2)) for v in p[2:4]))[12, 12, 0, 0] True
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
Space Shooter: מנועSpace Shooter: the engine
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה Shooter(seed=0, w=480, h=320): חללית ב-x=w/2, נשק עם delay 12, יריות (מלבנים 4×12 שעולים 8), גל אויבים (7×3 מלבנים 26×18 ב-x=60+c×50, y=40+r×30) שצועד ב-1.5, score, wave = 1. step(move, fire): מזיזה חללית (4 פיקסלים, בתוך המסך), יורה, מזיזה יריות (מוחקת שיצאו), צועדת, פגיעות (10 נקודות לאויב), וגל ריק = גל חדש עם wave += 1 ומהירות גדולה ב-0.4.
Write a Shooter(seed=0, w=480, h=320) class: a ship at x=w/2, a gun with delay 12, bullets (4×12 rects moving up 8), an enemy wave (7×3 rects 26×18 at x=60+c×50, y=40+r×30) marching at 1.5, score, wave = 1. step(move, fire): moves the ship (4 pixels, on screen), fires, moves bullets (removing those that left), marches, hits (10 points an enemy), and an empty wave = a new wave with wave += 1 and speed 0.4 faster.
הפתרון המלא והפלט שלו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 Shooter:
def __init__(self, seed=0, w=480, h=320):
self.w, self.h = w, h
self.ship_x, self.wait, self.bullets = w / 2, 0, []
self.score, self.wave, self.speed = 0, 1, 1.5
self.spawn()
def spawn(self):
self.enemies = [[60 + c * 50, 40 + r * 30, 26, 18] for r in range(3) for c in range(7)]
self.dx = self.speed
def step(self, move, fire):
self.ship_x = max(15, min(self.w - 15, self.ship_x + 4 * move))
self.wait = max(0, self.wait - 1)
if fire and self.wait == 0:
self.bullets.append([self.ship_x - 2, self.h - 40, 4, 12])
self.wait = 12
for b in self.bullets:
b[1] -= 8
self.bullets = [b for b in self.bullets if b[1] + 12 > 0]
if any(not 10 <= e[0] + self.dx <= self.w - 36 for e in self.enemies):
self.dx = -self.dx
for e in self.enemies:
e[1] += 10
else:
for e in self.enemies:
e[0] += self.dx
hit = [e for e in self.enemies if any(overlap(e, b) for b in self.bullets)]
self.bullets = [b for b in self.bullets if not any(overlap(e, b) for e in hit)]
self.enemies = [e for e in self.enemies if e not in hit]
self.score += 10 * len(hit)
if not self.enemies:
self.wave += 1
self.speed += 0.4
self.spawn()
g = Shooter()
for frame in range(3000):
target = min(g.enemies, key=lambda e: abs(e[0] + 13 - g.ship_x))
g.step((target[0] + 13 > g.ship_x) - (target[0] + 13 < g.ship_x), True)
if g.wave == 2:
break
print(g.wave, g.score, frame < 3000, round(g.dx, 1))2 210 True 1.9
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מאגר יריותA bullet pool
תזכורת: מה ביקשוReminder: the task
יצירה ומחיקה של אלפי עצמים עולה זמן. כתבו BulletPool(size) שמחזיקה מראש size יריות (מילונים עם x, y, active=False). fire(x, y) מפעילה את הירייה הלא-פעילה הראשונה ומחזירה אותה, או None אם כולן פעילות. update(speed, top) מזיזה את הפעילות ומכבה את מי שעברה את top. active_count().
Creating and deleting thousands of objects costs time. Write BulletPool(size) holding size bullets up front (dicts with x, y, active=False). fire(x, y) activates the first inactive bullet and returns it, or None if all are active. update(speed, top) moves active ones and deactivates those past top. active_count().
הפתרון המלא והפלט שלוFull solution and its output
class BulletPool:
def __init__(self, size):
self.items = [{"x": 0, "y": 0, "active": False} for _ in range(size)]
def fire(self, x, y):
b = next((b for b in self.items if not b["active"]), None)
if b is not None:
b.update(x=x, y=y, active=True)
return b
def update(self, speed, top):
for b in self.items:
if b["active"]:
b["y"] -= speed
if b["y"] < top:
b["active"] = False
def active_count(self):
return sum(b["active"] for b in self.items)
pool = BulletPool(3)
first = pool.fire(10, 100)
print([pool.fire(10, 100) is not None for _ in range(3)], pool.active_count())
for _ in range(15):
pool.update(8, 0)
print(pool.active_count(), pool.fire(20, 50) is first)[True, True, False] 3 0 True
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
אויבים שיורים בחזרהEnemies that shoot back
תזכורת: מה ביקשוReminder: the task
כתבו enemy_fire(enemies, rng, chance): רק האויב התחתון בכל עמודה (לפי x מעוגל) יכול לירות, וכל אחד כזה יורה בהסתברות chance (rng.random() < chance). מחזירה רשימת נקודות (x + 13, y + 18) ממוינת. אויב הוא [x, y].
Write enemy_fire(enemies, rng, chance): only the lowest enemy in each column (by rounded x) may shoot, and each such enemy shoots with probability chance (rng.random() < chance). Return a sorted list of points (x + 13, y + 18). An enemy is [x, y].
הפתרון המלא והפלט שלוFull solution and its output
import random
def enemy_fire(enemies, rng, chance):
lowest = {}
for x, y in enemies:
col = round(x)
if col not in lowest or y > lowest[col][1]:
lowest[col] = (x, y)
shots = []
for col in sorted(lowest):
x, y = lowest[col]
if rng.random() < chance:
shots.append((x + 13, y + 18))
return sorted(shots)
wave = [[60 + c * 50, 40 + r * 30] for r in range(3) for c in range(4)]
print(enemy_fire(wave, random.Random(1), 1.0))
print(enemy_fire(wave, random.Random(1), 0.4))[(73, 118), (123, 118), (173, 118), (223, 118)] [(73, 118), (223, 118)]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.