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

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • רשת: (עמודה, שורה)grid: (column, row)
  • פיקסלים = משבצת × CELLPixels = cell × CELL
  • רשימת טאפלים, הראש ראשוןA list of tuples, head first
  • תנועה: ראש חדש בהתחלה, מוחקים את הזנבMove: a new head in front, remove the tail
  • ראש על האוכל → לא מוחקים זנבHead on the food → don't remove the tail
  • אוכל חדש רק במשבצת פנויהNew food only on a free cell
  • ראש בתוך הגוף = סוףHead inside the body = game over
  • קיר: סוף או מעבר לצד השניWall: game over or wrap-around
  • טיק כל 120ms, ציור כל פרייםA tick every 120ms, drawing every frame

מונחיםTerms

  • רשת משבצותgrid: עולם מחולק למשבצות שוות, כמו לוח שחמט. מיקום הוא (עמודה, שורה), והמרה לפיקסלים: כפול גודל המשבצת.A world divided into equal cells, like a chessboard. A position is (column, row), and in pixels: times the cell size.
  • טיקtick: צעד של לוגיקת המשחק. בנחש הנחש זז פעם בטיק, גם אם המסך מצויר 60 פעמים בשנייה.One step of game logic. In Snake the snake moves once per tick, even if the screen is drawn 60 times a second.
  • מעבר מקצה לקצהwrap-around: יציאה מצד אחד של המסך וחזרה מהצד השני. בעזרת %: (x + 1) % COLS.Leaving one side of the screen and coming back on the other. With %: (x + 1) % COLS.
  • תור קלטinput queue: רשימה של לחיצות שממתינות לטיקים הבאים, כדי שלחיצות מהירות לא ילכו לאיבוד.A list of presses waiting for the next ticks, so fast presses aren't lost.

Cheatsheet

רשת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):
נחשSnake
snake = [(5, 5), (4, 5), (3, 5)]
direction = (1, 0)
for tick in range(3):
    head = (snake[0][0] + direction[0], snake[0][1] + direction[1])
    snake.insert(0, head)
    snake.pop()
    if tick == 1:
גדילהGrowing
import random

random.seed(2)
COLS, ROWS = 6, 4
snake = [(2, 1), (1, 1), (0, 1)]
food = (3, 1)
for tick in range(2):
התנגשותCollision
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:
קלטInput
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)]:
משחקGame
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)

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
AssertionErrorמערבבים משבצות ופיקסלים.Mixing cells and pixels.AssertionError: 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.
AssertionErrorמזיזים את הראש בלי להוסיף, ומאבדים את הגוף.Moving the head without inserting, losing the body.AssertionError: 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().
AssertionErrorאוכל שמופיע על הנחש.Food appearing on the snake.AssertionError: food landed on the snake at ...: בוחרים מתוך רשימת המשבצות הפנויות, לא מכל הלוח.AssertionError: food landed on the snake at ...: choose from the list of free cells, not the whole board.
AssertionErrorבודקים התנגשות מול כל הנחש, כולל הזנב שעומד לזוז.Checking collision against the whole snake, including the tail that's about to move.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).
AssertionErrorמאפשרים פנייה הפוכה.Allowing a reverse turn.AssertionError: 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.
IndexErrorרשימת המשבצות הפנויות ריקה כשהנחש ממלא את כל הלוח.The free-cell list is empty when the snake fills the board.IndexError: 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.

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