在蛇游戏中增加蛇的长度

时间:2019-05-10 13:57:22

标签: python pygame

我当前的代码使吃苹果的任何额外长度仅保持在蛇头后面的一条直线上。我该如何做,使其像普通的蛇游戏一样步道?如果有人可以帮助我解决问题,而不是粘贴,那就太好了。

这是我的完整代码(它使用png文件,因此如果尝试它可能无法运行)

import pygame, random, time

pygame.init()

screenWidth = 500
screenHeight = 500
window = pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption("Snake")
x = random.randint(30, 440)
y = random.randint(30, 44)
snakex = x-30
snakey = y
previousx = snakex
previousy = snakey
run = True
appleNeeded = True
direction = "right"
lengthNeeded = False
length1 = True
lengthAmount = 3
check = True


snake_body = []
#Create images (Snake head, apple, and snake tail)

#class SnakeHead(pygame.sprite.Sprite):

#   def __init__(self, ):
snakeHeadUp = pygame.image.load("snakeHeadUp.png")
snakeHeadUp = pygame.transform.scale(snakeHeadUp, (30, 30))
snakeHeadLeft = pygame.image.load("snakeHeadLeft.png")
snakeHeadLeft = pygame.transform.scale(snakeHeadLeft, (30, 30))
snakeHeadRight = pygame.image.load("snakeHeadRight.png")
snakeHeadRight = pygame.transform.scale(snakeHeadRight, (30, 30))
snakeHeadDown = pygame.image.load("snakeHeadDown.png")
snakeHeadDown = pygame.transform.scale(snakeHeadDown, (30, 30))
apple = pygame.image.load("apple.png")
apple = pygame.transform.scale(apple, (30, 30))
snakeHead = snakeHeadRight

while run:
    if check == True:
        snake_body.append((x, y))
        check = False

    #Create screen with boundaries
    window.fill((0, 0, 255))

    #Create snake head (sprite)

    #Create snake


    #Create apple randomly (either rect or sprite) and if needed
    if appleNeeded == True:
        randomx = random.randint(30, 440)
        randomy = random.randint(30, 440)
        if randomx > 5:
            randomx = randomx - (randomx % 5)
        elif randomx < 5:
            randomx = randomx + (5 % randomx)
        if randomy > 5:
            randomy = randomy - (randomy % 5)
        elif randomy < 5:
            randomy = randomy + (5 % randomy)

        appleNeeded = False
    window.blit(apple, (randomx, randomy))

    #Determine if snake head has touched apple
    if x-15 >= randomx-30 and x-15 < randomx and y-15 >= randomy-30 and y-15 < randomy:
        appleNeeded = True
        lengthAmount += 1
        snake_body.append("1")

    #Check for key updates

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        direction = "left"
        snakeHead = snakeHeadLeft
    if keys[pygame.K_RIGHT]:
        direction = "right"
        snakeHead = snakeHeadRight
    if keys[pygame.K_UP]:
        direction = "up"
        snakeHead = snakeHeadUp
    if keys[pygame.K_DOWN]:
        direction = "down"
        snakeHead = snakeHeadDown

    if direction == "left":
        x -= 5
        snakex = x+30
        snakey = y
    elif direction == "right":  
        x += 5
        snakex = x-30
        snakey = y
    elif direction == "up":
        y -= 5
        snakex = x
        snakey = y+30
    elif direction == "down":
        y += 5
        snakex = x
        snakey = y-30


    #Update snake length
    window.blit(snakeHead, (x, y))
    for i in range(lengthAmount):
        if i == 0:
            previousx = snakex - (30 * i)
            previousy = snakey
        if direction == "left":
            previousx = snakex + (30 * i)
            previousy = snakey
        elif direction == "right":  
            previousx = snakex - (30 * i)
            previousy = snakey
        elif direction == "up":
            previousx = snakex 
            previousy = snakey + (30 * i)
        elif direction == "down":
            previousx = snakex  
            previousy = snakey - (30 * i)

        for body in snake_body:
            pygame.draw.rect(window, (0, 175, 0), (previousx, previousy, 30, 30))


    #Don't allow snake to leave the window (game over if True)
    if x >= 470 or x <= 0 or y <= 0 or y >= 470:
        run = False

    #Don't allow snake to eat itself (game over if True)


    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

pygame.quit()

1 个答案:

答案 0 :(得分:4)

在您的情况下,这有点棘手。

您必须将蛇已满足的所有位置存储在列表中。
蛇的一部分的长度为30,步长为5。因此,列表中的第6个位置是蛇的一部分的位置:

snake_pos = []
while run:

    # [...]

    # append position at the head of the list
    snake_pos = [(x, y)] + snake_pos

    # draw the parts of the body at each 6th position of the list 
    for i in range(lengthAmount):
        pi = min((i+1)*6, len(snake_pos)-1)
        pygame.draw.rect(window, (0, 175, 0), (*snake_pos[pi], 30, 30))

    #window.blit(snakeHead, (x, y))
    pygame.draw.rect(window, (175, 50, 0), (x, y, 30, 30))

    # delete all paositons from the list which are not further need
    del snake_pos[lengthAmount*6:]