【发布时间】:2014-07-31 21:47:58
【问题描述】:
我正在创建一个游戏,您可以在其中探索地形,始终是随机的和计算机生成的。玩家是一个精灵,应该只能在草块上奔跑,而不能跑到树上。也就是说,玩家只能在草地上奔跑。
然而,尽管调试了几个小时,玩家仍然可以在树上运行,这很烦人。
import pygame, player # the module where the Player class is defined
import block # the module where the Block class is defined
...
#setting varibles, player, ...
run = True
clock = pygame.time.Clock()
create_world() # create the map of the world
while run:
clock.tick(30)
hit = pygame.sprite.spritecollide(player, blocks, False)
location = player.rect.centerx # defined to use as return spot in case of tree
# player is player.Player instance, blocks is group of all the blocks
# the block.Block class has an attribute called 'type'; grass = 'block'
# tree = 'tree'
for e in pygame.event.get():
if e.type == pygame.QUIT:
run = False
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_UP:
speed = [-30, 0] # the varible to update player's location
if hit[0].type == tree: # if hit tree
player.rect.centerx = location
...
if e.type == pygame.KEYUP:
reset_speed() # speed = [0, 0], to prevent constant movement
player.update(speed) # update the player
reset_speed() # not really useful
render_world() # blit the world & player
pygame.quit()
if hit[0].type == 'tree': ... 应该有效,但它没有。为什么?
任何帮助表示赞赏。
【问题讨论】:
-
你的树在草地上吗? :P 所以 hit[0] == 'grass' 和 hit[1] == 'tree' ? :P
-
没有。我的树不在草地上。 render_world() 函数在树和草之间进行选择,所以这是不可能的。不过我会试试的。
-
@JulienPalard:没用。
-
Julien 的评论提出了一个问题,spritecollide 返回一个列表,并且您总是取第一个元素,您应该检查可能返回的任何其他元素,如果不是因为这个问题,那么可能是另一个未来!
标签: python class events pygame sprite