我正在重新提供帮助,我需要有人建议我如何使蛇变长并随蛇变长。我不知道该怎么做。如果有人有任何真正有用的想法。



请不要给我任何代码,您能解释一下我要挑战自己时要实现我想要做的事情吗?



这是到目前为止的代码:

import pygame, sys, random
from pygame.locals import *
pygame.init()
movement_x = movement_y = 0
RED = (240, 0, 0)
GREEN = (0, 255, 0)
ran = [0,25,50,75,100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,475,500]
ax = 0
ay = 0
x = 0
y = 0
sizex = 500
sizey = 500
tilesize = 25
screen = pygame.display.set_mode((sizex,sizey))
pygame.display.set_caption('Snake')
pygame.display.set_icon(pygame.image.load('images/tile.png'))
tile = pygame.image.load('images/tile.png')
tile = pygame.transform.scale(tile, (tilesize, tilesize))

clock = pygame.time.Clock()

vel_x = 0
vel_y = 0
ap = True
while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    for row in range(sizex):
        for column in range(sizey):
            screen.blit(tile,(column*tilesize, row*tilesize,tilesize,tilesize))
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_UP:
                vel_y = -25
                vel_x = 0
            elif event.key == K_DOWN:
                vel_y = 25
                vel_x = 0
            elif event.key == K_LEFT:
                vel_x = - 25
                vel_y = 0
            elif event.key == K_RIGHT:
                vel_x= 25
                vel_y = 0

    inBounds = pygame.Rect(0, 0, sizex, sizey).collidepoint(x+vel_x, y+vel_y)
    if inBounds:
        y += vel_y
        x += vel_x
    else:
        basicFont = pygame.font.SysFont(None, 48)
        text = basicFont.render('Game Over!', True, GREEN, RED)
        textRect = text.get_rect()
        textRect.centerx = screen.get_rect().centerx
        textRect.centery = screen.get_rect().centery
        pygame.draw.rect(screen, RED, (textRect.left - 20, textRect.top - 20, textRect.width + 40, textRect.height + 40))
        screen.blit(text, textRect)
        ay = -25
        ax = -25
        x = -25
        y = -25
        sys.exit()
    if ap:
        pygame.draw.rect(screen, GREEN, pygame.Rect(ax,ay,tilesize,tilesize))
    if x == ax and y == ay:
        pygame.draw.rect(screen, GREEN, pygame.Rect(ax,ay,tilesize,tilesize))
        ax = random.choice(ran)
        ay = random.choice(ran)
    pygame.draw.rect(screen, RED, pygame.Rect(x,y,tilesize,tilesize))
    pygame.display.update()
    clock.tick(100)

最佳答案

因此,如果蛇生活在栅格上,并且您在蛇上拥有蛇及其尾巴的位置。

您可以创建一个在给定网格位置的情况下绘制正方形的函数。

然后有一个数组,用于存储蛇的每个部分(位置),并具有一个循环,该循环遍历位置数组并绘制每个位置。

然后,如果要移动蛇,则可以在移动到数组的前面之后插入头部的新位置,并删除数组的最后一个元素(蛇的尾巴)。

要添加到蛇,您只需将新位置附加到数组即可。

如果您需要任何澄清,请问:)

10-04 22:22