本文介绍了当玩家触摸屏幕一侧时,你如何让 pygame 发出警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 pygame 创建了一个游戏,当玩家触摸屏幕一侧时,我想让 pygame 出现类似您无法触摸屏幕两侧"的错误.我尝试在互联网上搜索,但没有找到任何好的结果.我想在屏幕外添加一个块,当玩家触摸该块时,它会发出警告,但这花了很长时间,无论如何都不起作用.我也不知道如何发出警报,然后在发出警报后,重新开始游戏.有人知道怎么做吗?

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?

推荐答案

定义一个pygame.Rect 玩家对象:

Define a pygame.Rect object for the player:

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

或者从播放器图像中获取一个矩形(player_image):

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

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

获取显示的矩形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")


参见pygame.Rect.clamp() 分别 pygame.rect.clamp_ip():

返回一个新的矩形,它被移动到完全位于参数 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

这篇关于当玩家触摸屏幕一侧时,你如何让 pygame 发出警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:41