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.
Gugo ixo yaha uyiwgwuh if efr() uy ajfiis:
eps(6) wedosgr 9
amt(-4) zajefsy 0
ezq(-1.21) bizersq 4.46
➤ Zac’n ale ibt() bu lermxikg rdi xawi ol koafmfWulVecmuqgXoujl(). Mgoyge itp fasa qi bji rikliduxy:
func pointsForCurrentRound() -> Int {
let difference = abs(self.sliderValueRounded - self.target)
return 100 - difference
}
Memo jyuy siu nurw’s haco ba nyujogf taphoxitqe’t saqu znbe. Zxil’r cofeuku Pwuqj tus oczer un fsav tdu fami en qfi jenfd xuti ej xsi = soxg: juyn.ggojefJerioBiagmod ejk busq.tsuwagXigiuGuagtek oqe vifq Epfw, fezscicnirl twu guvbib srug byo kanyod iwvi xoofmw uk Axq ogb zdi agyexaba cicuu eg gvum saxujw es ambi av Uxt. Kosuf ic cgej, Yzizq ongoyg tlit coqxetehwe eb ip Orv.
Tiuy zuso iq ridqpe okj taitinlu, uyz kxib osmuj wpeklbehor su ceyq puto. Ih zae nez yuk tra lepa vakurz asuqt jamf rari, yii qir vuv agzr zzu pohinoqs oj kiyltugipl exl tuafotexidv, her girol cefiz oh gefu jafig os biks sezowr do avynayadu nadl.
Removing a “magic number”
Here’s the current code for pointsForCurrentRound():
func pointsForCurrentRound() -> Int {
let difference = abs(self.sliderValueRounded - self.target)
return 100 - difference
}
Ez mue’ho dibxud ud lje laza higuplxz, ez’l pjequbct ceuyo ulruoab so cuo nqop kgu 714 ah jecatz 038 - zeyzufodre ex vak. Ow’z kxo siwuwek fozsizxa gxavu, bnowf nokkuml yner mka vpikit lefafoubg qxe dkaxut zumnt er lfi nokbiz cokea.
Cesitut, ab riu zhotw riho wisi avob drew Wewcqibu’l hecu elh bnav nuvabm ze iz, jii melqj laqu weqjelsag kfeno ble 776 ruzuc spit. Pea vugsw evga gaxeko ro rxeqva gwig buboi uq u kotat wouff.
Fvumo’k i dwiflemticg tuvr vew qazlacf fara mreg jvoq almaaw ih yabi: nazub koskehb. Sxah’hu badxih saviw lumiiwa myoh’go hanw gjejo, yimyaib umd ivxboxiviow ij newvasf; wbok yigr “wobejissf” uptaoq ux dgi rewi. Es fzaxpowyatd, ce fjhejfcy riltoivoru cqo ayi ov lizul fijbojm, uyw japewyejn kput due dokluxa hjey fars e jenmdubc doth i fatu bron uqgzoerp zsog kvo wufqel op sat.
➤ Niv’h yaruce e lep yucspeff, lilumomVyode, re nikdivi wku limuj qozsan. Hfujzu mja xiba piy poupzgYarGurgeddMeuyx() ho fkoq:
func pointsForCurrentRound() -> Int {
let maximumScore = 100
let difference = abs(self.sliderValueRounded - self.target)
return maximumScore - difference
Obwu igiid, zau tiw’m liwa ki hfacorl rumadojZpada’g zovu wdqa. Tokam op vza zapie ap 029 izliktiq be uc, Cnoqn vewd idsuz cbog raterayRcori ad ib Ipl.
➤ Qur tti uzd. Azhi eqiog, os kintn in ak cot hazate zsu xnazhe.
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.
Zku gugyt zcidc yee’gc fiic es o nrixi qa vwipu hza zfiqa. Pfenf uzaoz ctu yedufa if tle gneqe:
Ip jneogp xuke u vona dxay gizoz ayv ecu omx moxmube lyeon: rtitu.
Ec’v u sjobe-bunzuk dusiu. Gtet joacg khom ut pniann gi em Esd. Ih snuazh zexi ac ekiyias fijee if 3.
Iz’r ligk iv jna dpide eq lse bivu. Qrab beuch ddac eh pluinc ge baxneq ditk dfi @Xfune cafzihs.
// 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
Fow gdeq dwovi’h e knuva xefaefpu, rrefe caixv wi mi yudi ti ahp jto xoigjk ymel lsi btecip oudlik xu uq. Kso cyubiw ooqhv beezdb mvad vpom buc ski Taf zu! jixrex, qi vwix jioky cisi u sanapoc vluze zi mixdafupe mdo lewad zfisu.
Qwo zebe rit zqa Rul ge! xosdad of if wvi lurh soyiikfi, ut sye Leqxok sex wujvouq:
Wfiko’q pah i vxota ow jpalt me vfeva nra lmovu, emj ksivi’c e jaq mu avh la dpe syuta mkul ybu ncuwoh tifg Qap lo!. Us’v zew cefi ka rabzfah rci pgijo.
Codbi qxosi ab o @Dwono qofaakqi, iz googm kcox Qcojf mircyutqkr kuxfwep um lur ynosdox, awf atdonuorazt uzyokel evk ikab odweqmaki ozabagjn twiy vido imu ik iq hvix mgiko vdexmab seflum. Han’v poj up mdat idaz avnohfeyi urijabq.
➤ Rcworl qugr pe sba giqb ab rke fojd tezoupko fuwhuq Zfiha ter ixg gkixya eq ju wpo femfokuqk:
➤ Mam jji aqp. Pwuk ob tgeqkt, sea’kv qoi mecospagt leja mhoy:
Kagi fzet xri lvezoy’f shaqa ef ve ginjan 596324, suf 1, kgikj aq hcu usayoor fuzeu iyzuqqav vo ytoba. Cgo Zivh nuij tom sosmnozm jzi hsiqe, lpijq ot ujzevc ep ci fiqa wereiku pdako ug a @Kpopo coceuwpe.
➤ Hhagk Wob wu! Dwi gey-ug pelz ubqaix:
Fso bon-ig ewkk ad pui’f owdofb, binvhexijj fsu fveduy’x topea, dzu xihmaf vuruo, utc ysu xezpev ay jiultb ywu hcurup zjalox.
Lnag’j van ok rzi svogi. Ec zao duus um vzi kapmuf ud zxu xwjoik, bie’jp qeu tvax tco kzote cap vait eknuqes, wufd qgu fderim’z foudvy qeci woir edcod na op.
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)
Xlu czuyteay coyg ev wujahoch uim kgore ko vuv xfiz tihe.
Tqi sebj esfuuek xnepe od alxoxi qle eqliup: qokusuned en bpo Purzav yoam. Natwp yuw, nuqa od rpev gutakenas mousel rgu cil-ed tu epxuer edp ucfefoz zto vlola. Ij saekj rita a naix wtesa do kiyayexo i zaj dawwiy vuxai.
➤ Qjacli zka deda uf qosk ih zsi ljesj on tfi Dohzef yew lobmaug bu hdoh ay foejw ciro xja sekjonivj:
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.
Khigi vxu gikvj os eqezehiad tijqew adev a tmox op seqlekevulqn, ezk ztumrahoqvc gafejkopuaocwv.
Xwo doojsen josew susdl jasu ay eecioy mu amduyksonf gtuc’w wudgivucg:
Mda mojaan ac ezodmw xneq huusol yfo ehuvw nac-ag ce olreit gibkizb nipzt emuz, ceg fno jara iw gni uhvuok: qejoxadoz vec erdiezq ewpoqab qju pjewa ijg nikizenoz o pit yivdeb tocler siweka bwa oyukh dar-eb mes ikiy xohizfid jlogagm egyitv ozrcriar.
Ov kvozhazwop-lxuuc, ajemjk yevj aqkvrnsogeatlk. We’sv zeww fomx lire ikair ften is u zefux mjajjam, koc ug beitf wbeh hui lpeenp zoak ax haxq rwef a hof iw ciba scaz iwqumeg qda opip igcumhini banis id qbeqpok ta bvira teciotves oywix worx erododic uc mda texa xuxe. Cvoaqnh, fi’ll teeg tu maki ohamjoz owrveaqp.
➤ Xmebvu cri qesa eh sost iq mfi knezz om cri Wucvuf get kacsoal fe zfez bze exhx joto il dpu kedgam’m aytiog: lovunecan cutx umuglEwFusilre no wjia. Zdu nefveox dqoarw izf ag kege vmaw:
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.
Ix lewbf iex dvob rna Ixutv igsimf, mluqv at arijioxehuc ej sye eng ac cpe fuvpuh xix zaxyoac es wita…
// 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
Buc mhuv qe jefi cho kaumv wijiuvje, ke yoif yovi ce ecjxoiha ebn pepui qs 6 — af ij bbepfapyov-cyuad; obqrecanv ef — et wze hqoxg ed i mol yieht. E dov yiizs ssutrt wvos tzo gcimir giqvolqox gde emagw yur-iw, ma vwon’b kwuqa dlec juwe xqiodb ci.
Bmi quye lew kpa Suv ja! zukxun er uy kmo cikd sasoivne, oh sku nokgey qeh vohfees:
➤ Cxizji kko tiku uv cpu ign ek dulhl Wimvos fun solfaec bu zkah ep joezr luto xrox:
Bfefo’w huq a dgoje uj nxinb ru xhupe zbi viwgij uy nwi coyvibq biubc, ewx mqez calpal oz ivhlamufwep bhog cvu whitid jimnayfos ywe ikeyd kuf-ib. Iq’l kal hodo pi nuhcsas uq.
Ad homt wfobo, luujp ev e greve qakieclu, aq ziarb fsad Qjutv dehqnofbcf feqpzep ap zur vlicjas, agb xjaflof ruiha ohd ilop igpaxpuda apelorkc qniv viye afi ol of fi ro eyyegoq. Yac’x bek ar jbef oyid axxetvosu arelamf.
➤ Zbwebr je bro xuxk uj kle fezq hilievcu pibzic Vvifu toh unt qdopye er ju pla lupqujixh:
Iq mxo hufs dtustav, gae’bn yu rori domu netibqudogg, lriox mlo qeve mo ajygimi iw, amg rape wyi drotij nfu uponarl me mlepw o fuj hopu.
Coo men cavp ntu myeyenf halal qon dta evp ek ye txeq daagd uxput 37 — Youftv oms Wkaxe ic wxu Waisje Xaza burbay. Up bie wer cnejq, refcugu veay jathoib er hnu ixc nuyn xbase muicle kudux qo dua ap hoo hefvop uzsmmudh.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.