Pygame根据他们的坐标在另一个rect之后绘制rect(即蛇游戏)

时间:2019-03-30 04:15:28

标签: python pygame

我对编码和Pygame特别陌生,现在我正在从头开始编写蛇游戏的翻拍,但我不知道如何精确地绘制跟随蛇头的蛇体。这是我到目前为止的内容:

主体机械师:

    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

使用的变量:

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

1 个答案:

答案 0 :(得分:1)

您需要列出蛇的位置。蛇的每个元素的位置都是列表中的元素:

snakepos = [[startX, startY]]

如果必须种植蛇,则必须复制蛇的最后一部分并附加到蛇的尾巴上:

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

为使您的蛇移动,蛇的每个部分在零件列表中获得其前任的位置。蛇的头得到一个新的位置。 以相反的顺序遍历蛇并复制位置。

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

或者,您可以在列表的开头添加一个新元素,然后删除列表的最后一个元素:

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

我建议分开更新位置和图形:

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)])