banner-nll

Logic of Conditional Commands - cont.

If and Ifelse statements are powerful tools to have different turtles or patches run commands.  They are essential in any programming environment. 

A procedure that uses one if or ifelse statement is quite simple to follow.  But conditional commands can be nested.  A procedure can have multiple if/ifelse statements. nested inside of one another  

For example, in the Model Library there is a NetLogo implementation of the classic arcade game PAC-MAN.

Just look at the code which implements the “Play” procedure:

to play  ;; Observer Forever Button
  ;; Only true at this point if you died and are trying to continue
  if dead?
  [ stop ]
  every (1 - difficulty / 10)
  [ move-pacman ]
  every 0.25
  [ update-bonuses ]
  if floor (score / 35000) > extra-lives
  [ set lives lives + 1
   set extra-lives extra-lives + 1 ]
  if dead?
  [ ifelse lives = 0
   [ user-message "Game Over!\nScore: " + score ]
   [ set lives lives - 1
     ifelse lives = 0
     [ user-message "You died!\nNo lives left." ]
     [ ifelse lives = 1
       [ user-message "You died!\nOnly 1 life left." ]
       [ user-message "You died!\nOnly " + lives + " lives left." ]
     ]
     ask pacman
     [ setxy (item 0 home-pos) (item 1 home-pos)
       set heading 0
     ]
     ask ghosts
     [ setxy (item 0 home-pos) (item 1 home-pos)
       set heading 0
       set shape "ghost"
     ]
     set dead? false
   ]
   stop
  ]
  if level-over?
  [ user-message "Level Complete!\nScore: " + score 
   no-display
   set level level + 1
   load-map
   display
   set level-over? false
   stop ]
  every 1.6 * (1 - difficulty / 10)
  [ move-ghosts ]
  every next-bonus-in
  [ create-bonus ]
end

 

The complexity in this code example is far beyond anything we would expect you to be able to write at this stage, but it is a good illustration of the nuances of IF and IFELSE statements.


With Support from:

The NetLogo Learning Lab is part of modelingcomplexity.org, the home of the Mesa State College Center for Agent-Based Modeling.

This website is copyright by Mesa State College, 2004. All rights are reserved.

Some materials are adapted from the NetLogo User manual, and are copyright Wilensky, U. (1999). NetLogo.  Center for Connected Learning and Computer-Based Modeling. Northwestern University, Evanston, IL.