|
🌈writeinfront🌈🧸大家好,我是Aileen🧸.希望你看完之后,能对你有所帮助,不足请指正!共同学习交流.🆔本文由Aileen_0v0🧸原创CSDN首发🐒如需转载还请通知⚠️📝个人主页:Aileen_0v0🧸—CSDN博客🎁欢迎各位→点赞👍+收藏⭐️+留言📝📣系列专栏:Aileen_0v0🧸的PYTHON学习系列专栏——CSDN博客🗼我的格言:"没有罗马,那就自己创造罗马~" 目录首先,在python上安装pygame然后,创建文件夹 要注意分级别 插入的图片主函数Aileen_invasion的文件创建外星人aileen的文件子弹bullet的文件按钮button的文件 游戏数据game_stats的文件游戏分数scoreboard的文件游戏设置settings的文件 游戏飞船ship的文件编辑 全屏模式下的游戏编辑小窗口下的游戏首先,在python上安装pygame资源--->https://download.csdn.net/download/Aileenvov/88301424?spm=1001.2014.3001.5503然后转到228页,根据步骤进行安装然后,创建文件夹 要注意分级别 插入的图片插入图片:需要注意图片的大小比例,否则可能显示不出来,这需要根据系统屏幕大小进行设置,将所需要的图片和音乐拖到对应的文件夹,这是我的图片主函数Aileen_invasion的文件importsysfromtimeimportsleepimportpygamefromsettingsimportSettingsfromgame_startsimportGameStatsfromscoreboardimportScoreboardfrombuttonimportButtonfromshipimportShipfrombulletimportBulletfromaileenimportAileenclassAileenInvasion:"""Overallclasstomanagegameassetsandbehavior.整体类来管理游戏资产和行为"""def__init__(self):#初始化"""Initializethegame,andcreategameresources."""pygame.init()self.settings=Settings()self.screen=pygame.display.set_mode((0,0),pygame.FULLSCREEN)self.settings.screen_width=self.screen.get_rect().widthself.settings.screen_height=self.screen.get_rect().height#self.screen=pygame.display.set_mode(#(self.settings.screen_width,self.settings.screen_height))#类中变量前有self,说明该变量绑定在当前实例化本身pygame.display.set_caption("AileenInvasion")#Creationaninstancetostoregamestatistics.self.stats=GameStats(self)#Createaninstancetostoregamestatics,#andcreateascoreboard.self.sb=Scoreboard(self)self.ship=Ship(self)self.bullets=pygame.sprite.Group()#Group可以批量使用的函数self.aileens=pygame.sprite.Group()self._create_fleet()#Maketheplaybutton.self.play_button=Button(self,"Play")self.bg_color=(0,0,225)#代表红绿蓝三颜色#def_create_fleet(self):#"""Createthefleetofaileens."""##Makeaaileen#aileen=Aileen(self)#self.aileens.add(aileen)##setthebackgroundcolor.defrun_game(self):#功能:1监听事件,2处理事件,3更新屏幕事件"""Startthemainloopforthegame."""whileTrue:#1监听事件函数--监听和处理用户的行为self._check_events()#将监听事件(封装)外包给这个函数,减轻run_game的工作量---这个过程叫重构(refactory)ifself.stats.game_active:#2处理事件函数self.ship.update()#更新子弹self._update_bullets()self._update_aileens()#3屏幕更新函数self._update_screen()def_update_bullets(self):self.bullets.update()ifnotself.aileens:#Destoryexistingbulletsandcreatenewfleetself.bullets.empty()self._create_fleet()#Getridofthebulletsthathavedisappeared.forbulletinself.bullets.copy():ifbullet.rect.bottom=screen_rect.bottom:#Treatthisthesameasiftheshipgothit.self._ship_hit()break#Redrawthescreenduringeachpassthroughtheloop.更新画布颜色def_update_aileens(self):"""Checkifthefleetisatanedge,thenupdatethepositionsofallaliensinthefleet."""self._check_fleet_edges()"""Updatethepositionsofallaileensinthefleet."""self.aileens.update()#Lookforaileen-shipcollisions.ifpygame.sprite.spritecollideany(self.ship,self.aileens):self._ship_hit()print("Shiphit!!!")#Lookforaileenshittingthebottomofthescreenself._check_aileens_bottom()def_check_fleet_edges(self):"""Respondappropriatelyifanyaileenshavereachedanedge."""foraileeninself.aileens.sprites():ifaileen.check_edges():self._change_fleet_direction()breakdef_change_fleet_direction(self):"""Droptheentirefleetandchangethefleet'sdirection."""foraileeninself.aileens.sprites():aileen.rect.y+=self.settings.fleet_drop_speedself.settings.fleet_direction*=-1def_ship_hit(self):"""Respondtotheshipbeinghitbyanallien"""ifself.stats.ships_left>0:#Decrementships_left.andupdatescoreboardself.stats.ships_left-=1self.sb.prep_ships()#Getridofanyremainingaileensandbullets.self.aileens.empty()self.bullets.empty()#Createanewfleetandcentertheship.self._create_fleet()self.ship.center_ship()#Pausesleep(0.5)else:self.stats.game_active=Falsepygame.mouse.set_visible(True)def_update_screen(self):"""Updateimagesonthescreen,andfliptothenewscreen"""self.screen.fill(self.settings.bg_color)self.ship.blitme()forbulletinself.bullets.sprites():bullet.draw_bullet()self.aileens.draw(self.screen)#Drawthescoreinformation.self.sb.show_score()#Drawtheplaybuttonifthegamesisinactive.ifnotself.stats.game_active:self.play_button.draw_button()self.bullets.draw(self.screen)pygame.display.flip()defcheck_high_score(self):"""Checktoseeifthere'sanewhighscore."""ifself.stats.score>self.stats.high_score:self.stats.high_score=self.stats.scoreself.prep_high_score()if__name__=='__main__':#Makeagameinstance,andrunthegame.ai=AileenInvasion()#游戏本身的实例化,ai就是那个AileenInvasionai.run_game()创建外星人aileen的文件importpygamefrompygame.spriteimportSpriteclassAileen(Sprite):"""Aclasstorepresentasinglealieninthefleet"""def__init__(self,ai_game):"""Initilizetheaileenandsetitsstartingposition."""super().__init__()self.screen=ai_game.screenself.settings=ai_game.settings#Loadtheaileenimageandsetitsrectattribute.self.image=pygame.image.load("images/aileen.png")self.rect=self.image.get_rect()#Starteachnewaileennearthetopleftofthescreen.self.rect.x=self.rect.width#将矩形左上角的值作为外星人的宽度self.rect.y=self.rect.height#通过飞船左上角的坐标来控制其它图片的位置#Storetheaileen'sexacthorizontalposition.self.x=float(self.rect.x)defcheck_edges(self):"""ReturnTrueifaileenisatedgeofscreen"""screen_rect=self.screen.get_rect()ifself.rect.right>=screen_rect.rightorself.rect.leftself.stats.high_score:self.stats.high_score=self.stats.scoreself.prep_high_score()defprep_level(self):"""Turnthelevelintoarenderedimage."""level_str=str(self.stats.level)self.level_image=self.font.render(level_str,True,self.text_color,self.settings.bg_color)#Positionthelevelbelowthescore.self.level_rect=self.level_image.get_rect()self.level_rect.right=self.score_rect.rightself.level_rect.top=self.score_rect.bottom+10defshow_score(self):"""Drawscore,level,andshipstothescreen"""self.screen.blit(self.score_image,self.score_rect)self.screen.blit(self.high_score_image,self.high_score_rect)self.screen.blit(self.level_image,self.level_rect)self.ships.draw(self.screen)游戏设置settings的文件 classSettings:"""AclassstoreallsettingsforAileenInvasion."""def__init__(self):"""Initializethegame'settings"""#Shipsettingsself.ship_speed=1.5self.ship_limit=3#Screensettingsself.screen_width=1200self.screen_height=800self.bg_color=(255,255,255)#Bulletsettingsself.bullet_speed=1self.bullet_width=3self.bullet_height=15self.bullet_color=(60,60,60)self.bullets_allowed=3#Aileensettingsself.aileen_speed=1.0self.fleet_drop_speed=10#Howquicklythegamespeedsupself.speedup_scale=2#Howquicklytheaileenpointvaluesincreaseself.score_scale=1.5self.initialize_dynamic_settings()definitialize_dynamic_settings(self):"""Initializespeedsettings"""self.ship_speed=1.5self.bullet_speed=1.5self.aileen_speed=10#Scoringself.aileen_points=50#fleet_directionof1representsright;-1representsleft.self.fleet_direction=1defincrease_speed(self):"""Increasespeedsettings""""""Increasespeedsettingsandaileenpointvalues"""self.ship_speed*=self.speedup_scaleself.bullet_speed*=self.speedup_scaleself.aileen_speed*=self.speedup_scaleself.aileen_points=int(self.aileen_points*self.score_scale)print(self.aileen_points)'运行运行游戏飞船ship的文件importpygamefrompygame.spriteimportSpriteclassShip(Sprite):"""Aclasstomanagetheship."""def__init__(self,ai_game):"""Initializetheshipandsetitsstartingposition."""super().__init__()self.screen=ai_game.screenself.settings=ai_game.settingsself.screen_rect=ai_game.screen.get_rect()#返回窗口矩形#Loadtheshipimageandgetitsrect.self.image=pygame.image.load("images/ship.png")self.rect=self.image.get_rect()#取得屏幕的矩形rect=rectangle拿到图片矩形#Starteachnewshipatthebottomcenterofthescreen.self.rect.midbottom=self.screen_rect.midbottom#通过赋值:图片的中下方的坐标,等于屏幕中下方的坐标#Storeadecimalvaluefortheship'shorizontalposition.self.x=float(self.rect.x)self.y=float(self.rect.y)#Movementflagself.moving_right=Falseself.moving_left=Falseself.moving_up=Falseself.moving_down=Falsedefcenter_ship(self):"""Centertheshiponthescreen"""self.rect.midbottom=self.screen_rect.midbottomself.x=float(self.rect.x)defupdate(self):"""Updatetheship'spositionbasedonthemovementflag"""#Updatetheship'svalue,nottherect.#ifself.moving_right:ifself.moving_rightandself.rect.right0:self.x-=self.settings.ship_speedself.rect.x-=1#topifself.moving_upandself.rect.top>720:self.y-=self.settings.ship_speedself.rect.y-=1ifself.moving_downandself.rect.bottom
|
|