【发布时间】:2020-08-17 17:43:44
【问题描述】:
我正在尝试编写类似于游戏小鸟的代码。在我的程序中,我希望能够检查小鸟是否与管道接触,如果是,游戏应该结束。我有一个管道类和一个鸟类,我有两个管道类的实例:
bird = bird(125,185)
pipe1 = pipe(300, 255)
pipe2 = pipe(520, 255)
在我的管道类中,我有这两种与管道高度和位置相关的方法:
def __init__(self, x, y):
self.bottom = pygame.transform.scale(pygame.image.load("pipe.png"), (52,145))
self.x = x
self.y = y
self.width = 52
self.height = 145
def resize(self): # The height of the pipe will vary randomly
self.height = random.randint(100,150)
self.bottom = pygame.transform.scale(pygame.image.load("pipe.png"), (52,self.height))
self.y = 400 - self.height
def draw(self, win):
if self.x > -52:
self.x -= 5 # Pipe will move to the left of the screen
else:
self.x = 400
self.resize()
win.blit(self.bottom, (self.x,self.y))
self.top = pygame.transform.rotate(self.bottom, 180) # There is a bottom pipe and a top pipe
win.blit(self.top, (self.x,0))
如您所见,对于管道类的每个实例,屏幕上都绘制了两个管道。一个在屏幕顶部,另一个在底部。然后两个管道都在屏幕上移动。
这是bird类的一些代码:
def __init__(self, x, y):
self.bird1 = pygame.transform.scale(pygame.image.load("bird1.png"), (34,24))
self.bird2 = pygame.transform.scale(pygame.image.load("bird2.png"), (34,24))
self.bird3 = pygame.transform.scale(pygame.image.load("bird3.png"), (34,24))
self.birdpics = [self.bird1, self.bird2, self.bird3]
self.x = x
self.y = y
self.width = 34
self.height = 24
self.moveCount = 0
self.jumpCount = 7
self.isJump = False
self.image = self.birdpics[self.moveCount]
def draw(self, win):
self.moveCount += 1
if self.moveCount >= len(self.birdpics):
self.moveCount = 0
self.image = self.birdpics[self.moveCount]
win.blit(self.image, (self.x,self.y))
# The image of the bird on the screen switches between 3 images. The height and width of the bird stay constant.
当用户单击鼠标左键时,小鸟会根据用户的鼠标点击跳跃并在管道之间“飞翔”(每次单击鼠标,小鸟的 y 坐标都会增加,小鸟的 y 坐标也会增加)当用户什么都不做时稳步下降)。我现在如何找到一种方法来检测鸟是否真的接触到了其中一个管道,在这种情况下游戏将结束?
【问题讨论】:
-
@Rabbid76 如何为管道的顶部和底部制作一个矩形?
-
你必须制作 3 个矩形。一个用于鸟,一个用于底部管道,一个用于顶部管道。您必须测试鸟是否撞到顶部
or底部管道。
标签: python pygame collision-detection