Top Banner
Table of Contents 1.1 Introduction 1 1.2 Getting Setup 2 1.3 Your first PHP webpage 3 1.4 Working with text 4 1.5 Talking to the user 5 1.6 Comparison & If statements 6 1.7 If & Else 7 1.8 Cleaning up the game 8 1.9 Remembering values 9 1.10 Finishing your game 10 I'm learning: PHP BEGINNER PHP 1
21

Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

Jun 15, 2018

Download

Documents

LyMinh
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

TableofContents

1.1Introduction1

1.2GettingSetup2

1.3YourfirstPHPwebpage3

1.4Workingwithtext4

1.5Talkingtotheuser5

1.6Comparison&Ifstatements6

1.7If&Else7

1.8Cleaningupthegame8

1.9Rememberingvalues9

1.10Finishingyourgame10

I'mlearning:PHP

BEGINNERPHP

1

Page 2: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

IntroductionI'mlearning:PHP

BEGINNERPHP

2

Page 3: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

TheseSushiCardswillhelpyoulearntobuildwebpagesusingPHP,averypopular

programminglanguagethat'susedtobuildwebsiteslikeFacebookandWikipedia.You

cancombineitwithHTML(andcheckouttheHTMLSushiCardsifyoudon'tknowhowto

codeHTMLyet!).

1

First,you'regoingtoneedsomewheretocode!PHPneedsafewdifferentpiecesinplace

tomakeitworkand,ifyou'regoingtoreleaseawebsitelater,you'lleventuallyneedto

learnhowtosetthatup.Fornow,though,let'sjustgetgoingquicklybyusingCloud9,an

onlineeditorthatwilldoallthesetupforyou!Checkitoutatdojo.soy/php-edit.

2

YoucanuseyourGitHuborBitbucketaccounttosigninifyouhaveone.Otherwise,sign

upwithyouremailaddress.3

Choose"Createanewworkspace"andfillitinasfollows:

Workspacename:beginner-php

Description:MyfirstPHPwebsite

MakesurethatHostedworkspaceisselected

ChooseaPrivateworkspace

SkipovertheClonefromGitorMercurialURL—youdon'tneedto

cloneanything

ChoosethePHP,Apachetemplate

4

GettingSetupI'mlearning:PHP

BEGINNERPHP

3

Page 4: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

NowjustclickonCreateworkspaceandyou'reallset!5

Onceyourworkspaceisupandrunning,you'llnoticeyou'vebeengivenafewfiles,which

youcanseeinthesidebar.6

You'regoingtoneedtocreateanewfiletoputallyourcodein.Youcandothisby

choosingFile>NewFileinthemenu.7

Oncethefileisopened,youcansaveitbychoosingFile>SaveAsandgivingitaname.

Savethisonenowasindex.php8

You'rereadytomakeyourfirstPHPwebpage!9

GettingSetupI'mlearning:PHP

BEGINNERPHP

4

Page 5: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

TimetostartcodingyourfirstrealPHPwebpage!You'regoingtostartwithoneofthe

classics,saying"Hello!"toyouruserand,bytheendofthesecards,you'llbemakinga

numberguessinggamefortheusertoplay!

1

So,tobeginwith,everyPHPwebpagewillhaveatleastalittlebitofHTMLinit.Startby

makingareallybasiconebytypingthiscodeintoyourindex.phpandsavingit.

<!DOCTYPEhtml>

<html>

<head>

<title>MyPHPwebpage</title>

</head>

<body>

ThisisjustHTMLtext,itisnotcleverlikeyourPHPtextwillbe!

</body>

</html>

Thethingsintheanglebrackets(<>)arecalledHTMLtagsandyou'llbecomingacross

afewoftheminthesecards.Therearelotsmore,though,andyoucanlearnaboutthem

intheHTMLSushiCardsandinloadsofotherplacesonline!

2

YourfirstPHPwebpageI'mlearning:PHP

BEGINNERPHP

5

Page 6: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

Runthatpageandyou'llseeabasicHTMLpage.Tobeginwith,yourPHPpageisgoing

tolookprettysimilar,butveryquicklyyou'llbeusingthepowerofPHPtodothingsthat

HTMLnevercouldalone!Togetstarted,replacethatHTMLtextwithsomespecialPHP

code.

<body>

<?php

echo"Helloeveryone!ThisismyfirstPHPprogram!";

?>

</body>

NoticethatPHPcodealwaysappearsinside<?phpand?>.Thisissothecomputercan

tellwhichpartsarePHPandwhichpartsareHTML.Usingthese,youcanputPHPcode

anywhereinsidetheHTML.

Also,noticethatthePHPcodealwaysendseachlinewithasemicolon(;).Thisisso

PHPknowstoendthiscommandandstartanother.Ifyouforgettodothis,PHPcanget

veryconfused.

3

NowsaveandrunyourPHPfile.Congratulations!Ifitallworked,you'vejustwrittenyour

firstPHPwebpage!4

YourfirstPHPwebpageI'mlearning:PHP

BEGINNERPHP

6

Page 7: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

Nowit'stimetostartworkingonyourgame!Thefirstthingyou'regoingtoneedistoteach

theplayertherules.

Youmightwanttochangethingslikethesmallestandbiggestnumbers,orthenumberof

guessesyou'regoingtogivetheplayer.IfyouwroteouttheruleswithplainHTML,you'd

havetogobackandre-writethemeverytimeyouchangedanyofthosethings.Youdon't

needtodothat,though.YoucanusePHPandvariablestoincludethenumbersaspart

ofyourtext!

1

First,you'regoingtoneedtotoupdateyourtext,sochangethePHPcodeonyourpage

tothis:

echo"I'vepickedanumberbetween1and9<br/>";

echo"Youwillhave5chancestotrytoguessmynumber!";

The<br/>isapieceofHTMLthattellsthebrowsertostartanewlineafterit.Youcan

putanyHTMLinsideyourPHPanditwillbetreatedexactlyasifithadbeenwrittenas

HTML.

Noticethatyou'reusingdoublequotes(")aroundyourtextinsteadofsinglequotes

('),fortworeasons:

PHPwillgetconfusedifyouuseanapostropheinsideofsinglequotes.

Tryitandsee!Whathappens,andwhy?

PHPwilldosomethingspecialinsideofdoublequotesthatitwon't

insideofsinglequotes,whichyou'llseebelow.

2

WorkingwithtextI'mlearning:PHP

BEGINNERPHP

7

Page 8: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

Nowit'stimeforyoutostartaddingvariables!Thesearelabelsthatyoucanusetostore

values,likeastringoftextoranumber.PHPremembersthosevaluesandletsyouuse

thevalueslaterbyusingtheirlabel.Thisletsyousetavalueonceanduseitloadsof

timesinyourprogram.

InPHP,allvariablenamesstartwithadollarsign($)andareusuallywrittenin

camelCase,wherethefirstwordstartswithasmall(lowercase)letter,thereareno

spaces,andanylaterwordsstartwithcapital(uppercase)letter.

Putthislinein,insidethe<?phpbutbeforetheecholines

$minValue=1;

$maxValue=9;

$guesses=5;

Allofthesevariablesarenumbers,butyou'llbeworkingwithtextvariableslater.

3

Now,updateyourtwoecholinessotheylooklikethis:

echo"I'vepickedanumberbetween{$minValue}and{$maxValue}<br/>";

echo"Youwillhave{$guesses}chancestotrytoguessmynumber!";

Noticethecurlybraces({and})aroundthevariablenamestotellPHPnottotreat

themlikeregulartext!

4

Runyourprogramandseewhathappens.Thentrychangingthevaluesofsomeofthe

variablesandrunitagain.Justmakesuretoseteverythingbacktothewayyou'vegotit

herebeforemovingon!

5

WorkingwithtextI'mlearning:PHP

BEGINNERPHP

8

Page 9: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

Ok,soyoucangetinformationfromavariableandshowittotheplayerwithecho,but

howdoyougetinformationfromtheplayer?Afterall,thisisaguessinggame,soyou

needsomewaytocollecttheirguesses!

1

You'regoingtouseacombinationofHTMLandPHPtodothis.TheHTMLyou'llbeusing

isgoingtobenew,evenifyou'vealreadydonetheHTMLSushiCards,sincetheydon't

usemanyformsandyourPHPprogramswillprobablyusealotofthem.Youcansee

themonalmosteverywebsiteyouusetheinternetandthecodeforthemisprettyeasy!

<formmethod="get">

Yourguess:<inputtype="text"name="guess"/>

</form>

AHTMLformisasimpleidea:controls—liketextboxes,drop-downmenus,checkboxes

orbuttons—areusedtocollectinformationfromusersandsendthatinformationtoyour

PHPprogram.Sometimes,responsesaresenttotheusers.You'llbesendingresponses

inyourgames.

2

Now,timetoaddaformtoyourpage!SoyoucanusePHPvariablesandothercodein

creatingyourform,you'regoingtouseechostatementstocreateit,insteadofjusttyping

theHTMLintothefile.So,addthefollowingbelowyourtwoexistingechostatements:

echo"<formmethod="get">";

echo"Yourguess:<inputtype="text"name="guess"/>";

echo"</form>";

Runthiscodeandseewhathappens!

3

TalkingtotheuserI'mlearning:PHP

BEGINNERPHP

9

Page 10: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

Well,thatdidn'tquiteworkright,didit?Anyideawhy?It'sbecauseofthedoublequotesin

<formmethod="get">.PHPisn'tsmartenoughtorecognisethattheyarepartoftheHTML

tag;itreadsthemastheendofthestringoftextthatechoistryingtoinsertintothe

page.Afterthat,it'slookingforasemicolon(;)butinsteaditfindsgandgetsvery

confused!Thiskindofproblemcancomeupquiteofteneitherbecauseyou'veforgotten

whichkindofquotestouseoryou'recopyingfromanotherofyourprogramsandused

quotesdifferentlythere.Luckily,it'sveryeasytofix.Justputabackslash(\)infrontof

yourallyourdoublequotes(don'tforgettheonesintheinputtag!)likethis,toescapethe

normalruleofendingthestring!

echo"<formmethod=\"get\">";

4

Runthecodeagain!Nowyou'vegotsomewhereforyourusertoputtheirtext!Type

somethinginandpresstheenterkey.WatchthepageURLinthebrowserandnotice

whatchanges!

5

TalkingtotheuserI'mlearning:PHP

BEGINNERPHP

10

Page 11: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

ThetextthatappearedontheendoftheURLiscalledaqueryparameterandyoucan

haveloadsofthemonthesameURL.Theformautomaticallyaddedone(becauseyou

setmethod="get"),butyoucouldjustaseasilytypethemin,separatedbysemicolons.

PHPreadstheendoftheURLforthepageit'sloadedonandturnsallthequery

parametersintosomethingcalledakey,valuearray.Youdon'tneedtoknowexactly

whatthatisrightnow,we'llgointoitinalaterSushiCardseries.Whatyoudoneedto

knowishowtogetvaluesoutofit.

1

Allyouneedtodotogetavalueoutofthearrayispassinthekeyofavaluethat'sin

there.Sinceyourformaddstheguessfield,that'stheoneyou'llbelookingfor.You'll

wanttoassignthatvaluetoaplayerGuessvariable,soaddthislinejustbeforeallyour

echolines:

$playerGuess=$_GET['guess'];

2

Now,remindtheplayerwhattheirlastguesswasbyaddinganotherechojustbeforethe

inputform:

echo"Yourlastguesswas{$playerGuess}.<br/>";

Runthecode.Nowyou'retakinginputfromyourplayerandgivingitbacktothem.Very

cool!

3

Comparison&IfstatementsI'mlearning:PHP

BEGINNERPHP

11

Page 12: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

TryremovingallthequeryparametersfromtheURLandreloadingthepage.Noticethat

younowget"Yourlastguesswas."

That'snotideal.Whatyouwanttohappenis:

Checkifthere'savalue(maybetheyhaven'tmadeaguessyet)

ifso,showthemessageaboutthelastguess

4

PHPcanfigureallthisoutanddoitforyou!Youjustneedtouseanifstatement.

Anifstatementusesatest(inbrackets),thathasananswerthat'seithertrueorfalse

and,ifit'strue,apieceofcodetorun.Youcandothistocheckifyourvariablecontains

anythinglikethis:

if(!empty($playerGuess)){

echo"Yourlastguesswas{$playerGuess}.";

}

Hereempty()isaspecialpieceofPHPthatcheckswhetherthevariableinsideits

bracketshasavalueandanswerseithertrueifitdoesn'torfalseifitdoes.The!before

itreversesthisanswer,turningatrueintoafalseandafalseintoatrue.Sowhatthis

codesaysis:"Ifthereisnotnovaluein$playerGuess,thenprintoutYourlastguesswas

[thevalueofplayerguess]."

Replaceecho"Yourlastguesswas{$playerGuess}.";withthecodeaboveandtestit

withandwithoutanswerstoseeitworking.

5

Comparison&IfstatementsI'mlearning:PHP

BEGINNERPHP

12

Page 13: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

Nowthatyouknowhowtouseifstatements,youcanstartwritingthecodetogetyour

gametorun!You'lldealwithusingarandomnumberinalatercard,butfornowjustadd

anothervariableupatthetopwithalltheotherstosetyour"secret"number,likethis:

$secretNumber=5;

1

Whatyouwanttodonowiscomparetheplayer'sguesswiththesecretnumber,andtell

themiftheyguessedcorrectly.Tocompareonevaluetoanotherandgetatrueorfalse

result,youusetwoequalssigns(==).Ifthevaluesoneithersidearethesame,thenthe

resultistrue;otherwise,it'sfalse.

Here'showyou'dchecktheplayer'sanswerinyourPHP:

if($secretNumber==$playerGuess){

echo("<br/>That'sright!Iwasthinkingof{$secretNumber}!");

}

Addthiscodein(afterthosevariables'valuesareset!)andthenruntheprogram.Try

guessingcorrectly(i.e.5)andincorrectly.

2

If&ElseI'mlearning:PHP

BEGINNERPHP

13

Page 14: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

Haveyounoticedafewissueswithwhat'shappeninghere?Foronething,theplayeris

stillaskedtopickanumberevenwhenthey'vewonthegame!Youcanfixthat,though,by

usingelsestatements,afteryourifstatements.Youcan'tuseelseonitsown,it

onlyrunsthecodeinsideitifthetestontheifstatementjustbeforeitwasfalse.

So,toonlyshowtheformforthenextguessiftheplayerhasnotyetguessedthesecret

number,youneedtoaddanelseontoyouriffromaboveandmovealltheformcode

intoit,likethis:

if($secretNumber==$playerGuess){

echo("<br/>That'sright!Iwasthinkingof{$secretNumber}!");

}

else{

echo"<formmethod='get'>";

echo"Yourguess:<inputtype='text'name='guess'/>";

echo"</form>";

}

3

If&ElseI'mlearning:PHP

BEGINNERPHP

14

Page 15: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

Itdoesn'tmakesensetogivetheplayertheinstructionsonhowtoplayeverysingleturn.

However,itwouldbeusefultotellthemhowmanyguessestheyhaveleft.Todothis,

you'llneedtocreateanothervariable,guessesLeftandaddittoyourfile:

$guessesLeft=$guesses;

Notethatbecauseyouaresettingthisvariabletothevalueofanother,itmustbedeclared

afterthatvariable.

1

Next,taketherulesechocodeandstickitintoanifthatchecksifthenumberof

guessestheplayerhasleftisequaltothenumbertheystartedwith.Ifitis,thenyouknow

it'sthefirstturnandyoucanshowthemtherules.Ifit'snot,thentellthemhowmany

guessestheyhaveleft.

if($guessesLeft==$guesses){

echo"I'vepickedanumberbetween{$minValue}and{$maxValue}<br/>";

echo"Youwillhave{$guesses}chancestotrytoguessmynumber!<br/>";

}

else{

echo"Youhave{$guessesLeft}guessesleft.<br/>";

}

2

CleaningupthegameI'mlearning:PHP

BEGINNERPHP

15

Page 16: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

Ifyourunthiscodeandplaythroughitafewtimes,you'llnoticethatthenumberof

guessesnevergoesdown!Therearetworeasonsofthat,andyou'llsolvethemoneata

time.ThefirstisthatyouneverdecreasethevalueofguessesLeft!Therearetwothings

youneedtodotomakethishappenandyou'llgothroughbothofthemonthiscard.First,

youneedtocheckiftheplayermadeaguessand,ifso,setguessesLefttoonelessthan

thecurrentvalue.

Youalreadyhavethetestformakingaguess,sinceyoucheckforaguessbefore

decidingwhethertoshow"Yourlastguesswas...".Youcanjustupdatethatcodeto

includeasecondlinethatdecreasesguessesLeft,likethis:

if(!empty($playerGuess)){

echo"Yourlastguesswas{$playerGuess}.";

$guessesLeft=$guessesLeft-1;

}

3

Nowit'simportanttokeepaneyeontheorderofyourcode.Ifyourunthiscodeas

written,you'llnoticethecountofguessesstilldoesn'tdrop!Thisisbecausetheecho

codethatprintsthevalueofguessesLeftrunsbeforethecodethatchangesthatvalue!All

youneedtodoismove(cutandpaste)thecodesoitcomesjustafterallyourvariable

declarationsatthestartandthingsshouldworkfine.Dothatnowandtryrunningitagain.

4

CleaningupthegameI'mlearning:PHP

BEGINNERPHP

16

Page 17: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

You'llnoticethatnowthecountofguessesdoesgodownto4,butitnevergoesany

lower!Anyideawhy?It'sbecauseofthewayPHPworks:Everytimethepageloads,the

programrunsagainfromthestart,withnomemoryofthelasttimeitran!Thatmeansit

alwaysresetsthevalueofguessesLeftto5andthen,ifaguesswasmade,subtracts1.

So,whatyouneedtodohereisstorethatvaluesomewhereandpassitintotheprogram

thenexttimeitruns.Well,youalreadyhavesomethinglikethat:theformontheweb

page!YoucanwritethecurrentvalueofguessesLeftintotheformandreaditbackout

from$_GETlater.Startwiththewriting,byupdatingyourformcreationcodetolooklike

this:

echo"<formmethod='get'>";

echo"Yourguess:<inputtype='text'name='guess'/>";

echo"<inputtype='hidden'name='guessesLeft'value='{$guessesLeft}'/>";

echo"</form>";

Thetypeofthefieldis"hidden",soitwon'tbevisible,butwillbesentinontheURL.The

valueissettothecurrentvalueof'guessesLeft'.

1

RememberingvaluesI'mlearning:PHP

BEGINNERPHP

17

Page 18: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

Nowyouneedtopickupthevalueyou'vesavedandwriteitintoguessesLeft.Thisgetsa

littlecomplicated,sincetherewon'talwaysbeavalueintheURL(thefirsttimethegame

isrun,forexample).Soyouneedtoreplacethecurrentline$guessesLeft=$guesseswith

this:

$guessesLeft=$_GET['guessesLeft'];

if(!isset($guessesLeft)){

$guessesLeft=$guesses;

}

ThiscodetriestogetthevaluefromtheURLand,ifitdoesn'tfindit,leavesguessesLeft

empty,whichcausesthecodeintheifstatementtorun,fillingitwiththevalueof

guesses.Thereasonwedidn'tuseemptyhereisbecauseemptywillgiveafalseifthe

valueis0,whichisgoingtohappenhere,whentheplayerrunsoutofguesses.Try

runningtheprogramagainandyou'llseethatitallworksnow!

2

Youmayhavenoticedonelastproblem:Thegamedoesn'tendwhenyourunoutof

guesses!We'lllookathowtofixthat,andhowtouseasecretnumberthatactually

changes,onthenextcard!

3

RememberingvaluesI'mlearning:PHP

BEGINNERPHP

18

Page 19: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

First,let'slookatmakingtheplayerlosethegame.Thisneedstohappenwhenthey've

usedtheirlastguessup,sowhen$guessesLeft==0.Whenthishappens,keepshowing

themtheirlastguess,andthattheyhavenoguessesleft,butnottheformortherules.To

makethathappen,you'llneedtouseanewbitofcode:elseif.

1

Asyoumighthaveguessedelseifisacombinationoftheelseandifstatements.

Likeelse,itonlyhappensiftheconditioninanifstatementisfalse,butlikeifit

hasitsowncondition.

Youcanuseasmanyelseifstatementsasyouwant,butonlythefirstonethathasa

trueconditionwillrun.Ifnoneofthemaretrue,theelsestatementwillrun,justlikewith

aregularif.

Togetyourgametotelltheplayerthey'velost,youjustwanttoaddanelseiftothe

codethatcheckstheiranswerandshowsthemtheforto,iftheyhavenowguessesleft,

showthemadifferentmessageinstead,likethis:

if($secretNumber==$playerGuess){

echo("<br/>That'sright!Iwasthinkingof{$secretNumber}!");

}

elseif($guessesLeft==0){

echo("<br/>Gameover!Youlose!");

}

else{

echo"<formmethod='get'>";

echo"Yourguess:<inputtype='text'name='guess'/>";

echo"<inputtype='hidden'name='guessesLeft'value='{$guessesLeft}'/>";

echo"</form>";

}

2

FinishingyourgameI'mlearning:PHP

BEGINNERPHP

19

Page 20: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

Ok,nowyouhaveagamewheretheplayercanguessanumber,getacertainnumberof

triesandbetoldiftheywinorlose.Verycool!However,rightnow,thatnumberisalways

5...whichislesscool.PHPisprettygoodatcomingupwithrandomnumbers,though.To

usearandomnumberinsteadyoujustneedtochangethecodeforsecretNumberlike

this:

$secretNumber=$_GET['secretNumber'];

if(!isset($secretNumber)){

$secretNumber=rand($minValue,$maxValue);

}

Therandisafunctionthattakestwonumbersandgivesyoubackarandomnumber

betweenthem.You'reusingminValueandmaxValueheresoyouonlyhavetochange

thosenumbersinoneplaceandthey'llchangeeverywhereinyourcode!

3

Nowyouneedtomakesurethatit'sthesamerandomnumberthroughoutthegame.It

wouldn'tbefairtokeepchangingitonyourplayer!Youalreadyknowhowtodothisone

though:ahiddenformfield.Justaddthistoyourechocodefortheguessingform(you

won'tneedtokeepstoringitiftheplayerwinsorloses!).

echo"<inputtype='hidden'name='secretNumber'value='{$secretNumber}'/>";

4

Now,trytoplayyourgame!5

Howelsecouldyouusethiscode?You'vegotallthepiecesheretomakeaquizoran

interactivestory,whereyoukeepscore,askdifferentquestionsoneachpageandeven

sendtheplayerindifferentdirectionsbasedontheiranswers!

6

FinishingyourgameI'mlearning:PHP

BEGINNERPHP

20

Page 21: Beginner PHP - kata.coderdojo.comkata.coderdojo.com/images/5/5c/Beginner_php_en.pdfBEGINNER PHP 1. Introduction ... (and check out the HTML Sushi Cards if you don't know ... put any

FinishingyourgameI'mlearning:PHP

BEGINNERPHP

21