A colorful way to teach computer programming.

Patent pending

This website is a part of SIX PROJECTS Follow this link to find my email address.

CODEPEGS grew from my previous projects MAKE THEM MAD and FIREPEGS. I wanted you to know about them all and draw connections. Spatiotemporal very large pixel patterns are paramount for teaching, and they are all we need to teach the fundamentals of computer programming. Computer programs are just spatiotemporal pattern makers, after all.

What are spatiotemporal patterns? To find out instantly, run FIRESHOW. Like all my demo websites, it's free, totally non-commercial and contains 100% my JavaScript.

I call such patterns very large pixel patterns to tell them from regular bitmap images and from the drawings produced with turtles and pens in Logo-like programs. For brevity, I often call very large pixels just pegs.

Very large pixel patterns are for everybody. A learner does not have to be a computer artist or an aspiring game designer to deal with them, although images and vector graphics can be incorporated in several ways.

Very large pixel patterns are more accessible, intellectually challenging and rewarding than anything I see in teaching programming yet. Remember how many games were created for alphanumeric computer terminals.

Except for the patterns and computer programming itself, nothing in CODEPEGS is beyond the knowledge and skills of a regular 4th grader. Most patterns, in turn, I tried and proved on a 4 years old. Schools don't teach such things, but kids get them quite easily.

The technique is language-independent. I had to use JavaScript, which is a terrible choice for beginners. I did my best to make it accessible.

The beginning of PART 1 was made to intrigue. PART 2 is technical, but it's about web-programming. Part 3 is about just programming.

I like Sidewalk LOOPS in the beginning of PART 3. I've never thought that loops could be introduced so nicely. The patterns kick in next, and I trimmed off half of what I wrote about them to keep this demo accessible.


The magic behind the window.

The secret of spells

You speak, something listens!

Scattered along this and the following pages are playboxes, like the one found below. The black box on the left, often called textarea, is for typing or pasting texts. On the right you see the pegboard, which you can change. The little squares are evolutionary descendants of the pegs, even though they look more like tiles.

Important: it's not FIREPEGS. The pegs are not connected and they do not behave on their own. They are empty shells.

To change a color of a peg, click inside the black rectangle and type the spell.


To cast a spell, click inside the text area, then anywhere outside it. To re-cast, do it again.

Note that (1,1) addresses the central peg on a 3x3 board. The top left one is (0,0).

Textarea is a simple text editor. Textareas are very common on the web, but even if they were not, those who know one simple text editor, know them all. Here is what you can do, very briefly.

You can erase the old text and type in something new. Textarea has a caret (also called cursor), so you see where you delete or insert characters.

To select, drag the mouse pointer with the left button pressed. Ctrl/A selects everything. You can delete and/or replace a selection at once.

You can copy/paste and drag/drop the text, selected anywhere on the page, or right inside the textarea.

While picking the spells from the page, make sure to select the spells, and nothing else. Remember, computer is stupid.

One more suggestion: you can select the end of line and copy it to the textarea too. Simply point somewhere in the beginning of the first character of the line, click, select a little bit, then pull the cursor down and to the left. You can also start in the end of the spell and pull the cursor backward.

Like most editors, textarea undoes the changes and brings back your former spells if you press CTRL+Z.

I am not sure about searching. This may depend on the browser. Usually, if I search the whole page, text areas are included.

I hope, by now, the middle peg in your board has turned white. Let's try more magic. Select this spell, drag it into the textarea, drop, and cast, clicking inside and outside. The whole window will change its color:'gray';

OK, I don't like this too. To get your browser's background back, carefully replace gray with white. Remember, one wrong letter voids the power of the spell. Be sure to change only the name of the color. Don't touch anything else, including quotation marks. In case you messed it up, the second spell must look like this:'white';

By the way, if you did not clean the board and added the second spell after the first one, that's perfectly fine. You will change gray to gray, then gray to white. However, dropping a spell in the middle of another spell ruins both.

What the spells mean

Where and what.

Look again at how we've made the whole page's background white.'white';

Although strange, it's certainly more legible than, for example, barcode. The words are more or less English, but what do they mean?

Here is a new spell:'white';

For your convenience, it comes preloaded into the following playbox. Click inside and outside to cast. By the way, all playboxes do the same. You may erase preexisting text and drop any spell anywhere. To change the size of the board, use the spell size(), For example, size(6,4) make a board 6 pegs high and 4 pegs wide.

Uh-oh, what have you done! Hurry up, click where the textarea was and hit Ctrl/A. See it? White letters are no longer visible on white and the whole textarea became invisible on the page, but the spell is there. Delete the selection. Select, then drag and drop the following.'black';

Click inside and outside to cast it. The text is now black, but where is the textarea?

Try this.'thin solid black';

Did you draw the border? Good.

Now let's compare the last two backgroundColor spells.'white';'white';

Did it start making sense to you? The dots separate the intermediate destinations, like US.Ohio.Cincinnati, etc. Once we've navigated to where we want, we can address something called style and tell it which color to paint its owner's background. This last part is the same for the page and for a text area because, after all, they both are rectangles on the screen.

Another - and even more important - way to think about it, is that everything belongs somewhere. Street belongs to the city, building belongs to the street, etc. Street name is not enough if we don't know which city it belongs to. Just style is not enough. Both the document's body and the textarea have styles. Every peg has it. We have to tell whose style we are talking about.

What the spells do

Find rectangle and color it.

A spell as simple as setting backgroundColor reveals how browser fills the  s   p   a   c   e .

A web page is made out of rectangles. This, I believe, is essential to learn first and foremost. You can pull up the list of all rectangles on the page, and change them one after another.


If you want to try, copy the spell and paste it into the first playbox on this page, because that's there the events are going to start. Cast, then increment the number in the square brackets and cast again. Sometimes nothing visible will happen. Some numbers may make your browser to curse back. Most of your spell will turn the next visible area pink. Some elements are sitting inside the other elements. To reach them, you need to dig deeper.

Now how about change(1,1,'white')? A peg is a rectangle, OK, and we set up its color. Why does this spell look so different?

Because I sugarcoated it. The actual spell is


You may try it with any two numbers, as long as they fit the board, and with any color name you can think of, except I do not guarantee that your browser knows it.

I wrapped the backgroundColor spell into this change() thing called function for three reasons. The first one is easy: I just wanted it to be short.

I also wanted to bunch up several more spells with the actual color-changing one, so that they would always come together. For example, I wanted to change colors by numbers. Try to put numbers from 0 to 5 in place of the color name, with quotation marks or without them. It will work, but only for my pegs. The page will not get it.

Third, I did not want to scare you off with insane square brackets too early, but I wanted numbers. Remember US.Ohio.Cincinnati? Next will be the street name and then the street number. Assigning a name to every door would be utterly impractical. For similar reasons, I did not name every peg. I numbered them. As for the square brackets, I will introduce you to them in another chapter.

The numbering of the board is reliably consistent. All of the pegs are visible, and none of them is missing. We can navigate from peg to peg by adding and subtracting distances. Click inside and outside to cast the following preloaded spell, and try to understand what's happened.

Kicking a web browser is an engaging method to explore the mechanisms behind WWW. Textarea is a hatch, hacked through the web page into the darkness of the browser's belly. You may imagine yourself standing at it calling: "Dear document, I'd like to speak to your body! Hello body, may I say something to your style? Hi style, please paint the body's background pink."

What you just read was another kind of sugarcoating called metaphor. Without metaphors the harsh reality of computer systems would be unbearable even for the brainiest. Unfortunately, there are too many metaphors floating around. This one is very useful, even if not quite applicable. In web browsers the objects do not talk to each other nicely. They simply take what they need.

I can only wonder how many internet users know how accessible is the magic, which they call "technology". A simple playbox lets us tinker with the existing web page immediately, through the browser's Document Object Model, or DOM, avoiding the famous "tag soup" of HTML. We see it, we change it, we can add new elements and configure them. Technically, we can build web pages this way.

The science of education calls this experiential learning. Some speculate it is omnipotent, or, at least, more powerful than a traditional systematic approach. Just give them computers and leave them alone.

Every bit of my experience with the kids having practically unrestricted access to computers tells me the opposite, but I agree that we usually provide the answers and demand the students to remember them before they asked any questions.

Desk top or bento box

A brief history of user interface. Long, but may be useful.

With the advent of home PCs, I remember how parents were eager to teach their children to use computer mice. By now those kids have barely entered productive life, and they are teaching their toddlers touch interfaces like the whole their future depends on this.

What's wrong? Only the direction. Computers are not running away from us. They are struggling to approach us. The later we will start teaching our kids consumer-grade computing, the less they will have to forget and to regret. Don't teach them at all, they'll learn this stuff anyway because it's made to be easy for everybody. Advanced skills, meanwhile, do and will require advanced thinking.

Through all the changes, one kind of user interface has been standing unshaken since it emerged in the late 50s as so-called console typewriter, and then evolved into alphanumeric video terminal. In modern systems it's the most dreaded, cryptic and powerful black screen, through which wizards talk to computers in spells. If you want your kids to learn something durably marketable, teach them command line.

The recent developments allowed us to admit that, in spite of (or, maybe, because of) the abundance of mandatory education, we hate abstractions. Most people tolerate speaking and listening, but reading and writing is too taxing for them.

In 1972 - ages before YouTube - the team of Xerox scientists made a groundbreaking concession to the popular demand. They developed the first graphical user interface, also known as GUI, or WIMP (windows, icons, menus, pointer). The seed took ten years to germinate, but in the end everybody wanted the fruit, and got it. Unfortunately, GUI had become possible via a new tool: computer mouse.

We humans hate any tools, but computer mouse was (and still is) particularly noxious. To this day, serious users avoid GUI, preferring keyboard shortcuts. Mice tie us to chairs and tables, causing pain in our arms, hands and butts. Billions of users rejoiced over usable, portable, affordable touch screens, when they finally became available. Tectonic move from chairs to sofas came to be known as mobile computing revolution. For the limbs, by the way, touch is hardly better than mouse, but which body part is more important, after all?

Like so many words in computer business, graphical user interface was a misnomer. Instead of describing the users' experience, it was telling how the computer monitor was being operated. It could have been a mistake too. As far as I can tell, the majority of users open one maximized window at a time.

Computer programmers are not much different from the rest of us. The same team that gave us WIMP, created the first program called browser. It was not for the web, and it was not like a web-browser. It probably was the mother of modern Integrated Development Environments. The big idea was to keep everything in one window divided into panes. Hence, being two-dimensional thinkers themselves, software developers cold-bloodedly confined their customers to the horrors of three-dimensional desktops.

A well-known example: it took years and years to introduce the tabs, allowing web browser users to switch between multiple almost full-screen windows. The masses have been asking for this, and nobody listened.

Wherefrom, whereto

How did I get here, and where I am going to proceed.

The previous chapters were about web-programming, because I wrote every program in these demo websites in JavaScript, and attached it to a web page using HTML and CSS.

I decided to use JavaScript based on its reputation, and it was less than one year ago (correction: by the time of this editing, it became less than two). I didn't know the browser scripting before. I started from scratch, and I must admit that it did not live up to my expectations.

As a user, I have never liked the WWW. I appreciate the information it delivers, but not how it delivers it. JavaScript to me is 99% pure evil. It steals tons of my computer's resources to spy on me and tell me what to do.

On the other hand, modern web-programming, with its complexity and ability to entangle people and organizations, must be a wonderful business for its practitioners. Potentially, as good as medicine or law. I am just not getting paid for this. I only suffer.

With this in mind, in PART 2 I worked out two lesson plans with an intermission in the form of a game-like activity. Then, in PART 3, I show how I would teach conventional programming using the board as an output (and even as an input) device. If you don't want web programming right now...

... use this link to jump to PART 3..


And a lucrative one.

They are from Jupiter

The reasons behind the lessons.

Learning web programming, I went through many sources and read many questions, asked by the fellow learners. Soon, I understood, that the creators of HTML and CSS do not see the web as we users see it.

According to the authorities, web pages are supposed to be like books. Think of WWW Consortium's own web-content. The backbone is a stream of text, a story flowing from the beginning to the end. Everything else, like tables, pictures, formulas, is tucked between the words or hangs beside them.

Web-users (including those who ended up learning web-craft) are from another planet. Of all the pages, the ones most viewed are like dashboards. The stories, if present, are contained within rectangles. The layout of those rectangles defines everything else.

Beginners want to reproduce what they see, and discover the painful truth: even though web browsers build pages from rectangles, apparently using bit block transfer technique, the language-level methods to create layouts of rectangles are hard to get. The WWW pundits must have been incredibly wise to have made them so obscure.

My computer-simulated pegboard is a bunch of rectangles, and even a grid. Pegboards live submerged in the story pages, and I can turn them inside out. Two lessons are not enough, but they are steps in this direction.

Plan A: Build an array.

Let the board fall apart and bring the parts together.

To make the lessons look simpler (and my ridiculous playboxes easier to use), I prepared two more sugarcoats.

In addition to two-dimensional numeration of the board, I will use one-dimensional numeration available through the name line. For 5x5 pegs, board[4][4] is the same as line[24]. The spatial order is the one of the Western writing. You'll see how it works.

To access the styles of the pegs, I will use the name styles. Instead of writing




I will write


I will also use loops, even though I just edited out the long introduction to them. The loops are thoroughly explained in PART 3. These imaginary lesson plans are about web-programming.

Magically speaking, loops are like brooms. We can use them to repeat certain actions. A broom can carry the water bucket by bucket, a loop can change the styles peg by peg. I borrowed the look from MIT Scratch. Some readers may remember those brown grips.

Speaking of scratch, the following step-by-step instruction scrolls separately from the page. The playbox stays in place. This bounding allows you to click on the link to inject the spells right into the textarea. You only need to cast it then, but be careful doing this, especially if you changed the spell: another click on the link will inject the same code again.

The scratch is right below, in the beginning of Sidewalk A. You may use the spell, which freezes window scrolling. It works differently in different browsers, but, as long as your cursor is in the sidewalk, you are safely confined to it. Even with a motorized mouse like mine, you will never fall off.

To freeze the window scrolling, please click on the stop sign or next to it. To unfreeze, click in the end of the sidewalk.

Welcome to Sidewalk A.
Stop if you are scrolling up.
Click to freeze window scroll.
Click in the end to unfreeze it.

Step 0

Come or return here to start from scratch. The following spell creates a brand new board (and erases any changes made to it). Next it makes every peg small and numbers each one. Like Alice in Wonderland, pegs can contract and expand, maintaining their identities. Pegs may contain any text, although I only needed one digit here.

You may click on the injector link to get the spell into the textarea. Remember, injection cleans the board and, depending on your browser, may also clean the editing history. To keep the history and the content of the textarea, copy and paste the spell as you did before. Cast the spells as usual, clicking inside and outside.

for (var i=0;i<line.length;++i){

By the way, px after a number means pixels. You know, those tri-color dots on your screen. Without this or some other unit of measurement, such spells would not work.

Step 1

Your board must now look like a crude numeric keypad. To make it cuter, I'll pad the pegs to push the numbers further inside. And how about giving the pegs some other ugly color? Is pink appropriate for a playground?

for (var i=0;i<line.length;++i){

Did you notice all the pegs suddenly swell? If you did not, you may try again. Change '4px' to '0px', cast the spell, change it back to '4px' and re-cast. That was a CSS box model at work. Beware of it, and be afraid.

Why so? If we have a box and decided to pad it, how can its external dimensions be affected? To me, this can only mean that CSS creators were thinking inside that box. The content of the box must not suffer, no matter what. If you want to cut your page (or any other box) into smaller compartments, you must be concerned about the outer sizes.

The programmer in me demanded to divide the size by 3 or 4,instead of setting it equal to 32. No, thanks. The simplest known to me spell for this would look like


where i is the number of the peg, provided by the loop spell. Taking into account the border (and, potentially, every other component wrapped around the usable space inside) would make this calculation scarier than five lessons like this.

Step 2

Now I am going to remove the glue, which is holding the pegs in this neat array.

for (var i=0;i<line.length;++i){

I hope you understood that we just canceled two so-called properties of every peg's style. One is officially called cssFloat (or simply float). Another one is called clear.

The name of the property cssFloat suggests that there was another float, but there is none. The word has been reserved, never used, eventually released, etc.

Before you proceed: the following package brings the board to this point from scratch.

for (var i=0;i<line.length;++i){

Step 3

If we don't tell how to arrange the pegs, the browser floats them to the left and stacks them down. Such is the default behavior.

Let's put away the loop spell, and change the pegs one by one. Here is the spell, but please don't cast it yet.


Before using this spell, the question mark between the square brackets must be replaced with the number of the peg, that we would like to enchant. Without a loop spell, this is your responsibility. Otherwise the browser will respond with a curse, which will appear below the pegboard.

Let's start with peg 0. Erase the question mark and type in 0 instead. Did you cast the spell? What's happened?

Nothing should have happened to peg 0, but where is peg 1? Only the number remains. It moved slightly up, and now overlaps peg 2.

Change the number between the square brackets to 1, and cast the spell. The missing peg 1 emerged to the right from peg 0. The following peg 2 is nowhere to be seen, but its number jumped slightly upward and now overlaps peg 3.

Further floating will not uncover much that's new. Every time the peg next to the last floated peg will disappear like, say, the Cheshire Cat, leaving its text content behind.

Step 4

Let's do something dramatically different. The last peg is peg 8. Where can it go if we float peg 7? Do it now, using the spell from the previous step. I assume that pegs from 2 to 8 are not floating yet.

You must be able to see that the body of peg 8 has truly gone, and this is what's happened to every other peg after a floated peg. But where are they hiding?

To find out, let's change the color of peg 8. You did it before.


No luck. OK, let's make the missing peg bigger. You may keep and cast both background and height changing spells.


On the previous step we lost peg 2. Make it green and 40px high too. Make sure to change both 8s to 2s in the las two spells.

It turned out that peg 2 was hiding behind peg 0 (and not behind peg 1). Web browsers are programmed to lay out floated elements with its left hand, non-floated elements with its right hand, and not to let the right hands know what the left hand is doing. Once we tell peg 0 to float, the left hand is taking care of it, and for the right hand this peg no longer exists. The right hand puts peg 1 at the top left corner, then the left hand slaps peg 0 over it.

Step 5

To prevent overlapping, we have to set clear property. Do it for the two "lost and found" pegs.


Hence, the browser was very well aware of every peg on the board, floated or not.

I hope you learned something about the perils we face and fight, in trying to set up a rectangular layout covering the page and organizing the texts on it. Disappearing areas are frustrating enough, but web browsers have more tricks up their sleeves. We naturally assume that area containing text is like a display on a dashboard. It can go hide, OK, but how can the text fall off? What they were thinking?

Step 6

The case of disappearing pegs was closed, but the problem was not solved yet. How to get those little pink squares back in order?

First of all, let's make them all float and cancel any clearances. I am not asking you to enchant every peg by hand anymore. We have the loop spell for this.

for (var i=0;i<line.length;++i){

What you see is the default behavior of the floating pegs. They line up from left to right, next to each other, like letters or words. Order them to float right, and they will be lining up from right to left - that's how the other part of humankind learns to write.

One difference between how browsers display the floated pegs and printing traditions in English (Latin) script is immediately obvious. Pegs align their tops and hang down if they are bigger than their neighbors. A bigger letter (or character, as computer people prefer to call them) extends upward, aligning its bottom with the rest of the line and pushing the line down to clear more room.

Step 7

Do the floated pegs behave like letters or like words? More specifically, can pegs "wrap" like words? See, for example, the Format menu in Windows Notepad if you are not sure what Word Wrap means.

Let's find out. At this moment, I expect you to see a line of pegs numbered from left to right, all 32 pixels wide. Pegs 0, 1, 3, 4, 5, 6, 7 are pink and 32 pixels high, pegs 2 and 8 are green and 40 pixels high. The following spell will make every peg 64 pixels wide, which is two times bigger than they currently are. Just let me shut up this guy who wants to multiply the width by two. OK, done. Fortunately, I am not much of a programmer.

Please inject and cast this spell. If pegs can wrap, they will start forming a new line once the first one is full.

for (var i=0;i<line.length;++i){

This lesson is already too long, so let me tell you how I understand what the browser was thinking. The pegs did "wrap" very much like words, but not exactly. The browser was placing them from left to right (with its left hand, yes). The space was limited. Peg 6 did not fit, so it dove down and started sliding left under the bottom of the last successfully placed peg, which was peg 5.

Leftbound peg 6 kept sliding at the level of the bottom of peg 5, until it hit a snag. That happened to be another left-floated peg, i.e. peg 2, because its bottom was protruding down. Hence peg 6 stuck to the right side of peg 2, and every consequent pegs piled up to the right because this is what floating left is about.

Step 8

Please adapt the spell from Step 4 to make peg 5 40 pixels high. At this level, overflown pegs must travel the whole way to the left unstopped.

You certainly realized that we just found one method to build a 3x3 array. We can make the pegs even wider, so only 3 of them will fit the line. The width must be around 150 pixels, I guess. You may try to do it later. If you chose to play now, that's fine, but remember, by the beginning of the next step I expect all the pegs to be 32 by 32 in size.

The following spell tidies up everything I could think of. I don't care about the numbers any more, but I don't want snagging.

for (var i=0;i<line.length;++i){
//Make this peg 32 pixels wide.
//Make this peg 32 pixels high.
//Make this peg light green.
//Disable clearance for this peg.
//Make this peg float left.

Lines starting with two slashes // are called comments. The browser is not supposed to pay attention to anything from double slash to line's end. For sorcerers, the comments can be very helpful. Unlike my writings on the sidewalk, the comments are embedded in the spell at certain points, explaining what is supposed to happen next.

Step 9

If everything was done right, you now see a horizontal line of 9 light green pegs of the same size. I am going to demonstrate another method to fold this line into a 3x3 array, which will be completely independent from the relation between the width of the pegs and the width of their enclosure. Simply speaking, such an array will be stable not only in a room tight enough to hold it, but anywhere, if only the room is big enough to accommodate it.

To achieve it, I will force some pegs to start a new line. Not sure if you know or care, but in computers a new line is a character. Often even two characters. In typewriters Carriage Return (CR) made the paper move the whole way to the right, or the printing head move the whole way to the left, depending on the design of the typewriter. Line Feed (LF) advanced the paper up. Nothing was printed, but the next printable characters appeared in the leftmost position of the next line.

Pegs are complex objects with attributes like background color, dimensions, etc. We can also mark any peg as a new line peg. You already know how to do it. If the pegs are floated left, you set clear to 'left'. The pegs' attributes are held in its style, so here is what you do to make peg 3 an end-of-line peg:


Please enchant peg 6 next. Problem solved. Note that both peg 3 and peg 6 remain floated left, but the following pegs start building new lines after them.

If you froze the window scroll (which means, there is no main scrollbar along the right side of the window), click below to unfreeze it.

Sidewalk A ends here.
Stop if you are scrolling down.
Click to unfreeze window scroll.
Good bye.

Web programming would make a treasure chest for school science. So much can be uncovered through experimentation, observation and speculation. And you know what? This keeps the community of web developers busy.

Recess: play a game

The board as a puzzle.

I thought that the piece of information technology, introduced in Plan A above, looked weird enough to lend itself to a computer game. Here I am going to offer a conceptual prototype. Not only to entertain, but also to prepare you to take on Plan B.

The game is not very exiting, even boring, but so is practically every free web-game offered by Disney, Nickelodeon, PBS and you know better whom. I am sure I could rival them by adding motions, colors, sounds delivered by generic ghosts, knights, robots, fairies, dinosaurs, jesters and other funny animals.

HTML and CSS themselves provide unlimited opportunities. I could mix the pegs of different sizes to create playful pileups, or combine floating and non-floating pegs to add a thrill of hide-and-seek. Don't let me forget, from this game you may actually learn a little bit of something useful and well paid.

The game will start with the pegs on the board being intentionally disarranged. The goal is to order them using as few moves as possible. There is only one way to make a move: pick a peg and place it right before some other peg.

Textarea below is preloaded with the spell to create the numbers and the colors. Just cast it. In case you need this spell again, here it is.

var color=['#ff2020','#fcfc00','#10ff10'];
for (var i=0;i<line.length;++i){

The following spell changes the order of the pegs. Make sure to clean the textarea before loading it. The numbers in the square brackets tell the browser which peg must be inserted before which respectively. The spell casted as below will tell the browser to insert peg 1 (yellow) before peg 2 (green).

Keep this spell in the textarea as you play. Change only the numbers. Remember, they start from 0.


More challenging case: the board below has 9 pegs, all floated left, and they are forming a 3x3 array because 3 of them (0, 3, 6) have their clear properties set to 'left'. The textarea is preloaded with the spell. You are expected to cast it to make the pegs small, number them and disarrange them, all at once. Then you may try to order the pegs using the same spell as before.


I could do it in 3 steps.

Here is a spell to create a new board and prepare it for playing

for(var i=0;i<line.length;++i){

To shuffle the pegs, use the following spell. Once you've loaded it in the textarea, you can edit the line of numbers, which looks like '3 6 1 2 4 5 7 8 0'. This is the order of the pegs to create. Make sure to change the numbers only. Spaces and quotation marks are required for the spell to work.

var p='3 6 1 2 4 5 7 8 0';
var k,i,l=line.length;
p=p.split(' ');
for (var i=0;i<l;++i){

In the language of mathematics, rearranging a set without changing it is called permutation. The modern American school curriculum includes some combinatorics, and permutations are mentioned, even though briefly. Indeed, they are mostly useful for artists, scientists, engineers, statisticians and other hard-to-meet folks. Imagine a medical office assistant or a grocery shelf stocker doing this.

In practice, a set may contain practically anything - for example, sounds. So-called method ringing, invented by English church bell ringers - please excuse me, I could not find out how long ago - was about permutations. A braid is a sequence of permutations too.

Some permutation games are notoriously hard. Rubik's Cube is one of them, if you are not allowed to permute the stickers. Ordering a 3x3 board is very easy. Yet, if you solved the last problem, you must have understood how float and clear work together.

Any permutation can be achieved through a sequence of transpositions of two adjacent elements. The spell that puts an element in front of another elements is more powerful than that. It shifts everything between them back or forth, because the elements moving to a new position disappears from where it was. Draw the arrows showing how the pegs move, and you will see that they make a cycle.

This game, like the rest of pegboarding, descended from MAKE THEM MAD. Before my student turned four, I started testing her, trying to find out if she really learned the patterns and the symmetries. One such test involved spoiling the layouts, that she'd just built, transposing some pegs two by two. She immediately cracked this strategy, so I started building long cycles of transpositions, encouraging her to remove all misplaced pegs, and then repair the patterns taking the right pegs from the pool of those previously removed.

Plan B. Build a spinner.

Rotational symmetry and a weird text formatter.

Spinner is our favorite, and I've been using them too much through this demo. Even knowing this, I could not resist. Spinner is a rotational shape, most suitable for the polar coordinate system, yet it wonderfully illustrates how Cartesian thinkers struggle with floating squares.

Let me remind you what a spinner is. The playbox below is preloaded with the spell to build a spinner out of 8 pegs in the dumbest way, just by coloring them. Here is the code.


This spell colors 8 pegs red. The other 8 pegs remain gray and form the background. However, if we put such 4x4 rectangles next to each other, the plane will be tiled with red and gray spinners, and nothing else.

We'll try to build this layout from 8 elongated elements using their float and clear properties. Please remember, it's not a lesson for a student, it's a bunch of suggestions for a teacher, but you may take it on your own. Essentially, it's just a puzzle in disguise, and I provided plenty of magic carpet rides.

Allow me one very important warning. A spell casting job may seem safe and easy like texting with friends, but it's not. In fact, it requires the most meticulous attention to every minor detail of your wizardry. You got to spell exactly right, or face the consequences. Spell it wrong, and your spell will do nothing at best.

The ancient tale of the sorcerer's apprentice had a happy ending. That's why we know it. The overwhelming majority of sorcery students disappear without a trace before acquiring any practicable magic power. As the progress of this trade went on, the rate of survival kept falling, and the number of graduates became statistically insignificant. That's why your chances to meet a real magus nowadays are negligible.

I don't expect you to cause any harm to you or your computer yet, but in this lesson you may annihilate some or all of your pegs. I mean, they will be lost forever. Should this happen, you would have to start from scratch.

The scratch is right below, in the beginning of Sidewalk B. You may use the spell, which freezes the window scrolling. It works differently in different browsers, but as long as your cursor is in the sidewalk, you are safely confined to it. Even with a motorized mouse like mine, you will never fall off.

To freeze window scrolling, please click on the stop sign or next to it. To unfreeze, click in the end of the sidewalk.

Welcome to Sidewalk B.
Stop if you are scrolling up.
Click to freeze window scroll.
Click in the end to unfreeze it.

Step 0

I'd like to number the pegs, arrange them in a line from left to right (float='left', clear='none'), slightly change their style, and, last but not least, make them disappear. Please do it for me.

for (var n=0;n<line.length;++n){

In the first written account of invisibility (which, as it is widely believed, was given by Plato), the invisible man was not stripped of his body. It might not immediately follow from the story itself, yet subsequent speculations made it clear enough. The invisible man of H. G. Wells - probably, the most famous and exceptionally well documented case - could have been caught and killed. A web browser can serve invisibility, but disappearance is more than that. The display='none' piece of the spell above renders the pegs completely bodiless. They take no room in this world.

A disappeared peg still exists. It simply is not here. As long as we have a way to address it, we can change it and call it back.

Step 1

Let's pull peg0 back out of nowhere, and make it look different.

var n=0;

Cast the spell, and keep it in the textarea. You will use it to enchant the following pegs. Read through the lines to understand what it does. Changing size, color (called background), float and clear is nothing new. We did this before. Display is a property, which makes elements disappear and appear. After display='block' the element appears as a rectangle.

The spell in textarea is a DIY tool kit. Double slash tells the browser to ignore the rest of the line, presumably because it contains a comment. Wizards often use comment markers to make parts of complex spells invisible to the browser. This is known as commenting out.

Step 2

The spell in Step 0 - the one that made the pegs disappear - set their height and width to 60 pixels. The pegs are not with us, but they keep these dimensions. To build the spinner, we need horizontally and vertically elongated paddles. Making the height of a peg equal to 120 pixels (and keeping the width unchanged) we turn this peg into a vertical paddle. The width equal to 120 pixels (again, with unchanged height) makes a horizontal paddle.

Spellkit has two separate spells for making width and height equal to '120px'. It's up to you to comment out one of them, and leave the other one visible to the browser. Don't uncomment both at the same time, or you will make a peg 120x120 pixels big. Should this happen to you, uncomment both height and width, and set them to '120px' and '60px' as appropriate. Then change '60px' to '120px' and comment out one of them.

There is a spell to make a peg gray. The next one makes it red. Leave both spells uncommented, and the second spell will override the first. Comment out the second spell, and the first spell will rule.

Setting display='block' will make a peg appear. The next spell sets display='block', and it is commented out. Remove the comment mark, and the peg will disappear. Similarly, you can turn on and off float='left' and clear='left'.

To fix a mistake, get the comment marks right, and recast the whole kit. If you changed something other than a comment mark and got lost, inject the spell again. And remember, a single slash is just a slash. It takes two of them to comment out.

If you were playing with the properties of the peg (as I expected you to do), inject the last spell and cast it again. We want peg0 to appear gray, vertically extended, floated left and not 'cleared'.

Step 3

Your spell kit enchants one peg at a time. Which one?

The pegs can be addressed as line[?], and the number in place of the question mark tells the browser which peg to enchant. I also extracted and lined up the styles. Instead of line[?].style, we can address any peg's style simply as style[?].

Look at the spell kit again. To enchant a peg, do we have to put its number between every pair of square brackets?

The kit employs a magic trick to type the number only once, and use it as many times as we want. The first line var n=0; creates a single-letter name n and gives it to number 0. The name n appears between every pair of square brackets. The browser is smart enough to understand: there's got to be a number here, and they gave me a name. Is there a value behind it? Eventually, the name will be evaluated, which simply means, it will be replaced with 0.

And here is the best part: if you replace 0 with any other number, the browser will happily substitute it for n everywhere. To apply the spell kit to a different peg, just type that peg's number on the right side of the = sign. I packed many spells together to change them all from one place.

Step 4

The following table tells how we need the pegs to look. It does not tell how to make them look this way. Use the kit to set up long dimension, background color, display, float and clear properties for peg1, peg2, peg3 (peg0 must be transformed already). Make sure to make n one bigger every time.


Why didn't I turn this table into web-form? Well, first of all, I am not discussing how to teach using web-forms. This site is about how to teach creating them. But OK, here is a better deal. Click to inject a magic carpet spell, which will bring you to this point from scratch. It's long and boring. You may view it in the teŃ…tarea, if you like.


Congratulations, we've got the first problem: how to park peg3 right below peg2? Uncommenting clear='left' will send peg3 to the first available far left spot under peg0 and peg1. What else can we do?

Comment out clear='left', uncomment clear='none' and recast. Let's leave peg 3 where it wants to be for the time being, and move ahead.

Step 5

To move ahead we need spell kit again, and here it is, customized for peg4. Please note, it's setting clear='left' for the first time.

var n=4;

Now we are facing an ominous situation. The pegs were numbered in the order we used to write: from left to right, then down. Starting from peg4 this rule is not quite applicable. Two vertical pegs 5 and 6 are to the right of it, but their bottoms are not higher than the bottom of peg7 will be.

It's not the worst case scenario though. With thinner blades, it could be worse. For now, let's apply the rule to the centers of the pegs. Which means, go right.

Step 6

The following table defines transformations for peg5, peg6 and peg7.


Would you prefer a magic carpet? Click below...


and don't forget to cast.

I told you it's not going to end well. Without clear='left' peg7 would stick to the right side of peg6. With clear='left' it slipped under its bottom and floated the whole way to the left, staying at the same level. We've seen this behavior before.

Step 7

Did we take a wrong turn? How about counting down after 4, and only then to the right?

To try this layout, I could make peg5 horizontal, gray and "cleared" left like peg7. Peg 6 would be like peg5, and peg7 like peg6.

Moving peg7 in front of peg5 is much easier to do, but harder to understand. Hope you don't need an injector for this.


Time for another explanation. Remember how the pegs stayed organized before we even numbered them? That's because they are lined up in the browser's mind. My spell, which runs playboxes on this page, told the browser to create the pegs one by one, and the browser remembered them in that order. Array of pegs on the board is really the line of pegs folded up. We labeled the pegs with numbers, but the browser did not care. We could just as well use any letters or words.

The spell insertBefore() shuffles the pegs in the browser's mind. The pegs are moving around with all their possessions - background, height, width, textContent, etc. So after the move the browser thinks that peg7 stands before peg5 and after peg4.

What's the difference? Well, before the move peg5 was sticking to the right side of peg4, aligning it's top with peg4's top. After the move peg5 is sticking to peg7 under the same rules. And this is not what we want.

Before going ahead, please hack the last spell to return peg7 to its birthplace. Where? Before peg8, of course. We have 9 pegs, numbered from 0 to 8. You only need to change one number. Peg 8 is not with us yet, but the browser remembers it.

Step 8

Working on Plan A, we forced nine pegs into 3x3 array by making them bigger, so that only 3 of them could fit into one row. Can we do it again?

We can try, and that's where peg8 would come in handy. Or, rather, the other pegs could handy come into it. The spell for this is appendChild(). But first of all, let me remind you that you are supposed to be back at the point, to which the magic carpet spell from Step 6 can bring you from scratch. Inject and cast it, if you are lost.

Let's call peg8 and change it to better suit our purpose. The size will be set to 400x400 pixels, the background color will be white... excuse me, but aren't you getting spellish yet?

style[8].border='2px solid black'

The following spell will erase everything inside peg8. At the moment there is only number 8 in there.


To move peg0 into peg8, load and cast this, and never use the red spell again.


Let me translate. Dear peg number 8 in the line, please adopt peg number 0 in the line.

Step 9

I strongly recommend you to move the pegs one by one, changing 0 to 1, to 2, etc, and trying to understand how and why your layout is changing. But if you prefer not to do it, then OK, here is a magic broom, which casts adoption spell on every peg from 0 to 7.

for (var n=0;n<8;++n) 

Now as all the eight pegs are captured, we can tighten the noose. Want a bet? Which misplaced peg will submit? Use this spell to find out.


The first problem solved. Now try '280px'. You may change the height only.

Step 10

Failure to squeeze peg7 in its intended place gave me a fresh idea. When we tried to put peg7 before peg5...


...the gap between them became the sticking point for pegs 5 and 6. What if we cover this gap, putting peg 4 and 7 into another peg?

Remarkably, we don't even need to break the natural order of the pegs for this. Watch you hands.

Restore the natural order of the pegs (the number will be removed from peg8).


Prepare peg8. It will emerge as a little black rectangle below peg7.


Ask peg8 to adopts peg4, then peg7. For every peg, click on the link, make sure injection worked, and cast.

INJECT line[8].appendChild(line[4]);

INJECT line[8].appendChild(line[7]);

Finally, manipulate the browser's mind to make it think that peg8 with both it's "children" is in front of peg5 in the line.

INJECT your.brd.insertBefore(line[8],line[5]);

Step 11

Note that we did not have to size peg8. Even with float and clear properties set to 'none', pegs 4 and 7 would be sitting tightly, with peg8 holding them snugly, as long as it's dimensions are set to 'auto' and float to 'left'. We could apply this technique to pegs 2 and 3, but we don't have any pegs left.

I know how to make more pegs. I just want to try something else for a change. The new magic technology is positioning. Until this moment we have been relying on the browser, occasionally trying to trick it into doing what we want. Instead we can just tell it what to do (and hope it will get it).

The easiest (or, at least, the most immediate) method to position a peg is setting its margins. Look how it works. The following spell will move peg3 down by 60 pixels.

INJECT style[3].marginTop='60px';

You probably understood that browsers use writing coordinate system. The positive direction are down and to the right. We need to shift peg3 to the left, so the horizontal margin must be negative.

APPEND style[3].marginLeft='-120px';

Step 12

Did we do it? Not quite. To begin with, why peg3 overlaps peg2?

That was dread CSS box model again. So many learners banged their heads at it, but it stands. When we set dimensions to 120 and 60 pixels, the browser thinks we mean internal dimensions. On top of this every peg has a border, which is 2 pixels wide. The border wraps all the way around the peg, so the external dimensions are 124 and 64 pixels. To place peg3 right we have to shift it by that numbers.

True, counting borders on top of dimensions only seem wrong if you put pegs into something else. Put something else into pegs, and it will be just right. However, this chapter is about filling page with rectangles, assuming that we are going to fill rectangles with pictures and texts, and pictures and texts are very flexible. In this very common case CSS box model is not our friend.

Another problem of this origin: two pegs of the same orientation do not form a square. Dimension across the pegs is 2+60+2+2+60+2=128. Dimension along the pegs is 2+120+2=124.

If I change margins to 64 and -124 (try it), I can get this layout right, but only in Internet Explorer. FireFox and Chrome push peg3 visibly too far. Finding out what's happening is easy. Internet Explorer is doing exactly what I ordered: dimensions for the pegs are 60 and 120 pixels, and the borders are 2 pixels wide. Firefox makes my pegs 121 and 61 pixels big, surrounding them with 1 pixel borders. Chrome: 60, 120 and 1.6 pixels!

At first I thought the rounded corners were the reason, but no, with rounding or without, the numbers are the same. My next best guess was what the difference had to do with so-called borders collapsing. The browsers' developers are always eager to save those helpless web designers from their stupidity. The ability to please the crowd (say, in Chrome all my pages look fine) promotes the products and cultivates certain qualities in their customers.

On the other hand, Web design is a business like no other. Something as simple as building a spinner easily turns into a research project, which may keep a developer busy for days and weeks.

Step 13

I failed to find out how to get rid of those helping hands (and I admit, I did not try hard enough). Let's get rid of the borders then. A magic carpet first? Right here.


The spell below zeros the borders and their corners' radii, just in case.

for (var n=0;n<9;++n){

Oh, I forgot the margins.


Much better.

If you froze the window scroll (which means, there is no main scrollbar along the right side of the browser's window), click below to unfreeze it.

Sidewalk B ends here.
Stop if you are scrolling down.
Click on the sign to unfreeze window scrolling.
Good bye.

Without the borders, I would build a spinner putting rectangles into squares. It's only necessary for top right and bottom left corners, but I made all four to elucidate the striking differences between the ours and the web's geometries. To begin with, two top pegs are gray on red, and two bottom pegs are red on gray. I expected a chessboard kind of tessellation before I started putting this layout together. There are other solutions, but none of them is right. You can push a vertical paddle to the left or to the right, but you can not push a horizontal paddle all the way down. Web browsers are the text formatters to the core, the only thriving offspring of this all but bygone class of software. They can't do rotation properly.

The spinner is on the right. I left it slightly loose, so you can see how the parts are coming together. The spell is on the left, and it's a new kind of spell. You can not cast it through a textarea (at least, not easily). Even to display this text on the page, I had to rewrite it beyond recognition. Unbelievable, but true.

.sr,.sg {float:left;margin:2px;
.vr,.vg,.hr,.hg {margin:4px;} 
.vr,.vg {height:221px;width:118px;}
.hr,.hg {height:118px;width:221px;}
.sr,.vr,.hr {background-color:red;}
.sg,.vg,.hg {background-color:gray;}
<div style='float:right;width:480px;'>
  <div class='sr'>
    <div class='vg'></div>
  <div class='sr'>
    <div class='hg'></div>
  <div class='sg'>
    <div class='hr'></div>
  <div class='sg'>
    <div class='vr'></div>

Not sure if it was useful, but I hope you will agree what the experience of building a spinner was different. Normally web-teachers tell a new word, show a new rule, and offer an oversimplified example. Suppose you want to do this. I usually think, excuse me, I don't want to do what you wanted to do, I want to do something else. And I don't even understand what did you want to do.

Spinner provides a lucid and abstract goal. Don't ask me why do I want to build it, and forget for a moment what did you want to build. Let's build this funny shape, just for the heck of it. That's how we stop collecting the recipes and start getting the meaning.

A whole lot of meaning, by the way, and I have barely scratched the surface. I could have built many more lessons around this shape, given the sheer amount of complications piled around container elements in CSS. The evolution of this technology is truly amazing. Who would believe it started as an accessible way to make web-pages, and in the beginning even a total stranger like me could build a website to own.

Superficially, HTML and CSS still look like they were invented for programophobes. They grew to become like those complete idiot's books. A walk by a bookshelf proves that, of all readers, only dummies can rival complete idiots in erudition and diligence. To afford the modern web-design as a modest hobby, I need to live ten lives at the same time.

Regarding those borders and dimensions, I lost another day on them, and finally found that the difference appeared only when my screen was enlarged to 125% (and it usually is). Microsoft Windows has had this option since I remember it, yet, of 3 major browsers, only MSIE does the trick right. I took out those elements, created a very simple test page and changed the peg's borders' width to 1 pixel. Hereby the problem was alleviated (but not eliminated).

I went on playing with this, and more complicated grids (like in FIREPEGS). Soon I found that the problem has to do with floating numbers and precision. Strangely, the browser do not do this to margins. They mess up only borders. Using margins is a "solution".

Web world is weird like quantum mechanics, except it's changing. Analogies, derived from observations and depictions of the real world, will be defied. Expectations, based on what you learned before, will deceive you.

Think floats and clears are strange? Get a new 3x3 board, make the pegs smaller (or return to the beginning of Plan A), load the margin setting spells from the end of Plan B, change 3 to 4 (the number of the central peg) and play with the small margin numbers, making them negative or positive. You will quickly realize that the interactions of the repositioned peg4 with it's neighbors is not symmetrical, but there is method in't.

Absolute and relative positioning is one of my favorite thing to teach because it's a very enabling knowledge. Yet I would not want to explain CSS positioning to my kids. They may forget how to find the bathroom.

In the wonderful world of web, few teachers are developing the laws of innature, and they make them wild. Millions of students are spending hundreds millions hour trying to figure out the rules, finding the ways to circumvent them and passing this sacred knowledge to the others through increasingly diluted and distorted messages. And it's not Minecraft. Everybody is getting paid for what they do.

Did I tell you I am not? That's why I am leaving behind this chapter without regret.


Pegboard, keyboard and mouse.

What's Spellish

A language to change the pegs and yourself.

Your must be very familiar with magic. Most people are nowadays. I am, in fact, a die-hard illiterati. Imagine, I've never opened a single Harry Potter book, and know next to nothing about Hobbits. To the best of my knowledge, true spells are simply words and phrases in the languages, which we have never had a chance to learn.

This particular dialect is very accessible and fully open to the public. Every web browser understands it, and browsers are not very smart. There are only 34 words, all in plain English (four are substandard: const, instanceof, typeof and var). The rules are not nearly as complicated as in any language used between us humans.

I could give you thousands very good reasons to learn and use this stuff. It's just not my goal at the moment. Let me say that I unconditionally want my children to learn it. I mean, no matter what they are going to do with their lives, this will be the most empowering and useful skill.

Mastering computer spelling makes you a different, and a much more capable person. You learn to fight staying cool, to avoid mistakes and to find them quickly. You explore, invent, design and build at the pace unimaginable in any other trade. You research, diagnose, investigate, set up and run experiments to prove and disprove your ideas, and you often do it many times a day.

Computer spelling is really the cream of the crop of intellectual occupations. It teaches to understand, design, troubleshoot and manage complex dynamical systems, be it business, family, or your body. It does not teach you everything you need for success, in a sense, it's rather narrow, but it's very rewarding, especially if you do it for yourself.

In the beginning of PART 1 you tried playboxes and used few simple spells. Let's now learn that the sorcerer's apprentice did not.

Substitute and rule

Every teacher a substitute.

It would have been easier with water because water is just water. Every bucket of water is the same. Inside computer everything is personalized in some way, and everything belongs to something. If we pick a peg. It's always some particular peg, linked to the board and made different from any other peg. Technically, we can create just a peg, but it will immediately disappear.

A terrifying secret of any rule is: the subjects must be made indistinguishable from each other. The rule may mention a student or a motorist. You substitute yourself for a student, leaving out your personality.

The following spell colors a row of pegs red. Remember, even if a spell is preloaded, you need to click inside and outside the textarea to cast it.

Like before, both vertical and horizontal numberings start from 0. The peg numbered (0,0) is in the top left corner. The vertical number (the number of the row) comes first.

On 5x5 board, the central peg is numbered (2,2), and every peg has the first number of 2 because it belongs to the same row. If you replace the first 2 with, say, 3, the spell will make row 3 red. It's boring, OK, but it works.

We can rewrite the spell to make changing the row easy

var rowNumber=3;

The spell var rowNumber=3; in the first line is a substitution called variable. It's not the same as variable in math. The equal sign has a different meaning too. It solves the problems instead of making you solve them (this is what computer spelling is about).

Here is what var rowNumber=3; means: Dear browser, find all the worlds rowNumber in my spell and replace every one of them with 3. Then please color those pegs.

Look, we took away the personalities of the pegs, and made the five line spell from the beginning of this chapter good for any row! There is one problem though. Row 2 is already red. Rows 0, 1, 3, 4 are left for you to play, and it's not much. Well, you may cast this to make a fresh gray board...


or here is a better idea: we can substitute the color too, and make the rows easy to repaint.

var rowNumber=3;
var pegColor='blue';

What's left? Why capital letters in the names? It's a tradition in computer spelling, which came from the time of the first graphical user interface and the browser. There is a chapter in PART 1, which I hid in order not to put the readers off with so much irrelevant information, but you can retrieve it if you want. Reportedly, the XEROX scientists forgot to put the _ (underscore) sign on the keyboard of their experimental computer. However, the programmers got used to it because they were not allowed to break the names with the spaces (even today computers are not smart enough for such things). So they invented this


and use it to scare off the public since then.

You teacher? Oh, yes. How could I forget. Your teacher is a role, which can be played by practically anybody. Variable in computer spelling means very much the same as role. That's how this could look.

var Miredyth_Undervincle=new Teacher(); 
var Jakop_Stenchmyar=new Teacher();
var my_teacher;
//That's why in computer spelling they call 
//the the equal sign = the assignment operator.
//At any moment you can reassign...
//...or choose to have no teacher at all

What? I did not tell you about //? It's a short spell, which for your browser means "I am not talking to you". The browser pretends it does not see anything from // and to the end of the line.

Let's make a loop

Think you know what is boring?

Substitution in different forms is one the reason why computers are so powerful. The other reason is their ability to loop.

Consider the spells from the previous chapter. After several improvements, they still name every peg in a row. It takes five spells to color five pegs, and they are not good for 10 pegs. To cover ten pegs, we need ten spells.

For the modern computers millions of operations is next to nothing. What human can possibly enjoy writing a spell like this, even for one million pegs? And do we need a new spell for every new number?

We know there a better way. Remember sorcerer's apprentice? He enchanted the broom and made it carry water by buckets. Here I am going to explain how such spells work, and how to build them. Remember though, they are dangerous.

Magic brooms are possible because of the loop control statements. Every loop control statement is a container. We fill them up with the spells, carrying out some useful activity, and we tune them up, telling how to start, how to go and how to stop to prevent the useful activity from becoming harmful.

Time to start from scratch. Do you see it? The scratch is right below, in the beginning of Sidewalk LOOPS. You may use the spell, which freezes the window scrolling. It works differently in different browsers, but, as long as your cursor is in the sidewalk, you are safely confined to it. Even with a motorized mouse like mine, you will never fall off.

To freeze the window scrolling, please click in the beginning of the sidewalk, on the stop sign or next to it. To unfreeze, click in the end of the sidewalk, or just reload the page.

Welcome to Sidewalk LOOPS.
Stop if you are scrolling up.
Click to freeze window scroll.
Click in the end to unfreeze it.

Step 0

For a starter, let's create a new board with a vertical red line. To achieve this, I keep the second (the column) number the same, changing only the first (the row) number. If your are new to CODEPEGS, please inject the spell. To cast it, click inside the textarea, then outside it.


Step 1

I created a variable named j. It will receive a new number before every change() spell. The code builds a column or pegs, like the code before, except I colored it blue, just to make a difference.

var j=0;

What's the point? Well, bear with me for one more step. Solving problems, we often walk away from the goal or do something apparently senseless.

In case you wondered why did I name the variable j, and not columnNumber, the answer is, because j is shorter. The names have no meaning to your browser. It remembers them, looks them up and substitute when needed.

Step 2

In SHNUMBERS, I told you about increment and decrement: the secret unary operations, more elementary than addition and subtraction, yet just as capable as multiplication and division. Increment is counting (or adding one, if we look back at it from addition).

In computer spelling, increment and decrement are so important, that many computer languages offer the signs of operation ++ and --. Don't ask me why. The story is too sad to tell. And worse than that, it is long. But look below.

var j=0;

In this code, ++j means "make the number, assigned to j, one bigger". Suppose we made var j=1. Then ++j is the same as j=2.

Step 3

I want to rewrite our code to help you find the pattern. But first, let me tell you what the semicolons mean. They mark the ends of so-called statements. In programming statements are sort of like sentences in human languages, except they are much simpler and the rules for building them are very strict.

The most important rule is that a statement can be executed. Say change, and you browser will not get it. You have to add parenthesis (to show you want to call a function), then to supply 3 pieces of information: the number of the row, the number of the column and the color. The browser will demand the closing parenthesis to make sure that you told all. Then you can happily add semicolon. Which means, the statement is ready, now do it.

It's not advisable to have more than one statement in one line, but it's not forbidden either. Here is the new edition...

var j=0;
change(j,2,'green'); ++j;
change(j,2,'green'); ++j;
change(j,2,'green'); ++j;
change(j,2,'green'); ++j;
change(j,2,'green'); ++j;

...where all five color-changing spells look exactly the same. They don't do the same because the value of j is changing, but we don't see it, so why should we care? Can we leave only one color changer and cast it repeatedly? After all, what do we have to lose?

Step 4

We don't want to create a new gray board every time, and we want to keep the the variable. Please cast the following code only once.


Now let me explain. This is tricky. Just j would not work. A variable is created and destroyed every time we run the spell, but we want to use the number assigned to it on the previous casting.

Remember the beginning of CODEPEGS. I gave the new variable j to your, and your is one of the ways to address the playbox while you are casting the spell from it. The variable becomes a property of the playbox. As long as this playbox exists, the variable will exist too (unless we delete it on purpose).

I took the previous code, changed the color, discarded four change() statements out of five, and rewrote the remaining one to use your.j instead of j. Try to inject it and cast several times without changing anything.

change(your.j,2,'crimson'); ++your.j;

Did you color a column of pegs crimson? Interesting!

Step 5

Let's try one more mod to better understand what's going on. We'll start with...


...did you cast it? Good. And now we will create a new big board every time:

change(your.j,2,'gold'); ++your.j;

The gold peg must appear to be traveling down like a fire in FIREPEGS. That's how the classical computer animation works. You clean up first, then drop the sprite somewhere close to its previous location.

Step 6

Not to bewilder you, but we can compact the code even more. Consider those two statements in one line: the first statement uses the number assigned to your.j, the second statement increments it.

We can use and increment the number in one place. The browser just needs to know what to do first: to use or to change. By convention, if we put the ++ sign after the name, the operation must be performed after the use. Hence, your.j++ allows to use the value, then makes it one bigger.

The following code initializes two variables. Then both of them are getting changed on every step. Please cast this once...


...then keep casting this until you reach the opposite corner:


Step 7

On 5x5 board the opposite corner was not very far away, but suppose you have a list of email addresses, and you want to send the same message to every one of them. Spam lists can be quite big today. Billions of entries, maybe. Who is going to click the button two billion times? We need a clicker!

We could have built a button-clicking robot, but we already have computer behind the browser. Note that we can cast a bunch of spells from a single click. Once started, the browser goes from statement to statement automatically. The problem is, it only goes forward, and we want it to go in loop, which means, return and replay.

Long time ago, when computer programming was in its infancy, we had the statements allowing to leap back or forth and continue execution from any point. In 1968 a prominent Mufti named Edsger Wybe Dijkstra published a fatwa, in which he claimed that such statements are evil, and "should be abolished". So abolished they were.

At present we only have dedicated loop statements, like, for example, do/while. I am applying it to our code. Remark that I turned from your.j back to var j because everything will be done in one casting.

var j=0;
while (j<5);

The spells between do and while was replayed 5 times. We got an enchanted broom, but don't be afraid to call it to work. It already knows where to stop.

Step 8

Like the loop control statements from SORCERER'S APPRENTICE part, do/while statement wraps around our payload code and limits the magic broom's job description. Everything before do will be played only once. Everything between do and while will be replayed while(your.j<5). The question enclosed after while makes or breaks the loop. After every replay, the browser must ask itself if your.j is smaller than 5. If yes, the payload will be replayed. If no, the browser will go on, executing every following statement only ones. I put alert() statement after the loop to confirm that the loop breaking condition was satisfied.

Now here is the best part. We checked for 5 because we knew the height of the board, but our code does not have to rely on our knowledge. For every playbox there is a variable height. If we type its name in place of 5, our code will be good for any board. We can even use it to count the board's height.

var j=0;
while (j<height);

If you froze the window scroll (which means, there is no main scrollbar along the right side of the browser's window), click below to unfreeze it.

Sidewalk LOOPS ends here.
Stop if you are scrolling down.
Click on the sign to unfreeze window scroll.
Good bye.

I prefer another kind of loop control statement, which defines all the critical elements of a loop in one place.

for (var j=0;j<height;++j) 

The keyword is for, and it can accommodate up to 3 statements. The first is var j=0;. It creates the loop control variable and/or assigns the initial number. The second i<height; is the loop breaking condition. The third statement j++ tells how the loop control variable must be advanced.

If the breaking condition (given by the second statement in parentheses after for) is not worded right, or if the loop control variable is not advancing properly, your loop may never start, or stop too early, or, worst of all, never stop. This is what the story of the enchanted broom was about.

Unless you water cool your processors, there will be no flood, but your browser window will become unresponsive. Should this happen, just wait. After a while, the browser will ask you if you want to stop the script, which is another name for program, code or spell. Agree, but remember, clicking inside and outside of black text area will start the script again to the same result. If you want to investigate, click inside and comment out the loop control statement putting // spell in front of it. You may also clean off the program text altogether (Ctrl+A, then erase). Remember, you can always close the tab or the whole browser.

To color rectangle of pegs, we need a loop-in-loop. It may seem strange, but how else can you do this? Imagine, the pegs are on the wall in front of you. You are holding a marker. You start in the upper-left corner, you color this peg, then you move to the right. Since you are repeating the same movements, that's a loop.

Having finished a row of pegs, you return to the left and start coloring another row. The whole activity of coloring a row of pegs unfolds in the same way as before. Hence we have the second loop, which goes from row to row.

A simple loop inside another loop is demonstrated by the piece of code below. It comes preloaded into a new playbox.

for (var j=0;j<height;++j)  //1
  for (var i=0;i<width;++i) //2 
    change(j,i,'orange',0.1);     //3

I added the comments with the numbers. The loop control statement for in line 1 has lines 2 and 3 to replay. The statement for in line2 replays only line3. The first for goes through vertical numbers from 0 to height-1. It makes these numbers one by one, and leaves them available to its payload. The part of this payload is the second loop control statement for, which makes horizontal numbers from 0 to width-1. Every time the change() statement starts, it finds new pair of vertical and horizontal numbers under the same names jand i, so it colors the next peg.

Browser knows no manners

Computer talks like an accomplished smartass.

If you made mistake and your browser sent back a curse, remember this chapter and read it.

At some moment in the history of human-computer relationships, it was widely thought that everybody must and will master some Spellish. Needless to say, this did not happen. The most immediate obstacle, I believe, is that computers are very stupid, but they talk back to us like accomplished smartasses. Not because they are, but because smartasses made them respond this way. They would not do this if they were smartheads.

I opened playboxes in three major browsers and entered two letters: hi. Not sure if you noticed, below every textarea is an empty line for the browser's response. Here is what they said.

ChromeReferenceError: hi is not defined
MSIEReferenceError: 'hi' is undefined
FirefoxReferenceError: hi is not defined

Let me explain. Web browser understands 34 words plus unlimited number of names. Names are names everywhere. My second name, being one of the most common in Russia, makes absolutely no sense and is practically unpronounceable in English. This never prevented anybody from building correct English sentences around it. Likewise, names in Spellish are not supposed to make any sense. Browsers only match them up and pass around.

Normally, if a browser meets an unknown word, it assumes it is a name and memorizes it as such. However, I casted a spell prohibiting this. I don't want accidental names resulting from my mistakes. If I want a new name, I declare it as a variable, or var. So the browsers report to me every time they see something unknown and undeclared.

I tried one more time: hi there. Here is what the browsers barked back.

ChromeSyntaxError: Unexpected identifier
MSIESyntaxError: Expected ';'
FirefoxSyntaxError: missing ; before statement

Dealing with such an attitude takes guts. Many parents tried, suffered, failed and told their kids that computers are unforgiving, arrogant and outright impossible to please. No wonder most people do not want to talk to computers anymore.

Be prepared, and don't get put off. The browser is not doing this to humiliate you. It simply does not know what to do. The browser's developers could have done much better job, but they could not cope with human language anyway. So they didn't even try.

Computers are not smart enough to understand you. You are the smart one. Try to understand computers. Help them do what you want. It pays.

Loops and patterns

They both are about repeating something.

Once we taught loops, we opened the door to entirely new generation of challenges, because we can turn computers into pattern making machines. Let's start from building periodic tessellations.

for (var j=0; j<height; j+=2)
  for (var i=0; i<width; i+=2) 

Mysterious j+=2 makes j two bigger. Hence we skip every odd number both ways, along horizontal and vertical loops.

Adding 2 every times is multiplication. Instead of j=1 and j+=2 we can increment the loop variables and multiply them by 2 to figure out the index numbers.

for (var j=0; j<height; j++)
  for (var i=0; i<width; i++) 

I don't think this idea is useful here and now, but let's save it for later.

Now I am going to repeat this double loop 4 times, creating a four-color pattern. First loop colors every second peg green. It starts from j=0 and i=0 (00 for shortness). The red loop starts at 01, the yellow one at 10 and the blue one at 11.

for (var j=0; j<height; j+=2)
  for (var i=0; i<width; i+=2) 
for (var j=1; j<height; j+=2)
  for (var i=0; i<width; i+=2) 
for (var j=0; j<height; j+=2)
  for (var i=1; i<width; i+=2) 
for (var j=1; j<height; j+=2)
  for (var i=1; i<width; i+=2) 

Here is the code, preloaded.

We can use this technique to produce periodic tessellations of any complexity. Here is another example. Try to change dimensions in the first line.

function paint(J,I,c){
  for (var j=J; j<height; j+=3)
    for (var i=I; i<width; i+=3) 

Even though the pattern was not awfully complex, I could not resist defining a function.

This tessellation was produced like the one before. We ran a nested double loop 8 times to paint 8 tessellations. I could have spent another day demonstrating how this can be done from inside a nested double loop tile by tile, or use a nested triple loop and a table. Remark that 2-pegs same-color elements are not tiles. The real tiles are 9 pegs big. There are many ways to carve them out. If you are interested, look for nonomino. You can even find a four-color spinner here (which is, of course, an octomino, but we may count a white peg as a hole).

Finally, let's do some photoshoping. I built this triple loop for you to produce a crude color gradient. Don't try this at home.

var j,i,k,c,r,g;
for (k=0;k<height/2;++k)
  for (j=k;j<height-k;++j)
    for (i=k;i<width-k;++i) {
//10 changes per second

Now load the following layout to cut out the shapes. You may append this code to the preloaded one if you like.

Loop controls and control loops

What do loops, toilets and traps have in common.

Loop controls and control loops sound like practically the same. Ever since I learned control theory and programming, I have been wondering if they actually have anything in common. Correct me if I am wrong - quite likely I am - but I have never seen their commonality investigated.

Due to the lack of time, knowledge and readers, my investigation will be short. As usual, I only wanted to point your attention to some learning opportunities.

A simple control loop, universally recognized as such, is found in every toilet bowl. You pull up the flapper and the water gushes out. The float falls down opening the fill valve while the flapper returns to its closed position. As the water fills the tank, the float goes up. When the water level gets high enough, the float closes the fill valve.

Let's now consider a mousetrap, particularly a cage-based one. Until I came to the US, my experience with mouse catching was rather limited. More precisely, I've never done this. When I was a child, we lived in an old apartment building, where my grandmother was waging perpetual war on mice. Every night she set a cage trap. Next morning - not every day, but often - another mice would be found inside, perfectly alive. The old lady then would boil a tea kettle and disappear behind the toilet door carrying the kettle in one hand and the trap in the other. Once I asked her what she was doing there. Reluctantly, she explained that she poured the water on the mouse, opened the trapdoor and flushed the toilet. I was probably twelve years old at that time, but I was very impressed with her ruthlessness. I don't think she was looking at the mouse while boiling it alive, though. The side effect of this procedure was, probably, cleaning and disinfecting of the trap.

In the US we rented two relatively old homes, then bought the third, which was new, and expensively built. All three were infested. The one we bought was uninhabited for a while, so the mice were not there. I immediately took measures to prevent them from coming back. With the first two, however, I had to learn how you catch your mice in this country.

I'm afraid you thought my grandmother's method was barbaric. How about glue traps then? The first mouse I caught I threw in the trash alive. I am still sorry about it. I felt so bad that I carefully pulled my next catch off the glue and released outside. I was afraid I damaged him, but no, he ran away quite lively. I would never believe that regular mice can jump so high.

There was no moral to that story. I only wanted to draw connection between flush toilets and mouse traps. But now I am going to take a hard look at it.

The most obvious difference between two devices is that mousetraps usually have only one gate. If you think this is important, then OK, I found two-gate varieties. One gate may serve for flushing mice out, alive or dead, the other one for letting them in. Either way, upon entering the cage, the mouse pulls the bait, activating feedback loop. Eventually the latch releases the gate, and it closes. The device then stands full until the next flush.

The real difference is in the eye of the beholder. Or call it the designer's intention. Flush toilet has automatic regulator, which is supposed to keep the water in the tank at a certain level. We don't think a mousetrap has an automatic regulator, which is supposed to keep the population of the mice inside the cage at a certain level, but why not?

A flush toilet's adds more water as it leaks through the flap or evaporates. A mousetrap would not compensate for partial loss of mouse but, after all, live mice are indivisible like we humans.

There is a different difference, though. A properly configured feedback can make the system oscillate. Oscillation is a spatiotemporal pattern. You've seen oscillating firepegs. They were doing this due to delayed feedbacks.

We can make flush toilet oscillate by tying the float to the flapper. When the tank is full, but slightly before the fill valve closes, the float must pull the flapper up and drain the tank. I don't think it's going to work on your toilet. The float may not be big enough, and the system may need some hysteresis to oscillate. Elastic tie, maybe. The running out water keeps the flapper open. In the end it's must be feasible. I've seen antique public toilets, flushing themselves automatically every once in a while.

Mousetrap would not oscillate, but not because of any fault in its design. What's missing is steady stream of energy, delivered with incoming water. The tank stores potential energy, ready to carry the mass of the water out. Mice, in comparison, are weak and unreliable. The mousetrap operates on it's owner's energy, not to mention the origin of baits.

We can think about design, which would kick the mouse out because it pulled the bait or tried to reach it. The mouse would then return, which may count as oscillation. Unfortunately, such returns are not guaranteed. We might consider fixing the bait to the wall and putting the mouse into a running wheel. Rotation is closely related to oscillation. Yet, any such solution will not be more predictable than making the bait inedible, leaving the gate open, and watching the mice walking in and out.

Yes, I am talking about stochastic process. You don't need a mouse farm for this. Just, maybe, a school toilet to watch. It's another kind of spatiotemporal pattern, and I am not sure yet what can be the age for understanding such things. With TLG I reviewed several kinds of magnitudes - distance, volume, angle, force - time was included, but, playing with firepegs, I realized she was not quite getting it. Checking on her siblings' temporal thinking, I found that it was very poor. I am sure I was much better at their ages, but I walked alone twice a day for 30 minutes from school and back since the first grade. Guess, in couple years from now TLG will be able to plot simple processes.

The kind of program loops I demonstrated thus far were very similar to flush toilets. In a program we change the value of the loop variable, zeroing (flushing) or incrementing it. The gates are in computer's hardware. Often, zeroing and incrementing are even handled differently. You may think that the purpose of the loop is to keep the loop variable value at a certain level. But wait, the level of the water in toilet tank is not what we want! We really want to accumulate a given volume, or amount of water, and in the loop variable we want to accumulate a given number of ones.

Computer programs' propensity for oscillating is well known to everyone who has tried to develop them. To prove that a program can serve as a model of a flush toilet, I am going to turn a simple incremental loop to an oscillator flushing the loop variable before the breaking condition kicks in. Conceptually, this is no different from tying a float to the flapper.

The following code runs once, coloring all the pegs in the column from the bottom up. Then it will stand waiting for you to flush it, clicking inside and outside of the teaxarea. Just like a real toilet does. Let me remind you that you can press (even press and hold) the Enter key to advance through the alerts. Don't agree to prevent them from appearing. If you do, the page will no longer work. Close it entirely and reopen.

Remark that here, for the first time, I use asymmetric Cartesian board.

var n,k=3;
for (n=1;n<=height;++n){
//  if (n==height) flush(); //The tie
function flush(){
  if (--k==0) return; //The stopper

Two lines are tail-commented, and one of them is also commented out entirely. If you uncomment it, the "float" (the loop variable) will be linked to the "flapper" (the flush() function) and the system will oscillate. The second line is always on. It stops oscillation after a given number of cycles. The number is in the first line of code. It's equal to 10, and you can change it.

Below are two simplified plots. The upper one is approximately what I would expect from an oscillating toilet. Ideally sharp corners are impossible in macroscopic systems, and the falling part of the sawtooth (so-called relaxation) is probably not linear.

The lower plot is exactly what we see in computer model, except computer time is not the same as physical time. The browser can only use time slots, which the operating system allocates for it to run.

The plots are heavily out of scale. Web browsers are laggards, but even my relatively modern notebook can run around 1000 cycles per second. Think of a toilet flushing in 1/10000 of a second. That would be quite a water show. Don't stand anywhere near it.

The upper plot is smooth because the water is coming through a pipe at a constant rate. The digital models always have steps. Imagine, however, that you enchanted a toothbrush and made it fill the tank carrying water in a cup.

Remember the sawtooth pattern. Soon we will see it again.

Abridge chapter 1

What's missing.

Before I reached Sidewalk LOOPS, I purged 7 chapters, mostly because they were aimed to teach programming, and I did not think I could afford more than demonstrating few concepts. Most regrettably, I discarded the chapters on the history of loops and the detailed description of playboxes.

After the first patterns, I tried to explain the various meanings of the equal sign. This is very important (not only for programming, for mathematics too), but is not exactly specific to pegboarding. So I edited it out.

In case you had any doubt, let me assure you that pegs can be used to build user interfaces. They naturally sense mouse, touch or stylus. We only need to tell them what to do. Here is an example. Sorry, everything after for is a single line.


I had to break it into pieces because of its length. Not sure if the web programmers are getting paid per character, or is this what they call to obfuscate the code. It's not my fault, anyway, I just have to do what everybody else is doing.

Once casted, this virulent spell drops the spell hidden inside it into every peg on the board, and disappears.

for (var i=0;i<width*height;++i)

Then you can set the color of the starting peg by hand. Just type in the color name and cast.


Since this moment and until the board exists (which means, until the next size() occurs for any reason) clicking on any peg you change its color to the color of the starting peg. Next job would be to develop a simple way to save those layouts. Not that it would be very hard, but can I do it some other time?

The following code colors everything below the diagonal.

for (var x=0; x<width; x++)
  for (var y=1; y<=x; y++) 

Essentially, this is a toilet tank with time sweep, like on the diagram. In regular math notation this would look like Y = X. Such kind of linkage, where one quantity defines another one by some rule, they call function.

An interesting (and rather mysterious for me) topic was the difference between the functions in programming and in mathematics. Somehow I linked it to the concept of degree of freedom and reversibility, which probably was too reckless for an engineer.

I could not resist cursing JavaScript. It's is not a teaching language anyway, but after I found out that there was no easy way to compare the colors of the pegs, I could not help but wondering if they could do anything right. The worse trouble, however, is the way they handle events (timing in particular). To be sure, it's a boon to the practitioners. A learner needs to hire a Javascript professional just to slow down the execution of the code to see what's going on.


The most challenging affine transformations: rotation.

To rotate a space around (0,0), we multiply vectors by a matrix. The problem is, not every board has a central hole. An evenly dimensioned square, for example, does not. Technically, we can assume 0 to be in the middle, surrounded with 4 holes, but then we'll have to count the distances to the holes in halves (fractions, that is).

True 90 degrees rotation of any board in whole numbers is surprisingly easy. Instead of rotating it around it's center, we can rotate it around a corner hole, and translate it back in place at the same time. Here is an example, which must be familiar for those who went through the pictures in MAKE THEM MAD.

var D=10;
var X,Y;
for (X=0; X<D/2; X++)
  for (Y=X; Y<D-X-1; Y++){

To understand what's going on, you may comment out change() statements and uncomment them one by one. This is an awkward, but otherwise the best way to execute your program piece by piece.

A necessary explanation (from another discarded chapter): initializing a board, I can define the origin (which does not have to be (0,0)) and the order of the numbers. I currently use three orders: writing, Cartesian and numerical. The origin of this board is in the bottom left corner, which implies Cartesian order.

Save leftovers for math

Unshredded chapter about modulo and programming.

This chapter is about the Cinderella of elementary math teaching. They don't even consider it an operation. It's a by-product of the operation called division with remainder.

Discussing it with my bigger American children, i realized that they were not even sure about the name. Is in reminder or remainder?

At school, remainder is for the beginners. Advanced learners know how to convert it to a fraction. Fortunately, not everybody is smart enough to do this. In mathematics, they call remainder modulo, and they even invented modular arithmetic.

The following program was designed to remind you what is division and how does modulo come about. The code is not for reading. Let's say, it's just a spell. It is unduly confusing, partially because I wanted to be able to support several independent animations in different playboxes, but mostly because in JavaScript such things were made much more complicated than in any other language I can think of. Or, maybe. I just don't know how to get it right. Don't learn Javascript from me, I told you.

This code is too big for a playbox. Click here to display it on the page or to hide it.

As usual, click inside and outside of the textarea to cast the preloaded spell. It will create a software object called Euclid. The last two lines clean the textarea and shrink the playbox accordingly.

The last line of the preloaded code made Euclid demonstrate division of 6 by 4. I was tempted to write division of 6 to 4 to tell you what's happened here. Six ones (coins, cupcakes, carrots or just pegs) were distributed between 4 recipients (pirates, students, rabbits or just stacks) as evenly as possible. Which means, two of them were left.

The following spell tells Euclid to take control of the board and to play out the division of 53 by 7.


The number your.fps sets so-called frames per second rate (your could have seen it in my apps before). If you just created Euclid, it must be running at the pace of 3 frames per second. The rate of 10, like below, is fast. The rate of 1 is slow.


Once Euclid has finished it's job, you may throw in one more one and see how your division will change. Drug the following code to the empty textarea and cast it as many tines as you like (or can afford, given your computer's capacities).


Modulo is the red shnumber on top of the blue stack. It follows the behavior of an oscillating toilet tank, going from 0 to being just one short of the value of the divisor (denominator), falling back to 0 and climbing up again. Another good metaphor would be the punishment of the ancient king Sisyphus. In the realm of the signals this one is called a sawtooth wave.

For computer programming, modulo may be just a convenient notation. Like other math functions, it's not being taken literally. Computers do not draw triangles and measure their sides to use trigonometry, as you know.

Not only modulo is a periodic function, but we can use it to build any other integer periodic function. Rotations and even calculus are here too. You know what I appreciate. The challenges. They are abundant, and all this wondrous stuff is ready to be learned by the third graders, if only we cared to teach them.

Let's start from creating a square wave out of two saw teeth. Understandably, the length of the wave must be an even value, so we start with a number d and multiply it by 2.

D = 2d
y = (x mod D) - (x mod d)

in JavaScript and is some other computer languages there is modulo operator % (they do not use percent sign for any other purposes). However, in Javascript this is not exactly modulo. I don't know what they were thinking and could not find an explanation, but you can only rely on JavaScript % dealing with positive numbers. In the following chapter, I will apply a popular workaround.

D = d + d;
y = x%(2d) - x%d;

Here is the code, and a new playbox is waiting for you.

//Sawtooth to square
var d=5;
var D=d+d;
var x,y,b=0; 
for (x=0;x<width;++x){ 
  for (y=1;y<=x%D-x%d;++y)
  b=D+1; //bottom
  for (y=1;y<=x%d;++y)
  for (y=0;y<x%D;++y)

Dealing with shnumbers, we don't need zero level lines. To make sure that your computer is not cheating you, just subtract the blue shnumber from the red shnumber along the column, according to the color formula.

G = R - B

Another familiar face is triangular wave. In JavaScript they use a function Math.abs() to get absolute value, which, coincidentally, is also known as modulus. You may drop the code in the playbox above.

//Sawtooth to triangle 
var d=8;
var h=(d-d%2)/2;
var x,y,b=0; 
for (x=0;x<width;++x){ 
  for (y=1;y<=Math.abs(x%d-h);++y)
  b=h+2; //bottom
  for (y=0;y<x%d;++y)

Adding a modulo to the same modulo inverted and shifted, we can produce rectangular wave with variable duty cycle. The width of the rectangles depends on the shift. The rectangles are floating up and down. To keep them at the same level, I included the value of the shift to the addition.

//Variable duty cycle
var s=1,d=8;
var l,x,y,b=0;
var p=['green','blue','magenta','red'];
for (x=0;x<width;++x){ 
  for (y=1;y<=l;++y) change(x,y,p[0]);
  b=d+d+1; //bottom
  for (y=1;y<=(x+s)%d;++y)
  for (y=0;y<s;++y)
  for (y=0;y<x%d;++y)

The vertical shnumbers add up as follows

G = R + M - B

Here is how the code is calculating them

Y = X%d + s - (X+s)%d

Please feel free to change the value of d (divider) and s (shift). Divisor changes the sizes of the saw teeth. Shift defines their relative position.

This trick is funny, even if not very valuable. It allows us to build any integer periodic function, but in programming we can achieve the same results comparing modulo to a number.

You may not care how modulo enables cryptography, but even these demo pages are thickly sprinkled with them. Modulo is in every board and every loop, which walks the value of a variable from here to there. Modulo lurks in positional model of quantity. We use it to count objects and to convert numbers. Being a periodic function, modulo is handy for periodic tessellations, especially because we can map numbers into colors. Here is a compact modular way to produce 4-color tiles, in which board, loops and positional model are working together.

for (var j=0; j<height; ++j)
  for (var i=0; i<width; ++i)

Let's use modulo to variegate the board with stripes.

var step=2;
for (var j=0; j<height; j++)
  for (var i=0; i<width; i++) 
    if ((j+i)%step==0) change(j,i,'g',0.1);

Oops, this looked more like a chessboard, but if you make step bigger, you will see what I mean.

Superimposing stripes makes moires. This one is simple and good looking. See, we are getting closer to a loom.

var s1=3, s2=4, k;
for (var j=0; j<height; j++)
  for (var i=0; i<width; i++){
    if (k%s1==0||k%s2==0) 
    else change(j,i,'b',0.1);

Can you think of crossing two such moires? And, by the way, how big is a tile in this tessellation? The underlying math: moire visualizes the concept of the least common multiple, also known as the least common denominator.

Here is one more tessellation (the last one, I promise) and below is the story. Suggestion first: drop the spell in the playbox above, uncomment the addLines(14);, run it once and comment out. You can change 14 to whatever you want, positive of negative, but remember, it adds lines every time it's casted. Sure enough, you can have more pegs: size(28,28) would show you exactly one tile. Yes, it's 4 times 7.

//tessellation with H
var i,j,is,cs,s,c;
for (c=1;c<5;++c){
  for (i=0;i<width;++i){
    for (j=0;j<height;++j){
      if (s%28<3) change(j,i,c);
      if ((s+18)%28<3) change(j,i,c);
      if ((s+22)%28<1) change(j,i,c);

If you think I am making my living designing pattern, you are wrong. This stuff is new to me, or, in some parts, it was well forgotten. I didn't even remember polyomino when I was playing with TLG. I read Martin Gardner's columns, but it was ages ago.

For 10x10 board polyomino is too much, and most of them are... uninspiring. Yet having this new media - a programmable pegboard - I decided to try my hand and picked a recognizable heptomino, which you just saw. With the additional complexity of four colors, I was wondering how challenging would it be to program such a pattern.

First, I drew it. I wanted to see the rule, and here is what I found.

The line marks the repeating red part, which on the picture is not completely assembled. Once I saw it, I knew how to build the whole using variable duty cycle functions. Rotational symmetries are more interesting, of course, but even this is impressive enough. The parts look like organic molecules, sticking to each other.

Take 3: OOP and AI

Shapes as software objects

Originally, is was a three-part study on handling multiple shapes. Only the last chapter made it to this demo. I wanted to see how imaginary learners could program the maneuvers, which I performed two years ago with a 4-year old. We did rotations too.

Take 1 was about hardcore procedural programming, which, predictably, did not work. In Take 2 I tried cels, like in classical animation. Here I used OOP, and found it surprisingly easy (although it may look scarier because it takes several times more writing). To appreciate the difference, compare how I rotate the colors in this chapter with the affine transformation.

Here is the first approximation.

function quincunx(){
new quincunx().appear();

Congratulations, we used JavaScript's OOP, we got a quincunx, and it was easy. Or so I hope. Well, JavaScript is JavaScript. Thises, functions everywhere.

Now I am going to get rid of Cartesian numbers in change(). The paradigm of computer language for complete mathophobes are HTML/CSS. Let's see... they have size, hight, width, margins (top, bottom, left and right), just left and right (as distances)... what else? OK, even they use x and y in overflow and, unbelievably, z-index. Oh, I forgot vertical without horizontal. It's not numerical, anyway. You know, I've seen enough really smart people not to consider myself to be one of them, but I don't belong to the proud league of complete idiots either. Can you tell me why do they make their lives so hard? Being reasonably smart may be scary, but it's much easier.

I decided to use margins. My favorite function now is


Will it be easy enough? Now how about addition? The following code tells quincunxes where to appear. To do the trick, the numbers in appear() must be added to the initial positions. Subtraction, by the way, is merely an addition of a negative number.

function quincunx(color){
  this.appear=function (T,L){
new quincunx('r').appear(+2,+1);
new quincunx('b').appear(+1,+4);
new quincunx('g').appear(+4,+2);
new quincunx('y').appear(+3,+4);

The previous code was probably not worth trying. It's the same change() calls, four times five of them. For most practical purposes, they are not worse than arrays and loops, which I used before, because they are bound to this particular shape.

Let's add two methods. New version of the constructor will be attached to the playbox, and the code will be erased. Past this point we can use prototype.

  this.appear=function (T,L){
    return this;
    return this;
    if (;


I changed the shortcut name for the playbox from your to my. Technically, my it's not correct, but it's in line with American habits and, probably, feels reassuring.

The code below creates four quincunxes and attaches them to the playbox. This must be the playbox, to which constructor was previously attached.

Variables h and w in the beginning define halves of pegboard dimensions. I want them be even. I also added simple calculations placing quincunxes around the center of the board of any size. With h=12 and w=12 the board will be 24x24.

var h=6;
var w=6;
my.N=new my.quincunx('r').appear(-3+h,-2+w);
my.E=new my.quincunx('b').appear(-2+h,0+w);
my.S=new my.quincunx('y').appear(0+h,-1+w);
my.W=new my.quincunx('g').appear(-1+h,-3+w);

In javaScript's Complete Idiot's Department their favorite example are cars. The cars can have anything you want, except they are not drivable. Quincunxes only remotely look like cars, and they have nothing a car must have, but you can drive them. Right now.

Delete the previous code and drop the following piece. Cast it several times.


Oh no. I forgot to uncomment all(). Without it, shapes leave trails, like pens. Please re-create quincunxes. It's eazy. Press Ctrl-Z, get the //CREATE spell back, cast it, and delete it again. Bring in the //FAN OUT spell, uncomment size() and start casting.

Hope it worked. If it did, quincunxes must have disappeared by now. We are not on torus anymore. Can you change //FAN OUT spell to make quincunxes FAN IN? Can you get them fan diagonally?

Our first objects knew only their colors, and they were ephemeral. Every quincunx lived as long as the browser was working on the code, submitted by the playbox. The pegs on the board are the objects linked to the page, and they persisted to keep the changes.

The current version of quincunx evolved to be aware of it's position through dead reckoning. Linking the quincunxes to the playbox and, ultimately, to the page, we extended their lives. They persist after the flow of control went away from our code.

With cels we stopped at moving the shapes independently because it deemed harder to implement. With OOP we started from where we have been stuck before, because we could talk to the object shapes immediately. The problem now is to move the shapes together. Sending the same message to each of them does not look very practical, but currently the shapes are listening to us only. We need some kind of organization. A control center, to which we could talk, maybe? The supershape?

Let's suppose the quincunxes form a wheel, and think about rotation. In a front-wheel drive car the front wheels are rotated by the hub, but there is no central shape in our layout to take this role. The rear wheels, however, are being pulled or pushed by their tires!

The following spell links the shapes, so every one of them knows which one is next. This powerful technique was invented in Artificial Intelligence research. Linking the pegs, we can bring a flexible orders to the board. Note that the pegs do hot have to be near each other.


We already have rotate() method in the code. Any shape can receive it and pass to the next shape, until it returns to the originator. In doing so, the shapes send forward their colors. In the following playbox you have everything to define, create and link four quincunxes.

Did you cast the code? If you did, you can now rotate the colors endlessly.


Or you can combine rotation with fanning out. Please note, we can start rotation from any shape. They are all the same.

var h=12;
var w=12;

Don't forget to comment out size(). Remember, the shapes are always here, but you may need to pull them back in view.

Translating all the shapes in the same direction for the same distance is easier. A student might take rotate() method and hack it into move(top,left). I even linked it to go(top,left) already.

Now here is the terrible truth: the method

    if (;

may be obvious, but it's only easy if somebody else wrote it. Not only it's tricky to write - it's tricky to debug. You go through rotate() calls, and realize, like every beginner did at some moment, that objects in OOP are more or less elaborate fakes, covering up the same old flow of control.