Lingo Game: Controlling with Keys (Pacman-like)

READING: Manual pages of the commands described here. See an example of user control through keys on pages 636-637 in D8D

File "Pacman.dir"

shows how to move a character using the arrow keys.
Each key on the keyboard, when pressed transmits a particular code (the keycode) that can be monitored.
For example,

  • 43 is the <,
  • 47 is the >,
  • 123 is the <-- and
  • 124 is the -->
on keyDown
   put the keycode
   x = sprite(1).locH -- remember the horizontal location of a sprite
   put x -- just to track down its location
   case (the keycode) of
      43, 123:         -- < go to the left
        sprite("ball").locH = sprite("ball").locH - 5
      47, 124:         -- > go to the right
         sprite("ball").locH = sprite("ball").locH + 5
   end case
end


Now our smilie can march off to the left or to the right for ever!

File "Pacman2.dir"

shows how to control its location on the stage. The "ball" can move in all four directions and can recognize the screen boundaries:

on keyDown
   case (the keycode) of
      123:      -- left
         sprite("ball").locH = sprite("ball").locH - 5
      125:      -- right
         sprite("ball").locV = sprite("ball").locV + 5
      126:      -- up
         sprite("ball").locV = sprite("ball").locV - 5
      124:      -- down
         sprite("ball").locH = sprite("ball").locH + 5
    end case
    checkLocation
    updateStage
end
on checkLocation -- IT ASSUMES THAT THE SCREEN IS 320 BY 240
   -- make sure the ball doesn't fall off the edge of the screen
   if sprite("ball").locH < 10 then sprite("ball").locH = 10
   if sprite("ball").locH > 310 then sprite("ball").locH = 310
   if sprite("ball").locV < 10 then sprite("ball").locV =  10
   if sprite("ball").locV > 230 then sprite("ball").locV= 230
end


That is painful, no?
Well, Director has a better solution: Constraining a sprite within the boundaries of another sprite. Experiment with

   sprite("ball").constraint = 1 -- stay within sprite 1

where sprite 1 is another sprite, a rectangle that you want to use as the constraining area (you have to create it first).


Now try to program the "chomper.dir" like you would in a pacman! It is better so simplify the programming part by using functions that abstract the chomper's movement and chewing animation:

on keyDown
   case (the keycode) of
      123: chompLeft
      125: chompRight
      126: chompUp
      124: chompDown
    end case
    eatFood
    updateStage
end


You know how to do all of the chomp functions, but how about eatFood? In this case, you want the chomper to realize it is touching the food balls and eat them by making them disappear. There is a very useful function in Lingo for this:

sprite("chomper").intersects("foodball") = 1 -- check if they intersect
      

Now you can quickly check if the chomper touches any of the foodballs using a loop.

 

 

Maintained By: Takis Metaxas
Last Modified: August 7, 2007