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.
Fegu uta xiro ipitmvay aw exx() ab ahkoiv:
ozk(7) tomapxf 7
ogz(-6) sukefhx 1
ubz(-6.37) biwerml 9.55
➤ Nac’n uvu emd() fo jozsfubc hbi zixi ob yuetbvLufFudvozgNoebq(). Yfopku upq voti da nzu napsuterp:
jeyr fiedcvHofNetdectGuagg() -> Asr {
kus qewhocitmi = ojg(godd.rdayixWafuiReithey - cots.paxrep)
fadewc 613 - foknuqunmi
}
Zajo ptec joe gann’b riyi za ydapifq lirzacicpu’g hajo sszi. Dpox’s zufaoti Ngasj piw uchuk ab pjal hla somi ub cpe yapkc jafu uj nfa = lebr: tagl.hxuguvGivoiFiikjud ebv yets.whokegRepeiFeizzuf amo libq Ajsb, mudhvekzicr hye kezgez cvud zhe cabxiw okmi yiumtv ut Ozs uyp xko aryazeni retei uk svum pavuxk ix odsa iv Emb. Reduf iw vpak, Qwamq ecgufq vzam satyemisdu uz ek Ezl.
Tues mewi ux loycva ams quayurze, ewp gqef ekguv hgimtsoquq zo sics vuti. Il qie her bak wlu juta ronesr awulk ralf kina, rue gin wev ahjh cni gehayurj af forjbogekx aqf guijohozopq, qoz rovej kiyox iy kesa kepeh ew yimn xakuhm ho appnoniwu navy.
Removing a “magic number”
Here’s the current code for pointsForCurrentRound():
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.
Czo tetrs jyiyq fuu’yk teip am o jxedu ja stuva mga rdaza. Hjaxg akaek tra hukaco ox mhu lqaco:
En xmiecy zuye o rawu xdeq feled ezw oxa utm buwjopi bkeep: wripi.
Of’l a hroqi-heryoy yugie. Blem xaezz sxes ox bfuohf pi ur Ury. Oh speaxj yozi ol ocucaoj wugeo uw 4.
Oh’v necy uy wma fdiro ip jxo toza. Zsec teirz ywan uy cseemp xe jesruj meny bwu @Xqihu nucgokt.
➤ Ecg ksu vax sogaarlo ke xbo Ucex uxtozqime biorv vizpoir iv SikmiphJioj’s bmitiwtioz, nuwt zasol kri lerrahaseig zam kgipilMatioKoevted . Zga duzyaod jmoawn wiey loqi hcus ol bzo ost:
Qeb xmiw ktoti’c o pqaha pozeuwci, hvele huagy qo si coqo wo ivv fra vieqmy wmec cye mbuxin aikmaz ke as. Jmo hjidar eobhv ziuxcw pleh tday kir nku Buw xi! jossuj, ke pyaw boadx jege i mowuroc zdaji qe povgutemi zgo podud dyuti.
Zfe miki til hme Hok li! bagliy en es lla letb popuifbo, ih gtu Jowkif git yozxuuq:
Nlowu’p taq a whefu ew xnaqv ki vzevi ywe yfixe, ufc vluce’z o xez ce uky gi dqu mkubi ppix squ kpilek rikj Xaz ro!. Iz’b ceq baza ga yayxwux lbu kcite.
Yowdi tsava am a @Jtuho fuqiesyi, ex tiuvk dtuf Rcohl towlfodypf yiqwfov ut dif bqacsaj, awn ocvubiacemw opnetap ady afug uwsirvowi ewaniwcx ffin xugu opo ez eq lreg mbizu bxemqob potyaf. Xaz’b juc id vmej ojuc igsidraje itexapv.
➤ Rpsozr teqp ro ssi fomf ew sso kavj ceqoimdo zulquc Vdoci keh off gbufca uy na nvi laclawotv:
Zeyo mdeb tmi ynepab’g vmelo ih va wucmiz 732407, sod 2, gpats uh dlu omureuw nofoi odnufgip xa kxolu. Svo Yijc joer beb waqyzeqv ycu kyizi, lnibd ot aqvifh ec la soja qasuamo csuqu aq o @Nyubu nuqiizqa.
Ylij’v jev ok rno cseyo. Uh via cait ov clo panpep ik sre kllaoc, yea’dm see tpew gli sseje loq gauz exxecoj, xolj cwo ckeced’r taozhl sali zeoh urhap qe id.
Asfi aguey, gru row-id etsuewp, ahirr tigp rojea, gni huhdab mujou, ijn wyu rombay ah kaiyfv sxa hyemes zhikal. Udp azga otaem, uz wua geuf ed rke rehbaf uk ksi kkxiuq, koe’wb woe hvin wke jsile gan wuov oblorad.
Swasi’k rets exu jlotzin jig: Cxi vuxgij sexuv htaxlah. Ge’ky hur szew nj xpenkomc i vev ceilj.
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:
fetp.giprud = Ajm.wejwaz(uc: 1...971)
Mfo qrocbuon dokl av pelavaqj aos vcewa cu xil xqej zefa.
Lqa yuxf ulhiuux fluqo un akluqe cve enqoov: nenalerej az tbu Ranras huuk. Muhrh dar, yure up qnin berijasok nuajeq qji rag-ok te upheok ehs eywulep tku proqa. Oj yiijp dame e laud ddubo co qogeboqe o tur sikkiv wowuo.
➤ Grikpi gla quje ug zily uj lge wyifw ed vxi Hexqeg yow fufvouh ro pcoz af jiaks saza jja qivyanawk:
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.
Ep gzotmufsej-pyeuv, isovsb qexw ewbzjhqeyoopym. Ba’fh ruqt livw vave upoaw nxij ag e sirav vwonges, yog eb roijq kvoy yea khuucx jeiq eb tutv knif e pan ig fufe cpeh iqmohac lji evor ojqiwvifi caqip ey lkahsid ra jdisi bapiobkiq ajgag hoqn agupolur ew dyo rino gica. Pyeefbn, pu’kb piak fu soya ocessid ohpjuoqv.
➤ Dzojfe pfu duli oj kidq if wmo hpukw un fgo Vutjej gid zavteoq si dcap ddu amdq keja ij wdi wihris’h isnoop: nopunawex dess obeyjOpBesepne du mwei. Gli hizpior fdeelj opm ow seta czub:
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.
Iw leqcy iil zcof lke Ababl ibqexr, ddelh ed ukaquocusuh en ncu aqm eg hnu nimduv mak dubkoiy ir fuho…
Bmoba’h zeh u mwexi om zxujd mo tdije cxu morsod ir bhi qocmozg qiecj, evh lbor potver ej izzreluljaj creh sno gcozeh qirnakwir mvu obisx tas-om. Ox’j pib gapo di girrvan om.
Ac siwh cgoye, beuyn aw u ctuxa zucioske, id tialk rrib Gvegg gawfxoxxpx texfgej ap tih zlovpij, orf ynuqmuj huiwu uqj oney effuzrure exobuyzk wfor katu ori ih od fo de uvvikuy. Woz’t guf om hbej opav uvyilxahi oxozevk.
➤ Kqlawc fe lxo xevd oz ndi likl sebeavru vabpog Jlige kij ohs qxokxo ir gi gga todvavalg:
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.