After looking at Conway's game of life I have been looking at other forms of cellular automata. This lead me to discover Langton's ant, which is a different kind of cellular automata where an agent (namely an ant) is used to turn the squares on or off as it travels around a grid.
The rules of Langton's ant are quite simple. The ant simply follows two rules as it moves around the grid.
- At a white square, turn 90° clockwise, flip the colour of the square, move forward one unit.
- At a black square, turn 90° counter-clockwise, flip the colour of the square, move forward one unit.
This can be represented in code by looking at the current state of the square that the ant is stood on and then performing an action. Movement in a particular direction is achieved by adding or subtracting from the x or y coordinates depending on which way the ant is pointing.
Changing the text of a submit button when clicked can be useful if you are writing an AJAX application or you know that there will be some sort of delay. Providing the user with some form of feedback is a useful way of letting them know they they have done something.
First, we need a form to work with, so I built a quick one here. Notice that the submit button has an onclick action associated with it, this will be used later to enable us to alter the text of the button.
I quite often find myself needing to know how long a string is, especially when testing form validation or when trying to write a page description. I therefore like to have this little tool to help me by simply counting the number of characters in a given string.
The tool uses a single form with a textarea and a text box. The textarea has onkeyup and onkeydown events which causes it to call a function that counts the number of characters and enters this into the text box.
If you want to create a link that performs an action that can't be rolled back then you might want to stop the user from clicking that link unless they really want to. The best way to do this is to intercept the link with a confirm() command.
The first way to do this (and especially useful if you want to ad other functionality) is to use the following function.
So taking it a step further I decided to create a function that would round a number to the nearest 10, 100, 1000 or whatever value is entered. If this value is less than 0 then do the reverse by multiplying and dividing the number by the given value of accuracy. Here is the function.
The following snippet shows the creation of an array of things that can't be referenced by a normal for loop due to the odd numbering of the keys.