Skip to main content

Engine State — Read mod, oyun, sahne, calisiyor, durakli, puan and hata through durum(). See why the returned copy cannot mutate the engine.

Game engine API · Lesson 6

Engine State

Read mod, oyun, sahne, calisiyor, durakli, puan and hata through durum(). See why the returned copy cannot mutate the engine.

durum() returns a copy of the observable state. A fresh object is produced on every call so outside code cannot mutate the engine.

What you will learn

  • The seven fields of durum()
  • Why mutating the copy has no effect
  • Reading the hata field

API signatures

CallResult
durum()state copy · mutation has no effect
basla(mod, config){ok, hata?} · validates mode and config
duraklat(){ok:true} · state is kept
puan()finite number · 0 when broken
devam(){ok:true} · loop resumes

Seven fields

The returned object contains mod, oyun, sahne, calisiyor, durakli, puan and hata. Initially mod/oyun/sahne are null, calisiyor and durakli are false, puan is 0 and hata is null.

Initial and running state

var M = window.OyunMotoru;
console.log(M.durum());
// {mod:null, oyun:null, sahne:null,
//  calisiyor:false, durakli:false, puan:0, hata:null}

var r = M.basla('3d', {
  kok: document.getElementById('oyunAlani3D'),
  oyun: 'geometri',
  genislik: 480,
  yukseklik: 320
});
var d = M.durum();
console.log(d.mod, d.oyun, d.calisiyor); // 3d geometri true

What happens in this code? In 3D mode setup is asynchronous, so the state opens immediately; the 3d-hazir event arrives once three.js has loaded.

The copy and the error field

durum() builds a new object on every call. Changing kopya.puan has no effect on the engine score.

When setup fails the hata field stays populated; a successful basla() resets it to null.

Mutate the copy, query the engine

var M = window.OyunMotoru;
M.basla('2d', { kok: document.getElementById('oyunAlani2D'), oyun: 'labirent' });
var kopya = M.durum();
kopya.puan = 999;
kopya.calisiyor = false;
console.log(M.puan());            // 0
console.log(M.durum().calisiyor); // true
M.duraklat();
console.log(M.durum().durakli);   // true
M.devam();
console.log(M.durum().durakli);   // false

What happens in this code? Because of this behaviour the state object is safe to log or pass to a UI layer; the engine cannot be damaged.

Common mistakes

Wrong approachResultCorrect approach
Writing durum().puan = 5The engine is unchangedUse puanAta(5)
Reading durakli instead of calisiyorMisleading resultEvaluate both fields
Ignoring the hata fieldSilent failureAlso check the basla() result
Calling durum() inside a loopAllocates an object per frameUpdate from events instead

Try it yourself

Print the state to the console. Confirm that durakli changes after duraklat() and devam(), and that mutating the copy leaves the engine untouched.