Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pygame问题:精灵在树上奔跑_Python_Class_Events_Pygame_Sprite - Fatal编程技术网

Python pygame问题:精灵在树上奔跑

Python pygame问题:精灵在树上奔跑,python,class,events,pygame,sprite,Python,Class,Events,Pygame,Sprite,我正在创建一个游戏,你可以探索地形,总是随机和计算机生成的。玩家是一个精灵,应该只能在草地上跑,而不能跑到树上。换句话说,运动员只能在草地上跑步 然而,尽管进行了数小时的调试,该播放器仍然可以在树上运行,这非常烦人 import pygame, player # the module where the Player class is defined import block # the module where the Block class is defined ... #setting

我正在创建一个游戏,你可以探索地形,总是随机和计算机生成的。玩家是一个精灵,应该只能在草地上跑,而不能跑到树上。换句话说,运动员只能在草地上跑步

然而,尽管进行了数小时的调试,该播放器仍然可以在树上运行,这非常烦人

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命中[0]。类型=='tree':。。。这件事本该成功的,但没有成功。为什么?
非常感谢您的帮助。

因此,为了帮助您自己,循环中的标准处理方法是先移动,然后处理碰撞,这样您就可以同时了解之前的位置和碰撞的位置

因此,在当前循环中,玩家可能会撞到一棵树,但只是移动到相同的位置

一步一步地阅读循环并尝试以下方法:

e、 g

等等等等。希望你能从中看到它正在工作,只是不像你预期的那样,我可以挖掘出关于计算机总是正确的这句老话

解决方案:


稍微重写一下,先考虑处理动作,然后在循环内检查第二次碰撞,这样就更容易理解了。所以点击[0]=“草”和点击[1]=“树”?:PNo。我的树不在草地上。render_world函数在树和草之间进行选择,因此这是不可能的。但是我会试试看。@JulienPalard:没用。Julien的评论提出了一个问题,SpriteClide返回一个列表,并且您总是使用第一个元素,您应该检查可能返回的任何其他元素,如果不是这个问题,那么将来可能会出现另一个问题!

 loop N:
  hit returns []
  location is set to (posN)
  speed is set
  player moves to (posN+1)
 loopN+1:
  hit returns [tree]
  location is set to (posN+1)
  speed is set
  player is reset to "location", but that is just (posN+1)
  player moves to (posN+2)