[英]How can I stop a character in pygame from leaving the edge of the screen?
我在pygame中創建了一個小程序,玩家在其中控制着一個藍色正方形在屏幕上移動,但是我想阻止玩家移過屏幕的邊緣。 這是我到目前為止的代碼,我該怎么做?
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
is_blue = not is_blue
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: y -= 5
if pressed[pygame.K_DOWN]: y += 5
if pressed[pygame.K_LEFT]: x -= 5
if pressed[pygame.K_RIGHT]: x += 5
screen.fill((0, 0, 0))
color = (0, 128, 255)
pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
pygame.display.flip()
clock.tick(60)
pygame.Rect
■找一個clamp
(和clamp_ip
,你可以用它來限制移動區域)的方法。 因此,創建一個具有屏幕大小的rect(在此稱為screen_rect
)和一個供玩家使用的rect( player_rect
),並在每次移動后調用clamp_ip
方法以將其保持在屏幕區域內。
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
BG_COLOR = pg.Color(30, 30, 50)
def main():
clock = pg.time.Clock()
image = pg.Surface((50, 30))
image.fill(pg.Color('dodgerblue'))
pg.draw.rect(image, pg.Color(40, 220, 190), (0, 0, 49, 29), 2)
player_rect = image.get_rect(topleft=(200, 200))
# This pygame.Rect has the dimensions of the screen and
# is used to clamp the player_rect to this area.
screen_rect = screen.get_rect()
speed = 5
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
pressed = pg.key.get_pressed()
if pressed[pg.K_UP]:
player_rect.y -= speed
if pressed[pg.K_DOWN]:
player_rect.y += speed
if pressed[pg.K_LEFT]:
player_rect.x -= speed
if pressed[pg.K_RIGHT]:
player_rect.x += speed
# Clamp the rect to the dimensions of the screen_rect.
player_rect.clamp_ip(screen_rect)
screen.fill(BG_COLOR)
screen.blit(image, player_rect)
pg.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()
pg.quit()
這應該工作
if pressed[pygame.K_UP] and y > 0: y -= 5
if pressed[pygame.K_DOWN] and y < 600 - 60: y += 5
if pressed[pygame.K_LEFT] and x > 0: x -= 5
if pressed[pygame.K_RIGHT] and x < 800 - 60: x += 5
屏幕尺寸為600和800,矩形尺寸為60
就像是:
if pressed[pygame.K_UP]:
if not (y > maxwidth or y < 0):
y += 5
以此類推。 maxwidth
在您的代碼中看起來像600,但是我將其放在代碼的頂部,因此您不必繼續在其他位置進行更改。
您嘗試做的事情稱為邊緣檢測,就像檢測您是否在邊緣一樣,在這種情況下,您希望邊緣成為屏幕的邊緣。 您應該做的是檢查x
或y
是否在邊緣,如果這樣,就不要再走了。
if pressed[pygame.K_UP]:
if 0 < y-5 < 600: #0 and 600 being the edges of your screen, you can use a variable to change it dynamically later one
y -= 5
請注意,這只會檢測左上角的正方形是否超出范圍,因為x
和y
是矩形的上下坐標,這意味着正方形的右下角仍將超出范圍,
如果要檢查整個平方,則必須在if
語句中進行調整計算,或者將x
和y
放在中心(您仍然必須將if語句修改為如下所示。) m根據您當前的代碼更改( x
和y
位於左上方)。
if pressed[pygame.K_UP]:
if (0 < y-5 < 600) or (0< y+60-5 <600) #0 and 600 being the edges of your screen, you can use a variable to change it dynamically later one
y -= 5
這將檢查正方形的另一側。 注意x
您將檢查水平極限,在這種情況下為800
。 另外,我們正在檢查是否包含-5
因為我們想知道我們要去的地方,而不是我們要去的地方。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.