How to create a mazepart 1 of 2Word文档格式.docx

上传人:b****2 文档编号:3417374 上传时间:2023-05-01 格式:DOCX 页数:25 大小:28.63KB
下载 相关 举报
How to create a mazepart 1 of 2Word文档格式.docx_第1页
第1页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第2页
第2页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第3页
第3页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第4页
第4页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第5页
第5页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第6页
第6页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第7页
第7页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第8页
第8页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第9页
第9页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第10页
第10页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第11页
第11页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第12页
第12页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第13页
第13页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第14页
第14页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第15页
第15页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第16页
第16页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第17页
第17页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第18页
第18页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第19页
第19页 / 共25页
How to create a mazepart 1 of 2Word文档格式.docx_第20页
第20页 / 共25页
亲,该文档总共25页,到这儿已超出免费预览范围,如果喜欢就下载吧!
下载资源
资源描述

How to create a mazepart 1 of 2Word文档格式.docx

《How to create a mazepart 1 of 2Word文档格式.docx》由会员分享,可在线阅读,更多相关《How to create a mazepart 1 of 2Word文档格式.docx(25页珍藏版)》请在冰点文库上搜索。

How to create a mazepart 1 of 2Word文档格式.docx

∙thenitstartsthemainalgorithm

∙afterthealgorithmfinishedit’sworkitrunsthedraw_maze()procedurethattranslatestheseriesofnumbersintoapictureofthemaze.

∙finallythemazeisshowedonscreenandtheprogramwaitsfor‘esc’tobepressed.

∙afterthe‘esc’beingpressedtheprogramde-initializes,meaningitclearsallthegraphicstuffanddeletesthemaze(freesthememory)

Thedrawingprocedureworkslikethis:

∙itscansthemazearrayandputsacoloredsquareforeachnumberinthatarray(forexample:

yellowforzero[floor],grayforone[wall]).Eventuallyyoucanaddmorenumbersandmorecolors(thiswillbeusefulforthemazesolvingalgorithmlater)

∙optionallyyoucanalsoaddanothersmallersquarethatwillbedrawnonthepositiongivenasanargumentofthefunction(thisisusefulfordeterminingthepositionoftheplayerinthemazegame;

I’llexplainitlater)

Nowforthealgorithm:

∙themainalgorithmstartsbycleaningthemazearray(fromallthetrashitmaycontain).Italsodrawstheouterwalls.

∙nextitsearchestherandomstartandgoalpositions.Theyareleveledtohaveequaloddsontheirrandomness,butcanonlybeplacedoncoordinatesthatconsistofoddnumbers(I’llexplainthislater).

∙nowtherealalgorithmstarts.Firstitfindsarandomlegalmoveandmakesit(movesthepositioncoordinatetothatplace,setsthecelltofloorandsetsthewallsbehindthatcell)

∙thenitenterstheloopwhichitrepeatsuntilthecountertellshimhefilledthewholemap(thecounterisalwaysright)

∙itfindsthenextlegalrandommoveandifsuchexistsherepeatsthewholeprocedure(movepos.,setfloor,setwalls)

∙ifnolegalmovefounditmakesabackstepandkeepstracingbackuntilitfindsanemptyspacetwocellsawayfromtheoneheiscurrentlypointingto(inotherwords,anemptycelloverthewall)

∙ifhefindssuchacellhemovesthepositioncoordonthewallseparatinghimfromthatcellandturnsittoafloor.Thenormalloopiscontinued.

Explainingthecode:

Toexplainthefirstpartofthetutorial,wearegoingtousethefilecalledmazefull.cpp(thiswasmyfinalresultofseveralattemptstocreatetheprogram).Firstlet’sexplaintheincludedfiles(usingthe#includedirective):

∙iostream.h-thisistheC++versionofstdio.h.Inmyprogram,itisusedtoprinterrormessages(forfurtherdetailschecksome‘iostream’andfileI/Otutorials).NOTE:

ifIweretorunthisprogramasitis(withonlythebasicarguments)theseerrormessageswouldbeprintedoutonscreen.Iuseasimplestreamre-directionbyadding“>

>

log.txt”aftertheprogramname,makingitprintoutitsmessagestoatextfile.Idon’tknowwheredoesthismethodoriginatefrom,butIsawitworkonLinuxsoItriedinDOSanditalsoworked…

∙allegro.h-thisistheheaderofthegraphicslibraryIintendtouseduringthistutorial.Itwillbeusedontwooccasionsinthefirstprogram:

uponinitializationofthegraphicsandinthedrawingprocedurecalleddraw_maze()…Ifyoure-implementthesetwopartsofthecodetoanotherlibrary,youmaycomment-out(orevendelete)boththisdirectiveandpartsofthecodeyou’vereplaced.

∙stdlib.h-neededforrandomnumbergeneratorandintegertoASCIIandviceversaconversions(srandom(),random(),itoa(),atoi()).

∙time.h-alsoneededforrandomnumbers.

Alsoonthebeginningofthefileweseethedirectivesthatdefinethemaximumscreenresolution(ifyouareusingWin2korWinNtandcompilethisinAllegro,changethisto320×

200soAllegrocouldchosestandardVGAdrivers,asWin2kandWinNtdon’tsupportVesa).Wealsoseedefinitionsof“floor”and“wall”whichmakesourprogrameasiertoread(thechararrayisfilledonlywithnumbers,1and0).Thefirstpartofthefilelookslikethis:

#include

//resolution:

#definemaxx1024

#definemaxy768

#definewall1//intvalueofwallonmap

#definefloor0//intvalueofflooronmap

Thenextpartoftheprogramisadefinitionofaclasscalled“coord”.Forthosethatdon’tknow,aclassisaspecialstructurethatletsusdefineavariablethatholdsseveralothervariablesandfunctionsthatchangethesevariables(socalled“member”variablesandfunctions).FordetaileddescriptionofclassesIrecommendreadingatutorial,becauseclassesaresomethingeveryintermediateprogrammershouldknowinsideout.Toaccessthesevariables-inside-variableswewillfirsthavetocreatetheso-calledobject(definedasimplevariable,butusingthatclassasthetype;

that’swhythattypeofprogrammingiscalledObjectOrientedprogramming)andaccessitsmembersbywritingthemafteradot,whichisafterthenameoftheobject.Likeso:

coordCoordinateA;

//defininganobject

CoordinateA.x=0;

//accesingthemembervariable"

x"

CoordinateA.ret(0,-1);

//accesingthememberfunction"

ret()"

Thecoordinateclassisveryuseful,causenotonlydoesitholdtwodifferentcoordinates(whichpreventsusfordefininguglyvariableslike:

intpos_x,pos_y),butitalsoprovidesacoupleofveryusefulfunctionsforconversionandautomationofthevaluesofthosevariables.Thismakesourcodemorelogicalandmuchmorereadable.Thefulldefinitionoftheclassisasfollows:

//Coordinateclass.Hasxandycoordinatesandsomehelperfunctions..

classcoord

{

public:

intx,

y;

coord():

x(0),y(0){}//emptyconstructor(usedtoshowaNULLcoordinate)

coord(inta,intb):

x(a),y(b){}//integerconstructor

coord(constcoord&

c)//copyconstructor

x=c.x;

y=c.y;

}

~coord(){}//emptydestructor

voidsetW(char*maze,intn)//setsacoordinagivenmazetowall

{maze[x*n+y]=wall;

}

voidsetF(char*maze,intn)//setsacoordinagivenmazetofloor

{maze[x*n+y]=floor;

coordret(intx_of,inty_of)//returnsacoordinateaftervectorchange

{returncoord(x+x_of,y+y_of);

intm_pos(intn)//returnstecoord.asanindexinthemaze

{returnx*n+y;

operatorint()//intconverter(usedtodetermineNULLcoordinates)

{returnint(x+y);

};

//Somesmallhelperfunctions:

intoperator!

=(coorda,coordb)//unequaloperatorforcoordiates

return(a.x==b.x&

&

a.y==b.y)?

0:

1;

intoperator==(coorda,coordb)//equaloperatorforcoordinates

1:

0;

Ihaveaddedthefirsttwohelperfunctionsonpurpose,becausetheyareoperatorsthatoperateontheobjectoftype“coord”(whichisourclass).Letmeexplaintheclassnow.Aswecanseeitscontentsareprettystraightforward.Allthemembersarepublic,whichmeansthattheycanbeaccessedfromanypartoftheprogramwithnolimitations.

Themembersare:

twointegervariables(xandycoordinates)andacoupleoffunctionsthatdealwitthosevariables.Firstthreefunctionshavenoreturntypeandcarrythenameoftheclassitself.Theyareso-calledconstructors.Eachtimeanobject(variable)oftype“coord”iscreatedacorrespondingconstructorisrun.Theyareusuallyusedtoinitializevalues,butarealsousedfortype-casting(ifwewantforexample,tochangeavalueoftwointegerstoa“coord”wecanjustruncoord(10,20)whichwillcreatea“coord”objectwithoutusingavariable).Iwillmentiontheuseofconstructorswhenitappearsintheprogram.Also,itisimportanttonoticethattherearethreeconstructors.Wecandothatduetofunctionoverload(inotherwords,youcandefineanyvalueoffunctionswiththesamenameaslongastheyhavedifferentarguments).

Thefirstconstructorcreatesanemptycoordinate,whichisusefulforusintwocases.First,whenwedeclareanobjectandnotbotherinitializingitwithanyvalues(likecoorda,b,temp;

andsoon).Thesecondtimeweusethisconstructoriswhenwewanttoinformourprogramthatacertaincoordinateisnotvalid.Becausethecellatcoordinate0,0isalwayssettowallatthebeginningoftheprogram(beforethestartofthealgorithm)andisneveraccessedafterthat,weareallowedtousethatvalueasatypeofNULLcoordinate.AnotherthingwecandoisaddingthetwovaluesofacoordinateandiftheyequalzerothenwearesurethatwearedealingwithourNULLcoordinate(noothercoordinate,whensummedgiveszero).Asyoumayhavenoticed,thelastmemberfunctionofourclassisanintegertypeconverter(aspecialfunctionthatconvertsacoordinatetoanint.Toactivateitallwehavetodoiswriteint(coord(20,30))or(int)coord(20,30)).Thesetwofunctionsputtogethergiveusaneasywaytodealwithinvalidvalues.Forexample,ifwegiveourprogramtofindthenextrandommoveandthereisnosuchmove,allthatsuchafunctionhastodoisreturnacoord()(emptycoordinate)andallwehavetodoischeckwhetherthe(int)r(ifristhereturnedcoordvalueofthefunction)isnon-equaltozero.Ifit’strue,thenwecanusethatcoordinate.Ifnotwehavetofindanotherwayaround.Thisisjustasimpletrick.Ofcoursethereareotherwaystodothat,butthisseemsgoodenoughtome(bothincodereadabilityandprogramefficiency).

Thesecondconstructortakestwointegersasarguments.Itisusedwhenwewanttocreateanobjectandinitializeitwithsomesensiblevalues(likecoorda(10,10),b(100,9);

andsoon).Itcanalsobeusedtosendvaluesdirectlyasobjec

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 工程科技 > 材料科学

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2