问题遇到的现象和发生背景
正在学习pygame(入门),使用pycharm制作flappy bird小游戏。而对于下方代码,小鸟总是在第一个档口死亡(并没有触碰管道);又或是不能触发死亡机制(在下方代码基础上,checkDead()中检验碰撞管道板块也加入return True的时候)。
问题相关代码,请勿粘贴截图
import sys
import pygame
class Bird:
def init(self):
self.birdRect=pygame.Rect(65,50,48,48)
self.birdStatus=[pygame.image.load("bird0_0.png"),pygame.image.load("bird0_1.png"),pygame.image.load("bird0_2.png")]
self.status=0
self.birdX=120
self.birdY=350
self.jump=False
self.jumpSpeed=10
self.gravity=5
self.dead=False
def birdUpdate(self):
if self.jump:
self.jumpSpeed-=1
self.birdY-=self.jumpSpeed
else:
self.gravity+=0.2
self.birdY+=self.gravity
class Pipeline:
def init(self):
self.wallx=400
self.pineUp=pygame.image.load("pipe_up.png")
self.pineDown=pygame.image.load("pipe_down.png")
def updatePipeline(self):
self.wallx-=5
if self.wallx<-80:
self.wallx=400
global score
score+=1
def createMap():
screen.fill((255,255,255))
screen.blit(background,(0,0))
screen.blit(Pipeline.pineUp,(Pipeline.wallx,-500))
screen.blit(Pipeline.pineDown,(Pipeline.wallx,500))
Pipeline.updatePipeline()
if Bird.dead:
Bird.status=2
else:
Bird.status=1
screen.blit(Bird.birdStatus[Bird.status],(Bird.birdX,Bird.birdY))
Bird.birdUpdate()
screen.blit(font.render("Score:"+str(score),-1,(255,255,255)),(100,50))
pygame.display.update()
def checkDead():
upRect=pygame.Rect(Pipeline.wallx,-500,Pipeline.pineUp.get_width()-10,Pipeline.pineUp.get_height())
downRect=pygame.Rect(Pipeline.wallx,500,Pipeline.pineDown.get_width() - 10, Pipeline.pineDown.get_height())
if upRect.colliderect(Bird.birdRect) or downRect.colliderect(Bird.birdRect):
Bird.dead=True
if not 0<Bird.birdRect[1]<height:
Bird.dead=True
return True
else:
return False
def getResut1():
final_test1="Game Over"
final_test2="Your Final Score Is:" +str(score)
ft1_font=pygame.font.SysFont("Arial",70)
ft1_surf=font.render(final_test1,1,(242,3,36))
ft2_font=pygame.font.SysFont("Arial",50)
ft2_surf=font.render(final_test2,1,(253,177,36))
screen.blit(ft1_surf,(screen.get_width()/2-ft1_surf.get_width(),100))
screen.blit(ft2_surf,(screen.get_width()/2-ft1_surf.get_width(),200))
pygame.display.flip()
if name=="main":
pygame.init()
pygame.font.init()
font=pygame.font.SysFont(None,50)
size=width,height=400,650
screen=pygame.display.set_mode(size)
clock=pygame.time.Clock()
Pipeline=Pipeline()
Bird=Bird()
score=0
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
if (event.type==pygame.KEYDOWN or event.type==pygame.MOUSEBUTTONDOWN) and not Bird.dead:
Bird.jump=True
Bird.gravity=5
Bird.jumpSpeed=10
background=pygame.image.load("bg_day.png")
if checkDead():
getResut1()
else:
createMap()
运行结果及报错内容
游戏运行不正常,无报错
我的解答思路和尝试过的方法
代码本身几乎照抄教材,后续又稍加改动。
尝试过上网搜寻,认为与小鸟、管道rect边界设置有关,又或是checkDead()出现了某种错误导致
我想要达到的结果
希望能指出上方代码的错误(最好),或者依据我的代码给出正确的代码