資源簡介
用python語言制作的管道小鳥游戲,可以通過鍵盤的空格鍵來控制小鳥的上下移動
代碼片段和文件信息
import?pygame
import?pygame.locals?as?locals
import?random
class?Game(object):
????SIZE?=?(300?400)
????FPS?=?30
????def?__init__(self):
????????self.surface?=?pygame.display.set_mode(Game.SIZE)
????????self.clock?=?pygame.time.Clock()
????def?init(self):
????????self.background?=?Background()
????????self.bird?=?Bird()
????????self.score_obj?=?Score()
????????self.pipes?=?[]
????????self.pipes.append(Pipe())
????????self.time?=?0
????????self.is_running?=?True
????????self.score?=?0
????def?start(self):
????????self.init()
????????while?self.is_running:
????????????self.time?+=?1
????????????if?self.time?==?100000000:
????????????????self.time?=?0
????????????self.control()
????????????self.update()
????????????self.draw()
????????????pygame.display.update()
????????????self.clock.tick(Game.FPS)
????def?control(self):
????????for?event?in?pygame.event.get():
????????????if?event.type?==?locals.QUIT:
????????????????exit()
????????????if?event.type?==?locals.KEYDOWN:
????????????????if?event.key?==?locals.K_SPACE:
????????????????????self.bird.fly()
????def?create_pipe(self):
????????if?self.time?%?50?==?0:
????????????self.pipes.append(Pipe())
????def?update_pipes(self):
????????index?=?len(self.pipes)?-?1
????????while?index?>=?0:
????????????if?self.pipes[index].need_remove():
????????????????del?(self.pipes[index])
????????????else:
????????????????self.pipes[index].update()
????????????index?-=?1
????def?draw_pipes(self?surface):
????????for?pipe?in?self.pipes:
????????????pipe.draw(surface)
????def?update(self):
????????if?self.bird.is_dead(self.pipes):
????????????self.is_running?=?False
????????for?pipe?in?self.pipes:
????????????if?pipe.need_add_score(self.bird):
????????????????self.score?+=?1
????????self.create_pipe()
????????self.background.update()
????????self.bird.update()
????????self.update_pipes()
????????self.score_obj.update(self.score)
????def?draw(self):
????????self.background.draw(self.surface)
????????self.bird.draw(self.surface)
????????self.draw_pipes(self.surface)
????????self.score_obj.draw(self.surface)
class?Background(object):
????def?__init__(self):
????????pass
????def?update(self):
????????pass
????def?draw(self?surface):
????????surface.fill((200?200?200))
class?Bird(object):
????IMG?=?pygame.image.load(“./res/bird.png“)
????def?__init__(self):
????????self.x?=?50
????????self.y?=?180
????????self.width?=?Bird
- 上一篇:python圖像處理三維重建所有代碼
- 下一篇:BP算法Python代碼
評論
共有 條評論