1
我的碰撞代碼確實是錯誤的,因爲紅色的「子彈」必須擊中玩家的中間才能在屏幕上運行遊戲。我需要幫助重構表達,所以如果紅色的「子彈」擊中玩家的任何地方它會運行我的遊戲結束代碼(代碼上的遊戲已經接近尾聲pygame.quit()之前)我無法在pygame中得到我的碰撞代碼
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()
它是安全的假設你所有的物體可以視爲圈子?如果是這樣,你可以檢查給定子彈(紅色圓圈)和玩家(綠色圓圈)的中心之間的距離是否小於這兩個物體/圓圈的半徑之和。 – CodeSurgeon