??====================================Author:YoungwookKim(Korean)========================================================================Contact:rumia0601@gmail.com========================================================================BasicTEMPLATEandOUTPUT======================================================================== IntoEvent-drivenandGUI====================================AsIsaid,PygameisbasedonGUIenvironment.Furthermore,Pygameisgoodformaking2Dgamebecauseofitsinput/outputformat.So,youhavetosaygood-byeforprintorinputstandardfunctionofPython(BecausetheyworkonlyonCUIenvironment).Then,whatfunctionsinPygamereplacethesefunctions?First,wehavetogobacktofriendly

HelloWorld!

project,whichislearningaboutbasictemplateandoutput.**(Requiringanyfontfile(.ttf)inthesameprojectdirectory)**

..image::Basic-ouput-sourcecode.png:class:inlined-right..code-block::python:linenos:importsys,pygamepygame.init()size=width,height=220,140speed=[2,2]black=0,0,0screen=pygame.display.set_mode(size)ball=pygame.image.load("Basic-ouput-sourcecode.png")ballrect=ball.get_rect()while1:foreventinpygame.event.get():ifevent.type==pygame.QUIT:sys.exit()ballrect=ballrect.move(speed)ifballrect.left<0orballrect.right>width:speed[0]=-speed[0]ifballrect.top<0orballrect.bottom>height:speed[1]=-speed[1]screen.fill(black)screen.blit(ball,ballrect)pygame.display.flip()..image::Bagic-ouput-result-screen.png:class:inlined-right..code-block::python:linenos:importsys,pygamepygame.init()size=width,height=220,140speed=[2,2]black=0,0,0screen=pygame.display.set_mode(size)ball=pygame.image.load("Bagic-ouput-result-screen.png")ballrect=ball.get_rect()while1:foreventinpygame.event.get():ifevent.type==pygame.QUIT:sys.exit()ballrect=ballrect.move(speed)ifballrect.left<0orballrect.right>width:speed[0]=-speed[0]ifballrect.top<0orballrect.bottom>height:speed[1]=-speed[1]screen.fill(black)screen.blit(ball,ballrect)pygame.display.flip()(SourceCodeforHelloWorldProjectanditsresultscreen)Wow,it scomplicatedincomparetopython sprint(

HelloWorld)(Justasinglelinecommand).It sbecausetextinGUIenvironmenthas5components:textcontents,font,size,colorandlocation.Ifyouwanttoprintanytextintoscreen,youhavetosetother4components,notonlystring(unlesswhenitisinGUIenvironment).Only``pygame.display.set_caption(HelloWorldProject)``functionin#7dothesamefunctionaspython sprint(HelloWorldProject).Theonlydifferenceisthatoutputstringisalwaysonwindowcaption(titleofcurrentprogram)

First,lookatthetemplateofsourcecodebeforeunderstandinghowtooutputsomething,sourcecodecanbedivedinto4sections:Header(#1-#2),Initialstatement(#3-#12),Alwaysstatement(#13-#20)andEventstatement(#16-#19).In**Header**,importingmoduleswillbeexecuted.``importpygame,sys``isalwaysneeded.Needlesstosay,becausethisispygameprojectandgamehastobeterminatedwhenplayerwanttoexit(``sys.exit()``at#19).``frompygame.localsimport*``isalsonecessarytouseusefulconstantsjustlike``QUIT``at#17.In**Initialstatement**(commandsbeforeinfiniteloop),someglobalvalueswillbeinitializedandsomefunctionswillbecalledforonetime.Globalvaluesjustlikecolorshastobeinitializedhereinordertoincreasereadability.Remember,thisisGUIwhichiscolorful.Colorhasthreecomponents:red,greenandblue.So,colorvaluehastobeinitializedjustlike``red=(255,0,0)``.Functionnamed``pygame.init()``mustbecalledprecedingtootherpygamefunctions.Thenotherpygamefunctionscanbeexecuted.(Otherpygamefunctionswillbeexplainedlater.)In**Alwaysstatement**(commandswithininfiniteloop),someglobalvalueswillbeupdatedroutinelyandsomefunctionswillbecalledroutinelyunlesstheyareenclosedintoconditionalstatement.Functionnamed``pygame.display.update()``shouldbecalledaftereveryprocessesaredone.Becausethisfunctionisprintingtheresultsofprocessesontoscreen(=monitor).IfthisfunctionisnotexecutedinthelastpartofAlwaysstatement,therewillbeaprobabilitythatcurrentscreenandinternaldatadoesnotmatch.(Otherpygamefunctionswillbeexplainedlater.)In**Eventstatement**(commandswithinloopwhichcheckeverypossibleevents),therewillbesuitableconditionalstatementswhencertaineventistriggered.``pygame.event.get()``functionreturnsalistofeventsoccurredbyprocessesinAlwaysstatement.Andthislistisautomaticallyarrangedbytime(oldesttonewest).So,usingfor-instatement,everytriggeredeventcausedbyAlwaysstatementcanberesolvedprocedurally.(Remindthatthisisthetraitofevent-driven.)Forexample,commandsin#17-#19willdealwithQUITevent.Inthiscase,pygamewillbeterminatedthensystemwillbeterminatedbecausesystemmustbeterminatedafterpygameisterminated!(Othereventswillbeexplainedlater.)Regardingthistemplateisfixed,thenwecanaddspecialfunctionsincorrectplacetoprint

HelloWorld!.First,weneedtoset**font**and**size**.``pygame.font.Font(HoonWhiteCatR,ttf,32)``functionat#9willsetnotonlyfontbyttffilebutalsosize(32).Returnvalueofthisfunctionneedtobestoredintoobject(=myTextFont).ThenmemberfunctionofmyTextFontnamed``render(HelloWorld!,True,red,green)``at#10willreturnavalue(=myText).renderfunctioncanset**textcontents**and**color**(rediscoloroftext,greeniscolorofareaoutsideoftext).ThenmemberfunctionofmyTextnamed``get_rect()``at#11willreturnavalue(=myTextArea).myTextAreameanstheareaallocatedforprintingtext.Whenget_rect()iscalled,arectangleareaisreturnedcorrespondingtotext slengthandfontsize.Now,allwehavetodoislocatingthisareasomewhere.IfwechangemembervalueofmyTextAreanamed``center``at#12intocenterofscreen,thenthetext scenter**location**willbecenterofthescreen.

Buthowtodeterminewhereisthecenterofscreen?First,wehavetodecidetherangeofscreen,byusing``pygame.display.set_mode((640,480))``in#8,canvas(whereallvalueswhichhassize,color,positionwillbedrawnwhendisplay.updateiscalled)willbegeneratedanditssizebecomes640x480.Then,itscenterisexactly(320,240).Ifthetotalsizeisgiven,wecandecideanypositionevenaccountingsomemarginwithlittlecalculation(Remindthatin2DGUI,everythinghasxandywhichhastobeprinted)(Justliketurtlegraphic,ifitgoes**right,xincreases**,ifitgoes**down**,**yincrease**.Don tconfused!).AndweknowthatallfunctionsImentionedwillbeputtedintoInitialstatement,becausethisinformationarefixedwhiletheprogramgoon.Althougheverythingisfixed,wehavetodesignthatfillandblitfunctionstobeputtedintoAlwaysstatement,becauseofthesefunctions trait.``fill(white)``functionin#14meansfillingcanvasbysinglecolor(white).``blit(myText,myTextArea)``functionin#15meansdrawingspecificobject(=myText)onspecificlocation(=myTextArea)ofcanvas.Noticethatdrawing(blit)hastobedoneafterfilling(fill).Wheneverythingisdrawnoncanvas,resultofcanvaswillbedisplayontowindowwhendisplay.updateisexecuted.Thatwastheexplanationoftheentiresourcecode,whichhas20lines.Itseemsittakestoomuchtimetounderstandsourcecodewithonly20lines.However,addingorchangingfromthissourcecodeisnotthathardbecauseweunderstandthetemplateofthissourcecodeandstepofprinting.Whataboutaddingprocesslogicinthissourcecode?Thatwillbenextproject.<ReferenceCode>::importpygame,sys#1frompygame.localsimport*#2white=(255,255,255)#3red=(255,0,0)#4green=(0,255,0)#5pygame.init()#6pygame.display.set_caption("HelloWorldProject")#7myScreen=pygame.display.set_mode((640,480))#8myTextFont=pygame.font.Font("HoonWhitecatR.ttf",32)#9myText=myTextFont.render("HelloWorld!",True,red,green)#10myTextArea=myText.get_rect()#11myTextArea.center=(320,240)#12whileTrue:#13myScreen.fill(white)#14myScreen.blit(myText,myTextArea)#15foreventinpygame.event.get():#16ifevent.type==QUIT:#17pygame.quit()#18sys.exit()#19pygame.display.update()#20




Edit on GitHub