我正在制作一个游戏,其中有一堆下落的圆圈,玩家(方 block )需要避开它们。问题是我找不到一种方法让圆圈和玩家碰撞以触发游戏结束。有什么办法可以让正方形和圆形碰撞来触发游戏结束或者让游戏在pygame中退出吗?
import pygame
from pygame.locals import *
import os
import random
import math
import sys
import time
white = (255,255,255)
blue = (0,0,255)
gravity = 10
size =10
height = 500
width =600
varHeigth = height
ballNum = 5
eBall = []
apGame = pygame.display.set_mode((width, height))
pygame.display.set_caption("AP Project")
clock = pygame.time.Clock()
class Player(object):
def __init__(self):
red = (255, 0, 0)
move_x = 300
move_y = 400
self.rect = pygame.draw.rect(apGame,red, (move_x, move_y, 10, 10))
self.dist = 10
def handle_keys(self):
for e in pygame.event.get():
if e.type == pygame.QUIT:
pygame.quit();
exit()
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
self.draw_rect(-1, 0)
elif key[pygame.K_RIGHT]:
self.draw_rect(1, 0)
elif key[pygame.K_ESCAPE]:
pygame.quit();
exit()
else:
self.draw_rect(0, 0)
def draw_rect(self, x, y):
red = (255, 0, 0)
black = (0, 0, 0)
'''apGame.fill(black)'''
self.rect = self.rect.move(x * self.dist, y * self.dist);
pygame.draw.rect(apGame, red , self.rect)
pygame.display.update()
def draw(self,surface):
red = (255, 0, 0)
move_x = 300
move_y = 400
pygame.draw.rect(apGame, red, (move_x, move_y, 10, 10))
move_x = 300
move_y = 400
red = (255, 0, 0)
black = (0, 0, 0)
player = Player()
clock = pygame.time.Clock()
'''apGame.fill(black)'''
player.draw(apGame)
pygame.display.update()
for q in range(ballNum):
x = random.randrange(0, width)
y = random.randrange(0, varHeigth)
eBall.append([x, y])
while True:
apGame.fill(black)
for i in range(len(eBall)):
pygame.draw.circle(apGame, blue, eBall[i], size)
eBall[i][1] += 5
if eBall[i][1] > height:
y = random.randrange(-50, -10)
eBall[i][1] = y
x = random.randrange(0, width)
eBall[i][0] = x
player.handle_keys()
pygame.display.flip()
clock.tick(30)
最佳答案
使用球的边界矩形进行碰撞测试就足够了。界限pygame.Rect
由 pygame.draw.circle()
返回。如果两个矩形相交,可以通过 colliderect()
来评估。
例如:
while True:
# [...]
for i in range(len(eBall)):
ball_rect = pygame.draw.circle(apGame, blue, eBall[i], size)
if player.rect.colliderect(ball_rect):
print("hit")
# [...]
如果你想在单独的循环中进行碰撞测试,那么你必须手动构造球的边界矩形:
while True:
# [...]
for ball in eBall:
ball_rect = pygame.Rect(ball[0]-size, ball[1]-size, size*2, size*2)
if player.rect.colliderect(ball_rect):
print("hit")
关于python - 如何在 pygame 中使正方形和圆形之间发生碰撞来触发游戏结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61989267/