Retro Snake: נחש רטרוRetro Snake
רשת משבצות, deque, טיימר צעדים, תור קלט ושלבים.
A grid, deque, a step timer, an input queue and levels.
01עולם של משבצותA world of cells
בנחש, העולם הוא רשת של משבצות. במקום לחשוב בפיקסלים, חושבים ב"עמודה 5, שורה 3", וממירים לפיקסלים רק בשביל הציור: כפול גודל המשבצת. זה מפשט הכול: התנגשות היא פשוט "אותה משבצת". רקע של משבצות לסירוגין עוזר לעין לראות את הרשת:
In Snake the world is a grid of cells. Instead of thinking in pixels, think "column 5, row 3", and convert to pixels only for drawing: times the cell size. That simplifies everything: a collision is just "the same cell". A checkerboard background helps the eye see the grid:
import pygame
CELL, COLS, ROWS = 16, 30, 20
pygame.init()
screen = pygame.display.set_mode((COLS * CELL, ROWS * CELL))
screen.fill((14, 20, 14))
for c in range(COLS):
for r in range(ROWS):
if (c + r) % 2 == 0:
pygame.draw.rect(screen, (22, 34, 22), (c * CELL, r * CELL, CELL, CELL))
cell = (5, 3)
pygame.draw.rect(screen, (255, 80, 80), (cell[0] * CELL, cell[1] * CELL, CELL, CELL))
print(screen.get_size(), "cell", cell, "-> pixels", (cell[0] * CELL, cell[1] * CELL))
pygame.quit()(480, 320) cell (5, 3) -> pixels (80, 48)
רשת היא כמו לוח שחמט: לא אומרים "הפרש 3.7 סנטימטר משמאל", אלא "הפרש ב-ג5".
A grid is like a chessboard: you don't say "the knight is 3.7 cm from the left", you say "the knight is on c5".
מערבבים משבצות ופיקסלים.
Mixing cells and pixels.
CELL = 16
head_cell = (5, 3)
food_pixels = (80, 48)
assert head_cell == food_pixels, "the head is on the food, but one is in cells and one in pixels: keep the logic in cells"Traceback (most recent call last):
File "/Users/you/python-course/grid.py", line 4, in <module>
assert head_cell == food_pixels, "the head is on the food, but one is in cells and one in pixels: keep the logic in cells"
^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: the head is on the food, but one is in cells and one in pixels: keep the logic in cellsAssertionError: the head is on the food, but ...: הלוגיקה כולה במשבצות, וההמרה לפיקסלים רק בשורת הציור.AssertionError: the head is on the food, but ...: all logic in cells, converting to pixels only on the drawing line.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02הנחש כרשימהThe snake as a list
הנחש הוא רשימה של משבצות, הראש בהתחלה. הטריק היפה: כדי לזוז לא צריך להזיז כל חוליה. מוסיפים ראש חדש במשבצת הבאה (insert(0, head)), ומוחקים את הזנב (pop()). כל השאר נשאר במקום, וזה נראה כמו זחילה. הסימולציה מראה את הרשימה משתנה:
The snake is a list of cells, head first. The lovely trick: to move, you don't move every segment. Add a new head in the next cell (insert(0, head)), and remove the tail (pop()). Everything else stays put, and it looks like crawling. The simulation shows the list changing:
מה קורה עכשיוWhat happens now
מסך הפלטOutput screen
הנחש הוא כמו רכבת של אנשים שהולכים בתור: הראשון זז קדימה וכל אחד נכנס למקום של זה שלפניו, אז מספיק להוסיף מקום מקדימה ולמחוק מאחורה.
The snake is like a queue of people walking in line: the first steps forward and each takes the spot of the one ahead, so it's enough to add a spot in front and remove one behind.
מזיזים את הראש בלי להוסיף, ומאבדים את הגוף.
Moving the head without inserting, losing the body.
snake = [(5, 5), (4, 5), (3, 5)]
snake[0] = (6, 5)
assert snake[1] == (5, 5), f"the body is {snake[1:]}: it never followed the head; insert a new head and pop the tail"Traceback (most recent call last):
File "/Users/you/python-course/snake.py", line 3, in <module>
assert snake[1] == (5, 5), f"the body is {snake[1:]}: it never followed the head; insert a new head and pop the tail"
^^^^^^^^^^^^^^^^^^
AssertionError: the body is [(4, 5), (3, 5)]: it never followed the head; insert a new head and pop the tailAssertionError: the body is [(4, 5), (3, 5)]: ...: עכשיו יש רווח בין הראש לגוף. הדרך הנכונה: insert(0, new_head) ו-pop().AssertionError: the body is [(4, 5), (3, 5)]: ...: now there's a gap between head and body. The right way: insert(0, new_head) and pop().צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03לאכול ולגדולEating and growing
גדילה היא הטריק הקודם הפוך: כשהראש נכנס למשבצת של האוכל, פשוט לא מוחקים את הזנב, והנחש מתארך בחוליה. את האוכל החדש שמים רק במשבצת שאין בה נחש: בונים רשימה של משבצות פנויות ובוחרים אחת באקראי:
Growing is the previous trick in reverse: when the head enters the food's cell, simply don't remove the tail, and the snake gets one segment longer. Put the new food only on a cell without snake: build a list of free cells and choose one at random:
import random
random.seed(2)
COLS, ROWS = 6, 4
snake = [(2, 1), (1, 1), (0, 1)]
food = (3, 1)
for tick in range(2):
head = (snake[0][0] + 1, snake[0][1])
snake.insert(0, head)
if head == food:
free = [(c, r) for c in range(COLS) for r in range(ROWS) if (c, r) not in snake]
food = random.choice(free)
print("ate! length", len(snake), "new food", food, "free cells", len(free))
else:
snake.pop()
print(snake)ate! length 4 new food (0, 2) free cells 20 [(4, 1), (3, 1), (2, 1), (1, 1)]
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
זה כמו לסחוב חבל מהסליל: בכל צעד שולפים עוד קצת, ורק כשרוצים להאריך, לא מגלגלים בחזרה.
It's like pulling rope from a reel: each step pulls a bit more out, and only when you want it longer do you skip rolling it back.
אוכל שמופיע על הנחש.
Food appearing on the snake.
import random
random.seed(0)
snake = [(c, 0) for c in range(9)]
food = (random.randint(0, 9), 0)
assert food not in snake, f"food landed on the snake at {food}: choose only from free cells"Traceback (most recent call last):
File "/Users/you/python-course/grow.py", line 5, in <module>
assert food not in snake, f"food landed on the snake at {food}: choose only from free cells"
^^^^^^^^^^^^^^^^^
AssertionError: food landed on the snake at (6, 0): choose only from free cellsAssertionError: food landed on the snake at ...: בוחרים מתוך רשימת המשבצות הפנויות, לא מכל הלוח.AssertionError: food landed on the snake at ...: choose from the list of free cells, not the whole board.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הנחש הוא רשימת משבצות: מוסיפים ראש, ומוחקים זנב אלא אם אכל.
The snake is a list of cells: add a head, and drop the tail unless it ate.
snake = [(2, 0), (1, 0), (0, 0)]
food = (4, 0)
for step in range(3):
head = (snake[0][0] + 1, 0)
snake.insert(0, head)
if head != food:
snake.pop()
print(snake)[(3, 0), (2, 0), (1, 0)] [(4, 0), (3, 0), (2, 0), (1, 0)] [(5, 0), (4, 0), (3, 0), (2, 0)]
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04התנגשויותCollisions
ברשת, התנגשות היא שאלה אחת: האם הראש החדש כבר ברשימה? head in snake. לקירות שתי אפשרויות: לסיים את המשחק, או לעבור לצד השני בעזרת %: (x + 1) % COLS הופך את עמודה 30 ל-0. שימו לב: בודקים התנגשות לפני שמוחקים את הזנב? לא! הזנב זז, אז מותר להיכנס למשבצת שהזנב עוזב:
On a grid, a collision is one question: is the new head already in the list? head in snake. For walls there are two options: end the game, or wrap-around with %: (x + 1) % COLS turns column 30 into 0. Note: should you check before removing the tail? No! The tail moves, so entering the cell the tail is leaving is allowed:
COLS = 10
print([(x + 1) % COLS for x in (8, 9)], (0 - 1) % COLS)
def step(snake, direction, grow=False):
head = ((snake[0][0] + direction[0]) % COLS, (snake[0][1] + direction[1]) % COLS)
body = snake if grow else snake[:-1]
if head in body:
return None
return [head] + body
ring = [(1, 1), (1, 2), (2, 2), (2, 1)]
print(step(ring, (1, 0)))
print(step([(1, 1), (2, 1), (2, 2), (1, 2), (0, 2)], (1, 0)))[9, 0] 9 [(2, 1), (1, 1), (1, 2), (2, 2)] None
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מעבר מקצה לקצה הוא כמו מסלול ריצה עגול: יוצאים מהקו ומגיעים לאותו קו מההתחלה.
Wrap-around is like a circular running track: you cross the line and arrive back at the start.
בודקים התנגשות מול כל הנחש, כולל הזנב שעומד לזוז.
Checking collision against the whole snake, including the tail that's about to move.
snake = [(1, 1), (1, 2), (2, 2), (2, 1)]
head = (2, 1)
crashed = head in snake
assert not crashed, "the head chased its own tail into a cell the tail is leaving this tick: check against snake[:-1]"Traceback (most recent call last):
File "/Users/you/python-course/collide.py", line 4, in <module>
assert not crashed, "the head chased its own tail into a cell the tail is leaving this tick: check against snake[:-1]"
^^^^^^^^^^^
AssertionError: the head chased its own tail into a cell the tail is leaving this tick: check against snake[:-1]AssertionError: the head chased its own tail ...: הזנב עוזב את המשבצת באותו טיק. בודקים מול snake[:-1] (אלא אם הנחש גדל בטיק הזה).AssertionError: the head chased its own tail ...: the tail leaves that cell on the same tick. Check against snake[:-1] (unless the snake grows this tick).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05טיקים וקלטTicks and input
הנחש לא זז בכל פריים: הוא זז בכל טיק, למשל כל 120 אלפיות שנייה, וזה הקצב שמרגיש "רטרו". שני כללי קלט: אסור לפנות 180 מעלות (הנחש היה נכנס בעצמו). ואם השחקן לוחץ למעלה ואז שמאלה מהר מאוד, בתוך טיק אחד, שומרים את הלחיצות בתור ומבצעים אחת בכל טיק:
The snake doesn't move every frame: it moves every tick, say every 120 milliseconds, the pace that feels "retro". Two input rules: no 180-degree turns (the snake would run into itself). And if the player presses up then left very fast, within one tick, keep the presses in a queue and apply one per tick:
from collections import deque
OPPOSITE = lambda a, b: a[0] + b[0] == 0 and a[1] + b[1] == 0
queue = deque()
direction = (1, 0)
for press in [(-1, 0), (0, -1), (-1, 0)]:
last = queue[-1] if queue else direction
if not OPPOSITE(press, last) and press != last and len(queue) < 3:
queue.append(press)
print("queued:", list(queue))
for tick in range(3):
if queue:
direction = queue.popleft()
print("tick", tick, "->", direction)queued: [(0, -1), (-1, 0)] tick 0 -> (0, -1) tick 1 -> (-1, 0) tick 2 -> (-1, 0)
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
תור קלט הוא כמו פתקים שמשאירים לנהג: "ימינה, ואז שמאלה". גם אם כתבתם את שניהם בבת אחת, הוא מבצע אותם לפי הסדר בצמתים הבאים.
An input queue is like notes left for a driver: "right, then left". Even if you wrote both at once, they're carried out in order at the next junctions.
מאפשרים פנייה הפוכה.
Allowing a reverse turn.
snake = [(5, 5), (4, 5), (3, 5)]
direction = (-1, 0)
head = (snake[0][0] + direction[0], snake[0][1])
assert head not in snake[:-1], f"turning straight back puts the head on {head}, the neck: ignore presses opposite the current direction"Traceback (most recent call last):
File "/Users/you/python-course/input_queue.py", line 4, in <module>
assert head not in snake[:-1], f"turning straight back puts the head on {head}, the neck: ignore presses opposite the current direction"
^^^^^^^^^^^^^^^^^^^^^^
AssertionError: turning straight back puts the head on (4, 5), the neck: ignore presses opposite the current directionAssertionError: turning straight back puts the head on (4, 5), the neck: ...: בודקים ש-press אינו הפוך לכיוון הנוכחי לפני שמקבלים אותו.AssertionError: turning straight back puts the head on (4, 5), the neck: ...: check press isn't opposite the current direction before accepting it.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06Retro Snake: המשחקRetro Snake: the game
המשחק השלם: נחש שזוחל ברשת, אוכל אדום שמופיע במשבצת פנויה, גדילה, התנגשות עצמית, מעבר מקצה לקצה, וניקוד. הגוף נצבע בירוק שהולך ונחלש לכיוון הזנב. כאן "שחקן אוטומטי" פונה לעבר האוכל; במחשב שלכם החיצים מכניסים פניות לתור:
The full game: a snake crawling on a grid, red food appearing on a free cell, growing, self-collision, wrap-around, and score. The body is coloured a green that fades toward the tail. Here an "auto-player" turns toward the food; on your computer the arrows add turns to the queue:
import random
import pygame
CELL, COLS, ROWS = 16, 30, 20
pygame.init()
screen = pygame.display.set_mode((COLS * CELL, ROWS * CELL))
font = pygame.font.Font(None, 26)
random.seed(4)
snake = [(10, 10), (9, 10), (8, 10)]
direction = (1, 0)
food = (20, 10)
score = 0
def free_cell():
return random.choice([(c, r) for c in range(COLS) for r in range(ROWS) if (c, r) not in snake])
for tick in range(160):
fx, fy = food
hx, hy = snake[0]
want = (1 if fx > hx else -1 if fx < hx else 0, 0) if fx != hx else (0, 1 if fy > hy else -1)
if (want[0] + direction[0], want[1] + direction[1]) != (0, 0):
direction = want
head = ((hx + direction[0]) % COLS, (hy + direction[1]) % ROWS)
if head in snake:
break
snake.insert(0, head)
if head == food:
score += 1
food = free_cell()
else:
snake.pop()
screen.fill((14, 20, 14))
for c in range(COLS):
for r in range(ROWS):
if (c + r) % 2 == 0:
pygame.draw.rect(screen, (18, 26, 18), (c * CELL, r * CELL, CELL, CELL))
pygame.draw.rect(screen, (255, 80, 80), (food[0] * CELL + 3, food[1] * CELL + 3, CELL - 6, CELL - 6), border_radius=4)
for i, (c, r) in enumerate(snake):
green = max(110, 230 - i * 6)
pygame.draw.rect(screen, (60, green, 90), (c * CELL + 1, r * CELL + 1, CELL - 2, CELL - 2), border_radius=3)
screen.blit(font.render(f"Score {score}", True, (200, 255, 200)), (8, 6))
pygame.display.flip()
print("length:", len(snake), "score:", score)
pygame.quit()length: 13 score: 10
הנחש מראה כמה רחוק אפשר להגיע עם רשימה פשוטה: כל המשחק הוא insert, pop ו-in.
Snake shows how far a simple list can take you: the whole game is insert, pop and in.
רשימת המשבצות הפנויות ריקה כשהנחש ממלא את כל הלוח.
The free-cell list is empty when the snake fills the board.
import random
free = []
random.choice(free)Traceback (most recent call last):
File "/Users/you/python-course/retro_snake.py", line 3, in <module>
random.choice(free)
~~~~~~~~~~~~~^^^^^^
File "/usr/local/lib/python3.13/random.py", line 351, in choice
raise IndexError('Cannot choose from an empty sequence')
IndexError: Cannot choose from an empty sequenceIndexError: Cannot choose from an empty sequence: אם אין משבצת פנויה, השחקן ניצח! בודקים if not free: ומציגים מסך ניצחון.IndexError: Cannot choose from an empty sequence: if there's no free cell, the player won! Check if not free: and show a victory screen.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.