How do you get pygame to give warning when player touches side of screen?

北城余情 提交于 2021-01-31 07:23:46

问题


I created a game using pygame, and I wanted to get pygame to give an error like "You can't touch the screen sides", when player touches screen side. I tried searching on the internet, but I didn't find any good results. I thought of adding a block off the screen and when the player touches the block, it gives warning but that took way to long and anyways didn't work. I also don't know how to give alert, and then after giving the alert, to get the game started again. Does anyone know how to do this?


回答1:


Define a pygame.Rect object for the player:

player_rect = pygame.Rect(w, y, width, height)

or get a rectangle from the player image (player_image):

player_rect = player_image.get_Rect(topleft = (x, y))

Get the rectangle of the display Surface (screen)

screen_rect = screen.get_rect()

Evaluate if the player is out of the screen:

if player_rect.left < screen_rect.left or player_rect.right < screen_rect.right or \
   player_rect.top < screen_rect.top or player_rect.bottom < screen_rect.bottom:
    printe("You can't touch the screen sides")

See pygame.Rect.clamp() respectively pygame.Rect.clamp_ip():

Returns a new rectangle that is moved to be completely inside the argument Rect.

With this function, an object can be kept completely in the window:

player_rect.clamp_ip(screen_rect)

You can use the clamped rectangle to evaluate whether the player is touching the edge of the window:

screen_rect = screen.get_rect()
player_rect = player_image.get_Rect(topleft = (x, y))

clamped_rect = player_rect.clamp(screen_rect)
if clamped_rect.x != player_rect.x or clamped_rect.y != player_rect.y:
    printe("You can't touch the screen sides")

player_rect = clamped_rect
x, y = player_rect.topleft


来源:https://stackoverflow.com/questions/65279570/how-do-you-get-pygame-to-give-warning-when-player-touches-side-of-screen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!