超级玛丽小游戏制作方法详细介绍(超级玛丽代码怎么写)

时间:2023-03-17 10:13:27 来源:网络 发布:手游网 浏览:10次

效果演示:

基础源码

1.基础设置(tools部分)

2.设置背景音乐以及场景中的文字(setup部分)

3.设置游戏规则(load_screen)

4.设置游戏内菜单等(main_menu)

5.main()

6.调用以上函数实现

1.基础设置(tools部分)

这个部分设置马里奥以及游戏中蘑菇等怪的的移动设置。

importosimportpygameaspgkeybinding={'action':pg.K_s,'jump':pg.K_a,'left':pg.K_LEFT,'right':pg.K_RIGHT,'down':pg.K_DOWN}classControl(object):"""Controlclassforentireproject.Containsthegameloop,andcontainstheevent_loopwhichpasseseventstoStatesasneeded.Logicforflippingstatesisalsofoundhere."""def__init__(self,caption):self.screen=pg.display.get_surface()self.done=Falseself.clock=pg.time.Clock()self.caption=captionself.fps=60self.show_fps=Falseself.current_time=0.0self.keys=pg.key.get_pressed()self.state_dict={}self.state_name=Noneself.state=Nonedefsetup_states(self,state_dict,start_state):self.state_dict=state_dictself.state_name=start_stateself.state=self.state_dict[self.state_name]defupdate(self):self.current_time=pg.time.get_ticks()ifself.state.quit:self.done=Trueelifself.state.done:self.flip_state()self.state.update(self.screen,self.keys,self.current_time)defflip_state(self):previous,self.state_name=self.state_name,self.state.nextpersist=self.state.cleanup()self.state=self.state_dict[self.state_name]self.state.startup(self.current_time,persist)self.state.previous=previousdefevent_loop(self):foreventinpg.event.get():ifevent.type==pg.QUIT:self.done=Trueelifevent.type==pg.KEYDOWN:self.keys=pg.key.get_pressed()self.toggle_show_fps(event.key)elifevent.type==pg.KEYUP:self.keys=pg.key.get_pressed()self.state.get_event(event)deftoggle_show_fps(self,key):ifkey==pg.K_F5:self.show_fps=notself.show_fpsifnotself.show_fps:pg.display.set_caption(self.caption)defmain(self):"""Mainloopforentireprogram"""whilenotself.done:self.event_loop()self.update()pg.display.update()self.clock.tick(self.fps)ifself.show_fps:fps=self.clock.get_fps()with_fps="{}-{:.2f}FPS".format(self.caption,fps)pg.display.set_caption(with_fps)class_State(object):def__init__(self):self.start_time=0.0self.current_time=0.0self.done=Falseself.quit=Falseself.next=Noneself.previous=Noneself.persist={}defget_event(self,event):passdefstartup(self,current_time,persistant):self.persist=persistantself.start_time=current_timedefcleanup(self):self.done=Falsereturnself.persistdefupdate(self,surface,keys,current_time):passdefload_all_gfx(directory,colorkey=(255,0,255),accept=('.png','jpg','bmp')):graphics={}forpicinos.listdir(directory):name,ext=os.path.splitext(pic)ifext.lower()inaccept:img=pg.image.load(os.path.join(directory,pic))ifimg.get_alpha():img=img.convert_alpha()else:img=img.convert()img.set_colorkey(colorkey)graphics[name]=imgreturngraphicsdefload_all_music(directory,accept=('.wav','.mp3','.ogg','.mdi')):songs={}forsonginos.listdir(directory):name,ext=os.path.splitext(song)ifext.lower()inaccept:songs[name]=os.path.join(directory,song)returnsongsdefload_all_fonts(directory,accept=('.ttf')):returnload_all_music(directory,accept)defload_all_sfx(directory,accept=('.wav','.mpe','.ogg','.mdi')):effects={}forfxinos.listdir(directory):name,ext=os.path.splitext(fx)ifext.lower()inaccept:effects[name]=pg.mixer.Sound(os.path.join(directory,fx))returneffects

2.设置背景音乐以及场景中的文字(setup部分)

该部分主要设置场景中的背景音乐,以及字体的显示等设置。

importosimportpygameaspgfrom.importtoolsfrom.importconstantsascORIGINAL_CAPTION=c.ORIGINAL_CAPTIONos.environ['SDL_VIDEO_CENTERED']='1'pg.init()pg.event.set_allowed([pg.KEYDOWN,pg.KEYUP,pg.QUIT])pg.display.set_caption(c.ORIGINAL_CAPTION)SCREEN=pg.display.set_mode(c.SCREEN_SIZE)SCREEN_RECT=SCREEN.get_rect()FONTS=tools.load_all_fonts(os.path.join("resources","fonts"))MUSIC=tools.load_all_music(os.path.join("resources","music"))GFX=tools.load_all_gfx(os.path.join("resources","graphics"))SFX=tools.load_all_sfx(os.path.join("resources","sound"))

3.设置游戏规则(load_screen)

from..importsetup,toolsfrom..importconstantsascfrom..importgame_soundfrom..componentsimportinfoclassLoadScreen(tools._State):def__init__(self):tools._State.__init__(self)defstartup(self,current_time,persist):self.start_time=current_timeself.persist=persistself.game_info=self.persistself.next=self.set_next_state()info_state=self.set_overhead_info_state()self.overhead_info=info.OverheadInfo(self.game_info,info_state)self.sound_manager=game_sound.Sound(self.overhead_info)defset_next_state(self):"""Setsthenextstate"""returnc.LEVEL1defset_overhead_info_state(self):"""setsthestatetosendtotheoverheadinfoobject"""returnc.LOAD_SCREENdefupdate(self,surface,keys,current_time):"""Updatestheloadingscreen"""if(current_time-self.start_time)<2400:surface.fill(c.BLACK)self.overhead_info.update(self.game_info)self.overhead_info.draw(surface)elif(current_time-self.start_time)<2600:surface.fill(c.BLACK)elif(current_time-self.start_time)<2635:surface.fill((106,150,252))else:self.done=TrueclassGameOver(LoadScreen):"""AloadingscreenwithGameOver"""def__init__(self):super(GameOver,self).__init__()defset_next_state(self):"""Setsnextstate"""returnc.MAIN_MENUdefset_overhead_info_state(self):"""setsthestatetosendtotheoverheadinfoobject"""returnc.GAME_OVERdefupdate(self,surface,keys,current_time):self.current_time=current_timeself.sound_manager.update(self.persist,None)if(self.current_time-self.start_time)<7000:surface.fill(c.BLACK)self.overhead_info.update(self.game_info)self.overhead_info.draw(surface)elif(self.current_time-self.start_time)<7200:surface.fill(c.BLACK)elif(self.current_time-self.start_time)<7235:surface.fill((106,150,252))else:self.done=TrueclassTimeOut(LoadScreen):"""LoadingScreenwithTimeOut"""def__init__(self):super(TimeOut,self).__init__()defset_next_state(self):"""Setsnextstate"""ifself.persist[c.LIVES]==0:returnc.GAME_OVERelse:returnc.LOAD_SCREENdefset_overhead_info_state(self):"""Setsthestatetosendtotheoverheadinfoobject"""returnc.TIME_OUTdefupdate(self,surface,keys,current_time):self.current_time=current_timeif(self.current_time-self.start_time)<2400:surface.fill(c.BLACK)self.overhead_info.update(self.game_info)self.overhead_info.draw(surface)else:self.done=True

4.设置游戏内菜单等(main_menu)

importpygameaspgfrom..importsetup,toolsfrom..importconstantsascfrom..componentsimportinfo,marioclassMenu(tools._State):def__init__(self):"""Initializesthestate"""tools._State.__init__(self)persist={c.COIN_TOTAL:0,c.SCORE:0,c.LIVES:3,c.TOP_SCORE:0,c.CURRENT_TIME:0.0,c.LEVEL_STATE:None,c.CAMERA_START_X:0,c.MARIO_DEAD:False}self.startup(0.0,persist)defstartup(self,current_time,persist):"""Calledeverytimethegame'sstatebecomesthisone.Initializescertainvalues"""self.next=c.LOAD_SCREENself.persist=persistself.game_info=persistself.overhead_info=info.OverheadInfo(self.game_info,c.MAIN_MENU)self.sprite_sheet=setup.GFX['title_screen']self.setup_background()self.setup_mario()self.setup_cursor()defsetup_cursor(self):"""Createsthemushroomcursortoselect1or2playergame"""self.cursor=pg.sprite.Sprite()dest=(220,358)self.cursor.image,self.cursor.rect=self.get_image(24,160,8,8,dest,setup.GFX['item_objects'])self.cursor.state=c.PLAYER1defsetup_mario(self):"""PlacesMarioatthebeginningofthelevel"""self.mario=mario.Mario()self.mario.rect.x=110self.mario.rect.bottom=c.GROUND_HEIGHTdefsetup_background(self):"""Setupthebackgroundimagetoblit"""self.background=setup.GFX['level_1']self.background_rect=self.background.get_rect()self.background=pg.transform.scale(self.background,(int(self.background_rect.width*c.BACKGROUND_MULTIPLER),int(self.background_rect.height*c.BACKGROUND_MULTIPLER)))self.viewport=setup.SCREEN.get_rect(bottom=setup.SCREEN_RECT.bottom)self.image_dict={}self.image_dict['GAME_NAME_BOX']=self.get_image(1,60,176,88,(170,100),setup.GFX['title_screen'])defget_image(self,x,y,width,height,dest,sprite_sheet):"""Returnsimagesandrectstoblitontothescreen"""image=pg.Surface([width,height])rect=image.get_rect()image.blit(sprite_sheet,(0,0),(x,y,width,height))ifsprite_sheet==setup.GFX['title_screen']:image.set_colorkey((255,0,220))image=pg.transform.scale(image,(int(rect.width*c.SIZE_MULTIPLIER),int(rect.height*c.SIZE_MULTIPLIER)))else:image.set_colorkey(c.BLACK)image=pg.transform.scale(image,(int(rect.width*3),int(rect.height*3)))rect=image.get_rect()rect.x=dest[0]rect.y=dest[1]return(image,rect)defupdate(self,surface,keys,current_time):"""Updatesthestateeveryrefresh"""self.current_time=current_timeself.game_info[c.CURRENT_TIME]=self.current_timeself.update_cursor(keys)self.overhead_info.update(self.game_info)surface.blit(self.background,self.viewport,self.viewport)surface.blit(self.image_dict['GAME_NAME_BOX'][0],self.image_dict['GAME_NAME_BOX'][1])surface.blit(self.mario.image,self.mario.rect)surface.blit(self.cursor.image,self.cursor.rect)self.overhead_info.draw(surface)defupdate_cursor(self,keys):"""Updatethepositionofthecursor"""input_list=[pg.K_RETURN,pg.K_a,pg.K_s]ifself.cursor.state==c.PLAYER1:self.cursor.rect.y=358ifkeys[pg.K_DOWN]:self.cursor.state=c.PLAYER2forinputininput_list:ifkeys[input]:self.reset_game_info()self.done=Trueelifself.cursor.state==c.PLAYER2:self.cursor.rect.y=403ifkeys[pg.K_UP]:self.cursor.state=c.PLAYER1defreset_game_info(self):"""ResetsthegameinfoincaseofaGameOverandrestart"""self.game_info[c.COIN_TOTAL]=0self.game_info[c.SCORE]=0self.game_info[c.LIVES]=3self.game_info[c.CURRENT_TIME]=0.0self.game_info[c.LEVEL_STATE]=Noneself.persist=self.game_info

5.main()

from.importsetup,toolsfrom.statesimportmain_menu,load_screen,level1from.importconstantsascdefmain():"""Addstatestocontrolhere."""run_it=tools.Control(setup.ORIGINAL_CAPTION)state_dict={c.MAIN_MENU:main_menu.Menu(),c.LOAD_SCREEN:load_screen.LoadScreen(),c.TIME_OUT:load_screen.TimeOut(),c.GAME_OVER:load_screen.GameOver(),c.LEVEL1:level1.Level1()}run_it.setup_states(state_dict,c.MAIN_MENU)run_it.main()

6.调用以上函数实现

importsysimportpygameaspgfrom小游戏.超级玛丽.data.mainimportmainimportcProfileif__name__=='__main__':main()pg.quit()sys.exit()

评论
评论
发 布