3 ms·
See my simple Tetris Game, https://github.com/jstimpfle/tetris-on-a-plane/blob/master/tetris.js https://github.com/jstimpfle/tetris-on-a-plane/blob/master/t...,
by jstimpfle 10y ago
See my simple Tetris Game, https://github.com/jstimpfle/tetris-on-a-plane/blob/master/tetris.js https://github.com/jstimpfle/tetris-on-a-plane/blob/master/t..., at the very bottom.
This implements a state machine in Javascript. It's a very simple case with only 2 states, "playing" and "paused". Each state registers its own event handlers on entrance, and unregisters them on leave.
This approach avoids the need to answer the question "where am I? what should I do?" every time an event handler is called.
While I think the approach is nice, the code is not so nice from a superficial point of view. The more general problem is that event-style sucks. Look up CSP by Tony Hoare, and Occam the language. What we need is better formalisms for sequential programs that include non-determinism like user events (i.e. view the user as part of the program).
(And, of course, also parallel execution of these sequential threads, and also sub-states that can access parent states in a way. Look up Harel's Statecharts. A good example would be a form with two text input boxes. We could view them as parallel sub-threads of the form thread).
- s_m_t 10y agoNice, I implemented something very similar, except in my game not every controllable entity a) implements every control, and b) implements controls the same way, so I store what a control would do as a member function of each object and store an array with the names of these functions in each object. The indices of the array with the names of the functions match the indices of an array that stores the key codes I listen for, from there I match the indices, grab the name of the function and call it from the object being controlled.
- jstimpfle 10y agoIn Javascript, you have to install event handlers. There is no control when they are executed, which is a problem. When writing a game engine, you typically create events yourself at the top of the game loop (reading the input sources in a non-blocking fashion). You have better control what handler is called and when, but what handler should be called probably still shouldn't be decided in a central location. So I figure your object-based approach is a good solution. (The individual handlers can rely on the fact that they are only called at the start of the loop). I realize a Javascript app could easily emulate the game loop style by letting handlers write to a queue.