You are on page 1of 5

MP5Codebreaker

DueWednesday,October1,2014at10:00p.m.

Overview
Yourtaskthisweekistoimplementthelogicforacodebreakinggame.Acodesequenceoffour
numbersfrom1to8isfirstchosenatrandom.Theplayerguessesasequenceoffournumbers
andisgivenfeedbackoneachguess.Thisfeedbackincludesthenumberofvaluesthatappear
inthesameplaceinthesolutioncode(thesewecallperfectmatches),thenumberofvalues
lessthantheircorrespondingnumberinthesolutioncode,andthenumberofvaluesgreater
thanthetheircorrespondingnumberinthesolutioncode.Iftheplayermanagestoguessthe
correctsequenceintenorfewerguesses,theywinthegame.Otherwise,theylose.

TheobjectiveforthisweekisforyoutogainsomeexperiencewithbasicI/O,toimplementcode
usingmultiplesubroutines,andtosolveaproblemthatrequiresmoderatelysophisticated
reasoningandcontrollogic.

Thetaskhereisthussomewhatmoredifficultthanlastweek's.Ifyouwanttoreadaheadand
usearrays,feelfreetodoso.Butthecodeshouldbefairlymanageablewithoutusingarrays(we
wrotethesolutionthatway,justtocheck).

ThePieces
Thefourfilesthatyoushouldexaminearethecodebreakerheaderfile,thecodebreakersource
filethatyoumustcomplete,themainfile,andthemakefile.

Let'sdiscusseachoftheseinalittlemoredetail:

main.cThiscontainstheprogramsmainfunction.Wegiveyouthiscode.Themain
functionwillcallthefunctionsyouwriteincodebreaker.ctoplaythegame.
codebreaker.hThisheaderfileprovidesfunctiondeclarationanddescriptionsofthe
functionsthatyoumustwriteforthisassignment.
codebreaker.cThesourcecodefileforthefunctionsnecessarytoplaythegame.
Functionheadersforallthefunctionsareprovidedtohelpyougetstarted.Wewillwork
togetherontheset_seedfunctioninprogrammingstudio.Thenexttwo,start_gameand
make_guessareleftforyoutofinishindependently.
Makefilethisincludesthemakeconfigurationtobuildthemp5program.

Wehavealsoincludedsomeadditionalfilesfortesting,butweleavediscussionofthosefilesfor
theTestingsectionofthisdocument.

Inprogrammingstudio,wewilldiscusspseudorandomnumbergenerationandtheideaof
errorcheckinguserinput,thendeveloptheset_seed functiontogethertorobustlytranslateuser
inputintoawelldefinedseedforthepseudorandomnumbergenerator.

Therestoftheassignmentmustbecompletedonyourown.Ifyouwanttogetstarted
beforeprogrammingstudio,youcanleavetheimplementationofset_seedprovidedinthe
distributionandworkonstart_game andmake_guess.Togetherwithset_seed,thesethree
functionscomprisethewholeassignmentforthisweek.

Details
Youshouldreadthedescriptionsofthefunctionsintheheaderfileandperusethefunction
headersinthesourcefilebeforeyoubegincoding.

Fortheset_seedroutinethatwewilldevelopinprogrammingstudio,thefunctionsignature
appearsbelow:

int set_seed (const char* seed_str);

Thefunctionreceivesastring(apointertoacharacter)asitsinputandproducesa32bitsigned
integerasoutput.Theconstqualifiermeansthattheroutineisnotallowedtochangethe
contentsofthestring.

Weusethefollowingtwolibrarycallstoproducesequencesofpseudorandomnumbers:

void srand (unsigned int seed);


int rand();

Theuserentersthevalueintheconsoleanditsdeliveredtotheset_seedfunctionasastring
whentheplayerpresses<Enter>.Theset_seedroutinemustthencheckwhetherthestring
representsanumber,and,ifso,useittoseedthepseudorandomnumbergeneratorviaacall
tosrand.Callstorandthenproducepseudorandomnumbersintherange
[0,2
31
1].

Thereturnvaluefromset_seedindicateswhethertheinputstringdidinfactcorrespondtoa
number.Whenthestringrepresentsanumber,thefunctionreturns1.Otherwise,thefunction
returns0.

Weusefixedseedsinthisassignmentbecauseafixedseedproducesafixedsequenceof
randomnumbers,whichmeansthatthesolutioncodewillalwaysbethesame.Determinism
makesdebuggingmucheasierimaginetryingtofindabugthatonlyappearsinonerunoutof
everymillion.

Nowlet'sconsiderthepartthatyoumustdoalone.Herearefunctionsignaturesforthetwo
functions:

int start_game (int* one, int* two, int* three, int* four);
int make_guess (const char* guess_str, int* one, int* two, int* three,
int* four);

Thestart_gameroutineselectsthesolutioncode,asetoffournumbersfrom1to8.Toensure
consistencybetweenyourprogram'soutputandours,youmustusethefollowingalgorithm
forgeneratingthesolutioncode.

Step1:Startingwiththefirstvalueinthecodesequence,generatearandomintegerinthe
range0to7inclusiveusingasinglecalltorandandasinglemodulus(%)operator.
Step2:Add1totheresultingnumbertogetavalueintherange1to8.
Step3:Repeatfortheotherthreesolutioncodevalues(inorder).

Youmustalsomakeyourowncopyofthesolutioncodeusingfilescopedvariables.Thiscopy
willbenecessarywhenyouimplementmake_guess.

Besurenottocallsrandoutsideoftheset_seedfunctionandnottocallrandoutsideofthe
start_gamefunction.Callingeitherofthesedisruptsthesequenceofrandomnumbersandwill
causeyouroutputtodifferfromours.

Finally,youmustwritethemake_guessroutinethatcomparesaplayer'sguesswiththesolution.
Theinputstothisroutineincludeastring(theplayer'sinput)andfourpointerstointegers.

Yourroutinemustvalidatethestringinthesamewaythatwedidforset_seed.Avalidstring
containsexactlyfournumbers(andnoextragarbageattheend).Allfournumbersinthestring
mustbebetween1and8.Ifthestringisinvalid,yourroutinemustprintanerrormessage,
set_seed: invalid seed\n,thenreturn0.

Foravalidstring,youmuststoreacopyoftheguessedcodeinorderinthefouraddresses
providedasinputparameters.

Yourroutinemustthencomparetheguessedcodewiththesolutioncodetocountthenumberof
perfect,high,andlowmatches,thenprintamessageinformingtheplayeroftheresults.

Let'sconsidersomeexamples.Imaginethatthesolutioncodeis1 1 2 3.Iftheplayerguesses1
2 2 4,thefirst(leftmost)andthirdcodevaluesmatchperfectly,sotheyhavetwoperfect
matches.Thesecondandfourthcodevaluesaregreaterthanthecorrespondingnumberinthe
solution.Sotherearetwohighmatchesandzerolowmatches.

Whathappensif(usingthesamesolutioncode:1 1 2 3theuserguesses4 4 1 1?Herethey


havenoperfectmatches.Howmanyhighandlowmatchesmatchesdoestheguesscode
have?Onceyourroutinehascalculatedthenumberofperfect,high,andlowmatches,itmust
printamessageusingexactlytheformatshownhere(withoutthequotes):

With guess 1, you got 0 perfect matches, 2 high, and 2 low.\n

Theguessnumberstartsat1andgoesupashighas10yourcodemustalsotrackthisvalue
usingafilescopedvariable.Notethatonlyvalidguessescountasturns.Donotadjusttheword
matchesforsubjectverbagreement.(i.e.leave1perfectmatchesasis).

Themake_guessroutineshouldreturn1whentheuserhasprovidedavalidguessstring.

Specifics
YourcodemustbewritteninCandandmustbecontainedinthecodebreaker.cfile
providedtoyou.WewillNOTgradefileswithanyothername.
Youmustimplementset_seed,start_game,andmake_guesscorrectly.
Yourroutine'sreturnvaluesandoutputsmustmatchthegoldversion'sexactlyforfull
credit.
Yourcodemustbewellcommented.YoumayuseeitherCstyle(/*canspanmultiple
lines*/)orC++style(//commenttoendofline)comments,asyouprefer.Followthe
commentingstyleofthecodeexamplesprovidedinclassandinthetextbook.

BuildingandTesting

AswithMP4,alloperationsmentionedhereshouldbeperformedfromyourMP5directory.

Youshouldtestyourprogramthoroughlybeforehandinginyoursolution.Wehaveprovidedyou
asetoftests,butyoushouldgetinthehabitofwritingyourowntests.

Tocompiletheprogram,type:
make

Ifsuccessful,thecompilerproducesanexecutablecalledmp5,whichyoucanexecuteby
typing:
./mp5

Youcanalsorunthecodewiththegdbdebuggerbytyping:
gdb mp5

ThetestFilessubdirectorycontainssomesampleinputandoutputfiles.Thesearenotscripts,
butdirectinput.Ifyouwanttotestyourprogramwiththeinputfilestype:

./mp5 < testFiles/input1 > myout1

Thendiffthemyout1filewithtest-examples/output1.

GradingRubric
Functionality(65%)
10%set_seedfunctionworkscorrectly
10%start_gamefunctionworkscorrectly
40%make_guessfunctionworkscorrectly
5%alloutputsmatchexactly
Style(15%)
5%compilationgeneratesnowarnings(note:anywarningmeans0pointshere)
5%doesnotuseglobalvariables(filescopedarenecessary)
5%indentationandvariablenamesareappropriateandreasonablymeaningful(index
variablescanbesingleletter)
Comments,clarity,andwriteup(20%)
5%introductoryparagraphexplainingwhatyoudid(evenifit'sjusttherequiredwork)
15%codeisclearandwellcommented

Notethatsomepointcategoriesintherubricmaydependonothercategories.Ifyourcodedoes
notcompile,youmayreceiveascorecloseto0points.

You might also like