How to program a computer if you are a child/Your turn

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Here is the scenario of a little game I programmed when I was twelve or thirteen, a long time ago:

| The bars here provide comments to the reader to help him or her understand the program. They are very important because they allow programs to be reused. If one does not comment, a program is often too difficult to understand, even for the one who wrote it, as soon as is forgotten what was done exactly. |

| This game displays a kind of simplified snake that keeps growing from the center. The player always ends the game by hitting one of the 4 walls of the room, the screen, or returning to a place where the snake has already left its trace. He or she must remain as long as possible by controlling the movement of the head of the snake. |

| It is assumed that the screen is capable of displaying 24 lines of 32 characters. |

X = 16 | The position of the snake's head is coded
Y = 12 | by these two numbers. X is the column number
       | and Y the row number.

| Right, Left, Down and Up are the commands given by the player, from a keyboard or a joystick. He or she is not allowed to do on-site: |

As long as the game is not over, do again and again
   If Right then add 1 to X
   If Left then subtracts 1 to X
   If Down then adds 1 to Y
   If Up then subtracts 1 to Y

   If # is already displayed on the Xth column of the Yth row
   or if X <1 or X> 32 or Y <1 or Y> 24
   then the game is over
   otherwise display # on the Xth column of the Yth row

 

A variant is possible for two players who compete in the same room, each with his or her snake.