Building JavaScript applications with JSEclipse

Build a species of evolving creatures while learning this useful tool
Skill Level: Nicholas Chase ( Freelance writer

18 Dec 2007 Using JSEclipse, JavaScript programmers now have their own Eclipse plug-in that provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse has been providing in the Java™ language and others for years. Learn to use this tool, while creating a colony of evolving "creatures" on your page.

Section 1. Before you start
This tutorial is for JavaScript developers who want to learn more about making their lives easier. It covers the JSEclipse tool, which plugs into Eclipse and provides features like code completion and templates. It also covers Firebug, which provides true debugging capabilities. This tutorial assumes you have a fairly good grasp of JavaScript programming. If you need to brush up, see Resources for some good introductions.

About this tutorial
Eclipse is a terrific programming tool, providing capabilities like code completion, easy navigation, and debugging for programmers of many languages. But until now, JavaScript wasn't one of them. Now JavaScript programmers have their own tool: JSEclipse — an Eclipse plug-in that provides many of those same features for

Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 1 of 51


JavaScript applications. In this tutorial, you will learn how to: • Install JSEclipse • Configure JSEclipse • Use JSEclipse's features • Create new content on a Web page dynamically • Use JavaScript classes to create evolving "creatures" • Create continuously moving objects You'll use JSEclipse to aid in the development of a system that creates creatures, which are simple objects that move around and evolve as they breed with each other.

System requirements
You must have the following software available and installed. Eclipse V3.3.x JSEclipse uses the latest version of Eclipse. While you may be able to install it into earlier versions, you will run into missing features and classes that can be difficult to locate. The core install of Eclipse V3.3.2, available at Eclipse Downloads, will install JSEclipse out of the box. JSEclipse You may follow the instructions in the tutorial to install JSEclipse via an update site, or you can download it directly from Adobe Labs. Operating system You need an operating system capable of running all of the above. We used Microsoft® Windows® when creating this tutorial, but you can use a modern version of Mac OS X or Linux®, as well. Adjust locations of files accordingly.

Section 2. Getting ready
This tutorial looks at two tools and at creating a whole new species, so let's get the lay of the land to start with.
Building JavaScript applications with JSEclipse Page 2 of 51

© Copyright IBM Corporation 1994, 2008. All rights reserved.


What we're going to accomplish
This tutorial chronicles the creation of an evolving "species" — elements that move around a Web page looking for fellow creatures to breed with and giving birth to new creatures with similar attributes — or dying off before finding them. This tutorial is only an hour long, so by necessity, the creatures will be pretty simple. They'll be squares of various size, color, and speed, and when they meet up with another creature, they'll breed to create a creature that combines their properties in a semi-random way. The result, if you're lucky, is a group of roaming creatures. Figure 1. A colony of creatures

This "colony" isn't anywhere near as sophisticated as others that have been created. For example, some createde by Second Life users, such as Laukosargas Svarog's Svarga and Luciftias Neurocam's Terminus, are stunningly beautiful. All of the properties in Pagan Bishop's Basic Evo Objects evolve with each generation, so even he doesn't know how they'll turn out. For our simple tutorial, bouncing, evolving squares will do quite nicely.

How the pieces fit together
Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 51


Accomplishing this will require several pieces, so let's take a look at what they are and how they'll fit together. We're building this application using JavaScript, so we start with a simple Web page and reference an external file with the script that controls the environment. That script references a single class representing the creatures. Tools-wise, you'll be using the Eclipse IDE with the JSEclipse plug-in. This provides you with a convenient JavaScript editor, as well as tools for auto-completing code. Initially, you'll be able to view the Web page we're creating in the browser from within Eclipse, so development will be fairly well contained in this one environment. JSEclipse doesn't provide an actual debugger, so when we get to that point, we'll leave the cozy confines of Eclipse and open the page directly in Firefox, where we'll debug it using the Firebug plug-in. Let's start putting the pieces together.

Obtaining JSEclipse
If you haven't installed the Eclipse IDE, do that now (see System requirements). This tutorial was written with Eclipse V3.3.1.1, so if you have installation issues with the plug-in, you might try installing that version to start with. The next step is to get the JSEclipse plug-in. The easiest way to do that is to use Eclipse's built-in update system: 1. 2. 3. 4. 5. Install Eclipse. Start Eclipse. If necessary, choose "Go to Workbench." From the Workbench menu, choose Help > Software Updates > Find and Install. Select Search for new features to install. Figure 2. Choose to search for new features

Building JavaScript applications with JSEclipse Page 4 of 51

© Copyright IBM Corporation 1994, 2008. All rights reserved.



Click Next to move on to creating a new update site.

Create a new update site
New Features and plug-ins are hosted on specific update sites. You'll have some of these sites preconfigured with your Eclipse install, but you'll need to add a new one for JSEclipse: 1. 2. Click New Update Site on the right-hand side of the window. Enter JSEclipse (or something else you'll remember) for the name and

Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 5 of 51

2008. Click OK to add the new site to your list. . then clicking for the URL. you can use it to install JSEclipse: http://download. Install JSEclipse Once you have the new site in place. All rights reserved. Add new update site information 3. Building JavaScript applications with JSEclipse Page 6 of 51 © Copyright IBM Corporation 1994.macromedia.developerWorks® ibm. Figure 3. Make sure the new site is selected for update by selecting the checkbox next to it.

For security (and code integrity) reasons. Page 7 of 51 . so it should be easy to find. Select the feature to install 3. JSEclipse is the only feature hosted on this site. Select the JSEclipse feature and click so confirm that you want to install this unsigned feature. Figure 5. the actual installation checks to see if the feature has been signed. as shown in Figure 5. Confirm installation Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. Agree to the license agreement and click Next. 4. Verify the Eclipse installation location and click developerWorks® 2. All rights reserved. 2008. It hasn't. Figure 4. 5. and click Install.

com/developerWorks When the installation is complete. you'll need to configure it. You shouldn't have to restart Eclipse. click Apply Changes. but if things act weird. . All rights reserved. 2008. To configure it. Configuring JSEclipse Building JavaScript applications with JSEclipse Page 8 of 51 © Copyright IBM Corporation 1994.developerWorks® ibm. choose Window > Preferences > JSEclipse to bring up the preferences. Now that JSEclipse has been installed. Figure 6. it's never a bad idea. Configuring JSEclipse The JSEclipse plug-in gives you a great deal of control over your user experience.

JSEclipse includes templates for commonly typed code. and whether to highlight other occurrences of the current variable. whether to perform error General preferences These are preferences. etc. such as function names. or match an existing color scheme.. Templates As you'll see in the Code templates made easy: Multidimensional arrays section. but also what color represents each item so you can make things easier for you to read. Page 9 of 51 . 2008. such as how long to wait before popping up the auto-complete pull-down menu. say. from another editor. Syntax coloring JSEclipse gives you complete control not only over what gets color-coded. variables. such as for Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. All rights developerWorks® JSEclipse preferences come in four varieties.

.js file extension and make sure that JSEclipse is the associated editor. Next. and to import new ones for your own purposes.developerWorks® ibm. etc. Choose Window > Preferences > General > Editors > File Associations. This panel gives you the ability to activate or deactivate existing templates. Figure 7. so it doesn't use the generic text editor. All rights reserved. Highlight the *. Configuring the JSEclipse editor to be the default editor Building JavaScript applications with JSEclipse Page 10 of 51 © Copyright IBM Corporation loops. Typing One advantage of using an IDE is that it can automate tasks like closing brackets. you can turn off this functionality here in the preferences. Set JSEclipse as the JavaScript editor You need to tell Eclipse that it has a special editor for JavaScript files. we need to tell Eclipse to use the plug-in. If that drives you crazy. functions. 2008.

js extension does not have JSEclipse as its default developerWorks® If the *.ibm. Page 11 of 51 . All rights reserved.js extension is missing. Now let's see JSEclipse in action. click the top Add button and add it in the dialog. click the bottom Add button. Select Internal Editors > JSEclipse HTML Editor and click Add to set it as the default. go ahead and start the actual project. Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. 2008. The basic project Now that you've got JSEclipse installed. Section 3. If the *.

a Java application. It's possible to work with existing JavaScript applications are generally simpler than. Create a new project: 1. 3. Create a new project Start by creating a new Eclipse project to hold all the pieces. you can uncheck Use default location and point to the folder containing your existing files.developerWorks® ibm. Enter a project name and choose a location for your project. . say. Figure 8. 2. as shown in Figure 8. If you already have an existing application. 2008. but we're going to assume that you're starting from scratch. Click Next. Set a name and location for your project Building JavaScript applications with JSEclipse Page 12 of 51 © Copyright IBM Corporation 1994. All rights reserved. but you've still got to keep the pieces together. Choose File > New > Project > General > Project.

Create the main page Now that you have a project. Click Finish to create the project. So let's start by creating the environment in which our creatures will evolve. Page 13 of 51 .html and click Finish. you need to create the main page. If. This should take you back to the familiar Eclipse Assuming you're creating a new file. of course. you created an empty project. and this one is no different. on the other hand. you can: Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. 2008. but you want to directly include an existing file. Right-click the project and choose New > File. All rights reserved. Most JavaScript applications run in a Web page. type the file name as developerWorks® 4.

developerWorks® ibm. 1. Creating a new file Building JavaScript applications with JSEclipse Page 14 of 51 © Copyright IBM Corporation 1994. All rights reserved. . Figure 9. Click Advanced. 2. 2008. Check Link to file in the filesystem. Browse to find the file.

width: 600px. Page 15 of 51 . The host HTML page The HTML page in which the application lives is fairly simple. with a solid three-pixel black border around it. in order to keep all of our development in one window as much as possible. Save the file by choosing File > Save or by pressing Ctrl+S. I've specifically set the position as relative so the position attribute will be inherited by the creatures we place in the div later. Click Finish. Listing 1.position: relative. All rights reserved. The basic HTML page environment. Enter the following code into the environment. That element is essentially a big box. When you right-click the file in the Project Explorer on the left. Figure 10.html file. the content of which consists of a single div element. height: 500px. Options for opening a file Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. border: 3px solid black."> </div> </body> </html> Here we have a simple HTML page. I'm referring to the browser within Eclipse.html <html> <head></head> <body> <div id="environment" style="float: right. you should see a menu of choices pop up. View the page in the browser As a JavaScript developer. But in this developerWorks® 4. 600 pixels wide by 500 pixels high. I'm sure you know how to open a page in your browser.

. you have a number of options. based on what Eclipse knows about the file extension. so you can see the color-coding behind the menu. Remember when you added a default editor for *. It's already assumed that we wanted to use the JSEclipse HTML editor. 2008. The basic HTML page Building JavaScript applications with JSEclipse Page 16 of 51 © Copyright IBM Corporation 1994. You should see the basic page.developerWorks® ibm.js files? This works on the same principle. Figure 11. Choose the Web browser. All rights As you can see.

com/developerWorks developerWorks® OK — it's not much to look at. Adding JavaScript to the page <html> <head> <script type="text/javascript"> var maxSize = 100. Page 17 of 51 . Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. Start by adding the following code to environment. as you'll see in a Listing 2. All rights reserved. Add a little JavaScript to the HTML When we were configuring Eclipse.html.js files. there's an easy way for us to deal with that issue. we made sure JSEclipse was the default editor for *. 2008. Now we just have to create them. but that box will be the environment in which our creatures live. but it's certainly not uncommon for JavaScript to be embedded in an HTML file. Fortunately.

. var maxHeight = 500. how do we edit it? Editing embedded JavaScript using JSEclipse To edit the script portion of the page in JSEclipse. border: 3px solid black. and we've created a single function. ."></div> </body> </html> The code itself is pretty simple. var theCreature2. but for now.position: relative. 2008. } </script> </head> <body onload="createNewEnvironment()"> <div id="environment" style="float: right. height: 500px."). just note that we're setting some initial variables. var interval = 100 function createNewEnvironment(){ alert("Creating new items.. right-click the script element on the page and choose Edit in JSEclipse. Now. All rights reserved.developerWorks® ibm. Right-clicking a script gives option to edit it using JSEclipse Building JavaScript applications with JSEclipse Page 18 of 51 © Copyright IBM Corporation 1994. createNewEnvironment(). which we call when the page first loads. var theCreature. Figure 12. We'll go into it in detail var maxWidth = 600. width: 600px.

com/developerWorks developerWorks® Once you choose Edit in Page 19 of 51 . the editor creates a temporary file and opens it in the JavaScript editor. Figure 13. All rights reserved. Editing the temporary file Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. 2008.

if nothing else.developerWorks® ibm. In most cases. Listing 3. .com/developerWorks Notice that the editor of this temporary page has all the capabilities we would expect. code outlining. let alone debug. This comes in handy for situations in which you have a "spaghetti" page. etc. you'll find that the changes are mirrored in the original page. In this case. it's usually better to include your scripts in separate files. Adding external files <html> <head> <script src="Creature. we've got three files. if you're using an IDE. 2008.js" type="text/javascript"></script> <script src="MultiDimensionalArray.js" Building JavaScript applications with JSEclipse Page 20 of 51 © Copyright IBM Corporation 1994. All rights reserved. in which you have a lot of embedded JavaScript that's hard to track down and edit. Using external scripts For maintainability. it's easier to use separate files. If you make a change to this temporary page and save it. such as color-coding. though.

html and add the code originally in the script element we just replaced. Interestingly. In this developerWorks® type="text/javascript"></script> <script src="environment.html and save them. and choose a random value from within that range. we create a range that encompasses the two original values. and speed. we see that populations with some properties do better than those with others. Starting at the bottom. but they still have well-defined behavior and attributes. How the creatures evolve Each creature has its own size. we get new creatures that are similar to the old ones. Create this new file in the same directory as environment. Also. and the Creature. Page 21 of 51 . The creatures The creatures we build are simple. To determine the properties of a new creature. For now. but not necessarily the same. Let's look at what those behaviors and attributes will be. Now we're ready to start discussing the actual application.js file will contain a utility class we're creating to track our creatures. by allowing values outside the range of the original two values. color.js" type="text/javascript"></script> </head> <body onload="createNewEnvironment()"> . which fires off the evolutionary process and keeps it going.. All rights reserved.js will contain the main control script. and the rest will start in the center. The first two will be placed in random positions in the environment.js file will contain the actual class definition for our creatures. 2008. create both of these scripts as empty files in the same directory as environment. plus 15 percent on the high and low ends.. Section 4. we see the basis for natural selection: Because we're also "killing off" our creatures after a specific period of But how does all of this translate into code? Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. we allow for the possibility of our creatures evolving in a new direction. environment. The MultiDimensionalArray. When two creatures come close enough to "breed" — as defined by the center of one being within the bounding box of the other — they combine to create a new creature.

we're creating a single div at the coordinates <200. 255).html file. Listing 4. First. Once we have the creatures. This is a perfect opportunity to use Object-Oriented Programming because all creatures follow the same basic template. We do that through the use of a 2-D array. 0. Creating a single creature Before we start worrying about classes and such. we need to take a couple of issues into consideration. The box is 100 pixels square and has a blue center. and breed()) and attributes like size and color. background-color: rgb(0. They're all instances of a Creature class. themselves.. 300>. border: 2px solid red. All rights reserved. Creating a single creature ."></div> </div> On the back end On the programming side. height: 500px. <div id="environment" style="float: right. width: 600px. Let's start by creating a single creature.position: relative. So we start by creating the Creature class and defining its methods. If you save the page and refresh your browser. it's helpful to create a single creature manually so we know what properties we're going to need to include in the class. . we need to think about the creatures. width: 100px. we need to maintain their positions in a convenient way. We can create a simple array that lists all the creatures. 2008.developerWorks® ibm. Add the code below to the environment. height: 100px. Because these aren't actually sentient creatures that can look around. we need to know whether any of the others are close enough to breed with it. left: 200px. such as move(). Figure 14. with a red border. we need to think about how to track them. but with different attribute values. border: 3px solid black."> <div id="creature1" style="position: absolute. A single manual creature Building JavaScript applications with JSEclipse Page 22 of 51 © Copyright IBM Corporation 1994.. you should see something like Figure 14. but each time one of the creatures moves. top: 300px.

this. this.colorBlue=0. this.x = 30.colorRed=0. All rights reserved.colorGreen=0.maxage = 500. this. The basic Creature class function Creature(){ this. this. Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. Page 23 of 51 . this. Add the code shown = 2.js and click Finish. Some. will be unchangeable.currentAge = 0.status = 1. this. The basic JavaScript class To create the new class file. right-click the project and choose New > File. this. like the border and the fact that position is absolute.yspeed = 3. Type the filename as Creature.y = = "thisId". this. this. Listing 5.size = 20. but we still need a class to track the rest of them. this. developerWorks® So now we know our creature will be fine with these properties.

if you have any errors in the code. We've added placeholder implementations for the methods we're going to use."). ypos){ alert("Rendering. this. In JavaScript.. greenLevel.createAt = function(idString.. blueLevel."). }. . Figure 15. } this. but the ability to dynamically define a method in this way can be extremely handy.renderAt = function(xpos.. }. Notice that we've broken the color up into three components so we can easily determine new color values when the object breeds. } this.. and there's potential for problems. Error checking in JSEclipse Building JavaScript applications with JSEclipse Page 24 of 51 © Copyright IBM Corporation 1994.bouncey = function(){ alert("Bounce Y!"). 2008. All rights reserved. xpos. gridIdx."). theSize."). JSEclipse will point them out to you. yspeedLevel){ alert("Creating creature. } } This is a fairly straightforward JavaScript class. this.bouncex = function(){ alert("Bounce X!"). such as the size and current speed. redLevel. }. xspeedLevel."). It includes attributes to store information about the individual object. We're also including methods." }.com/developerWorks this. } this. this.checkForPartner = function(){ alert("Checking. JSEclipse code checking Right away. as I originally did. ypos. as you can see.. this.die = function(){ alert("Killing this creature.breedWith = function(otherCreature){ alert("Making new creature..move = function (){ alert("Moving. we call them functions.developerWorks® ibm. But this is a lot of code to throw at you.

com/developerWorks developerWorks® Just as in regular Eclipse programming. Listing 6. you also can collapse functions or display just the definition with the option to expand and see all of the code. Let's go ahead and use this class to create a new creature. 2008. an error message. you can see the error. For example. Once the errors are corrected. Using content assist and finding definitions One place where JSEclipse shines is in providing assistance. Certainly beats trying to find that in a bare browser. theCreature1. such as showing available methods and attributes. if we were to type the code in Listing 6. Page 25 of 51 . JSEclipse shows available methods and options theCreature1 = new Creature(). All rights reserved. Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. and a quick visual queue as to the location of the error. This capability can make those long programs so much easier to JSEclipse would provide the available options automatically.

or you can "force" it by pressing Ctrl+Space.developerWorks® ibm. . and choose Open Declaration. theCreature1. Content assist in action This menu pops up automatically. Opening a declaration Building JavaScript applications with JSEclipse Page 26 of 51 © Copyright IBM Corporation 1994. right-click it. All rights Figure 16. 2008. as shown below. Listing 7. I could place the cursor in the createAt() reference.createAt() Figure 17. Typing this code helps in finding the implementation of a particular class or method theCreature1 = new Creature(). For example. JSEclipse also makes it easy to go in the other direction and find the implementation of a particular class or method. if I had typed the code in Listing 7.

Page 27 of 51 . as in developerWorks® This opens the definition of that class. To carry this diversion just a tiny bit further. All rights reserved. it's worth noting that once you're in the class definition (or any for that matter) you can also navigate quickly by using the code outline in the right-hand column. 2008. Navigating our files Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. places the cursor at the location of that method. and in the case of individual methods. assuming you've named the file with the name of the class. Figure 18.

this.colorRed = Now that you know where to find everything. this. this. just because we have a bunch of properties doesn't mean that we'll be able to see anything. All rights reserved.yspeed = yspeedLevel. Creating the creature with JavaScript Now. theSize.js file. 2008.colorBlue = blueLevel.size = theSize.y = ypos.x = xpos. this. this.xspeed = xspeedLevel. = idString. this. let's move forward and use that knowledge. Creating the creature . blueLevel. Add the following code to the Creature. we're going to have to create a div with those properties and add it to the environment.createAt = function(idString. yspeedLevel){ this..developerWorks® ibm. To really create the creature. gridIdx. this. ypos.. xspeedLevel. Building JavaScript applications with JSEclipse Page 28 of 51 © Copyright IBM Corporation 1994. greenLevel.gridIndex = gridIdx. xpos. redLevel. Listing 8.colorGreen = greenLevel. this. this. .

0. Next. 100. theEnv.left= this.. get a reference to the environment div we created earlier in the static HTML page. But doing all of that doesn't create something we can actually 0). we need to tell the page to do it. get a new reference to the current div and use that to set its properties..createElement('div'). } First we set the size.position="absolute". All rights reserved.size. Once you have Now we have the ability to create a div that has our properties. " +this. Save the files and remove the static div from environment. Next. "+this.js — the JSEclipse editor should come up automatically because we set it as the default — and add the following code to it.x+"px". 100. Note that some syntax is slightly different from the CSS properties you used earlier — specifically. Once we have that developerWorks® theDiv = document. so the first thing we need to do is to set its attributes.border="2px solid red". theEnv = document. theDiv. 150. Use the document object to create a new div element. You'll need to do that in order to reference it to set its styles. theCreature1.colorBlue+")". you'll see why in a moment.size. we can use its createAt() method to place the new creature on the page.appendChild(theDiv). much like Figure 19.getElementById('id'. From there. which we can do using the we create a new instance of the Creature class. this. To do that. size. } .backgroundColor= "rgb("+this.y+"px".ibm.height=this. We create the actual object in the control 2008. Double-click environment. we need to create a new div.colorGreen+". theDiv = document. theDiv. If you refresh the page. theDiv. theCreature1 = new Creature(). and set its ID attribute. Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. 150.createAt("thisId1". 150. Next. Creating the new creature function createNewEnvironment(){ size = 100. Page 29 of 51 . you can use it to add the new div as a child element. you should see a new creature.getElementById("environment").id). theDiv. theDiv.this. theDiv. Listing 9. theDiv. theDiv. background-color becomes backgroundColor.colorRed+". theCreature1.

com/developerWorks Figure 19 The new creature We can now create a creature via JavaScript. All rights reserved. var maxWidth = 600. Listing 10. function rand(maxNum){ return Math. var theCreature.random()). as shown in Listing 10. but we feed it random values. var theCreature2. Creating two random creatures Now we're ready to create our two random creatures. we simply use the createAt() method. so it's time to mix things up a little. our Adam and Eve. } function createNewEnvironment(){ Building JavaScript applications with JSEclipse Page 30 of 51 © Copyright IBM Corporation 1994. var interval = 100. To do that.round(maxNum*Math.js. . 2008. var maxHeight = 500. if you will. which shows environment. Creating two random creatures var maxSize = 100.developerWorks® ibm.

rand(20)). you'll see two random blocks.createAt("thisId2". rand(255). theCreature1 = new Creature(). we would multiple that value by 10. so we need to subtract the size from the height and width of the environment before requesting its position. Two randomly created blocks Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. rand(20)). And finally. size. First. OK — let's take this from the top. we set the speed. 1. rand(maxHeight-size). If you refresh the page. as long as we give it a new id attribute. 2008. rand(255).ibm. we round off the value because we need integers for all of our values. rand(maxWidth-size). From there. -10 + } 0. developerWorks® size = rand(maxSize). so to get a random number between.random() returns a pseudo-random number between 0 and 1. we're creating a convenience function for our random numbers. rand(255). 0 and 10.createAt("thisId1". theCreature1. rand(maxWidth-size). -10 + rand(20). theCreature2 = new Creature(). All rights reserved. -10 + rand(20). so we make the range 20 and simply offset the value by 10. rand(255). We don't want the creature hanging out the side of the environment. theCreature2. Page 31 of 51 . rand(255). Math. say. We need to do that first because we need it when determining the position. rand(maxHeight-size). Again. We use this same process to create a second creature. we set the size for our first creature. -10 + size = rand(maxSize). We want the speed to be between -10 (so it can go up or left) and 10 (so it can go down or right). we're setting the three components of the color separately. rand(255). size. Figure 20.

developerWorks® ibm. Moving creatures All right. 2008. add the following code to Creature. We need to get these creatures moving so they can find each other. just as they are. Moving the creatures based on speed Two properties that we set for our creatures were the horizontal and vertical speeds." To make that happen. These speeds represent the number of pixels the creature will move in a single "turn. Later. . you'll get two new creatures. All rights Each time you refresh. Listing 11. Section 5. you can use this capability to try and start out with a pair that you like. nobody's going to breed with anybody. Moving creatures Building JavaScript applications with JSEclipse Page 32 of 51 © Copyright IBM Corporation 1994.js.

this. Finally.x. setTimeout("nextTurn()". rand(255). size.renderAt(this. The nextTurn() function moves the two creatures. -10 + rand(20)). we need to tell the creature to move repeatedly. function createNewEnvironment(){ size = rand(maxSize). theCreature1 = new Creature(). theCreature1. we set the new position information on the object itself.move = function (){ this.js. } The setTimeout() function tells the JavaScript engine to execute some action after some period of time. We can do that by using JavaScript's setTimeout() function in environment.renderAt = function(xpos.. size. theCreature2 = new Creature(). In this case.y = this. First. size = rand(maxSize). 1.. theDiv. rand(255). this. -10 + rand(20). rand(height-size). } function nextTurn(){ theCreature1.y + this. interval). Listing 12. then we call the renderAt() method to place the actual div in the new location by changing its left and top style values. -10 + rand(20)).x = this. as we set it earlier. then sets the timeout again so the function runs in another one-tenth of a developerWorks® . theCreature2.y. Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994.createAt("thisId2". }.id). 2008.move(). Moving the creatures repeatedly .xspeed. 0.x. All rights reserved.move().. that action is the nextTurn() function. .style.x + this.yspeed. -10 + rand(20). this. this. ypos){ theDiv = document. setTimeout("nextTurn()". rand(height-size). rand(255). rand(width-size). and the period of time is one-tenth of a second (100 milliseconds).. rand(255). theDiv. interval).top = this. rand(width-size).left = this. this.y)..createAt("thisId1". Page 33 of 51 .ibm. }. rand(255). rand(255).getElementById(this.

interval).'). Figure 21.position: relative. add a new div to the environment.. function nextTurn(){ theCreature1. All rights reserved. theCreature2. you'll find that your creatures will start to move — right off the page. The stop switch .. The first thing we need to do is to create a way to stop them from moving..html page.js and checking it before moving them. } } We start out with everything on. if (ison){ setTimeout("nextTurn()".. To turn everything off..">Stop</div> <div id="environment" style="float: right. The off switch Building JavaScript applications with JSEclipse Page 34 of 51 © Copyright IBM Corporation 1994. Listing 13. var maxSize = 100. 2008. height: 500px. Then we can look at making them bounce off the edges of the environment instead of blowing right through them. width: 600px. If you save and refresh. . border: 3px solid black."> . ..alert('Stopping. Stopping the creatures Stopping our creatures is pretty simple. we'll continue to move our creatures. We just have to have a way to turn their movement on and off.. and as long as that's the case. Listing 14. you'll see the new div on the left.move(). var maxWidth = Now if you save the file and reload the browser.move().. Start by creating a new variable in environment.developerWorks® ibm. <body onload="createNewEnvironment()"> <div onclick="ison = false. Checking to see if movement is on var ison = true.

All rights reserved. we need to check each creature's position when we move it.xspeed = -1 * developerWorks® Now let's deal with our runaways. Page 35 of 51 . Instead. Listing 15. etc.js. this. }. we want it to reverse its speed. if the creature hits one of the side walls. 2008.xspeed. If it was traveling at 3px/turn to the right. as in these changes to Creature.bouncey = function(){ this. we want to now move 3px/turn to the left. we want them to bounce when they hit the edge of the environment.. Bouncing the creatures .ibm.bouncex = function(){ this.yspeed.yspeed = -1 * this. this. In other words.. Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. To do that. }. Detecting the edge of the world We won't get very far creating a colony if our creatures just run off.

top. but what about creating new ones? Next. . The first type of tracking we need to do is easy: We just need to be able to get a reference to each creature in turn to move it. All rights reserved.x = this. A matter of breeding Our creatures themselves are set. this.bouncey(). they'll be moving in the other direction. If they've reached the edge.x + this. If you save and refresh.y < 0) { this.bouncey().this.size) > maxHeight ){ this. Remember. this. } else if ((this. 2008.size.y = this. Tracking creatures The first thing we need to do is keep track of all the creatures we create. } this. We do that by adding a simple array to environment..y). . Section 6. they) know where they are.x = 0.this.x < 0) { this. this. Pong-style.move = function (){ this. and we call the bounce functions to change their velocity. } else if (this.xspeed.").bouncex(). }..y = maxHeight .x. we're checking to see if we've hit the sides. or bottom of the enclosure.x + this. this.size.y + this.bouncex(). if ((this. } this. consequently.renderAt(this. } else if (this.developerWorks® ibm.size) > maxWidth ){ this.y + this. you'll see your creatures literally bouncing off the walls. we look at breeding and at the technical issues that involves. Building JavaScript applications with JSEclipse Page 36 of 51 © Copyright IBM Corporation 1994. this. this. the origin of the creature is in its upper left-hand this. so we need to compensate for its size when looking for the right or bottom walls. so that we (and.js.die = function(){ alert("Killing this creature. Starting at the bottom. we reset their position slightly to make sure they're back in range.y = 0. The next time they move.x = maxWidth .

move().js. In this way. setTimeout("nextTurn()". 1.createAt("thisId1".createAt("thisId2". however. size. interval). Page 37 of 51 . so it'd be better if we moved the assignment (or in this -10 + rand(20)).length. rand(255). creatureList. rand(width-size). rand(255). thisCreatureIndex < creatureList. function rand(maxNum){ return Math. creatureList[1]. interval). 0. we're going to be creating creatures dynamically within the object. duplicated it) in the createAt() method in Creature. -10 + rand(20)). Tracking creatures . we can have an arbitrary number of creatures managed by the control script. rand(255). rand(255). } function createNewEnvironment(){ size = rand(maxSize). -10 + rand(20).colorBlue+")". rand(height-size). nextTurn() iterates through the array.backgroundColor= "rgb("+this.random()). creatureList[0] = new Creature().. creatureList[0]. All rights reserved. rand(255). } if (ison){ setTimeout("nextTurn()". 2008. Building JavaScript applications with JSEclipse © Copyright IBM Corporation developerWorks® Listing 16. Then. creatureList[1] = new Creature().. rather than explicitly moving the two objects by their variable names. thisCreatureIndex++) { creatureList[thisCreatureIndex].colorRed+".round(maxNum*Math. moving each creature in it. size = rand(maxSize). rand(height-size). -10 + rand(20).. and adding the two initial creatures to it rather than creating separate variables. "+this. rand(width-size). theDiv. Ultimately. } function nextTurn(){ for(var thisCreatureIndex size. rand(255). var interval = 100. var creatureList = new Array(). Add new creatures to the creatureList .colorGreen+". } } We start by creating a new array.. Listing 17. "+this.

js file to open it in the JSEclipse editor.gridIndex] = this. Fortunately. say.. so it's easy for us to add it in this way. you can have an array of arrays. this is a great opportunity for us to examine the use of code templates. But given that it's a pretty standard set of code. This leads to the idea of creating a MultiDimensionalArray class. Figure creatureList[this. The best way to do that is to create a multidimensional array. Fortunately. grid[233][412]. "What is the object at 233. 412?" by checking the value of. As you can see in Figure 22.. All rights reserved. } this. Start by typing just the letters "fun" (as in the beginning of "function") and press Ctrl+Space.breedWith = function(otherCreature){ . and we're going to use it here. we need a way to easily access information on who's where. we've made the gridIndex. this brings up the auto-insert function for the function template. Code templates made easy: Multidimensional arrays Now. one of the object's attributes. we need a multidimensional array. or the index the creature occupies on the creatureList. in order for one creature to know whether any other creatures are nearby. when we're trying to figure out which creature we're breeding with. This attribute will come in handy in a moment.developerWorks® ibm. which is not a feature of JavaScript. 2008. Inserting a template Building JavaScript applications with JSEclipse Page 38 of 51 © Copyright IBM Corporation 1994. so we could then determine easily. Double-click the empty MultiDimensionalArray. David Nishimoto has a great example of doing this (see Resources). To do that. and you can dynamically create them by simply assigning values. .

as you can see in Figure 23. 2008. Page 39 of 51 . All rights reserved. so go ahead and select it. As you can see in Figure 23. and it's what we want. and you'll see that JSEclipse can also provide a template for the for loop. Go ahead and start to type the class. Figure This automatically drops the code into the page. Inserting a loop Building JavaScript applications with JSEclipse © Copyright IBM Corporation developerWorks® The box to the right shows what the currently selected template is. You'll see the complete code in a moment. there's a twist.

for (thisColumn=0. the other instances change. in addition to just inserting code. Very convenient! Let's get to the complete code for the MultiDimensionalArray In this case. thisRow < numRows. so I only have to do it once. thisColumn < numCols. var arrayRet = new Array(numRows). 2008. } Building JavaScript applications with JSEclipse Page 40 of 51 © Copyright IBM Corporation 1994." to "thisRow. Listing 18. Notice here that I've started changing the index variable. All rights reserved." As I type in the first variable box. as well.numCols) { var thisRow.developerWorks® ibm. thisColumn++) { arrayRet[thisRow][thisColumn] = -1. formerly "i. . for(thisRow=0. Creating a MultiDimensionalArray class function MultiDimensionalArray(numRows. } } return(arrayRet). the template makes it easy to perform tasks like customizing variables. thisColumn. thisRow++) { arrayRet[thisRow] = new Array(numCols).

y] = this.colorGreen+". Then we need to assign creatures to the appropriate spots on the grid when we render them in Creature. but we have to make sure to remove it from that spot when it's no longer "+this.gridIndex.yspeed. All rights reserved. Page 41 of 51 .backgroundColor= "rgb("+this. we specify that "empty" has a value of -1. theDiv. ypos. . this. creatureList[this.colorRed+".style.. (Fortunately. " developerWorks® Because arrays are re-dimensioned (enlarged) automatically when we add a higher index. greenLevel.move = function (){ grid[this. xspeedLevel.y + this.createAt = function(idString.renderAt = function( We need to handle this in two locations. } this.. Setting the position of each creature this. var creatureList = new Array(). all we really need to do is create entries for each potential spot on the grid. this. theDiv.. yspeedLevel){ . redLevel.x + this. so we can happily have numbers and objects in the same array.) Now we can create an instance of the array and place objects into it. blueLevel. Listing 19.js. with the grid represented by a multidimensional array. we need to create the grid array itself in environment. Creating the environment grid .y = this. In this case. this. theSize.x][this.getElementById(this.colorBlue+")"..js. Tracking creature locations The idea here is to have each creature in its location on the grid.x][this.x = this.. var grid = new MultiDimensionalArray(maxWidth. var interval = 100. grid[this. That means we can add the creature to its coordinates in the grid array when we create = this. Listing 20. theDiv. maxHeight).gridIndex] = this. First.y] = -1. ypos){ theDiv = document. gridIdx. Building JavaScript applications with JSEclipse © Copyright IBM Corporation = this. xpos.y. JavaScript is loosely typed.

}.y+size. All rights reserved.. ytocheck++) { if (grid[xtocheck][ytocheck] != -1 && grid[xtocheck][ytocheck] != this. .. } for(var xtocheck = this..x][this. . Listing 21. if (this. this. xtocheck < xmax. so we're setting it to -1.. That means we need to clear the old location before we move it. this. this.x. } ymax = this..checkForPartner = function(){ xmax = this. ytocheck < ymax.move = function (){ .x+size > maxWidth){ xmax = maxWidth.breedWith( creatureList[grid[xtocheck][ytocheck]]).y] = grid[this.y). this. } } } } } When we move a creature. Finding a partner . We're adding the creature to the grid array when we create it. 2008. if (this. Make the changes below to Creature.y+size > maxHeight){ ymax = maxHeight. Finding a partner We tried to make the process of finding a potential mate as simple as possible. That method Building JavaScript applications with JSEclipse Page 42 of 51 © Copyright IBM Corporation 1994. break. and when we render it at a new location.y.gridIndex.checkForPartner().gridIndex){ this.. Now we need to check that grid for partners to breed with. xtocheck++) { for(var ytocheck = this. }.renderAt(this.x..js.developerWorks® ibm. All we're doing is checking the grid coordinates within the current creature to see if any other creature is present. as we did when we created the array in the first place. we run the checkForPartner() method. this. .x+size.

round(low * . 255). 0. 20). If it finds one.round(high * . this.Math.xspeed. otherCreature.yspeed. -20. old2.15).colorGreen. 0. index. otherCreature.getNewValue(this. } if (high > max){ high = max..15). Creating the new creature . we send that object off for developerWorks® just determines the coordinates that make up the body of the creature and loops through each of those coordinates checking for spots that are not empty. otherCreature. Listing 22. min. All rights reserved.getNewValue(this. -20. 255). babysize = this. } Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. high = high + Math. } low = low . } this. babycolorred = this. babyxspeed. 20). babycolorgreen.length..yspeed. 100). otherCreature. 2008. 255).breedWith = function(otherCreature){ babyxspeed = this.getNewValue(this.xspeed. } else { low = old2.size. babycolorgreen = this. babyyspeed). maxHeight/2.js. } this. otherCreature..size. Breeding The actual process of combining the attributes of two creatures to create a new one takes place in Creature. maxWidth/2. babyyspeed = this. index = creatureList. babysize. 0.getNewValue(this.checkForPartner = function(){ . baby.getNewValue(this.getNewValue(this. high = old1. babycolorblue. Page 43 of 51 . baby = new Creature().colorRed.colorBlue. high = old2.colorGreen. babycolorblue = this. max){ if (old1 < old2){ low = old1.createAt("index" babycolorred.colorBlue. if (low < min){ low = min. 0.. otherCreature.getNewValue = function(old1.

. For each parameter we can set on the object. } } There's a lot of code there. we use them to create a new object and add that object to the creatureList.random()*spread). The new values get calculated based on the old ones. but each object gets added in the center of the grid. All rights reserved. 2008. and add that offset to the low value to get the new value. From there. use it to randomly choose the offset. Creating new creatures Building JavaScript applications with JSEclipse Page 44 of 51 © Copyright IBM Corporation 1994.low. in case you want to change how the evolution works. Figure 24. For example. we make it really easy to change how to determine the spread = high . we determine the spread. When you get a collision.developerWorks® ibm. but it's actually pretty straightforward. you could add a step in which you randomly mutate a value. By pulling this routine into a separate function. Save these changes and refresh the browser. we're using the getNewValue() method to combine the current value of the two parents to get a third. you'll find that you suddenly have a baby boom. It'll get added to the grid array when we render it. return low + offset. new value. Once we have the new values.round(Math. offset = Math. We expand the range by 15 percent and make sure we're not exceeding the minimum or maximum values.

we slow things down so a new creature can only be created every 50 turns. var elapsedTurns = 0. is that the original creatures don't completely pass each other instantaneously. 2008.. and they breed constantly. of course. function rand(maxNum){ return Math.. Page 45 of 51 . We track those turns in developerWorks® The reason for this. Listing 23... which means at least two creatures get created in the same place. All rights reserved. We need to slow the process down.. Tracking turns . } .round(maxNum*Math. if (ison){ setTimeout("nextTurn()".ibm. interval). Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. function nextTurn(){ .js. until we have to stop the process or crash the computer.. Slowing the birth rate To solve the baby-boom problem.random()).

Listing 24. babyxspeed. we're checking to see whether 50 turns have elapsed before we create the new creature. you might opt to check for elapsedTurns before checking for partners. otherCreature. then increment elapsedTurns for each time nextTurn() runs. All rights reserved. of course. this. Figure 25. Checking the elapsedTurns value . Now if you save your files and refresh the page. If they have. we reset that value and proceed as before. babyxspeed = this. maxWidth/2.xspeed.. } We start out at zero. index. -20.createAt("index"+index.js. babycolorblue. 20).xspeed. . We can then check this value when we try to create a new creature in Creature. babysize. you'll see something much more like a colony.developerWorks® ibm. instead..getNewValue(this. In this case. Note that for performance purposes. More of a colony Building JavaScript applications with JSEclipse Page 46 of 51 © Copyright IBM Corporation 1994. 2008. babycolorgreen. baby.. babycolorred. . } } .. babyyspeed)..breedWith = function(otherCreature){ if (elapsedTurns < 50){ // do nothing } else { elapsedTurns = } elapsedTurns++. maxHeight/2.

theDiv = document.size = = function(){ this.] = -1. this.backgroundColor = "white". Page 47 of 51 . We do that by giving them an "age. } All rights developerWorks® The only remaining problem is that things can get pretty crowded.xspeed = 0.status = 0. 2008.yspeed = 0.. this..x][this. Dying of old age The final change we will make is to give each creature a limited lifespan. theDiv." after which we will remove them from the list.border = "0px". grid[this. this. Expiring creatures .getElementById(this. theDiv.move = function (){ Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. Listing 25.

.developerWorks® ibm.y + this.. } }.xspeed. } else { this. setting it as the same color as the background.. this.die(). . but rather hides it.checkForPartner(). 2008.currentAge > this.y = this. you can run the simulation.maxage){ this. and easier code organization and color-coding. All rights reserved.currentAge++. The tutorial also chronicled the creation of creatures that evolve with each successive generation. so we can increment the age each time we move the creature. Starting at the bottom. That method doesn't really get rid of the element. we call the die() method to get rid of this. The plug-in provides capabilities such as code completion and code templates.x + this. creating new values based on the old and bouncing around the environment looking for mates.x = this. Have fun with it! Section 7. When it's old enough. this.yspeed. Summary In this tutorial. and others will die out before they catch on. remember that we defined maxage and currentAge as part of the class. . you learned how to use the JSEclipse plug-in for the Eclipse IDE to ease JavaScript development. Some simulations will be successful.. Finally.. if (this. Building JavaScript applications with JSEclipse Page 48 of 51 © Copyright IBM Corporation 1994.

com/developerWorks developerWorks® Downloads Description Source code Information about download methods Name Size Download method Page 49 of 51 .zip 3KB HTTP Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. 2008. All rights reserved.source.

• To see a more complex artificial ecosystem. • David Nishimoto has a great example of Building a MultiDimensional Array in JavaScript.developerWorks® ibm. Building JavaScript applications with JSEclipse Page 50 of 51 © Copyright IBM Corporation 1994. Evolve in Online World" from National Geographic. • Check out the "Recommended Eclipse reading list. webcasts. trade shows. see "Getting started with the Eclipse Platform. • Check out upcoming conferences. check out Second Life's Svarga. and other Events around the world that are of interest to IBM open source developers." • Be sure to check out these: Tutorial: Introduction to JavaScript and Introduction to JavaScript from w3schools. ." • Browse all the Eclipse content on developerWorks. check out check out developerWorks podcasts. tools." • Read Simon Willison's "A (Re)-Introduction to JavaScript. and project updates to help you develop with open source technologies and use them with IBM's products. All rights reserved. • Watch and learn about IBM and open source technologies and product functions with the no-cost developerWorks On demand demos. and how to extend Eclipse with plug-ins. • Expand your Eclipse skills by checking out IBM developerWorks' Eclipse project resources." • Stay current with developerWorks' Technical events and Resources Learn • Find all about the Europa release of Eclipse in the developerWorks article "A whirlwind tour of Eclipse Europa. • Visit the developerWorks Open source zone for extensive how-to information. • For an introduction to the Eclipse platform." • Get an introduction to Eclipse and a peek at its colorful history in "Get started with the Eclipse Platform. • Learn about artificial ecosystems in "Virtual Critters Thrive. • To listen to interesting interviews and discussions for software developers. • New to Eclipse? Read the developerWorks article "Get started with Eclipse Platform" to learn its origin and architecture.

All rights reserved. Rational®. • Download Eclipse Platform and other projects from the Eclipse Foundation. Building JavaScript applications with JSEclipse © Copyright IBM Corporation 1994. and get your hands on application development tools and middleware products from DB2®. • Participate in developerWorks blogs and get involved in the developerWorks developerWorks® Get products and technologies • Check out the latest Eclipse technology downloads at IBM alphaWorks. (Selecting this will launch your default Usenet news reader application and open Tivoli®. Page 51 of 51 . About the author Nicholas Chase No bio. • Download IBM product evaluation versions. 2008.) • The Eclipse newsgroups has many resources for people interested in using and extending Eclipse. • Innovate your next open source development project with IBM trial software. Lotus®. available for download or on DVD. Discuss • The Eclipse Platform newsgroups should be your first stop to discuss questions regarding Eclipse. and WebSphere®.

Sign up to vote on this title
UsefulNot useful