我的碰撞代码确实有问题,因为红色的子弹'必须击中玩家的正中间才能在屏幕上运行游戏。我需要帮助重构表达式,所以如果红色的子弹'在任何地方点击播放器它将在代码上运行我的游戏(代码游戏接近结束pygame.quit()之前)
import pygame
import random
BLACK = (0,0,0)
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
pygame.init()
size = (700,700)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Dodger")
done = False
clock = pygame.time.Clock()
def resetpositions():
global bulletrect1, bulletrect2, bulletrect3, bulletrect4, bulletrect5, circlerect
bulletrect1 = pygame.rect.Rect((350, 0, 20, 20))
bulletrect2 = pygame.rect.Rect((175, 0, 20, 20))
bulletrect3 = pygame.rect.Rect((525, 0, 20, 20))
bulletrect4 = pygame.rect.Rect((525, 0, 20, 20))
bulletrect5 = pygame.rect.Rect((525, 0, 20, 20))
circlerect = pygame.rect.Rect((350, 600, 20, 20))
resetpositions()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
circlerect.x += 5
bulletrect1.y += 1
bulletrect2.y += 2
bulletrect3.y += 3
bulletrect4.y += 4
bulletrect5.y += 5
screen.fill(BLACK)
pygame.draw.circle(screen, GREEN, (circlerect.center), 15)
pygame.draw.circle(screen, RED, (bulletrect1.center), 20)
pygame.draw.circle(screen, RED, (bulletrect2.center), 20)
pygame.draw.circle(screen, RED, (bulletrect3.center), 20)
pygame.draw.circle(screen, RED, (bulletrect4.center), 20)
pygame.draw.circle(screen, RED, (bulletrect5.center), 20)
if bulletrect1.y == 800:
bulletrect1.y = 0
bulletrect1.x = random.randint(20,680)
if bulletrect2.y == 800:
bulletrect2.y = 0
bulletrect2.x = random.randint(20,680)
if bulletrect3.y == 800:
bulletrect3.y = 0
bulletrect3.x = random.randint(20,680)
if bulletrect4.y == 800:
bulletrect4.y = 0
bulletrect4.x = random.randint(20,680)
if bulletrect5.y == 800:
bulletrect5.y = 0
bulletrect5.x = random.randint(20,680)
if circlerect.x == 685:
circlerect.x = 15
if circlerect.collidelist((bulletrect1, bulletrect2, bulletrect3, bulletrect4, bulletrect5)) == 0:
screen.fill(BLACK)
font = pygame.font.SysFont('Calibri',40,True,False)
text = font.render("GAME OVER",True,RED)
screen.blit(text,[250,350])
pygame.display.update()
pygame.time.delay(3000)
resetpositions()
pygame.display.flip()
clock.tick(300)
pygame.quit()
答案 0 :(得分:0)
pygame.Rect.collidelist
返回列表中冲突矩形的索引,这意味着您只检查circlerect
是否与索引0
处的子弹冲突。如果列表中没有rects,则返回-1
,因此如果它没有返回-1
,则其中一个rects与玩家发生冲突并且游戏结束:
if circlerect.collidelist((bulletrect1, bulletrect2, bulletrect3, bulletrect4, bulletrect5)) != -1:
# Game over.