Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a grid in pygame

Tags:

python

pygame

I am trying to create a basic snake game with Python and I am not familiar with Pygame. I have created a window and I am trying to split that window up into a grid based on the size of the window and a set square size.

def get_initial_snake( snake_length, width, height, block_size ):
    window = pygame.display.set_mode((width,height))
    background_colour = (0,0,0)
    window.fill(background_colour)

    return snake_list

What should I add inside window.fill function to create a grid based on width, height, and block_size? Any info would be helpful.

like image 915
Noah Dukehart Avatar asked Nov 27 '15 18:11

Noah Dukehart


People also ask

How do you draw a line in pygame?

Just put the line of code for the line you draw in the while loop and it should draw the line. Also put your "pygame. display. flip()" at the end of your loop.


2 Answers

You can draw rectangles

for y in range(height):
    for x in range(width):
        rect = pygame.Rect(x*block_size, y*block_size, block_size, block_size)
        pygame.draw.rect(window, color, rect)

I assumed that the height and width is the number of blocks.


if you need one pixel gap between rectangles then use

rect = pygame.Rect(x*(block_size+1), y*(block_size+1), block_size, block_size)

To draw snake you can use list and head_color, tail_color

snake = [(0,0), (0,1), (1,1), (1,2), (1,3)]

# head

x, y = snake[0]
rect = pygame.Rect(x*block_size, y*block_size, block_size, block_size)
pygame.draw.rect(window, head_color, rect)

# tail

for x, y in snake[1:]:
    rect = pygame.Rect(x*block_size, y*block_size, block_size, block_size)
    pygame.draw.rect(window, tail_color, rect)
like image 66
furas Avatar answered Oct 31 '22 01:10

furas


Using the for loop as a reference from the answer: https://stackoverflow.com/a/33963521/9715289

This is what I did when I was trying to make a snake game.

BLACK = (0, 0, 0)
WHITE = (200, 200, 200)
WINDOW_HEIGHT = 400
WINDOW_WIDTH = 400


def main():
    global SCREEN, CLOCK
    pygame.init()
    SCREEN = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    CLOCK = pygame.time.Clock()
    SCREEN.fill(BLACK)

    while True:
        drawGrid()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        pygame.display.update()


def drawGrid():
    blockSize = 20 #Set the size of the grid block
    for x in range(0, WINDOW_WIDTH, blockSize):
        for y in range(0, WINDOW_HEIGHT, blockSize):
            rect = pygame.Rect(x, y, blockSize, blockSize)
            pygame.draw.rect(SCREEN, WHITE, rect, 1)

How the result looks like:

How the result looks like

like image 26
theshubhagrwl Avatar answered Oct 31 '22 01:10

theshubhagrwl