How to make a grid in pygame

时光总嘲笑我的痴心妄想 提交于 2019-12-24 00:12:59

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/33963361/how-to-make-a-grid-in-pygame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!