问题描述
我正在尝试重新创建一个通常称为 Tron 的游戏。游戏的目标是让玩家尽可能长时间地活着。玩家不断移动并且只能在 90 度转弯时改变方向,如果玩家踩到他们之前已经站过的地方,他们就会死亡并且游戏会重置。 我对存储玩家已经站过的地方的坐标的列表有问题。当玩家第一次移动时,它会立即记录失败并重置游戏。 请查看我下面的代码,告诉我问题所在,尤其是游戏循环结束时的最后一个“if 块”。
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((600,600))
clock = pygame.time.Clock()
player_y = 300
player_x = 300
player_x_list = [300]
player_y_list = [300]
player_rect = pygame.Rect(0,25,25)
player_direction_y = 0
player_direction_x = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s and player_direction_y == 0:
player_direction_y = 25
player_direction_x = 0
if event.key == pygame.K_w and player_direction_y == 0:
player_direction_y = -25
player_direction_x = 0
if event.key == pygame.K_d and player_direction_x == 0:
player_direction_x = 25
player_direction_y = 0
if event.key == pygame.K_a and player_direction_x == 0:
player_direction_x = -25
player_direction_y = 0
player_y += player_direction_y
player_x += player_direction_x
# This is supposed to record every x coord the player was located in on a list,# and every y coord a player was located in on a list
# I only record the coord once as seen below
if player_x_list.count(player_x) == 0:
player_x_list.append(player_x)
if player_y_list.count(player_y) == 0:
player_y_list.append(player_y)
player_rect.center = player_x,player_y
# This right here is supposed to reset the game when the player steps on
# coords that were already stepped on previosly.
# If you remove this,the player is able to move freely,so the issue is here
if player_x_list.count(player_x) > 0 and player_y_list.count(player_y) > 0:
player_x = 300
player_y = 300
player_direction_x = 0
player_direction_y = 0
player_x_list.clear()
player_y_list.clear()
screen.fill((pygame.Color('black')))
pygame.draw.rect(screen,(pygame.Color('white')),player_rect)
pygame.display.update()
clock.tick(10)
我真诚地感谢您的时间。
解决方法
我认为问题在于您在更新坐标并将其附加到坐标列表后检查坐标。因此,在对坐标列表进行任何更改之前,尝试将您的 if
语句移动到循环的顶部。
另外,在一个不相关的注释中,您可以使用单个元组列表作为坐标,而不是两个整数列表。