נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
40
חלקPart 7: משחקים עם PygameGames with Pygame כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Retro Snake: נחש רטרוRetro Snake

רשת משבצות, deque, טיימר צעדים, תור קלט ושלבים.

A grid, deque, a step timer, an input queue and levels.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

משבצות לפיקסליםCells to pixels

תזכורת: מה ביקשוReminder: the task

כתבו to_pixels(cell, size) שמחזירה את הפינה השמאלית העליונה בפיקסלים, ו-to_cell(px, py, size) שעושה את ההפך (איזו משבצת מכילה את הפיקסל).

Write to_pixels(cell, size) returning the top-left corner in pixels, and to_cell(px, py, size) doing the reverse (which cell contains the pixel).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def to_pixels(cell, size):
    return cell[0] * size, cell[1] * size

def to_cell(px, py, size):
    return px // size, py // size

print(to_pixels((5, 3), 16), to_cell(95, 48, 16), to_cell(0, 15, 16))
פלטOutput
(80, 48) (5, 3) (0, 0)

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

צעד של נחשA snake step

תזכורת: מה ביקשוReminder: the task

כתבו step(snake, direction, food, cols, rows) שמחזירה (new_snake, ate, alive): ראש חדש עם מעבר מקצה לקצה; אם הראש על האוכל, הנחש גדל (ate=True); אחרת הזנב נמחק. אם הראש פוגע בגוף (בלי הזנב, אלא אם גדלים), alive=False והנחש לא משתנה.

Write step(snake, direction, food, cols, rows) returning (new_snake, ate, alive): a new head with wrap-around; if the head is on the food, the snake grows (ate=True); otherwise the tail is removed. If the head hits the body (excluding the tail, unless growing), alive=False and the snake is unchanged.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def step(snake, direction, food, cols, rows):
    head = ((snake[0][0] + direction[0]) % cols, (snake[0][1] + direction[1]) % rows)
    ate = head == food
    body = snake if ate else snake[:-1]
    if head in body:
        return snake, False, False
    return [head] + body, ate, True

s = [(9, 0), (8, 0), (7, 0)]
print(step(s, (1, 0), (0, 0), 10, 5))
print(step(s, (0, -1), (3, 3), 10, 5))
print(step([(1, 1), (1, 2), (2, 2), (2, 1), (2, 0)], (1, 0), (9, 9), 10, 5))
פלטOutput
([(0, 0), (9, 0), (8, 0), (7, 0)], True, True)
([(9, 4), (9, 0), (8, 0)], False, True)
([(1, 1), (1, 2), (2, 2), (2, 1), (2, 0)], False, False)

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

אוכל במקום פנויFood on a free cell

תזכורת: מה ביקשוReminder: the task

כתבו place_food(snake, cols, rows, rng) שבוחרת משבצת פנויה באקראי בעזרת rng.choice (rng הוא random.Random), או מחזירה None אם הלוח מלא. השתמשו ב-set כדי שהבדיקה תהיה מהירה.

Write place_food(snake, cols, rows, rng) choosing a free cell at random with rng.choice (rng is a random.Random), or returning None if the board is full. Use a set so the check is fast.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import random

def place_food(snake, cols, rows, rng):
    occupied = set(snake)
    free = [(c, r) for c in range(cols) for r in range(rows) if (c, r) not in occupied]
    return rng.choice(free) if free else None

rng = random.Random(1)
print(place_food([(0, 0), (1, 0)], 2, 2, rng), place_food([(0, 0), (1, 0), (0, 1), (1, 1)], 2, 2, rng))
פלטOutput
(0, 1) None

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

תור כיווניםA direction queue

תזכורת: מה ביקשוReminder: the task

כתבו מחלקה Controls(direction) עם press(d) שמוסיפה כיוון לתור אם הוא לא הפוך ולא זהה לכיוון האחרון בתור (או לנוכחי אם התור ריק), ושהתור לא מעל 2. next() מוציאה כיוון מהתור (אם יש), מעדכנת ומחזירה את הכיוון הנוכחי.

Write a Controls(direction) class with press(d) adding a direction to the queue if it isn't opposite or equal to the last queued direction (or the current one if the queue is empty), and the queue holds at most 2. next() takes a direction from the queue (if any), updates and returns the current direction.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from collections import deque

class Controls:
    def __init__(self, direction):
        self.direction = direction
        self.queue = deque()

    def press(self, d):
        last = self.queue[-1] if self.queue else self.direction
        if d == last or (d[0] == -last[0] and d[1] == -last[1]) or len(self.queue) >= 2:
            return
        self.queue.append(d)

    def next(self):
        if self.queue:
            self.direction = self.queue.popleft()
        return self.direction

c = Controls((1, 0))
for d in [(-1, 0), (0, -1), (-1, 0), (0, 1)]:
    c.press(d)
print([c.next() for _ in range(3)])
פלטOutput
[(0, -1), (-1, 0), (-1, 0)]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

Retro Snake: המשחק בלי חלוןRetro Snake: the game without a window

תזכורת: מה ביקשוReminder: the task

כתבו מחלקה SnakeGame(cols, rows, seed=0): נחש באורך 3 במרכז שפונה ימינה, אוכל ראשון במשבצת פנויה (random.Random(seed)), score, alive. turn(d) מעבירה ל-Controls (מהתרגיל הקודם, כתבו מחדש בקצרה), ו-tick() מבצעת צעד (עם מעבר מקצה לקצה), גדילה וניקוד, ואוכל חדש. אחרי מוות tick לא עושה כלום.

Write a SnakeGame(cols, rows, seed=0) class: a length-3 snake in the centre facing right, the first food on a free cell (random.Random(seed)), score, alive. turn(d) passes to the controls (from the previous exercise, rewritten briefly), and tick() performs a step (with wrap-around), growing and scoring, and new food. After death, tick does nothing.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
retro_snake.py
import random
from collections import deque

class SnakeGame:
    def __init__(self, cols, rows, seed=0):
        self.cols, self.rows = cols, rows
        self.rng = random.Random(seed)
        cx, cy = cols // 2, rows // 2
        self.snake = [(cx, cy), (cx - 1, cy), (cx - 2, cy)]
        self.direction, self.queue = (1, 0), deque()
        self.score, self.alive = 0, True
        self.food = self._place()

    def _place(self):
        taken = set(self.snake)
        free = [(c, r) for c in range(self.cols) for r in range(self.rows) if (c, r) not in taken]
        return self.rng.choice(free) if free else None

    def turn(self, d):
        last = self.queue[-1] if self.queue else self.direction
        if d != last and (d[0], d[1]) != (-last[0], -last[1]) and len(self.queue) < 2:
            self.queue.append(d)

    def tick(self):
        if not self.alive:
            return
        if self.queue:
            self.direction = self.queue.popleft()
        x, y = self.snake[0]
        head = ((x + self.direction[0]) % self.cols, (y + self.direction[1]) % self.rows)
        ate = head == self.food
        body = self.snake if ate else self.snake[:-1]
        if head in body:
            self.alive = False
            return
        self.snake = [head] + body
        if ate:
            self.score += 1
            self.food = self._place()

g = SnakeGame(10, 6, seed=2)
g.food = (7, 3)
for _ in range(2):
    g.tick()
print(g.score, len(g.snake), g.snake[0], g.food not in g.snake)
for d in [(0, 1), (-1, 0), (0, -1)]:
    g.turn(d)
    g.tick()
print(g.alive, g.snake[0])
פלטOutput
1 4 (7, 3) True
True (6, 3)

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

נחש חכם: BFSA smart snake: BFS

תזכורת: מה ביקשוReminder: the task

כתבו path_to_food(snake, food, cols, rows) שמוצאת את המסלול הקצר ביותר מהראש לאוכל בלי לעבור דרך הגוף (בלי מעבר מקצה לקצה), בעזרת חיפוש לרוחב (BFS) עם deque. מחזירה רשימת כיוונים, או None אם אין מסלול. מהזנב מותר לעבור (הוא זז).

Write path_to_food(snake, food, cols, rows) finding the shortest route from the head to the food without passing through the body (no wrap-around), using breadth-first search (BFS) with a deque. Return a list of directions, or None if there's no route. Passing through the tail is allowed (it moves).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from collections import deque

DIRS = [(1, 0), (-1, 0), (0, 1), (0, -1)]

def path_to_food(snake, food, cols, rows):
    blocked = set(snake[1:-1])
    start = snake[0]
    queue = deque([(start, [])])
    seen = {start}
    while queue:
        (x, y), path = queue.popleft()
        if (x, y) == food:
            return path
        for dx, dy in DIRS:
            nxt = (x + dx, y + dy)
            if 0 <= nxt[0] < cols and 0 <= nxt[1] < rows and nxt not in blocked and nxt not in seen:
                seen.add(nxt)
                queue.append((nxt, path + [(dx, dy)]))
    return None

snake = [(2, 2), (2, 1), (2, 0), (1, 0)]
print(path_to_food(snake, (2, 4), 5, 5))
wall = [(1, 1), (0, 1), (1, 0), (1, 2), (0, 2), (5, 5)]
print(path_to_food(wall, (0, 0), 5, 5), path_to_food([(0, 0)], (0, 0), 3, 3))
פלטOutput
[(0, 1), (0, 1)]
None []

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

שמירת מצב משחקSaving the game state

תזכורת: מה ביקשוReminder: the task

כתבו save_state(game) שמחזירה מחרוזת JSON עם snake, direction, food, score (טאפלים כרשימות), ו-load_state(text, cols, rows) שמחזירה מילון עם אותם שדות כטאפלים, אחרי בדיקה: כל המשבצות בלוח, נחש בלי כפילויות, ואוכל לא על הנחש. מצב לא תקין: ValueError.

Write save_state(game) returning a JSON string with snake, direction, food, score (tuples as lists), and load_state(text, cols, rows) returning a dict with the same fields as tuples, after checking: every cell on the board, a snake without duplicates, and food not on the snake. An invalid state: ValueError.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import json

def save_state(game):
    return json.dumps({"snake": [list(c) for c in game["snake"]], "direction": list(game["direction"]),
                       "food": list(game["food"]), "score": game["score"]})

def load_state(text, cols, rows):
    d = json.loads(text)
    snake = [tuple(c) for c in d["snake"]]
    food = tuple(d["food"])
    inside = lambda c: 0 <= c[0] < cols and 0 <= c[1] < rows
    if not snake or not all(inside(c) for c in snake + [food]):
        raise ValueError("cell outside the board")
    if len(set(snake)) != len(snake) or food in snake:
        raise ValueError("overlapping cells")
    return {"snake": snake, "direction": tuple(d["direction"]), "food": food, "score": int(d["score"])}

text = save_state({"snake": [(3, 2), (2, 2)], "direction": (1, 0), "food": (5, 1), "score": 4})
print(text)
print(load_state(text, 10, 6))
פלטOutput
{"snake": [[3, 2], [2, 2]], "direction": [1, 0], "food": [5, 1], "score": 4}
{'snake': [(3, 2), (2, 2)], 'direction': (1, 0), 'food': (5, 1), 'score': 4}

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

נבנה על ידיBuilt by Ariel Yohimovich