python - 如何检查矩形是否超出 pygame 屏幕

标签 python python-3.x pygame python-3.7

我正在用 pygame 重新制作贪吃蛇游戏。

如何检测方 block 是否在屏幕之外? 我正在使用 x =y = 移动方 block 。

这是到目前为止的代码:

import pygame, sys, random
from pygame.locals import *
pygame.init()
movement_x = movement_y = 0
RED = (240, 0, 0)
GREEN = (0, 255, 0)
ran = [0,25,50,75,100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,475,500]
ax = 0
ay = 0
x = 0
y = 0
sizex = 500
sizey = 500
tilesize = 25
screen = pygame.display.set_mode((sizex,sizey))
pygame.display.set_caption('Snake')
pygame.display.set_icon(pygame.image.load('images/tile.png'))
tile = pygame.image.load('images/tile.png')
tile = pygame.transform.scale(tile, (tilesize, tilesize))

clock = pygame.time.Clock()

vel_x = 0
vel_y = 0
ap = True
while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    for row in range(sizex):
        for column in range(sizey):
            screen.blit(tile,(column*tilesize, row*tilesize,tilesize,tilesize))
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_UP:
                vel_y = -25
                vel_x = 0
            elif event.key == K_DOWN:
                vel_y = 25
                vel_x = 0
            elif event.key == K_LEFT:
                vel_x = - 25
                vel_y = 0
            elif event.key == K_RIGHT:
                vel_x= 25
                vel_y = 0

    if ap:
        pygame.draw.rect(screen, GREEN, pygame.Rect(ax,ay,tilesize,tilesize))
    y += vel_y
    x += vel_x
    if x == ax and y == ay:
        pygame.draw.rect(screen, GREEN, pygame.Rect(ax,ay,tilesize,tilesize))
        ax = random.choice(ran)
        ay = random.choice(ran)
    pygame.draw.rect(screen, RED, pygame.Rect(x,y,tilesize,tilesize))
    pygame.display.flip()
    clock.tick(100)

最佳答案

如果一个点在矩形内可以通过 pygame.Rect.collidepoint() 检查.
矩形由屏幕边界定义,点是蛇头的新位置:

inBounds = pygame.Rect(0, 0, sizex, sizey).collidepoint(x+vel_x, y+vel_y)
if inBounds:
    y += vel_y
    x += vel_x

关于python - 如何检查矩形是否超出 pygame 屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54872383/

相关文章:

python - 将列表列表转换为Python中的字典字典

python - Python 3 中的图形、绘图

python - 我的游戏角色只有当鼠标在屏幕上移动时才会移动,而它需要鼠标

python - 使用python向后读取二进制文件

python:使用 y0 和 dy 偏移量绘制条形图

python - 如何将 Base64 图像字符串从 Flask Python 代码传递到 HTML?

python - 使用 pandas 对齐数据框中的列

python - 在 pygame 中旋转图像,使其看起来像在旋转

python - 如何在 PyOpenGL 中将 png 图像作为图像叠加层进行 blit?

python - Django模板中的 "|"符号是什么意思?