DEV Community

David Newberry
David Newberry

Posted on

Pygame Snake, Pt. 2

In part 1, we just got pygame going. We have a 1000x1000 pixel canvas, with a 50x50 square moving more-or-less continuously. Snake is played on a fixed grid.

Instead of 50x50 pixels, we'll shrink the snake parts/tiles to 20x20, and we'll shrink the canvas to 600x600 pixels, treated as a 30x30 grid. (30 tiles x 20 pixels = 600 pixels.)

We'll add three variables to represent these values:

W = 30 # width
H = 30 # height
S = 20 # tile size
Enter fullscreen mode Exit fullscreen mode

Now we should replace all other numbers in the code with references to these values.

screen = pygame.display.set_mode((W * S, H * S))
Enter fullscreen mode Exit fullscreen mode
dot = pygame.Vector2(W / 2, H / 2) # approx. the center
Enter fullscreen mode Exit fullscreen mode
    square = pygame.Rect(dot * S, (S, S))
Enter fullscreen mode Exit fullscreen mode

These values are referenced in several places in the code. By using variables, you can update them in one place and it will be reflected everywhere. You can easily change the width, height, or tile size.

Add this just above square = ... (the line shown above):

    if dot.x > W: dot.x = 0
Enter fullscreen mode Exit fullscreen mode

Full code at this point:

import pygame

W = 30
H = 30
S = 20

# pygame setup
pygame.init()
screen = pygame.display.set_mode((W * S, H * S))
clock = pygame.time.Clock()
running = True

dot = pygame.Vector2(W / 2, H / 2)

while running:
    # poll for events
    for event in pygame.event.get():
        # pygame.QUIT = user closed window
        if event.type == pygame.QUIT:
            running = False

    # fill buffer with white
    screen.fill("white")

    dot.x += 1
    if dot.x > W: dot.x = 0
    square = pygame.Rect(dot * S, (S, S))
    screen.fill("black", square)

    # copy buffer to screen
    pygame.display.flip()

    # limits FPS
    clock.tick(20)

pygame.quit()
Enter fullscreen mode Exit fullscreen mode

Now we are treating the board itself as a 30x30 grid of 1x1 tiles. It is then being scaled up when being drawn. The code dot * S takes the Vector2 variable with a value like (15, 15). Assuming S = 20, dot * S would then produce the point (300, 300), i.e. (15 * 20, 15 * 20).

Top comments (0)