下面给大家带来python实现超级玛丽小游戏的源码分享 效果演示: 基础源码 1。基础设置(tools部分) 2。设置背景音乐以及场景中的文字(setup部分) 3。设置游戏规则(loadscreen) 4。设置游戏内菜单等(mainmenu) 5。main() 6。调用以上函数实现 1。基础设置(tools部分) 这个部分设置马里奥以及游戏中蘑菇等怪的的移动设置。importosimportpygameaspgkeybinding{action:pg。Ks,jump:pg。Ka,left:pg。KLEFT,right:pg。KRIGHT,down:pg。KDOWN}classControl(object):Controlclassforentireproject。Containsthegameloop,andcontainstheeventloopwhichpasseseventstoStatesasneeded。Logicforflippingstatesisalsofoundhere。definit(self,caption):self。screenpg。display。getsurface()self。doneFalseself。clockpg。time。Clock()self。captioncaptionself。fps60self。showfpsFalseself。currenttime0。0self。keyspg。key。getpressed()self。statedict{}self。statenameNoneself。stateNonedefsetupstates(self,statedict,startstate):self。statedictstatedictself。statenamestartstateself。stateself。statedict〔self。statename〕defupdate(self):self。currenttimepg。time。getticks()ifself。state。quit:self。doneTrueelifself。state。done:self。flipstate()self。state。update(self。screen,self。keys,self。currenttime)defflipstate(self):previous,self。statenameself。statename,self。state。nextpersistself。state。cleanup()self。stateself。statedict〔self。statename〕self。state。startup(self。currenttime,persist)self。state。previouspreviousdefeventloop(self):foreventinpg。event。get():ifevent。typepg。QUIT:self。doneTrueelifevent。typepg。KEYDOWN:self。keyspg。key。getpressed()self。toggleshowfps(event。key)elifevent。typepg。KEYUP:self。keyspg。key。getpressed()self。state。getevent(event)deftoggleshowfps(self,key):ifkeypg。KF5:self。showfpsnotself。showfpsifnotself。showfps:pg。display。setcaption(self。caption)defmain(self):Mainloopforentireprogramwhilenotself。done:self。eventloop()self。update()pg。display。update()self。clock。tick(self。fps)ifself。showfps:fpsself。clock。getfps()withfps{}{:。2f}FPS。format(self。caption,fps)pg。display。setcaption(withfps)classState(object):definit(self):self。starttime0。0self。currenttime0。0self。doneFalseself。quitFalseself。nextNoneself。previousNoneself。persist{}defgetevent(self,event):passdefstartup(self,currenttime,persistant):self。persistpersistantself。starttimecurrenttimedefcleanup(self):self。doneFalsereturnself。persistdefupdate(self,surface,keys,currenttime):passdefloadallgfx(directory,colorkey(255,0,255),accept(。png,jpg,bmp)):graphics{}forpicinos。listdir(directory):name,extos。path。splitext(pic)ifext。lower()inaccept:imgpg。image。load(os。path。join(directory,pic))ifimg。getalpha():imgimg。convertalpha()else:imgimg。convert()img。setcolorkey(colorkey)graphics〔name〕imgreturngraphicsdefloadallmusic(directory,accept(。wav,。mp3,。ogg,。mdi)):songs{}forsonginos。listdir(directory):name,extos。path。splitext(song)ifext。lower()inaccept:songs〔name〕os。path。join(directory,song)returnsongsdefloadallfonts(directory,accept(。ttf)):returnloadallmusic(directory,accept)defloadallsfx(directory,accept(。wav,。mpe,。ogg,。mdi)):effects{}forfxinos。listdir(directory):name,extos。path。splitext(fx)ifext。lower()inaccept:effects〔name〕pg。mixer。Sound(os。path。join(directory,fx))returneffects2。设置背景音乐以及场景中的文字(setup部分) 该部分主要设置场景中的背景音乐,以及字体的显示等设置。importosimportpygameaspgfrom。importtoolsfrom。importconstantsascORIGINALCAPTIONc。ORIGINALCAPTIONos。environ〔SDLVIDEOCENTERED〕1pg。init()pg。event。setallowed(〔pg。KEYDOWN,pg。KEYUP,pg。QUIT〕)pg。display。setcaption(c。ORIGINALCAPTION)SCREENpg。display。setmode(c。SCREENSIZE)SCREENRECTSCREEN。getrect()FONTStools。loadallfonts(os。path。join(resources,fonts))MUSICtools。loadallmusic(os。path。join(resources,music))GFXtools。loadallgfx(os。path。join(resources,graphics))SFXtools。loadallsfx(os。path。join(resources,sound))3。设置游戏规则(loadscreen)from。。importsetup,toolsfrom。。importconstantsascfrom。。importgamesoundfrom。。componentsimportinfoclassLoadScreen(tools。State):definit(self):tools。State。init(self)defstartup(self,currenttime,persist):self。starttimecurrenttimeself。persistpersistself。gameinfoself。persistself。nextself。setnextstate()infostateself。setoverheadinfostate()self。overheadinfoinfo。OverheadInfo(self。gameinfo,infostate)self。soundmanagergamesound。Sound(self。overheadinfo)defsetnextstate(self):Setsthenextstatereturnc。LEVEL1defsetoverheadinfostate(self):setsthestatetosendtotheoverheadinfoobjectreturnc。LOADSCREENdefupdate(self,surface,keys,currenttime):Updatestheloadingscreenif(currenttimeself。starttime)2400:surface。fill(c。BLACK)self。overheadinfo。update(self。gameinfo)self。overheadinfo。draw(surface)elif(currenttimeself。starttime)2600:surface。fill(c。BLACK)elif(currenttimeself。starttime)2635:surface。fill((106,150,252))else:self。doneTrueclassGameOver(LoadScreen):AloadingscreenwithGameOverdefinit(self):super(GameOver,self)。init()defsetnextstate(self):Setsnextstatereturnc。MAINMENUdefsetoverheadinfostate(self):setsthestatetosendtotheoverheadinfoobjectreturnc。GAMEOVERdefupdate(self,surface,keys,currenttime):self。currenttimecurrenttimeself。soundmanager。update(self。persist,None)if(self。currenttimeself。starttime)7000:surface。fill(c。BLACK)self。overheadinfo。update(self。gameinfo)self。overheadinfo。draw(surface)elif(self。currenttimeself。starttime)7200:surface。fill(c。BLACK)elif(self。currenttimeself。starttime)7235:surface。fill((106,150,252))else:self。doneTrueclassTimeOut(LoadScreen):LoadingScreenwithTimeOutdefinit(self):super(TimeOut,self)。init()defsetnextstate(self):Setsnextstateifself。persist〔c。LIVES〕0:returnc。GAMEOVERelse:returnc。LOADSCREENdefsetoverheadinfostate(self):Setsthestatetosendtotheoverheadinfoobjectreturnc。TIMEOUTdefupdate(self,surface,keys,currenttime):self。currenttimecurrenttimeif(self。currenttimeself。starttime)2400:surface。fill(c。BLACK)self。overheadinfo。update(self。gameinfo)self。overheadinfo。draw(surface)else:self。doneTrue4。设置游戏内菜单等(mainmenu)importpygameaspgfrom。。importsetup,toolsfrom。。importconstantsascfrom。。componentsimportinfo,marioclassMenu(tools。State):definit(self):Initializesthestatetools。State。init(self)persist{c。COINTOTAL:0,c。SCORE:0,c。LIVES:3,c。TOPSCORE:0,c。CURRENTTIME:0。0,c。LEVELSTATE:None,c。CAMERASTARTX:0,c。MARIODEAD:False}self。startup(0。0,persist)defstartup(self,currenttime,persist):Calledeverytimethegamesstatebecomesthisone。Initializescertainvaluesself。nextc。LOADSCREENself。persistpersistself。gameinfopersistself。overheadinfoinfo。OverheadInfo(self。gameinfo,c。MAINMENU)self。spritesheetsetup。GFX〔titlescreen〕self。setupbackground()self。setupmario()self。setupcursor()defsetupcursor(self):Createsthemushroomcursortoselect1or2playergameself。cursorpg。sprite。Sprite()dest(220,358)self。cursor。image,self。cursor。rectself。getimage(24,160,8,8,dest,setup。GFX〔itemobjects〕)self。cursor。statec。PLAYER1defsetupmario(self):PlacesMarioatthebeginningofthelevelself。mariomario。Mario()self。mario。rect。x110self。mario。rect。bottomc。GROUNDHEIGHTdefsetupbackground(self):Setupthebackgroundimagetoblitself。backgroundsetup。GFX〔level1〕self。backgroundrectself。background。getrect()self。backgroundpg。transform。scale(self。background,(int(self。backgroundrect。widthc。BACKGROUNDMULTIPLER),int(self。backgroundrect。heightc。BACKGROUNDMULTIPLER)))self。viewportsetup。SCREEN。getrect(bottomsetup。SCREENRECT。bottom)self。imagedict{}self。imagedict〔GAMENAMEBOX〕self。getimage(1,60,176,88,(170,100),setup。GFX〔titlescreen〕)defgetimage(self,x,y,width,height,dest,spritesheet):Returnsimagesandrectstoblitontothescreenimagepg。Surface(〔width,height〕)rectimage。getrect()image。blit(spritesheet,(0,0),(x,y,width,height))ifspritesheetsetup。GFX〔titlescreen〕:image。setcolorkey((255,0,220))imagepg。transform。scale(image,(int(rect。widthc。SIZEMULTIPLIER),int(rect。heightc。SIZEMULTIPLIER)))else:image。setcolorkey(c。BLACK)imagepg。transform。scale(image,(int(rect。width3),int(rect。height3)))rectimage。getrect()rect。xdest〔0〕rect。ydest〔1〕return(image,rect)defupdate(self,surface,keys,currenttime):Updatesthestateeveryrefreshself。currenttimecurrenttimeself。gameinfo〔c。CURRENTTIME〕self。currenttimeself。updatecursor(keys)self。overheadinfo。update(self。gameinfo)surface。blit(self。background,self。viewport,self。viewport)surface。blit(self。imagedict〔GAMENAMEBOX〕〔0〕,self。imagedict〔GAMENAMEBOX〕〔1〕)surface。blit(self。mario。image,self。mario。rect)surface。blit(self。cursor。image,self。cursor。rect)self。overheadinfo。draw(surface)defupdatecursor(self,keys):Updatethepositionofthecursorinputlist〔pg。KRETURN,pg。Ka,pg。Ks〕ifself。cursor。statec。PLAYER1:self。cursor。rect。y358ifkeys〔pg。KDOWN〕:self。cursor。statec。PLAYER2forinputininputlist:ifkeys〔input〕:self。resetgameinfo()self。doneTrueelifself。cursor。statec。PLAYER2:self。cursor。rect。y403ifkeys〔pg。KUP〕:self。cursor。statec。PLAYER1defresetgameinfo(self):ResetsthegameinfoincaseofaGameOverandrestartself。gameinfo〔c。COINTOTAL〕0self。gameinfo〔c。SCORE〕0self。gameinfo〔c。LIVES〕3self。gameinfo〔c。CURRENTTIME〕0。0self。gameinfo〔c。LEVELSTATE〕Noneself。persistself。gameinfo5。main()from。importsetup,toolsfrom。statesimportmainmenu,loadscreen,level1from。importconstantsascdefmain():Addstatestocontrolhere。runittools。Control(setup。ORIGINALCAPTION)statedict{c。MAINMENU:mainmenu。Menu(),c。LOADSCREEN:loadscreen。LoadScreen(),c。TIMEOUT:loadscreen。TimeOut(),c。GAMEOVER:loadscreen。GameOver(),c。LEVEL1:level1。Level1()}runit。setupstates(statedict,c。MAINMENU)runit。main()6。调用以上函数实现importsysimportpygameaspgfrom小ahrefhttps:www。q578。coml60targetblankclassinfotextkey游戏a。超级玛丽。data。mainimportmainimportcProfileifnamemain:main()pg。quit()sys。exit()