简体   繁体   English

如何在 Pygame 中创建边框

[英]How to create a border in Pygame

I would like to know how to create a border in Pygame to stop the user controlled object from exiting the screen.我想知道如何在 Pygame 中创建边框以阻止用户控制的对象退出屏幕。 Right now, I only have it so python prints some text when the user controlled object has come near one of the 4 sides.现在,我只有它,所以当用户控制的对象靠近 4 个边之一时,python 会打印一些文本。

Here is my code so far.到目前为止,这是我的代码。

import pygame
from pygame.locals import *
pygame.init()

#Display Stuff 
screenx = 1000
screeny = 900
screen = pygame.display.set_mode((screenx,screeny))
pygame.display.set_caption('Block Runner')
clock = pygame.time.Clock()
image = pygame.image.load('square.png')




#Color Stuff
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
white = (255,255,255)
black = (0,0,0)


#Variables
x_blocky = 50
y_blocky = 750
blocky_y_move = 0
blocky_x_move = 0



#Animations
def Blocky(x_blocky, y_blocky, image):
screen.blit(image,(x_blocky,y_blocky))

#Game Loop

game_over = False
while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                blocky_y_move = -3
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                blocky_y_move = 0

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                blocky_y_move = 3
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_DOWN:
                blocky_y_move = 0

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                blocky_x_move = 3
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT:
                blocky_x_move = 0

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                blocky_x_move = -3
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                blocky_x_move = 0

        if x_blocky > 870 or x_blocky < 0:
            print(' X Border')


        if y_blocky > 750 or y_blocky < 2:
            print(' Y Border')



    y_blocky += blocky_y_move
    x_blocky += blocky_x_move


    screen.fill(white)
    Blocky(x_blocky, y_blocky, image)
    pygame.display.update()
clock.tick(60)

Well, simply don't increase your move variable any further, if you detect that the user object is near or at the border.好吧,如果您检测到用户对象靠近或位于边界处,请不要再增加移动变量。 Or reverse the move direction, depending on your general intent.或者根据您的总体意图反转移动方向。

    if x_blocky > 870 or x_blocky < 0:
        print(' X Border')
        blocky_x_move = 0


    if y_blocky > 750 or y_blocky < 2:
        print(' Y Border')
        blocky_y_move = 0

Don't use integers to store your position.不要使用整数来存储您的位置。 Use a Rect .使用Rect

So instead of所以代替

x_blocky = 50
y_blocky = 750

use

blocky_pos = pygame.rect.Rect(50, 750)

Now you can simply use现在你可以简单地使用

blocky_pos.move_ip(blocky_x_move, blocky_y_move)

to move your object.移动您的对象。

After moving, you can simply call clamp / clamp_ip to ensure the blocky_pos Rect is always inside the screen.移动后,您可以简单地调用clamp / clamp_ip来确保blocky_pos Rect始终在屏幕内。

blocky_pos.clamp_ip(screen.get_rect())

Also, you don't need to define basic colors yourself, you could simply use pygame.color.Color('Red') for example.此外,您不需要自己定义基本颜色,例如您可以简单地使用pygame.color.Color('Red')

I also suggest you use pygame.key.get_pressed() to get all pressed keys to see how to move your object instead of creating 1000 lines of event handling code.我还建议您使用pygame.key.get_pressed()来获取所有按下的键来查看如何移动您的对象,而不是创建 1000 行事件处理代码。

Also, you have some redundant code with your keyboard movement.此外,您的键盘移动有一些冗余代码。 Instead of writing而不是写作

if event.type == KEYDOWN:

over and over again, group the KEYUP if statements and KEYDOWN if statements.一遍又一遍,将 KEYUP if 语句和 KEYDOWN if 语句组合在一起。

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_UP:
        blocky_y_move = -3
    elif event.key == pygame.K_DOWN:
        blocky_y_move = +3

etc, and:等等,以及:

if event.type == pygame.KEYUP:
    if event.key == pygame.K_UP:
        blocky_y_move = 0
    elif event.type == pygame.K_DOWN:
        blocky_y_move = 0

etc等等

You can set the boundaries using the min and max functions.您可以使用minmax函数设置边界。

Here is the concept:这是一个概念:

We have a pygame object that moves in all four directions;我们有一个在所有四个方向上移动的 pygame 对象; lets say the user holds down the LEFT arrow key, so that the object reaches the top of the screen.假设用户按住向左箭头键,以便对象到达屏幕顶部。 The y-coordinate of the top of the screen will always be 0 , so we want the object to come to a stop at y-coordinate 0 .屏幕顶部的 y 坐标将始终为0 ,因此我们希望对象停在 y 坐标0

This may seem as simple as:这可能看起来很简单:

if char.rect.y > 0:
    char.rect.y -= char.speed

But this will result in a bug ig char.speed is greater than 1 .但这会导致错误 ig char.speed大于1 Like when the object is at y-coordinate 5 , and its speed is 10 ;比如物体在 y 坐标为5 ,速度为10 the condition still allows for one more step for the object, resulting in the object coming 5 pixels out of the pygame window.该条件仍然允许对象多走一步,导致对象超出 pygame 窗口5像素。 What we want to do is more like:我们想做的更像是:

if char.rect.y > 0:
    char.rect.y -= char.speed
if char.rect.y < 0:
    char.rect.y = 0

to push the object back into the boundaries.将物体推回边界。 The above block of code can be simplified with the max function:上面的代码块可以用max函数简化:

self.rect.y = max([self.rect.y - self.speed, 0])

For the object moving down:对于向下移动的物体:

if char.rect.y < HEIGHT - char.height:
    char.rect.y += char.speed
if char.rect.y > HEIGHT - char.height:
    char.rect.y = HEIGHT - char.height

or, the more efficient and clean method:或者,更有效和更干净的方法:

self.rect.y = min([self.rect.y + self.speed, HEIGHT - self.height])

For going left and right, simply replace the y s and height (and HEIGHT ) from two lines above with x s and widths (and WIDTH ) .对于左右移动,只需将上面两行中的y s 和height (和HEIGHT替换为x s 和widths (和WIDTH

All together:全部一起:

import pygame

pygame.init()

WIDTH = 600
HEIGHT = 600
wn = pygame.display.set_mode((WIDTH, HEIGHT))

class Player:
    def __init__(self):
        self.speed = 1
        self.width = 20
        self.height = 20
        self.color = (255, 255, 0)
        self.rect = pygame.Rect((WIDTH - self.width) / 2, (HEIGHT - self.height) / 2, 20, 20)

    def up(self):
        self.rect.y = max([self.rect.y - self.speed, 0])
        
    def down(self):
        self.rect.y = min([self.rect.y + self.speed, HEIGHT - self.height])
        
    def left(self):
        self.rect.x = max([self.rect.x - self.speed, 0])
        
    def right(self):
        self.rect.x = min([self.rect.x + self.speed, WIDTH - self.width])
        
    def draw(self):
        pygame.draw.rect(wn, self.color, self.rect)

char = Player()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        char.up()
    if keys[pygame.K_DOWN]:
        char.down()
    if keys[pygame.K_LEFT]:
        char.left()
    if keys[pygame.K_RIGHT]:
        char.right()
    wn.fill((0, 0, 0))
    char.draw()
    pygame.display.update()

在此处输入图片说明

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM