Tải bản đầy đủ - 0 (trang)
Chapter 4. Introducing the LlamaWorks2D Game Engine

Chapter 4. Introducing the LlamaWorks2D Game Engine

Tải bản đầy đủ - 0trang

AStep-by-StepOverview

ImentionedinpreviouschaptersthatwhenIstartedinto

graphicsprogramming,youhadtodoeverythingyourself.

WhengraphicslibrariessuchasOpenGLwerereleased,it

helpedalot.However,ifyoueverattempttowriteanOpenGL

programwithoutLlamaWorks2D,you'llquicklydiscoverone

thing:therearelotsofwaystogetablankscreen.It'svery

easytospendmanyfrustratedhourstryingtofigureoutwhy

you'renotseeinganythingbutanemptyscreen.Beenthere,

donethat,gotthet-shirt.

ThegreatthingaboutLlamaWorks2Disthatit'sincrediblyeasy

touse.Idesignedittomakegameprogrammingassimpleas

possible.Whenyou'restartingout,youcanignorealmost

everythingabouttheengineandyou'llstillgetadecentresult.

Itiswrittensothatitprovidesareasonabledefaultvaluefor

virtuallyeverything.Therefore,youcanoftenavoidspecifying

informationthattheengineneedsbecauseanythingyoudon't

specifyusesthedefaultvalue.Andwhenyouusethedefault

values,youshouldstillseesomethingreasonableonthe

screen.

TowriteaLlamaWorks2Dprogramyoumustcreateaprojectin

Dev-C++,configureitappropriately,andthenstartwritingyour

gamecode.Inyourgamecode,you'vegottocreateasoftware

objectcalledagameclass.Thegameclassrequiressome

importantinformation,butLlamaWorks2Dprovides

straightforwardwaysofspecifyingit.Typically,anOpenGLor

DirectXprogramrequiresthatyouwritehundredsoflinesof

codebeforeyoucanevengetaworking,butempty,windowon

thescreen.WithLlamaWorks2D,youcandothatinfewerthan

20linesofcode.Let'sseehow.



Phase1:CreateaDev-C++Project



It'stimetocreatetheprojectthatwillbecomeyourfirst

LlamaWorks2Dprogram.Here'showit'sdone.



CreateaProjectFileandAdda.CppFiletoIt.

1. InyourMyDocumentsfolder,createafoldercalledDevc++projects.

2. IntheDev-C++Projectsfolder,createafoldercalled

Simplegame.

3. InserttheCDthatcomeswiththisbook.Navigatetothe

folder:\Source\Chapter04\Prog_04_01,whereis

theletterofyourCD-ROMdrive.Inthatfolder,you'llfinda

filecalledProg_04_01.cpp.CopyittotheSimpleGame

folderyoucreatedinstep2.

4. StartDev-C++ifitisnotalreadyrunning.FromtheFile

menu,selectNewandthenProject.

5. IntheNewProjectdialogbox,clickontheWindows

Applicationicon.

6. EnterthenamesimplegameintheNameeditbox.Make

surethattheC++Projectradiobuttonisselected.Click

OK.

7. Inthedialogboxthatappears,navigatetothe

SimpleGamefolderyoucreatedinstep2.ClickSave.

8. Right-clickthemain.cpptabatthetopoftheeditwindow.

Inthemenuthatappears,chooseClose,andthenselect

Nointhedialogbox.



9. Right-clickthenameSimpleGameintheProjectpanethat

isalongtheleftsideoftheDev-C++window.ChooseAdd

toProject.

10. Inthedialogboxthatappears,findtheSimpleGamefolder

thatyoucreatedinStep2.Whenyoudo,selectthefile

Prog_04_01.cpp.NowclicktheOpenbutton.Thisaddsthe

filetotheproject.



That'sallittakestocreatetheproject.



Phase2:ConfiguretheDev-C++Project

Thenexttaskistoconfigureyourprojectsothatyoucanuseit

withLlamaWorks2DandOpenGL.WhenyouinstalledDev-C++

andOpenGLinchapter2,youhopefullyconfiguredDev-C++to

useOpenGLinallofyourprograms.Checktoensurethat's

donewiththefollowinginstructions.



EnsurethatDev-C++isReadytoUseOpenGL.

1. FromtheDev-C++Toolsmenu,selectCompilerOptions.

2. Ensurethatthereisacheckinthecheckboxthat'slabeled

"Addthesecommandstothelinkercommandline".Ifthe

checkisn'tthere,additnow.

3. Intheeditboxassociatedwiththe"Addthesecommandsto

thelinkercommandline"checkbox,addthefollowing

commandifitisnottherealready:

:\Dev-Cpp\lib\libopengl32.a



Replacetheinthiscommandwiththeletterofthedrive

whereyouinstalledDev-C++.ThisisusuallytheCdrive.If

that'sthecaseonyourcomputer,thecommandshouldread

C:\Dev-Cpp\lib\libopengl32.a

4. Clearthecheckfromtheboxlabeled"Usefastbutimperfect

dependencygeneration".ClickOK.



You'renowreadytouseOpenGL.

YoualsohavetoconfigureyourprojecttouseLlamaWorks2D.

IntheIntroduction,theinstructionshadyouinstall

LlamaWorks2DintoafolderinyourDev-C++program

directory.Ifyoudidnotdothat,pleasedoitnowusingthe

instructionsfromtheIntroductioninthesectioncalled

"InstallingLlamaWorks2D."Oncethat'sdone,youcanconfigure

yourprojecttouseLlamaWorks2D.



Warning

SettingDev-C++toalwayslinktotheOpenGL

librarymakesthingsmucheasierforthepurposesof

thisbook.However,ifyouwanttouseDev-C++to

developprogramsthatdonotuseOpenGL,youmust

unchecktheboxyoucheckedinStep2andremove

thecommandyouinsertedinStep3.



PutLlamaWorks2DIntoYourProgram.



1. UseWindowsExplorertocopytheLlamaWorks2Dfilesinto

theSimpleGamefolder.Ifyoufollowedtheinstructionsin

theIntroduction,itwillbeinyourDev-Cppfolder,whichis

probablyonyourCdrive.Thewholepathwillbe:\DevCpp\LlamaWorks2D\Source,whereistheletterofthe

drivewhereyourDev-Cppfolderresides.

2. AfteryoucopyalltheLlamaWorks2Dfilesintothe

SimpleGamefolder,right-clicktheprojectnameinthe

Projectpane.SelectAddfolderfromthemenuthatappears.

Intheresultingdialogbox,typellamaworks2dandthan

clickOK.

3. Right-clicktheLlamaWorks2DfolderintheProjectpane,and

chooseAddtoProjectfromthecontextmenu.Inthedialog

boxthatappears,navigatetotheSimpleGamefolder.Select

alloftheLlamaWorks2DfilesthatyoucopiedinStep1.Click

Open.

4. Right-clicktheprojectname(SimpleGame)intheProject

paneandselectProjectOptionsfromthecontextmenu.

5. IntheProjectOptionsdialogbox,clicktheDirectoriestab.

OntheDirectoriespage,clicktheIncludeDirectoriestab.In

thelower,single-lineeditbox,typethepathtoyour

LlamaWorks2D\Sourcedirectory.Mostlikely,thepathwillbe

C:\Dev-Cpp\LlamaWorks2D\Source.ClicktheAddbutton

andthenclickOK.



YourDev-C++projectisready.Nowlet'swriteaLlamaWorks2D

program.



Phase3:WriteaGameClass



TostartwritingagamewithLlamaWorks2D,youmustcreatea

gameclass.Writingagameclassisessentiallylikewritingany

otherC++class.Gameclasseshavepublicmemberfunctions

andprivatememberdata.Theyalsorequiresomeadditional

featuresthattypicalC++classesmaynothave.

I'veprovidedafile,calledProg_04_01.cpp,thatcontainsa

minimalgameclass.It'sontheCDinthefolder

\Source\Chapter04\Prog_04_01.Youaddedittoyourprojectin

Phase1.Listing4.1showsitscontents.



Listing4.1.ThesmallestpossibleLlamaWorks2D

program



1#include"LlamaWorks2d.h"

2

3usingnamespacellamaworks2d;

4

5classmy_game:publicgame

6{

7public:

8ATTACH_MESSAGE_MAP;

9private:

10};

11

12

13CREATE_GAME_OBJECT(my_game);

14

15START_MESSAGE_MAP(my_game)

16END_MESSAGE_MAP(my_game)



ThefileProg_04_01.cppbeginsbyincludingthefile

LlamaWorks2D.h.Recallfromchapter2that#includestatements

areawayofprovidingthecompilerwiththedefinitionsthat

yourprogramneedstocompile.ThefileLlamaWorks2D.hisa

kindof"ultimateincludefile"intheLlamaWorks2Dgame

engine.Allofthefilesyoucreateforyourgamesmustinclude

LlamaWorks2D.h.Soyoushouldputthestatementyouseeon



line1ofListing4.1atthebeginningofallyourC++sourcefiles

inyourgames.



Factoid

Programmershaveacoupleofdifferentnamesfor

filestheyusewith#includestatements.They'llrefer

tothemaseitherincludefilesorheaderfiles.



Thestatementonline3mustalsobepresenttousethe

LlamaWorks2Dgameengine.Backinchapter3,yousawthat

namespaceshelpgrouptypes,functions,andsoforthinto

relatedcollections.EverythingtheLlamaWorks2Dgameengine

providesisinthellamaworks2dnamespace.Theusingstatement

online3savesyoufromhavingtoputllamaworks2d::atthe

beginningofeveryvariabledeclarationinyourprogram.

Thedefinitionofthegameclassitselfbeginsonline5.Noticeat

theendofthelinethatthere'sacolon,followedbytheC++

keywordpublic,followedbythenamegame.I'llexplainexactly

whatallthatmeansinchapter6,"Inheritance:GettingaLotfor

aLittle."Fornow,justknowthatit'srequiredinyourgame

classdefinition.

Thestatementonline8isaspecialmarkercalledamacro.

WhatitdoesiscopyawholebunchofC++sourcecodeinto

yourgameclassforyou.Thesourcecodethismacroinsertsis

partoftheLlamaWorks2Dengine.Itaddsamessagemapto

yourgameclass.Amessagemapisatechniqueforassigning

specificfunctionstohandleplayerinput.Messagemapsare

widelyusedinalltypesofprograms.(Messagemapsare

presentedinmoredetailinchapter7,"GameProgram

Structure.")Everygameclassmusthaveamessagemap.It

doesnotmatterwhetheryourLlamaWorks2Dprogramactually



acceptsplayerinput.Infact,theprograminListing4.1ignores

allplayerinput.Evenso,thegameclassinListing4.1must

havethestatementshownonline8oritwillnotcompile.

InadditiontoATTACH_MESSAGE_MAP,LlamaWorks2Dalsoprovides

youwithothermacrosthatinsertalotofsourcecodeintoyour

game.Thissimplifiesyourlifebysavingyoufromhavingto

writelargeamountsofcodeyourself.Line13ofListing4.1uses

amacrotocreateanobjectfromyourgameclass.Recallthat

classesdefinewhatobjectscontain,butyoudon'thavean

objectuntilyoudeclareavariable.Themacroonline13creates

avariableoftypemy_game.



Warning

IfyouforgettheATTACH_MESSAGE_MAP;statementinyour

gameclass,thecompileroutputsanerrortellingyou

thatthefunctionProcessInputMessageMap()isnota

memberofyourgameclass.Ifyouseethiserror,

youknowyouaremissingtheATTACH_MESSAGE_MAP;

statementinyourgameclass.



Ifyouchangethenameofyourgameclasstosomethingother

thanmy_game,youneedtoputthatnamewithintheparentheses

oftheCREATE_GAME_OBJECT()macro;ithastocontainthetypename

ofyourgameclass.Inaddition,thismacromustalwaysappear

rightafterthedefinitionofyourgameclass.

Themacrosyouseeonlines15and16markthebeginningand

endingofthegameclass'smessagemap.AsImentioned,the

messagemapdoesnothingatthispoint.However,itmustbe

presentforyourgametocompile.



Warning



Ifthecompileroutputsanerrorstatingthatit

cannotfindthefunctionCreateGameObject(),youdidnot

puttheCREATE_GAME_OBJECT()macroinyourprogram.If

ittellsyouthatitcannotfindthefunction

ProcessInputMessageMap(),youdon'thavethe

START_MESSAGE_MAP()macroinyourprogram.Whenever

thecompilertellsyouthatitfoundthebeginningof

anotherfunctionbeforetheendof

ProcessInputMessageMap(),thatmeansyouleftoutthe

END_MESSAGE_MAP()macro.



Phase4:CompileandRuntheProgram

Nowcomestheeasypart.Ifyou'vedoneeverythingcorrectly,

allyouhavetodoispressF9orselectCompile&Runfromthe

Dev-C++Executemenu.Assumingallgoeswell,you'llseea

nicebluewindowthatcoversmostofyourscreen.PressAlt+F4

tocloseit.

Thatbluewindowmaynotseemlikemuch,butithidesalot

thatisgoingbehindthescenes.Thegameengineinitialized

WindowsandOpenGLforyou.Itsizedandpositionedtothe

window,andsetitsbackgroundcolor.Whileyougazeintothe

window'srelaxingblueness,thegameengineisdisplayinglots

andlotsofemptyframespersecond.It'scheckingforplayer

input,eventhoughitdoesn'tdoanythingwiththeinput.Itsits

patientlywaitingforyoutoaddyouruniqueanddazzlinggame

elementssothatitcandisplaythem.Notbadforjust16lines

ofcode.



HowDoesLlamaworks2DWork?

LlamaWorks2Disbuiltaroundobjects.RememberhowIsaidin

chapter3thatobjectscouldrepresentanything?LlamaWorks2D

usesthatabilitytohidemanyofthemundanetasksofgame

programmingfromyou.That'sagoodthing.Thetasksithides

fromyouaretheonesthatarenotdirectlyrelatedtomaking

games.They'reallaboutWindowsandOpenGL.

LlamaWorks2Dusesanapplicationobjectandagameobjectto

domostofitswork.Theapplicationobjectrepresentsthe

programitself.Thegameobjectisyourgameclassthatyou

sawbackinListing4.1Figure4.1illustrateshowtheseobjects

work.



Figure4.1.ThedesignofLlamaWorks2D.



Warning

Whenyoufollowtheinstructionspresentedhereto

createandcompileyourprogram,thecompiler

namestheprogramSimpleGame.exe.OntheCD,

I'veprovidedacompiledversionofthisprogram.

However,it'scalledProg_04_01.exeIdidthatto



makeiteasiertofigureoutwhichprogramgoeswith

whichexample.Whenyou'rewritinggames,the

nameofyourgame'sexecutablefileshouldbe

somethingthatresemblesthenameofthegame.



ThegameobjectinFigure4.1representstheportionofthe

programthatisyourgame.Whenyouwriteagamewith

LlamaWorks2D,youputallofyourgame'sdataandallofthe

functionsthatmakeyourgameoperateintoyourgameclass.

Notethatyoucanalsodefineotherclassesthatyourgame

classuses.Butthecodethatdefineswhatyourgameisand

howitworksgoesintothegameclass.Ofalltheobjectsin

Figure4.1,thegameclassistheonlyoneyouwrite.

LlamaWorks2Dprovidesyouwiththemessageobjects,sprite

objects(I'llexplainspriteobjectslaterinthischapterwhenwe

createastationaryball),andtheapplicationobject.

Byusinganapplicationobjectandagameobject,youensure

thatyourgamecodeisseparatedfromthecodethatmakesthe

overallprogramrun.Thatmeansyoudon'thavetobotherwith

thecodethatgetsWindowsandOpenGLupandrunning.You

don'thavetoknowalloftheinsandoutsofhandlinguserinput

(therearemany).Figure4.1showsthatplayerinputcomesinto

theapplicationobject,whichpackagesthatinputasmessage

objectsthatyourgamecanhandlefairlyeasily.



Note

Youmaybewonderingwhetheryoushouldlearn

howtoinitializeWindowsandOpenGLyourself.The

answerisyes,butnotnow.Whenyoufeellike

you'reaproficientC++programmer,feelfreetogo

throughthesourcecodeforLlamaWorks2D.Itwill

helpyoulearnbothWindowsandOpenGL



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 4. Introducing the LlamaWorks2D Game Engine

Tải bản đầy đủ ngay(0 tr)

×