【发布时间】:2019-10-03 23:14:49
【问题描述】:
尝试在 pygame 中使导入的 csv 矩形在主游戏循环中的 for 循环中迭代元组列表,以添加与列表中的矩形的碰撞。只有列表中的最后一个矩形有碰撞,这意味着在游戏循环中只考虑最后一个元组的参数。
while gameExit == False:
for event in pygame.event.get():
if event.type == QUIT:
gameExit = True
#Gets keypresses and moves the player accordingly
if event.type == pygame.KEYDOWN:
#print(str(event.key))
if event.key == pygame.K_LEFT:
xChange = -playersize/2
yChange = 0
#print(str(x)+", "+str(y))
elif event.key == pygame.K_RIGHT:
xChange = playersize/2
yChange = 0
#print(str(x)+", "+str(y))
elif event.key == pygame.K_UP:
yChange = -playersize/2
xChange = 0
#print(str(x)+", "+str(y))
elif event.key == pygame.K_DOWN:
yChange = playersize/2
xChange = 0
"""
#Make player stop moving after keyup
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or pygame.K_RIGHT:
xChange = 0
if event.key == pygame.K_UP or pygame.K_DOWN:
yChange = 0
"""
#if player goes out of bounds then move them to the other side of the screen
if pacX > width or pacX < 0 or pacY > height or pacY < 0:
if pacX > width: pacX = 0
if pacX < 0: pacX = width - playersize
if pacY > height: pacY = 0
if pacY < 0: pacY = height - playersize
#is the movement selected going to intersect with a boundary?
#THIS IS THE FOR LOOP REFERENCED ABOVE
for coord in xy:
x = float(coord[0])
y = float(coord[1])
rectwidth = float(coord[2])
rectheight = float(coord[3])
if pacX+xChange > round(x-playersize) and pacX+xChange < round(x+rectwidth) and pacY+yChange > round(y-playersize) and pacY+yChange < round(y+rectheight):
touching = True
else:
touching = False
#if not touching a boundary then allow move
if not touching:
pacX += xChange
pacY += yChange
elif touching == True:
pass
#print("Sorry, that's out of bounds...")
#draw everything on the display
DISPLAY.fill(grey)
pygame.draw.rect(DISPLAY,yellow,[pacX,pacY,playersize,playersize])
buildlevel(xy,DISPLAY,darkBlue)
pygame.display.update()
clock.tick(fps)
pygame.quit()
sys.exit()
CSV 文件: (每一个都是 pygame 中 pygame.draw.rect() 方法的坐标和尺寸参数。每一行在 xy 列表中存储为一个元组。)
100 100 100 100
200 200 100 100
300 300 100 100
300 300 100 100
400 400 100 100
【问题讨论】:
-
我不确定,但我猜
if not touching:测试应该在for coord in xy:循环内,不是吗?现在的方式,只是测试循环的最后一次交互,正如你所看到的那样。 -
循环体的缩进方式,唯一的作用是设置
touching变量,在下一次循环迭代时丢弃。
标签: python for-loop while-loop pygame iteration