问题描述
我使用 pygame.rect.collidedirect
来确保没有任何矩形发生碰撞。当我运行它时,它在终端中显示是,这意味着 rects 正在发生冲突,但我无法弄清楚它们在哪里发生冲突,但是在 pyagme 窗口中,一切都是完美的。
import pygame
from random import randint
pygame.init()
screen = pygame.display.set_mode((350,675))
pygame.display.set_caption("First Game")
x_poss = randint(0,350)
y_poss = randint(0,675)
width = 20
height = 20
vel = 8
bases = []
red = (255,0)
image_1 = pygame.image.load('bird.png').convert_alpha()
image_2 = pygame.image.load('base.png').convert_alpha()
image_3 = pygame.image.load('base2.png').convert_alpha()
image_4 = pygame.image.load('enemy.png').convert_alpha()
isJump = False
jumpCount = 10
run = True
def draw_rect(color,x,y,width,height):
pygame.draw.rect(screen,color,(x,height))
for i in range(5):
bases.append(pygame.draw.rect(screen,(255,255,255),(randint(0,330),randint(0,675),height)))
bases.append(pygame.draw.rect(screen,height)))
while run:
pygame.time.delay(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
key = pygame.key.get_pressed()
if key[pygame.K_LEFT] and x_poss > vel - width:
x_poss -= vel
if key[pygame.K_RIGHT] and x_poss < 350 - vel - width:
x_poss += vel
if not(isJump):
if key[pygame.K_UP] and y_poss > vel:
y_poss -= vel
if key[pygame.K_DOWN] and y_poss < 670 - height - vel:
y_poss += vel
if key[pygame.K_SPACE]:
isJump = True
else:
if jumpCount >= -10:
y_poss -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else:
jumpCount = 10
isJump = False
screen.fill((255,255))
for base_1 in bases[:5]:
screen.blit(image_2,base_1)
for base_2 in bases[5:]:
screen.blit(image_3,base_2)
#Here is the problem......
for base_2 in bases:
for base_1 in bases:
if base_1.colliderect(base_2):
print('yes')
#till here i think so....
draw_rect((0,0),300,440,10,10)
draw_rect((255,x_poss,y_poss,height)
screen.blit(image_4,pygame.draw.rect(screen,(0,(300,10)))
screen.blit(image_1,(x_poss,height)))
pygame.display.update()
pygame.quit()
解决方法
矩形与自身发生碰撞。您必须确保 import json
import pprint
pp = pprint.PrettyPrinter(indent=4)
mydata = []
lines = log.split("\n")
for line in lines:
if line.startswith("DEBUG: {"):
json_string = line.split("DEBUG: ")[1]
mydata.append(json.loads(json_string))
pp.pprint(mydata)
:
base_1 != base_2
碰撞测试可以进一步优化:
for base_2 in bases:
for base_1 in bases:
if base_1 != base_2 and if base_1.colliderect(base_2):
print('yes')
并通过使用 collidelist()
进行简化:
for i,base_2 in enumerate(bases):
for base_1 in bases[i+1:]:
if base_1.colliderect(base_2):
print('yes')