Skip to main content

Score System

Game engine API · Lesson 4

Score System

puan() always returns a finite number. Learn to write scores with puanAta(deger, sebep), reject NaN, and read the puan event fields.

The score lives in a single source of truth. Game logic never mutates it directly; it writes through puanAta() so the engine stays in control.

What you will learn

  • The puan() and puanAta(deger, sebep) signatures
  • Rejecting NaN and Infinity
  • The onceki, puan and sebep event fields

API signatures

CallResult
basla(mod, config){ok, hata?} · validates mode and config
puan()finite number · 0 when broken
puanAta(deger, sebep){ok, hata?} · emits puan on change
olay(ad, fn)function that cancels the subscription

Reading is always safe

puan() checks the stored value with Number.isFinite and returns 0 when it is broken. The UI can never print NaN or undefined.

Read the score

var M = window.OyunMotoru;
console.log(M.puan()); // 0
console.log(typeof M.puan()); // 'number'

What happens in this code? Calling puan() before the engine has started is safe; it never throws.

Writing and the event

puanAta converts the value with Number(). A non-finite value returns {ok:false} with an error message, and no event is published.

When the value changes, the puan event carries onceki, the new puan and the sebep text. The 2D layer updates the score in exactly this way.

Write a score and watch the change

var M = window.OyunMotoru;
var kapat = M.olay('puan', function (e) {
  console.log(e.onceki + ' -> ' + e.puan + ' · ' + e.sebep);
});
M.basla('2d', { kok: document.getElementById('oyunAlani2D'), oyun: 'sayi-yakalama' });
M.puanAta(10, 'dogru');   // {ok:true}
M.puanAta(30, 'bonus');   // {ok:true}
console.log(M.puan());     // 40
console.log(M.puanAta(NaN).ok);      // false
console.log(M.puanAta(Infinity).ok); // false
kapat();

What happens in this code? Assigning the same value twice publishes no event, because the engine checks onceki !== sayi. That prevents pointless UI updates.

Common mistakes

Wrong approachResultCorrect approach
Mutating the score directlyState and UI drift apartCall puanAta()
Passing NaN or InfinitypuanAta() rejects themCheck with Number.isFinite
Leaving sebep emptyThe event has no reasonPass a short reason text
Reading the score without an eventChanges are missedSubscribe with olay('puan', fn)

Try it yourself

Assign scores with three different reasons and confirm that the onceki values form a correct chain. Then pass null and confirm the write is rejected.