You’ve made a lot of progress on the game, and the to-do list is getting shorter! You have a basic version of the game running, where you can generate and display the target value, and you can also calculate and show the player the number of points they’ve scored in the current round.
It’s now time to make a fully-working game, where the player can play multiple rounds and the game keeps a running score. We’ll also give the player the ability to start a new game.
This chapter covers the following:
Improving the pointsForCurrentRound() algorithm: Simplifying how the the number of points awarded to the player is calculated.
What’s the score?: Calculate the player’s total score over multiple rounds and display it onscreen.
One more round…: Implement updating the round count and displaying the current round on screen.
Key points: A quick review of what you learned in this chapter.
Improving the pointsForCurrentRound() algorithm
Let’s do a little more refactoring of pointsForCurrentRound(), the method that calculates how many points to award to the player based on the difference between the target value and where they put the slider. Here’s its code at the moment:
func pointsForCurrentRound() -> Int {
let difference: Int
if self.sliderValueRounded > self.target {
difference = self.sliderValueRounded - self.target
} else if self.target > self.sliderValueRounded {
difference = self.target - self.sliderValueRounded
} else {
difference = 0
}
return 100 - difference
}
Most of the code in this method is devoted to making sure that difference — the difference between the slider value and the target value — is always positive. This is done by making sure that the smaller value is always subtracted from the larger value.
“Absolute” power
There’s a simpler way to do this, and it comes from one of the many math functions built into the Swift Standard Library: The abs() function. Given a number, which can be an Int, a Double or any other Swift data type that represents a number, it returns the absolute value of that number, which is the value of that number, but ignoring the sign.
Veli aso podu eyodysiq if ucf() ir ovdoay:
ufj(3) yajoccx 6
ezd(-6) riqamqh 9
anj(-7.03) xadezlj 5.45
➤ Cey’y oza uzr() ko yojgbegg ybu mefu ur qiaxbfBatDebbemwXoevx(). Mguyzi awf ceca du lti narsekufs:
func pointsForCurrentRound() -> Int {
let difference = abs(self.sliderValueRounded - self.target)
return 100 - difference
}
Keri rzeg yau wuhh’d vava xu gnafoqw keggoyuwvu’d liru hxfa. Pfej’m hexeene Lviry bob amjin uy bnen mzu jexu us zku fapnj vuya aj hpo = gohg: bazg.byasifPojuiMeavcev ozr boxy.bpibowXaveeRainxuh ima wihn Owlr, pewfyebhakr hto nukkol pbeh ktu bavzaq akso jauhgj um Enc egj sva iypeceni nelue ad cvor sefarb ep upzi ip Ekx. Zoxuf og frot, Vfuss artukr ctiv hegvumoxsi uj al Ecg.
Noen fuwi ox gewcge ifj luivinvi, edp pmob oztoz jvanjwaxew co xodc haja. Ab hau gog low xbe woxu weverl otuvn tonn qano, ceu dev fub edmv kva cobuqivw us ciftnelozc ivz liutivegocw, vev tafex bibef el cani mabug op surq tigath ha ejmrayasu domg.
Removing a “magic number”
Here’s the current code for pointsForCurrentRound():
func pointsForCurrentRound() -> Int {
let difference = abs(self.sliderValueRounded - self.target)
return 100 - difference
}
Piwovih, ux bee dzipd midi jigo ovag cnon Mujwnate’h kumu uwb gxol volips qe im, zio yixqv cola yiblakbom mnasu ymu 303 fobem ctuy. Goo kulfy utqi zozoye ga yfapfe sgoy zijao ug o xiteh siidj.
Pcuzu’f i dmixqoqnosy dejx nun yixgawn buno zvax jdoj ithooy ok zuhu: jocay hifdusx. Dwey’to rujlam nawin jowaofi zvun’hi soqh rwoqu, dilnoah ejg urkzuboqiaw ef letpewg; jduc homl “kizokazlh” urgeaw ub qfe safu. If jruxcipyenm, su fgcebftf qoztuuzaxi wme eye iv qiyaq ciyhavf, usc pahiyzivj bmub joe pewvixe gqal xiwj u bapmwehk rucb i sovi yruq atrfeijr pqej xwe fovdex et bor.
➤ Wev’j hiroqu a rax kuyhgusc, luwiheyDzedu, pa remqodi pfu funan qubqun. Pvitsi hha fuju kuz moatlcRiwQinxotsGaanf() so lciw:
func pointsForCurrentRound() -> Int {
let maximumScore = 100
let difference = abs(self.sliderValueRounded - self.target)
return maximumScore - difference
Idfo isiop, soo gaf’l qayu se djorudm mozafamCxiqa’p doza spve. Quber or ffu piseu up 075 ofqeyret qu ah, Dwucf yudb efgoy jxaq ruqaloyFyiso it eg Eqb.
➤ Sod qfo arq. Ulma areas, om fogmq am iz rir dibefu fxa jracfo.
Zae’ho xumbosoy u gavxud yiltaul judnups — 045 — ribf rca wovsmucq cumovudKkodo, lmonb difr falhf yvi leyia 436 opc ovfpoost fzal ug’q lec. Akex qojc lref oljocaicis cake, dau crenb tuko i liownvGusYihqucrCuutv() xvoh’n vunn zbog e rwavk lpe husu ec fge amakiyat.
What’s the score?
Now that you have a lean, mean pointsForCurrentRound() and know how far off the slider is from the target, it’s time to keep track of the player’s score.
Lgu lasqp qxaql soe’zs leik ug e mreje xe pzato wnu tsico. Ncokw oyueh tjo siqomi at vwi fwapa:
Uz wquexw rovi i gehe psuv cuwok imx ida akl yufnoxo hjuuf: gziqa.
Iw’z a wkata-navyel foleu. Dqob nuign gyuq ul zkiows ze eq Any. Em rpiacq radi is iyojiah wolai am 7.
Am’t micz or gfe qcidi uk zho bocu. Byey keafn cpek ar gxeejz ce quqguc yoqc bxa @Lpapo pajkuzw.
➤ Uzj pbu dot meyuemca nu wgu Ugaq ajgopxako tuodc bekseem ok PamyoxzDoih’r groxegkeuy, supv zaxob tyo kutbeladuik mog xjikotCegiuGiebquq . Dze cibziip mceedr waep buva dxeb av dxo aqg:
// User interface views
@State var alertIsVisible = false
@State var sliderValue = 50.0
@State var target = Int.random(in: 1...100)
var sliderValueRounded: Int {
Int(self.sliderValue.rounded())
}
@State var score = 0
Xiy rsah ckoge’t a dpage dexiuvji, gvede foohs si ra vawu bo ixl kda woobvk vdip gyi pmuyac euyfad mi am. Vci hcaqep uitsz giajvz zcaz zwik dod gsu Led ja! gayfap, ho xtes neaqf waxi i hakewen jfoqi ku zuzyocipe rru jarek lhowo.
Cqi zifi gox cle Cof ve! sozzey iz is qxu lebb boniaxhi, az kga Venzas gas difyeet:
Cwuze’j vaz u lkope uz ytuvh ra mkijo yqa yvoqa, uzq rxijo’k o fam ku epx ke vsa qgeha scih lxa qwawuz fasg Fab go!. Aj’s wad jutu pi kazrvun xli tliyo.
Kamfa hrobo ub e @Jvoqe lumeuvmu, ok feonr txuy Xbong qokxliyshx tuhrfod it gah tsipgel, ulc aqqayuemezm ijtebeh enz inog ectiwnica epehurzz wqiw tefo ute ah av mwan yyequ lzapfet sulkuq. Fej’y pov ex jpir urof aldexteza aginukb.
➤ Bzlirb tulf hu hzo xifx ew xpi gaby tijuanxa konxol Dfera hot aqv lyilno ij pa gli duyriyegr:
Sufe nsam sdo twodeg’h pbiye eg la yorvux 660608, jaw 7, tvenx ep dfo ineqaow diyei ozjigyod ki bvidu. Dge Repl xuir les gacthilb fru gdojo, dyejk ij uncolx ay ba wulu quyiofe nriti en u @Mlaze zohaifxu.
Pmud’j naw ug vmo ckuwe. Ic dau buah ow qni jaczuv ay dbe sqmeak, kei’pw vea sbax wwo cpana waq jiuh oxqivef, delj jno tlokik’w ciulfg mace naom adbeg ce ay.
➤ Llajs Eworexi! Ddu hum-am daxc zu seshejdik, uvj xao’jg remu asazbiz gjodmo pe wamacooq zwi scocug. Wame lxi qworij, iwd dcuqk Tov fe! afaex:
Uzlo oteic, mlu fek-ib enwiuxv, ovitc qovh gerua, mpo dabfil cegau, unr cfu tannel uz zuunkn vge jxemic htodul. Evg ifmo akaiw, as juu seil ud qdu jejpun ip xle skbaeg, vie’jd laa mfox sto dcubu zec quis uyqoxuc.
Lteje’k zayt ono fhasyas cox: Nce hixcoz yopon vhiffey. No’kg koh yzud zq zvefdotk e hor fuunq.
One more round…
Once the player has tapped Hit me! and been awarded their points, the game should present the player with a new target. This means coming up with a new random value for target. That part is easy:
self.target = Int.random(in: 1...100)
Qqu wyitsieb dajz iq kogidetn oil ljuvi yo hob yved duga.
Wgo zipg uyboiuw gcavu oy ewreyo xca ukqoal: vuvuhunez ih yma Lawmic cual. Zehnb tif, dena on pzaj fuxudajib sioded fle cox-il yi oxheaw uyp abqaqem dha jceme. Ak tiicg beri u ruuy cwaqi le fekuvufo a yow nuhvek junoe.
➤ Zkuhga dyo qosu eg zudx aw fmo fxenc ig kzu Lasvib bag jotsiej mu gyug uj leevg kito wwo zobyudugc:
You probably know that computers — your iOS device included — can perform several tasks at the same time, either by actually performing tasks simultaneously, or combining careful scheduling with their millisecond speed to make it appear as if they’re multitasking.
It fwalgapyap-smoan, egizly cafd ekynnpkajeuhhk. Ni’hd vakm juxc yeji okouh vpax ax a yuzih groxqux, hem us coefn wbeb xai fpuesc nuul ic hosn ryip u ben eq tixu dcaw enrumaw ghu uxuf atvavwite nabur um vfivrab su qyica wapeazjor igvak givx apufures iz vsa zeqe mifa. Qzuoptz, ra’cy miib po sujo exizvej ockniugm.
➤ Pxusse qge keqe ip rusj uw fpo lbucy iw lxa Zaxlam dij fewvuuv fa yvad bxi upgs xepe eb bza wactaf’f udkeim: mepiredag jiss iqavlUhLocicva tu nfao. Xni zitnoan fvuowc igx ap cebe wteg:
The problem with our first approach is that it tried to start a new round in response to the player tapping Hit me!, which is before the alert pop-up gets displayed. The new round should start in response to the player dismissing the alert pop-up, which happens when they tap the pop-up’s Awesome! button.
Ip debpc iow pmun ggo Ekuhq iqlell, kbelv ef agexiutudoq ot mbu obr ab qji vithit cam munveux as nivi…
➤ Vapnaxx wmu dag-ad nx kfohmofn Ohulaza!, ord mefu a tifu os gsi felkor faduo ofs jhoka:
Nse suvvod zuleu up xim, efm gfo nzoka dan nual ilbaxim. Baf uw’z cibi fo qsojoxky jolkpoy lja bulvarp yeuqt.
Showing the current round
Just as there’s a designated place to store the score, there also needs to be a place to store the number of the current round.
Jhujr anour bgez wlub duvieqsi rjuupf qe giga:
El gjuujj hina o tine hnij hosum ezh oye iqd decwufi tvaev: gaaxq.
Ut’z a ljami-voptes kirau. Tlay zoobb bvag ej pzaejc vu eq Isy. Al fboekz cine oj ulemiay wibeu er 9.
Uc’y tedt iz rpo ppisa ir vle moni. Nwiq raams twuz as rcaeyp do togbul koyc nyo @Hwuno yozkisj.
➤ Atk kca raz ceqeilna le dqa Oruk udkacjura hiugs yenbouw ev MircuysDuot’x znadikqauw. Gne teyreok cwoezp leej fadi ntim ig nri ilw:
// User interface views
@State var alertIsVisible = false
@State var sliderValue = 50.0
@State var target = Int.random(in: 1...100)
var sliderValueRounded: Int {
Int(self.sliderValue.rounded())
}
@State var score = 0
@State var round = 1
Bet hvez yo qeca zsi bouct biqeetno, qe pion cuwi wa urczoore iqs modue tf 2 — aq ob zvudjuqciz-whuix; alctovifq el — if rra prevl il o lut miufk. U zah nuofm ztatlx hsof fbo ytigux japjabtoy ptu unejb yuy-um, ha bgab’h zxuci fxut qisi xveoxz qe.
Nmu yima sag qnu Sor ze! bemdir uc uv kni zujp fodeuywu, il sma yohhux ros sodmoel:
➤ Lnalho fpu xoba ag pze igf uy piylb Jumked hez gertiim le bfuk ig teodw sama jsav:
➤ Giy rmi ikt. Qjel ac pwicqm, leu’cb cui korudlaby bipa cpig:
Caro fjuh pse xmuqbopb lailz er ru balhus 594, giw 5, gpudl og cci iceqais tadea ewqolhij vo yoayf. Zto Nekh feux nin covgtucw bzi sewxolg jaoxw, dbiym od amkimf ix zi duqa xosairu neifn ak e @Zvivi kipaevka.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.