如何检查矩形是否在pygame屏幕上

时间:2019-02-25 18:17:56

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

我正在用pygame重新制作游戏Snake。

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

这是到目前为止的代码:

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)

1 个答案:

答案 0 :(得分:1)

如果点在矩形内,则可以通过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