如何在Pygame中阻止图像在屏幕边缘移动?

时间:2019-01-14 19:21:28

标签: pygame

我刚开始使用pygame,并想制作一款带有武器(pixelart)的迷你游戏。我通过键盘上的箭头键使其移动,但是图像沿边缘移动,如何阻止图像比边缘更远呢?我的“角色”的尺寸为220x116像素

#!/usr/bin/env python

import pygame
from pygame.locals import *
from sys import exit

background_image = 'mario bg.png'
weapon = 'scar.png'

pygame.init()
SCREEN_SIZE = (800, 800)
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
pygame.display.set_caption("SCAR MINIGAME")
background = pygame.image.load(background_image).convert()
player = pygame.image.load(weapon).convert_alpha()


x, y = 150, 353
MOVE_RIGHT = x=+10
MOVE_LEFT = x=-10
MOVE_UP = y=-10
MOVE_DOWN = y=+10
direction = 0

while True:

for event in pygame.event.get():

    if event.type == QUIT:
        exit()

    if event.type == KEYDOWN:
        if event.key == K_LEFT:
            MOVE_LEFT = False
        elif event.key == K_RIGHT:
            MOVE_RIGHT = False
        elif event.key == K_DOWN:
            MOVE_DOWN = False
        elif event.key == K_UP:
            MOVE_UP = False

    elif event.type == KEYUP:
        if event.key == K_LEFT:
            MOVE_LEFT = True
        elif event.key == K_RIGHT:
            MOVE_RIGHT = True
        elif event.key == K_UP:
            MOVE_UP = True
        elif event.key == K_DOWN:
            MOVE_DOWN = True


if(direction == MOVE_LEFT):
    x-=0.4
elif(direction == MOVE_RIGHT):
    x+=0.4
elif(direction == MOVE_UP):
    y-=0.4
elif(direction == MOVE_DOWN):
    y+=0.4

screen.blit(background, (0, 0))
screen.blit(player, (x, y))
pygame.display.update()

1 个答案:

答案 0 :(得分:0)

您只需要检查player的坐标,并将其限制在屏幕上,或使其环绕即可。

我发现将窗口尺寸保留在全局变量中,并在设置函数和以后的计算中使用它们是方便

WINDOW_WIDTH=800
WINDOW_HEIGHT=800
screen = pygame.display.set_mode( (WINDOW_WIDTH,WINDOW_HEIGHT) , 0, 32)

因此,当您更新player的位置时:

# Check player is on-screen
if (player.x < 0):
    player.x = 0
elif (player.x > WINDOW_WIDTH):
    player.x = WINDOW_WIDTH
if (player.y < 0):
    player.y = 0
elif (player.y > WINDOW_HEIGHT):
    player.y = WINDOW_HEIGHT

screen.blit(background, (0, 0))
screen.blit(player, (x, y))

> WINDOW_WIDTH-sprite_width检查添加精灵的宽度将是一个更完整的答案,以便它仍显示在屏幕上,但该练习留给读者。

回到代码。新功能keepPointOnScreen()获取坐标并检查它是否在屏幕上,如果没有,请对其进行修改。每次更新播放器位置时调用此功能,使精灵保持在屏幕上。由于精灵是从左侧绘制的,因此仍然可以在右侧和底部“隐藏”该精灵。要解决此问题,keeper功能需要考虑位图宽度。

#!/usr/bin/env python

import pygame
from pygame.locals import *
from sys import exit

background_image = 'mario bg.png'
weapon = 'scar.png'

# Keep these as variables for checking later on the code
WINDOW_WIDTH=800
WINDOW_HEIGHT=800

# Setup the window
pygame.init()
SCREEN_SIZE = (WINDOW_WIDTH, WINDOW_HEIGHT)
screen      = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
pygame.display.set_caption("SCAR MINIGAME")

# load images & set starting positions
background    = pygame.image.load(background_image).convert()
player        = pygame.image.load(weapon).convert_alpha()
player_width  = player.get_width()
player_height = player.get_height()
print("Player image is [%u x %u]" % (player_width, player_height))

x, y       = 150, 353
direction  = 0
clock      = pygame.time.Clock()


###
### Given a co-ordinate, ensure the co-ordinate is inside the screen 
### bounds.  If it's outside the screen area, reduce it to inside,
### or wrap it to the other side
###
### The code uses the WINDOW_WIDTH and WINDOW_HEIGHT globals,
### Assuming the window is 0 to WIDTH-1 in pixels, and similiarly for height
####
def keepPointOnScreen(x,y, bm_width, bm_height, wrap=False):
    global WINDOW_WIDTH, WINDOW_HEIGHT

    if ( wrap == False ):
        # Block on the edges of the screen (no wrapping)
        if ( x < 0 ):
            x = 0
        elif ( x >= WINDOW_WIDTH-bm_width ):
            x = WINDOW_WIDTH-bm_width-1
        if ( y < 0 ):
            y = 0
        elif ( y >= WINDOW_HEIGHT-bm_height ):
            y = WINDOW_HEIGHT-bm_height-1
    else:
        # Wrap-around from side to side and top to bottom
        if ( x < 0 ):
            x = WINDOW_WIDTH-bm_width-1
        elif ( x >= WINDOW_WIDTH-bm_width ):
            x = 0
        if ( y < 0 ):
            y = WINDOW_HEIGHT-bm_height-1
        elif ( y >= WINDOW_HEIGHT-bm_width ):
            y = 0
    return x, y


while True:
    for event in pygame.event.get():
        if ( event.type == QUIT ):
            exit()

    # Movement keys 
    keys = pygame.key.get_pressed()
    if ( keys[pygame.K_LEFT] ):
        x -= 1
    elif ( keys[pygame.K_RIGHT] ):
        x += 1
    elif ( keys[pygame.K_UP] ):
        y -= 1
    elif ( keys[pygame.K_DOWN] ):
        y += 1

    # make sure the point is still on-screen
    x,y = keepPointOnScreen( x, y, player_width, player_height )

    # re-paint the window
    screen.blit(background, (0, 0))
    screen.blit(player, (x, y))
    pygame.display.update()
    clock.tick(60) # no more than 60 FPS