我创建了一个类似蛇的游戏,用户在其中移动精灵,精灵留下轨迹。如果用户遇到了他创建的足迹,我希望游戏结束,而玩家则输了。
我的一个想法是以某种方式跟踪精灵的过去位置(也许在列表中),然后创建一个“ if”语句,这将导致游戏失败(但是,我不清楚如何为此)。
我收到了针对以下列表的编码问题的答案:
”“我认为您可以像这样声明一个二维列表: pastPositions = [[400,300]] 然后,每次玩家位置移动时,请检查以下列表:
对于pastPositions中的行: 如果(player.rect.x == pastPositions [row] [0]和player.rect.y ==> pastPositions [row] [1]): 完成=正确#游戏结束 如果玩家还没来过,那么将该位置添加到列表中。 pastPositions.append([player.rect.x,player.rect.y])“
这看起来应该可行,但是当我尝试运行代码(在Python Interactive中)时,出现一条错误消息,内容为:“第86行,如果player.rect.x == astPositions [row] [ 0]和player.rect.y == pastPositions [row] [1]:IndexError:列表索引超出范围” – Gal 2天前
您建议我将范围更改为什么,以免发生这种情况?我尝试将其设置为pygame窗口的宽度和高度。
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface([15, 15])
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.change_x = 0
self.change_y = 0
def changespeed(self, x, y):
self.change_x += x
self.change_y += y
def update(self):
self.rect.x += self.change_x
self.rect.y += self.change_y
pygame.init()
screen = pygame.display.set_mode([800, 600])
pygame.display.set_caption('The Etch-a-Sketch Game')
myfont = pygame.font.SysFont('Times', 20)
textsurface = myfont.render('This is the Etch-a-Sketch Game', False, (255, 255, 255))
screen.blit(textsurface,(0,0))
myfont = pygame.font.SysFont('Times', 15)
textsurface = myfont.render('Feel free to draw, but if you cross your own path, you will die.', False, (255, 255, 255))
screen.blit(textsurface,(0,20))
player = Player(400, 300)
all_sprites_list = pygame.sprite.Group()
all_sprites_list.add(player)
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.changespeed(-3, 0)
elif event.key == pygame.K_RIGHT:
player.changespeed(3, 0)
elif event.key == pygame.K_UP:
player.changespeed(0, -3)
elif event.key == pygame.K_DOWN:
player.changespeed(0, 3)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player.changespeed(3, 0)
elif event.key == pygame.K_RIGHT:
player.changespeed(-3, 0)
elif event.key == pygame.K_UP:
player.changespeed(0, 3)
elif event.key == pygame.K_DOWN:
player.changespeed(0, -3)
player.update()
all_sprites_list.draw(screen)
pygame.display.flip()
clock.tick(75)
pygame.quit ()
答案 0 :(得分:0)
I think you could declare a two dimensional list like this:
pastPositions = [[400, 300]]
Then every time the player's position moves, check the list:
for row in pastPositions:
if (player.rect.x == row[0] and player.rect.y == row[1]):
done = true # game over
If the player hasn't been there yet, then add that position to the list.
pastPositions.append([player.rect.x, player.rect.y])
Are you looking for something like that?