Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...