如果两个矩形都在移动,如何检测一个矩形是否在另一个矩形中?

时间:2019-02-28 07:31:41

标签: python pygame

我正在重制蛇,我做了一切(在你们的一点帮助下),除非您触摸蛇的其他部分来结束游戏。

这是到目前为止的代码:

import pygame, sys, random
from pygame.locals import *

pygame.init()
movement_x = movement_y = 0
RED = (240, 0, 0)
GREEN = (0, 255, 0)
GREEN2 = (100, 255, 100)
ran = [0,25,50,75,100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,475]
sizex, sizey = 500, 500
tilesize = 25
screen = pygame.display.set_mode((sizex,sizey))
pygame.display.set_caption('Snake')
tile = pygame.Surface((tilesize, tilesize))
tile = pygame.image.load('images/tile.png')
tile = pygame.transform.scale(tile, (tilesize, tilesize))
snake = pygame.image.load('images/snake.png')
snake = pygame.transform.scale(snake, (tilesize, tilesize))
snake2 = pygame.image.load('images/snake2.png')
snake2 = pygame.transform.scale(snake2, (tilesize, tilesize))
apple = pygame.image.load('images/apple.png')
apple = pygame.transform.scale(apple, (tilesize, tilesize))
x2 = 0
pag = 0
clock = pygame.time.Clock()
sx, sy = 0, 0
vel_x, vel_y = 0, 0
x, y = 0, 0
sa = 0
ap = True

snake_parts = []

def slither( new_head_coord ):
    for i in range( len(snake_parts)-1, 0, -1 ):
        snake_parts[i] = snake_parts[i-1].copy()
    snake_parts[0].topleft = new_head_coord

def drawSnake():
    for p in snake_parts: 
        screen.blit(snake, p.topleft)

snake_parts.append(pygame.Rect(x,y,tilesize,tilesize))
ax, ay = random.choice(ran), random.choice(ran)
run = True
while run:
    sx, sy = x, y
    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 == QUIT:
            pygame.quit()
            run = False 
        if event.type == KEYDOWN:
            if event.key == K_UP:
                vel_x, vel_y = 0, -25
            elif event.key == K_DOWN:
                vel_x, vel_y = 0, 25
            elif event.key == K_LEFT:
                vel_x, vel_y = -25, 0
            elif event.key == K_RIGHT:
                vel_x, vel_y = 25, 0
            elif event.key == K_y:
                pag = 1
            elif event.key == K_n:
                pag = 2

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

    slither( (x, y) )
    if ap:
        screen.blit(apple,(ax,ay))
    if x == ax and y == ay:
        screen.blit(apple,(ax,ay))
        ax, ay = random.choice(ran), random.choice(ran)
        sa += 1 
        snake_parts.append(pygame.Rect(x, y, tilesize, tilesize))

    drawSnake()
    pygame.display.update()
    clock.tick(100)

我想阻止您进入蛇内。我已经有一个阻止您离开屏幕的代码。但是,这对蛇是行不通的,因为我不知道如何获得其他蛇的位置。 谢谢!

1 个答案:

答案 0 :(得分:2)

检查蛇的头部是否与蛇的任何其他部分相交。这可以通过pygame.Rect.colliderect()完成:

def snakeHitSelf():
    for i in range(1,len(snake_parts)):
        if snake_parts[0].colliderect(snake_parts[i]):
            return True
    return False  

def snakeHitSelf():
    return any([i for i in range(1,len(snake_parts)) if snake_parts[0].colliderect(snake_parts[i])])

在蛇的各部分的位置更新后(在调用函数slither之后)立即进行检查:

slither( (x, y) )
hitSelf = snakeHitSelf()
if hitSelf:
    pygame.quit()
    sys.exit()