נבנה על ידי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.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. איך הנחש זז צעד אחד בלי לגדול?How does the snake move one step without growing?

2. מה נותן (9 + 1) % 10?What does (9 + 1) % 10 give?

3. למה לא מאפשרים פנייה הפוכה?Why not allow a reverse turn?

תרגיליםExercises

תרגילExercise 1

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

כתבו 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).

איך הפלט אמור להיראות?What should the output look like?
(80, 48) (5, 3) (0, 0)
main.py
רמזHint 1: (cell[0] * size, cell[1] * size)(cell[0] * size, cell[1] * size)
רמזHint 2: (px // size, py // size)(px // size, py // size)
לפתרוןSolution
תרגילExercise 2

צעד של נחשA snake step

כתבו 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.

איך הפלט אמור להיראות?What should the output look like?
([(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)
main.py
רמזHint 1: head = ((x + dx) % cols, (y + dy) % rows)head = ((x + dx) % cols, (y + dy) % rows)
רמזHint 2: body = snake if ate else snake[:-1]body = snake if ate else snake[:-1]
לפתרוןSolution
תרגילExercise 3

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

כתבו 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.

איך הפלט אמור להיראות?What should the output look like?
(0, 1) None
main.py
רמזHint 1: occupied = set(snake)occupied = set(snake)
רמזHint 2: free = [(c, r) for ... if (c, r) not in occupied]free = [(c, r) for ... if (c, r) not in occupied]
לפתרוןSolution
תרגילExercise 4

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

כתבו מחלקה 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.

איך הפלט אמור להיראות?What should the output look like?
[(0, -1), (-1, 0), (-1, 0)]
main.py
רמזHint 1: last = self.queue[-1] if self.queue else self.directionlast = self.queue[-1] if self.queue else self.direction
רמזHint 2: הפוך: d[0] == -last[0] and d[1] == -last[1].Opposite: d[0] == -last[0] and d[1] == -last[1].
לפתרוןSolution
תרגילExercise 5

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

פרויקט מלווהCompanion project

כתבו מחלקה 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.

איך הפלט אמור להיראות?What should the output look like?
1 4 (7, 3) True
True (6, 3)
retro_snake.py
רמזHint 1: התחלה: [(cx, cy), (cx - 1, cy), (cx - 2, cy)] עם cx, cy = cols // 2, rows // 2.Start: [(cx, cy), (cx - 1, cy), (cx - 2, cy)] with cx, cy = cols // 2, rows // 2.
רמזHint 2: השתמשו ב-step וב-place_food מהתרגילים.Use step and place_food from the exercises.
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

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

כתבו 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).

איך הפלט אמור להיראות?What should the output look like?
[(0, 1), (0, 1)]
None []
main.py
רמזHint 1: תור של (cell, path) ו-set של seen.A queue of (cell, path) and a seen set.
רמזHint 2: חסומים: set(snake[1:-1]).Blocked: set(snake[1:-1]).
לפתרוןSolution
אתגרChallenge 2

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

כתבו 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.

איך הפלט אמור להיראות?What should the output look like?
{"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}
main.py
רמזHint 1: json.dumps({... "snake": [list(c) for c in game["snake"]] ...})json.dumps({... "snake": [list(c) for c in game["snake"]] ...})
רמזHint 2: len(set(snake)) == len(snake) בודק כפילויות.len(set(snake)) == len(snake) checks duplicates.
לפתרוןSolution

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