简体   繁体   中英

Pygame draw rect following another rect based on their coordinates (ie snake game)

I'm fairly new to coding and Pygame in particular, and right now I am coding a remake of the snake game from scratch, but I don't know how to exactly draw snake bodies that follow the head of the snake. This is what I have so far:

Main body mechanic:

    try:
        for pos in range(0, length):
            x = startX
            y = startY
            if moveX == 1:
                x = startX-pos
            elif moveX == -1:
                x = startX+pos
            elif moveY == 1:
                y = startY-pos
            elif moveY == -1:
                y = startY+pos
            snake1 = pygame.draw.rect(screen, yellow, [(margin + snakeposX*x, margin + snakeposY*y), (width, height)])
            snake = pygame.draw.rect(screen, white, [(margin + snakeposX*startX, margin + snakeposY*startY), (width, height)])
    except IndexError:
        pass

In

Variables used:

screen = pygame.display.set_mode(size)

width = 20
height = 20
margin = 5
snakeposX = (width + margin)
snakeposY = (height + margin)

white = (255, 255, 255)
yellow = (255, 255, 0)

startX = 6
startY = 6
moveX = 1
moveY = 0
length = 1

startX += moveX
startY += moveY

You need a list of the snakes positions. The position of each element of the snake is an element of the list:

snakepos = [[startX, startY]]

If the snake has to be grown, then the last part of the snake has to be copied and append to the tail of the snake:

snakepos.append(snakepos[-1][:])

To make your snake move, each part of the snake, gets the position of its predecessor in the list of parts. The head of the snake gets a new position. Traverse the snake in reverse order and copy the positions.

for i in range(len(snakepos)-1, 0, -1):
    snakepos[i] = snakepos[i-1][:]
snakepos[0][0] += moveX
snakepos[0][1] += moveY

Alternatively you can and add a new element to the head of the list and delete the last element of the list:

snakepos.insert(0, [snakepos[0]+moveX, snakepos[1]+moveY])
del snakepos[-1]

I recommend to separate the update of the position and the drawing:

for i in range(1, len(snakepos)):
    pygame.draw.rect(screen, yellow, [snakepos[i], (width, height)])
snake = pygame.draw.rect(screen, white, [snakepos[0], (width, height)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM