我正在尝试为我的 Python 编程课程制作一个 flappybird 游戏,并且我使用了诸如 drag.hit() 之类的提示,这会导致它们在每次碰撞框碰撞时打印(“hit”)。但是,龙和粗壮的碰撞箱的碰撞不起作用,我似乎无法让它起作用。
这是我的代码:
pygame.init()
class player(object): **class for dragon**
def __init__(self, x, y, width, height):
self.hitbox = (self.x + 5, self.y +3, 67, 65)
def draw(self,win): **drawing of hitbox for dragon**
self.hitbox = (self.x + 5, self.y +3, 67, 65)
pygame.draw.rect(win, (255, 0, 0), self.hitbox, 2)
def hit(self): **During collision of hitbox, print hit**
print("hit")
class stumpy(object): **class for obstacle 1**
def __init__(self, x, y, width, height):
self.hitbox = (self.x + 8, self.y+10, self.width - 18, self.height-15)
def draw(self, win):
win.blit(pygame.transform.scale(self.walkLeft[self.count//3], (75, 200)), (self.x, self.y)) #fx to scale up or down object. transform, dimension, placement
pygame.draw.rect(win, (255, 0, 0), self.hitbox, 2) #arguments - window, colour, dimension, thickness
self.hitbox = (self.x + 8, self.y+10, self.width - 18, self.height-15) #x-start, y-start, length, breath
class stumper(object): **class for obstacle 2**
def __init__(self, x, y, width, height):
self.hitbox = (self.x + 8, self.y+10, self.width - 18, self.height-20)
def draw(self,win):
self.hitbox = (self.x + 8, self.y+10, self.width - 18, self.height-20)
pygame.draw.rect(win, (255,0,0), self.hitbox, 2)
win.blit(pygame.transform.scale(self.walkLeft[self.count//1], (75,200)), (self.x,self.y))
def redrawGameWindow():
global walkCount
win.blit(bg, (bgX,0)) # This will draw our background image at (0,0)
win.blit(bg, (bgX2,0)) # This will draw our background image at (1024,0)
drag.draw(win)
for obstacle in obstacles:
obstacle.draw(win)
pygame.display.update()
speed = 30 **assign variable for fps**
drag = player(95, 396//2, 75, 73) #class for dragon, unnecessary
stump = stumpy(810, 310, 75, 200) #class for stump, unnecessary
Istump = stumper(810, -20, 75, 200)
obstacles= []
#main loop
run = True
while run:
redrawGameWindow()
pygame.time.delay(25)
for obstacle in obstacles:
if drag.hitbox[1] < Istump.hitbox[1] + Istump.hitbox[3] and drag.hitbox[1] + drag.hitbox[3] > stump.hitbox[1]: #must create player instance for this to work so using class is useless
if drag.hitbox[0] + drag.hitbox[2] > Istump.hitbox[0] and drag.hitbox[0] < Istump.hitbox[0] + Istump.hitbox[2]:
if drag.hitbox[0] + drag.hitbox[2] > stump.hitbox[0] and drag.hitbox[0] < stump.hitbox[0] + stump.hitbox[2]:
drag.hit()
obstacles.append(stumpy(250, 250, 100, 100))
redrawGameWindow()
pygame.quit()