6

In many languages you can do something like the following:

while true:
  handle events like keyboard input
  update game world
  draw screen
  (optional: delay execution)

while this is far from optimal it should suffice for simple games.

How do you do this in Squeak Smalltalk?

I can read keyboard input and react to it as described on wiki.squeak.org. But if I try to execute something like

1 to: 10 do: [ :i | game updateAndDraw ]

all the events are only ever handled after the loop has executed.

Higemaru
  • 354
  • 4
  • 10
  • You can check for examples of games implemented in Morphic, sure you can find several of them. I think that a common simplistic way is to have a single Morph for the game, which processes keyboard events (making changes in the model), and then #updateAndDraw redraws its sub-morphs, according to the current state of the model (positions of actors, visible indications of state and so on) – Carlos E. Ferro May 11 '17 at 16:52
  • I need to have the game keep updating even without input. How would you do that in your approach? – Higemaru May 11 '17 at 18:03

3 Answers3

7

Morphic already provides that main loop. It's in MorphicProject class>>spawnNewProcess:

uiProcess := [
    [ world doOneCycle.  Processor yield ] repeat.
] newProcess ...

And if you dig into doOneCycle you will find it

  • (optionally) does a delay (interCyclePause:)
  • checks for screen resize
  • processes events
  • processes step methods
  • re-displays the world

Your code should hook into these phases by adding mouse/keyboard event handlers, step methods for animation, and draw methods for redisplaying. All of these should be methods in your own game morph. You can find examples throughout the system.

codefrau
  • 4,583
  • 17
  • 17
  • Could you please point me to one example? It is not clear to me what goes where and which classes to subclass. – Higemaru May 13 '17 at 10:49
0

To perform an action a fixed number of times:

10 timesRepeat: [game updateAndDraw]

To use while semantics:

i := 5
[i > 0] whileTrue: [
  i printNl.
  i := i - 1.
]

To create a perpetual loop using while semantics,

[true] whileTrue: [something do]
ben rudgers
  • 3,647
  • 2
  • 20
  • 32
0

You should be able to take advantage of the Morphic event loop by using the Object >> #when:send:to: message.

edcrypt
  • 31
  • 4