gpt4 book ai didi

python - 检查列表中的项目未按预期工作

转载 作者:行者123 更新时间:2023-12-04 07:54:34 25 4
gpt4 key购买 nike

我正在尝试重新创建一个通常称为 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, 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在对坐标列表进行任何更改之前,循环顶部的语句。
此外,在一个不相关的注释中,您可以使用单个元组列表作为坐标,而不是两个整数列表。

关于python - 检查列表中的项目未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66769499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com