gpt4 book ai didi

python - 如何为墙壁添加边界?

转载 作者:太空宇宙 更新时间:2023-11-04 11:09:40 25 4
gpt4 key购买 nike

我正在制作一款类似于《以撒的结合》的游戏。我想在屏幕周围放一些石头来阻挡玩家的移动。

制作岩石布局的地方:

"                                                                ",
" ",
" ",
" ",
" jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" "
]
rockxcoord = 0
rockycoord = 0
for row in level:
for col in row:
if col == "j":
rock = rocks(rockxcoord, rockycoord)
rockGroup.add(rock)
rockxcoord +=32
rockycoord += 50
rockxcoord = 0

边界在哪里设置

    for rock in rockGroup:
screen.blit(rock.image, [rock.rect.x, rock.rect.y])
rockCollisionList = pygame.sprite.spritecollide(playerOne, rockGroup, False)
for rock in rockCollisionList:
if playerOne.rect.x < rock.rect.x:
playerOne.rect.x = rock.rect.x - 90
if playerOne.rect.x > rock.rect.x:
playerOne.rect.x = rock.rect.x + 80

我已经成功地在 x 轴上添加了边界。但是,当对 y 轴执行相同操作时,它无法正常工作。

最佳答案

使用PyGame's Sprites .有一个 good tutorial在他们身上。最初需要做更多的工作,但以后会节省时间。真的,花时间学习它。这是值得的投资。

你的墙可以很简单:

class WallSprite( pygame.sprite.Sprite ):
""" A stationay sprite"""
def __init__( self, position, image ):
pygame.sprite.Sprite.__init__( self )
self.image = image
self.rect = self.image.get_rect()
self.rect.topleft = position

def udpate( self ):
# does not move
pass

创建一堆墙。显然,将 10 x 1 单位的墙作为单个 Sprite 制作更有效,但为了举例,我们将制作乐高™ 风格的墙。

# Create 20 randomly-placed walls
wall_image = pygame.image.load("brick_32.png").convert_alpha()
wall_sprites = pygame.sprite.Group() # a group for all the wall sprites
for i in range(20):
# create a wall at a random position
new_wall = WallSprite( ( random.randrange( 0, WINDOW_WIDTH ), random.randrange( 0, WINDOW_HEIGHT ) ), wall_image )
wall_sprites.add( new_wall ) # put into the sprite group

brick_32.png brick_32.png

在您的主循环中, Sprite 组可用于绘制 Sprite 和组碰撞函数以查看您的玩家是否撞到了任何墙。

# Main loop
done = False
while not done:

# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
# handle direction keys ...

# move / update the player sprite
player_sprite.update()

# handle player <-> wall sprite collisions (for *ALL* walls)
if ( len( pygame.sprite.spritecollide( player_sprite, wall_sprites, False ) ) > 0 ):
player_sprite.stop_moving()

# re-paint the window
screen.fill( GREEN )
wall_sprites.draw() # paints the entire sprite group
player_sprite.draw() # paint the player
pygame.display.flip()

pygame.quit()

关于python - 如何为墙壁添加边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58613724/

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