building javascript applications with jseclipse...provides many important features to aid in the...

52
Building JavaScript applications with JSEclipse Build a species of evolving creatures while learning this useful tool Skill Level: Nicholas Chase ([email protected]) 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 52

Upload: others

Post on 16-Oct-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Building JavaScript applications with JSEclipseBuild a species of evolving creatures while learning this usefultool

Skill Level:

Nicholas Chase ([email protected])Freelance writer

18 Dec 2007

Using JSEclipse, JavaScript programmers now have their own Eclipse plug-in thatprovides 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 ofevolving "creatures" on your page.

Section 1. Before you start

This tutorial is for JavaScript developers who want to learn more about making theirlives easier. It covers the JSEclipse tool, which plugs into Eclipse and providesfeatures like code completion and templates. It also covers Firebug, which providestrue debugging capabilities. This tutorial assumes you have a fairly good grasp ofJavaScript programming. If you need to brush up, see Resources for some goodintroductions.

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 52

Page 2: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

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 eachother.

System requirements

You must have the following software available and installed.

Eclipse V3.3.xJSEclipse uses the latest version of Eclipse. While you may be able to install itinto earlier versions, you will run into missing features and classes that can bedifficult to locate. The core install of Eclipse V3.3.2, available at EclipseDownloads, will install JSEclipse out of the box.

JSEclipseYou may follow the instructions in the tutorial to install JSEclipse via an updatesite, or you can download it directly from Adobe Labs.

Operating systemYou need an operating system capable of running all of the above. We usedMicrosoft® Windows® when creating this tutorial, but you can use a modernversion of Mac OS X or Linux®, as well. Adjust locations of files accordingly.

Section 2. Getting ready

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 2 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 3: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

This tutorial looks at two tools and at creating a whole new species, so let's get thelay of the land to start with.

What we're going to accomplish

This tutorial chronicles the creation of an evolving "species" — elements that movearound a Web page looking for fellow creatures to breed with and giving birth to newcreatures 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 withanother creature, they'll breed to create a creature that combines their properties ina 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'sSvarga and Luciftias Neurocam's Terminus, are stunningly beautiful. All of the

ibm.com/developerWorks developerWorks®

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

Page 4: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

properties in Pagan Bishop's Basic Evo Objects evolve with each generation, soeven he doesn't know how they'll turn out. For our simple tutorial, bouncing, evolvingsquares will do quite nicely.

How the pieces fit together

Accomplishing this will require several pieces, so let's take a look at what they areand how they'll fit together.

We're building this application using JavaScript, so we start with a simple Web pageand reference an external file with the script that controls the environment. Thatscript references a single class representing the creatures. Tools-wise, you'll beusing the Eclipse IDE with the JSEclipse plug-in. This provides you with aconvenient 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 withinEclipse, 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'llleave the cozy confines of Eclipse and open the page directly in Firefox, where we'lldebug 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). Thistutorial was written with Eclipse V3.3.1.1, so if you have installation issues with theplug-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 useEclipse's built-in update system:

1. Install Eclipse.

2. Start Eclipse.

3. If necessary, choose "Go to Workbench."

4. From the Workbench menu, choose Help > Software Updates > Findand Install.

5. Select Search for new features to install.

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 4 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 5: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Figure 2. Choose to search for new features

6. 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 ofthese sites preconfigured with your Eclipse install, but you'll need to add a new onefor JSEclipse:

ibm.com/developerWorks developerWorks®

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

Page 6: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

1. Click New Update Site on the right-hand side of the window.

2. Enter JSEclipse (or something else you'll remember) for the name andhttp://download.macromedia.com/pub/labs/jseclipse/autoinstall for theURL.Figure 3. Add new update site information

3. Click OK to add the new site to your list.

Install JSEclipse

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 6 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 7: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Once you have the new site in place, you can use it to install JSEclipse:

1. Make sure the new site is selected for update by selecting the checkboxnext to it, then clicking Finish.

2. JSEclipse is the only feature hosted on this site, so it should be easy tofind. Select the JSEclipse feature and click Next.Figure 4. Select the feature to install

3. Agree to the license agreement and click Next.

4. Verify the Eclipse installation location and click Finish.

5. For security (and code integrity) reasons, the actual installation checks tosee if the feature has been signed. It hasn't, so confirm that you want to

ibm.com/developerWorks developerWorks®

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

Page 8: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

install this unsigned feature, as shown in Figure 5, and click Install.Figure 5. Confirm installation

When the installation is complete, click Apply Changes. You shouldn't have torestart Eclipse, but if things act weird, it's never a bad idea.

Now that JSEclipse has been installed, you'll need to configure it.

Configuring JSEclipse

The JSEclipse plug-in gives you a great deal of control over your user experience.To configure it, choose Window > Preferences > JSEclipse to bring up thepreferences.

Figure 6. Configuring JSEclipse

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 8 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 9: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

JSEclipse preferences come in four varieties.

General preferencesThese are preferences, such as how long to wait before popping up theauto-complete pull-down menu, whether to perform error reporting, andwhether to highlight other occurrences of the current variable.

Syntax coloringJSEclipse gives you complete control not only over what gets color-coded,such as function names, variables, etc., but also what color represents eachitem so you can make things easier for you to read, or match an existing colorscheme, say, from another editor.

ibm.com/developerWorks developerWorks®

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

Page 10: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

TemplatesAs you'll see in the Code templates made easy: Multidimensional arrayssection, JSEclipse includes templates for commonly typed code, such as forloops, functions, etc. This panel gives you the ability to activate or deactivateexisting templates, and to import new ones for your own purposes.

TypingOne advantage of using an IDE is that it can automate tasks like closingbrackets. If that drives you crazy, you can turn off this functionality here in thepreferences.

Next, we need to tell Eclipse to use the plug-in.

Set JSEclipse as the JavaScript editor

You need to tell Eclipse that it has a special editor for JavaScript files, so it doesn'tuse the generic text editor. Choose Window > Preferences > General > Editors >File Associations. Highlight the *.js file extension and make sure that JSEclipse isthe associated editor.

Figure 7. Configuring the JSEclipse editor to be the default editor

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 10 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 11: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

If the *.js extension is missing, click the top Add button and add it in the dialog. If the*.js extension does not have JSEclipse as its default editor, click the bottom Addbutton. Select Internal Editors > JSEclipse HTML Editor and click Add to set it asthe default.

Now let's see JSEclipse in action.

Section 3. The basic project

ibm.com/developerWorks developerWorks®

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

Page 12: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Now that you've got JSEclipse installed, go ahead and start the actual project.JavaScript applications are generally simpler than, say, a Java application, butyou've still got to keep the pieces together.

Create a new project

Start by creating a new Eclipse project to hold all the pieces. It's possible to workwith existing files, but we're going to assume that you're starting from scratch.Create a new project:

1. Choose File > New > Project > General > Project.

2. Click Next.

3. Enter a project name and choose a location for your project, as shown inFigure 8. If you already have an existing application; you can uncheckUse default location and point to the folder containing your existing files.Figure 8. Set a name and location for your project

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 12 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 13: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

4. Click Finish to create the project. This should take you back to thefamiliar Eclipse workbench.

Create the main page

Now that you have a project, you need to create the main page. Most JavaScriptapplications run in a Web page, of course, and this one is no different. So let's startby creating the environment in which our creatures will evolve.

Right-click the project and choose New > File. Assuming you're creating a new file,type the file name as environment.html and click Finish.

If, on the other hand, you created an empty project, but you want to directly includean existing file, you can:

ibm.com/developerWorks developerWorks®

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

Page 14: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

1. Click Advanced.

2. Check Link to file in the filesystem.

3. Browse to find the file.Figure 9. Creating a new file

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 14 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 15: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

4. Click Finish.

ibm.com/developerWorks developerWorks®

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

Page 16: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

The host HTML page

The HTML page in which the application lives is fairly simple. Enter the followingcode into the environment.html file.

Listing 1. The basic HTML page

environment.html

<html><head></head><body>

<div id="environment" style="float: right; width: 600px;height: 500px; border: 3px solid black;position:relative;">

</div>

</body></html>

Here we have a simple HTML page, the content of which consists of a single divelement. That element is essentially a big box, 600 pixels wide by 500 pixels high,with a solid three-pixel black border around it. I've specifically set the position asrelative so the position attribute will be inherited by the creatures we place in the divlater.

Save the file by choosing File > Save or by pressing Ctrl+S.

View the page in the browser

As a JavaScript developer, I'm sure you know how to open a page in your browser.But in this case, I'm referring to the browser within Eclipse, in order to keep all of ourdevelopment in one window as much as possible. When you right-click the file in theProject Explorer on the left, you should see a menu of choices pop up.

Figure 10. Options for opening a file

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 16 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 17: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

As you can see, you have a number of options, based on what Eclipse knows aboutthe file extension. It's already assumed that we wanted to use the JSEclipse HTMLeditor, so you can see the color-coding behind the menu. Remember when youadded a default editor for *.js files? This works on the same principle.

Choose the Web browser. You should see the basic page.

Figure 11. The basic HTML page

ibm.com/developerWorks developerWorks®

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

Page 18: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

OK — it's not much to look at, but that box will be the environment in which ourcreatures live. Now we just have to create them.

Add a little JavaScript to the HTML

When we were configuring Eclipse, we made sure JSEclipse was the default editorfor *.js files, but it's certainly not uncommon for JavaScript to be embedded in anHTML file. Fortunately, there's an easy way for us to deal with that issue, as you'llsee in a moment.

Start by adding the following code to environment.html.

Listing 2. Adding JavaScript to the page

<html><head>

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 18 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 19: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

<script type="text/javascript">

var maxSize = 100;var maxWidth = 600;var maxHeight = 500;

var theCreature;var theCreature2;

var interval = 100

function createNewEnvironment(){alert("Creating new items...");

}

</script>

</head><body onload="createNewEnvironment()">

<div id="environment" style="float: right; width: 600px;height: 500px; border: 3px solid black;position:relative;"></div>

</body></html>

The code itself is pretty simple. We'll go into it in detail later, but for now, just notethat we're setting some initial variables, and we've created a single function,createNewEnvironment(), which we call when the page first loads.

Now, how do we edit it?

Editing embedded JavaScript using JSEclipse

To edit the script portion of the page in JSEclipse, right-click the script element onthe page and choose Edit in JSEclipse.

Figure 12. Right-clicking a script gives option to edit it using JSEclipse

ibm.com/developerWorks developerWorks®

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

Page 20: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Once you choose Edit in JSEclipse, the editor creates a temporary file and opens itin the JavaScript editor.

Figure 13. Editing the temporary file

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 20 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 21: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Notice that the editor of this temporary page has all the capabilities we would expect,such as color-coding, code outlining, etc. If you make a change to this temporarypage and save it, you'll find that the changes are mirrored in the original page. Thiscomes in handy for situations in which you have a "spaghetti" page, in which youhave a lot of embedded JavaScript that's hard to track down and edit, let alonedebug. In most cases, though, if you're using an IDE, it's easier to use separate files.

Using external scripts

For maintainability, if nothing else, it's usually better to include your scripts inseparate files. In this case, we've got three files.

Listing 3. Adding external files

<html><head>

ibm.com/developerWorks developerWorks®

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

Page 22: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

<script src="Creature.js" type="text/javascript"></script><script src="MultiDimensionalArray.js"

type="text/javascript"></script>

<script src="environment.js" type="text/javascript"></script>

</head><body onload="createNewEnvironment()">...

Starting at the bottom, environment.js will contain the main control script, which firesoff the evolutionary process and keeps it going. Create this new file in the samedirectory as environment.html and add the code originally in the script element wejust replaced. The MultiDimensionalArray.js file will contain a utility class we'recreating to track our creatures, and the Creature.js file will contain the actual classdefinition for our creatures. For now, create both of these scripts as empty files in thesame directory as environment.html and save them.

Now we're ready to start discussing the actual application.

Section 4. The creatures

The creatures we build are simple, but they still have well-defined behavior andattributes. Let's look at what those behaviors and attributes will be.

How the creatures evolve

Each creature has its own size, color, and speed. The first two will be placed inrandom positions in the environment, and the rest will start in the center.

When two creatures come close enough to "breed" — as defined by the center ofone being within the bounding box of the other — they combine to create a newcreature. To determine the properties of a new creature, we create a range thatencompasses the two original values, plus 15 percent on the high and low ends, andchoose a random value from within that range. In this way, we get new creaturesthat are similar to the old ones, but not necessarily the same. Also, by allowingvalues outside the range of the original two values, we allow for the possibility of ourcreatures evolving in a new direction.

Interestingly, we see the basis for natural selection: Because we're also "killing off"

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 22 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 23: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

our creatures after a specific period of time, we see that populations with someproperties do better than those with others.

But how does all of this translate into code?

On the back end

On the programming side, we need to take a couple of issues into consideration.

First, we need to think about the creatures, themselves. This is a perfect opportunityto use Object-Oriented Programming because all creatures follow the same basictemplate. They're all instances of a Creature class, but with different attributevalues. So we start by creating the Creature class and defining its methods, suchas move(), and breed()) and attributes like size and color.

Once we have the creatures, we need to think about how to track them. We cancreate a simple array that lists all the creatures, but each time one of the creaturesmoves, we need to know whether any of the others are close enough to breed withit. Because these aren't actually sentient creatures that can look around, we need tomaintain their positions in a convenient way. We do that through the use of a 2-Darray.

Let's start by creating a single creature.

Creating a single creature

Before we start worrying about classes and such, it's helpful to create a singlecreature manually so we know what properties we're going to need to include in theclass. Add the code below to the environment.html file.

Listing 4. Creating a single creature

...<div id="environment" style="float: right; width: 600px;

height: 500px; border: 3px solid black;position:relative;">

<div id="creature1" style="position: absolute;left: 200px; top: 300px;border: 2px solid red;height: 100px; width: 100px;background-color: rgb(0, 0, 255);"></div>

</div>

ibm.com/developerWorks developerWorks®

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

Page 24: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Here, we're creating a single div at the coordinates <200, 300>, with a red border.The box is 100 pixels square and has a blue center. If you save the page andrefresh your browser, you should see something like Figure 14.

Figure 14. A single manual creature

So now we know our creature will be fine with these properties. Some, like theborder and the fact that position is absolute, will be unchangeable, but we still needa class to track the rest of them.

The basic JavaScript class

To create the new class file, right-click the project and choose New > File. Type thefilename as Creature.js and click Finish. Add the code shown below.

Listing 5. The basic Creature class

function Creature(){

this.x = 30;this.y = 50;

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 24 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 25: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

this.colorRed=0;this.colorGreen=0;this.colorBlue=0;this.xspeed = 2;this.yspeed = 3;this.size = 20;this.status = 1;this.maxage = 500;this.currentAge = 0;this.id = "thisId";

this.bouncex = function(){ alert("Bounce X!"); };this.bouncey = function(){ alert("Bounce Y!"); };this.die = function(){ alert("Killing this creature."); }this.move = function (){ alert("Moving..."); };this.renderAt = function(xpos, ypos){ alert("Rendering..." };this.createAt = function(idString, gridIdx, xpos, ypos, theSize,

redLevel, greenLevel, blueLevel,xspeedLevel, yspeedLevel){

alert("Creating creature.");}this.breedWith = function(otherCreature){

alert("Making new creature.");}this.checkForPartner = function(){ alert("Checking..."); }

}

This is a fairly straightforward JavaScript class. It includes attributes to storeinformation about the individual object, such as the size and current speed. Noticethat we've broken the color up into three components so we can easily determinenew color values when the object breeds.

We're also including methods. In JavaScript, we call them functions, but the ability todynamically define a method in this way can be extremely handy. We've addedplaceholder implementations for the methods we're going to use.

But this is a lot of code to throw at you, and there's potential for problems.

JSEclipse code checking

Right away, if you have any errors in the code, as I originally did, JSEclipse will pointthem out to you, as you can see.

Figure 15. Error checking in JSEclipse

ibm.com/developerWorks developerWorks®

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

Page 26: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Just as in regular Eclipse programming, you can see the error, an error message,and a quick visual queue as to the location of the error. Certainly beats trying to findthat in a bare browser.

Once the errors are corrected, you also can collapse functions or display just thedefinition with the option to expand and see all of the code. This capability can makethose long programs so much easier to debug.

Let's go ahead and use this class to create a new creature.

Using content assist and finding definitions

One place where JSEclipse shines is in providing assistance, such as showingavailable methods and attributes. For example, if we were to type the code in Listing6, JSEclipse would provide the available options automatically.

Listing 6. JSEclipse shows available methods and options

theCreature1 = new Creature();

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 26 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 27: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

theCreature1.

Figure 16. Content assist in action

This menu pops up automatically, or you can "force" it by pressing Ctrl+Space.

JSEclipse also makes it easy to go in the other direction and find the implementationof a particular class or method. For example, if I had typed the code in Listing 7, Icould place the cursor in the createAt() reference, right-click it, and choose OpenDeclaration, as shown below.

Listing 7. Typing this code helps in finding the implementation of a particularclass or method

theCreature1 = new Creature();theCreature1.createAt()

Figure 17. Opening a declaration

ibm.com/developerWorks developerWorks®

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

Page 28: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

This opens the definition of that class, assuming you've named the file with the nameof the class, as in Creature.js, and in the case of individual methods, places thecursor at the location of that method.

To carry this diversion just a tiny bit further, it's worth noting that once you're in theclass definition (or any definition, for that matter) you can also navigate quickly byusing the code outline in the right-hand column.

Figure 18. Navigating our files

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 28 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 29: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Now that you know where to find everything, let's move forward and use thatknowledge.

Creating the creature with JavaScript

Now, just because we have a bunch of properties doesn't mean that we'll be able tosee anything. To really create the creature, we're going to have to create a div withthose properties and add it to the environment. Add the following code to theCreature.js file.

Listing 8. Creating the creature

...this.createAt = function(idString, gridIdx, xpos, ypos, theSize,

redLevel, greenLevel, blueLevel,xspeedLevel, yspeedLevel){

this.id = idString;this.gridIndex = gridIdx;this.x = xpos;this.y = ypos;this.size = theSize;

this.colorRed = redLevel;this.colorGreen = greenLevel;this.colorBlue = blueLevel;

ibm.com/developerWorks developerWorks®

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

Page 30: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

this.xspeed = xspeedLevel;this.yspeed = yspeedLevel;

theDiv = document.createElement('div');theDiv.setAttribute('id',this.id);

theEnv = document.getElementById("environment");theEnv.appendChild(theDiv);

theDiv = document.getElementById(this.id);theDiv.style.position="absolute";theDiv.style.left= this.x+"px";theDiv.style.top= this.y+"px";theDiv.style.border="2px solid red";theDiv.style.height=this.size;theDiv.style.width=this.size;

theDiv.style.backgroundColor="rgb("+this.colorRed+", "+this.colorGreen+", "

+this.colorBlue+")";

}...

We create the actual object in the control script, so the first thing we need to do is toset its attributes, which we can do using the keyword. But doing all of that doesn'tcreate something we can actually see. To do that, we need to create a new div.

Use the document object to create a new div element, and set its ID attribute. You'llneed to do that in order to reference it to set its styles. Next, get a reference to theenvironment div we created earlier in the static HTML page. Once you have that,you can use it to add the new div as a child element.

From there, get a new reference to the current div and use that to set its properties.Note that some syntax is slightly different from the CSS properties you used earlier— specifically, background-color becomes backgroundColor.

Now we have the ability to create a div that has our properties. Next, we need to tellthe page to do it. Double-click environment.js — the JSEclipse editor should comeup automatically because we set it as the default — and add the following code to it.

Listing 9. Creating the new creature

function createNewEnvironment(){

size = 100;theCreature1 = new Creature();theCreature1.createAt("thisId1", 0, 100,

100, size, 150, 150, 150, 0, 0);}

First we set the size; you'll see why in a moment. Next, we create a new instance of

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 30 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 31: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

the Creature class, theCreature1. Once we have that object, we can use itscreateAt() method to place the new creature on the page.

Save the files and remove the static div from environment.html. If you refresh thepage, you should see a new creature, much like Figure 19.

Figure 19 The new creature

We can now create a creature via JavaScript, so it's time to mix things up a little.

Creating two random creatures

Now we're ready to create our two random creatures, our Adam and Eve, if you will.To do that, we simply use the createAt() method, but we feed it random values,as shown in Listing 10, which shows environment.js.

Listing 10. Creating two random creatures

var maxSize = 100;var maxWidth = 600;

ibm.com/developerWorks developerWorks®

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

Page 32: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

var maxHeight = 500;

var theCreature;var theCreature2;

var interval = 100;

function rand(maxNum){return Math.round(maxNum*Math.random());

}

function createNewEnvironment(){

size = rand(maxSize);theCreature1 = new Creature();theCreature1.createAt("thisId1", 0, rand(maxWidth-size),

rand(maxHeight-size), size,rand(255), rand(255), rand(255),-10 + rand(20), -10 + rand(20));

size = rand(maxSize);theCreature2 = new Creature();theCreature2.createAt("thisId2", 1, rand(maxWidth-size),

rand(maxHeight-size), size,rand(255), rand(255), rand(255),-10 + rand(20), -10 + rand(20));

}

OK — let's take this from the top. First, we're creating a convenience function for ourrandom numbers. Math.random() returns a pseudo-random number between 0and 1, so to get a random number between, say, 0 and 10, we would multiple thatvalue by 10. From there, we round off the value because we need integers for all ofour values.

Next, we set the size for our first creature. We need to do that first because we needit when determining the position. We don't want the creature hanging out the side ofthe environment, so we need to subtract the size from the height and width of theenvironment before requesting its position.

Again, we're setting the three components of the color separately. And finally, we setthe speed. We want the speed to be between -10 (so it can go up or left) and 10 (soit can go down or right), so we make the range 20 and simply offset the value by 10.We use this same process to create a second creature, as long as we give it a newid attribute.

If you refresh the page, you'll see two random blocks.

Figure 20. Two randomly created blocks

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 32 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 33: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Each time you refresh, you'll get two new creatures. Later, you can use thiscapability to try and start out with a pair that you like.

Section 5. Moving creatures

All right, just as they are, nobody's going to breed with anybody. We need to getthese creatures moving so they can find each other.

Moving the creatures based on speed

Two properties that we set for our creatures were the horizontal and vertical speeds.These speeds represent the number of pixels the creature will move in a single"turn." To make that happen, add the following code to Creature.js.

Listing 11. Moving creatures

ibm.com/developerWorks developerWorks®

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

Page 34: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

...this.move = function (){

this.x = this.x + this.xspeed;this.y = this.y + this.yspeed;

this.renderAt(this.x, this.y);

};

this.renderAt = function(xpos, ypos){theDiv = document.getElementById(this.id);theDiv.style.left = this.x;theDiv.style.top = this.y;

};...

First, we set the new position information on the object itself, then we call therenderAt() method to place the actual div in the new location by changing its leftand top style values. Finally, we need to tell the creature to move repeatedly. Wecan do that by using JavaScript's setTimeout() function in environment.js.

Listing 12. Moving the creatures repeatedly

...function createNewEnvironment(){

size = rand(maxSize);theCreature1 = new Creature();theCreature1.createAt("thisId1", 0, rand(width-size),

rand(height-size), size,rand(255), rand(255), rand(255),-10 + rand(20), -10 + rand(20));

size = rand(maxSize);theCreature2 = new Creature();theCreature2.createAt("thisId2", 1, rand(width-size),

rand(height-size), size,rand(255), rand(255), rand(255),-10 + rand(20), -10 + rand(20));

setTimeout("nextTurn()", interval);}

function nextTurn(){

theCreature1.move();theCreature2.move();

setTimeout("nextTurn()", interval);}

The setTimeout() function tells the JavaScript engine to execute some actionafter some period of time. In this case, that action is the nextTurn() function, and

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 34 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 35: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

the period of time is one-tenth of a second (100 milliseconds), as we set it earlier.The nextTurn() function moves the two creatures, then sets the timeout again sothe function runs in another one-tenth of a second.

Now if you save the file and reload the browser, you'll find that your creatures willstart to move — right off the page.

The first thing we need to do is to create a way to stop them from moving. Then wecan look at making them bounce off the edges of the environment instead of blowingright through them.

Stopping the creatures

Stopping our creatures is pretty simple. We just have to have a way to turn theirmovement on and off. Start by creating a new variable in environment.js andchecking it before moving them.

Listing 13. Checking to see if movement is on

var ison = true;var maxSize = 100;var maxWidth = 600;...function nextTurn(){

theCreature1.move();theCreature2.move();

if (ison){setTimeout("nextTurn()", interval);

}}

We start out with everything on, and as long as that's the case, we'll continue tomove our creatures. To turn everything off, add a new div to the environment.htmlpage.

Listing 14. The stop switch

...<body onload="createNewEnvironment()">

<div onclick="ison = false;alert('Stopping...');">Stop</div>

<div id="environment" style="float: right; width:600px; height: 500px; border: 3px solid black;position: relative;">

...

ibm.com/developerWorks developerWorks®

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

Page 36: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

If you save and refresh, you'll see the new div on the left.

Figure 21. The off switch

Now let's deal with our runaways.

Detecting the edge of the world

We won't get very far creating a colony if our creatures just run off. Instead, we wantthem to bounce when they hit the edge of the environment. In other words, if thecreature hits one of the side walls, we want it to reverse its speed. If it was travelingat 3px/turn to the right, we want to now move 3px/turn to the left, etc. To do that, weneed to check each creature's position when we move it, as in these changes toCreature.js.

Listing 15. Bouncing the creatures

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 36 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 37: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

...this.bouncex = function(){

this.xspeed = -1 * this.xspeed;};this.bouncey = function(){

this.yspeed = -1 * this.yspeed;};

this.die = function(){ alert("Killing this creature."); }

this.move = function (){

this.x = this.x + this.xspeed;this.y = this.y + this.yspeed;

if ((this.x + this.size) > maxWidth ){this.x = maxWidth - this.size;this.bouncex();

} else if (this.x < 0) {this.x = 0;this.bouncex();

} else if ((this.y + this.size) > maxHeight ){this.y = maxHeight - this.size;this.bouncey();

} else if (this.y < 0) {this.y = 0;this.bouncey();

}

this.renderAt(this.x, this.y);

};...

Starting at the bottom, we're checking to see if we've hit the sides, top, or bottom ofthe enclosure. Remember, the origin of the creature is in its upper left-hand corner,so we need to compensate for its size when looking for the right or bottom walls.

If they've reached the edge, we reset their position slightly to make sure they're backin range, and we call the bounce functions to change their velocity. The next timethey move, they'll be moving in the other direction.

If you save and refresh, you'll see your creatures literally bouncing off the walls,Pong-style.

Section 6. A matter of breeding

Our creatures themselves are set, but what about creating new ones? Next, we lookat breeding and at the technical issues that involves.

ibm.com/developerWorks developerWorks®

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

Page 38: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Tracking creatures

The first thing we need to do is keep track of all the creatures we create, so that we(and, consequently, they) know where they are. The first type of tracking we need todo is easy: We just need to be able to get a reference to each creature in turn tomove it. We do that by adding a simple array to environment.js.

Listing 16. Tracking creatures

...var interval = 100;var creatureList = new Array();

function rand(maxNum){return Math.round(maxNum*Math.random());

}

function createNewEnvironment(){

size = rand(maxSize);creatureList[0] = new Creature();creatureList[0].createAt("thisId1", 0, rand(width-size),

rand(height-size), size,rand(255), rand(255), rand(255),-10 + rand(20), -10 + rand(20));

size = rand(maxSize);creatureList[1] = new Creature();creatureList[1].createAt("thisId2", 1, rand(width-size),

rand(height-size), size,rand(255), rand(255), rand(255),-10 + rand(20), -10 + rand(20));

setTimeout("nextTurn()", interval);}

function nextTurn(){

for(var thisCreatureIndex =0;thisCreatureIndex < creatureList.length;thisCreatureIndex++) {

creatureList[thisCreatureIndex].move();}

if (ison){setTimeout("nextTurn()", interval);

}}

We start by creating a new array, creatureList, and adding the two initialcreatures to it rather than creating separate variables. Then, rather than explicitlymoving the two objects by their variable names, nextTurn() iterates through thearray, moving each creature in it. In this way, we can have an arbitrary number ofcreatures managed by the control script.

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 38 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 39: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Ultimately, however, we're going to be creating creatures dynamically within theobject, so it'd be better if we moved the assignment (or in this case, duplicated it) inthe createAt() method in Creature.js.

Listing 17. Add new creatures to the creatureList

...theDiv.style.backgroundColor=

"rgb("+this.colorRed+", "+this.colorGreen+","+this.colorBlue+")";

creatureList[this.gridIndex] = this;}

this.breedWith = function(otherCreature){...

Fortunately, we've made the gridIndex, or the index the creature occupies on thecreatureList, one of the object's attributes, so it's easy for us to add it in thisway. This attribute will come in handy in a moment, when we're trying to figure outwhich creature we're breeding with.

Code templates made easy: Multidimensional arrays

Now, in order for one creature to know whether any other creatures are nearby, weneed a way to easily access information on who's where. The best way to do that isto create a multidimensional array, so we could then determine easily, "What is theobject at 233, 412?" by checking the value of, say, grid[233][412].

To do that, we need a multidimensional array, which is not a feature of JavaScript.Fortunately, you can have an array of arrays, and you can dynamically create themby simply assigning values. This leads to the idea of creating aMultiDimensionalArray class. David Nishimoto has a great example of doingthis (see Resources), and we're going to use it here.

But given that it's a pretty standard set of code, this is a great opportunity for us toexamine the use of code templates.

Double-click the empty MultiDimensionalArray.js file to open it in the JSEclipseeditor. Start by typing just the letters "fun" (as in the beginning of "function") andpress Ctrl+Space. As you can see in Figure 22, this brings up the auto-insertfunction for the function template.

Figure 22. Inserting a template

ibm.com/developerWorks developerWorks®

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

Page 40: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

The box to the right shows what the currently selected template is, and it's what wewant, so go ahead and select it. This automatically drops the code into the page, asyou can see in Figure 23.

Go ahead and start to type the class. You'll see the complete code in a moment, andyou'll see that JSEclipse can also provide a template for the for loop. As you cansee in Figure 23, there's a twist.

Figure 23. Inserting a loop

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 40 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 41: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

In this case, in addition to just inserting code, the template makes it easy to performtasks like customizing variables. Notice here that I've started changing the indexvariable, formerly "i," to "thisRow." As I type in the first variable box, the otherinstances change, as well, so I only have to do it once. Very convenient!

Let's get to the complete code for the MultiDimensionalArray class.

Listing 18. Creating a MultiDimensionalArray class

function MultiDimensionalArray(numRows,numCols){

var thisRow, thisColumn;var arrayRet = new Array(numRows);

for(thisRow=0; thisRow < numRows; thisRow++) {arrayRet[thisRow] = new Array(numCols);for (thisColumn=0; thisColumn < numCols; thisColumn++){

arrayRet[thisRow][thisColumn] = -1;}

}return(arrayRet);

ibm.com/developerWorks developerWorks®

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

Page 42: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

}

Because arrays are re-dimensioned (enlarged) automatically when we add a higherindex, all we really need to do is create entries for each potential spot on the grid. Inthis case, we specify that "empty" has a value of -1. (Fortunately, JavaScript isloosely typed, 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.

Tracking creature locations

The idea here is to have each creature in its location on the grid, with the gridrepresented by a multidimensional array. That means we can add the creature to itscoordinates in the grid array when we create it, but we have to make sure to removeit from that spot when it's no longer there.

We need to handle this in two locations. First, we need to create the grid array itselfin environment.js.

Listing 19. Creating the environment grid

...var grid = new MultiDimensionalArray(maxWidth, maxHeight);var creatureList = new Array();var interval = 100;

Then we need to assign creatures to the appropriate spots on the grid when werender them in Creature.js.

Listing 20. Setting the position of each creature

this.move = function (){

grid[this.x][this.y] = -1;

this.x = this.x + this.xspeed;this.y = this.y + this.yspeed;

...

this.createAt = function(idString, gridIdx, xpos, ypos, theSize,redLevel, greenLevel, blueLevel,xspeedLevel, yspeedLevel){

...theDiv.style.backgroundColor=

"rgb("+this.colorRed+", "+this.colorGreen+","+this.colorBlue+")";

grid[this.x][this.y] = this.gridIndex;

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 42 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 43: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

creatureList[this.gridIndex] = this;}

this.renderAt = function(xpos, ypos){theDiv = document.getElementById(this.id);theDiv.style.left = this.x;theDiv.style.top = this.y;

grid[this.x][this.y] = this.gridIndex;};

...

We're adding the creature to the grid array when we create it, and when we render itat a new location. That means we need to clear the old location before we move it,so we're setting it to -1, as we did when we created the array in the first place.

Now we need to check that grid for partners to breed with.

Finding a partner

We tried to make the process of finding a potential mate as simple as possible. Allwe're doing is checking the grid coordinates within the current creature to see if anyother creature is present. Make the changes below to Creature.js.

Listing 21. Finding a partner

...this.move = function (){

...this.renderAt(this.x, this.y);

this.checkForPartner();};

...

this.checkForPartner = function(){

xmax = this.x+size;if (this.x+size > maxWidth){

xmax = maxWidth;}

ymax = this.y+size;if (this.y+size > maxHeight){

ymax = maxHeight;}

for(var xtocheck = this.x; xtocheck < xmax; xtocheck++) {for(var ytocheck = this.y; ytocheck < ymax; ytocheck++) {

if (grid[xtocheck][ytocheck] != -1 &&grid[xtocheck][ytocheck] != this.gridIndex){

this.breedWith(creatureList[grid[xtocheck][ytocheck]]);

ibm.com/developerWorks developerWorks®

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

Page 44: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

break;}

}}

}}

When we move a creature, we run the checkForPartner() method. That methodjust determines the coordinates that make up the body of the creature and loopsthrough each of those coordinates checking for spots that are not empty. If it findsone, we send that object off for breeding.

Breeding

The actual process of combining the attributes of two creatures to create a new onetakes place in Creature.js.

Listing 22. Creating the new creature

...

this.breedWith = function(otherCreature){

babyxspeed = this.getNewValue(this.xspeed,otherCreature.xspeed, -20, 20);

babyyspeed = this.getNewValue(this.yspeed,otherCreature.yspeed, -20, 20);

babysize = this.getNewValue(this.size,otherCreature.size, 0, 100);

babycolorred = this.getNewValue(this.colorRed,otherCreature.colorRed, 0, 255);

babycolorgreen = this.getNewValue(this.colorGreen,otherCreature.colorGreen, 0, 255);

babycolorblue = this.getNewValue(this.colorBlue,otherCreature.colorBlue, 0, 255);

baby = new Creature();

index = creatureList.length;

baby.createAt("index"+index, index,maxWidth/2, maxHeight/2, babysize,babycolorred, babycolorgreen,babycolorblue, babyxspeed, babyyspeed);

}

this.checkForPartner = function(){...

}

this.getNewValue = function(old1, old2, min, max){if (old1 < old2){

low = old1;high = old2;

} else {low = old2;

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 44 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 45: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

high = old1;}

low = low - Math.round(low * .15);high = high + Math.round(high * .15);

if (low < min){low = min;

}if (high > max){

high = max;}

spread = high - low;offset = Math.round(Math.random()*spread);return low + offset;

}

}

There's a lot of code there, but it's actually pretty straightforward. For eachparameter we can set on the object, we're using the getNewValue() method tocombine the current value of the two parents to get a third, new value. Once wehave the new values, we use them to create a new object and add that object to thecreatureList. It'll get added to the grid array when we render it, but each objectgets added in the center of the grid.

The new values get calculated based on the old ones. We expand the range by 15percent and make sure we're not exceeding the minimum or maximum values. Fromthere, we determine the spread, use it to randomly choose the offset, and add thatoffset to the low value to get the new value.

By pulling this routine into a separate function, we make it really easy to change howto determine the values, in case you want to change how the evolution works. Forexample, you could add a step in which you randomly mutate a value.

Save these changes and refresh the browser. When you get a collision, you'll findthat you suddenly have a baby boom.

Figure 24. Creating new creatures

ibm.com/developerWorks developerWorks®

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

Page 46: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

The reason for this, of course, is that the original creatures don't completely passeach other instantaneously, which means at least two creatures get created in thesame place, and they breed constantly, until we have to stop the process or crashthe computer. We need to slow the process down.

Slowing the birth rate

To solve the baby-boom problem, we slow things down so a new creature can onlybe created every 50 turns. We track those turns in environment.js.

Listing 23. Tracking turns

...var elapsedTurns = 0;

function rand(maxNum){return Math.round(maxNum*Math.random());

}...

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 46 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 47: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

function nextTurn(){...

if (ison){setTimeout("nextTurn()", interval);

}elapsedTurns++;

}

We start out at zero, of course, then increment elapsedTurns for each timenextTurn() runs. We can then check this value when we try to create a newcreature in Creature.js.

Listing 24. Checking the elapsedTurns value

...this.breedWith = function(otherCreature){

if (elapsedTurns < 50){// do nothing

} else {elapsedTurns = 0;

babyxspeed = this.getNewValue(this.xspeed,otherCreature.xspeed, -20, 20);

...baby.createAt("index"+index, index,

maxWidth/2, maxHeight/2, babysize,babycolorred, babycolorgreen,babycolorblue, babyxspeed, babyyspeed);

}}

...

In this case, we're checking to see whether 50 turns have elapsed before we createthe new creature. If they have, we reset that value and proceed as before. Note thatfor performance purposes, you might opt to check for elapsedTurns beforechecking for partners, instead. Now if you save your files and refresh the page, you'llsee something much more like a colony.

Figure 25. More of a colony

ibm.com/developerWorks developerWorks®

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

Page 48: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

The only remaining problem is that things can get pretty crowded.

Dying of old age

The final change we will make is to give each creature a limited lifespan. We do thatby giving them an "age," after which we will remove them from the list.

Listing 25. Expiring creatures

...this.die = function(){

this.status = 0;grid[this.x][this.y] = -1;

this.xspeed = 0;this.yspeed = 0;this.size = 0;theDiv = document.getElementById(this.id);theDiv.style.backgroundColor = "white";theDiv.style.border = "0px";

}

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 48 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 49: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

this.move = function (){

this.currentAge++;if (this.currentAge > this.maxage){

this.die();} else {

this.x = this.x + this.xspeed;this.y = this.y + this.yspeed;

...this.checkForPartner();

}};

...

Starting at the bottom, remember that we defined maxage and currentAge as partof the class, so we can increment the age each time we move the creature. Whenit's old enough, we call the die() method to get rid of it. That method doesn't reallyget rid of the element, but rather hides it, setting it as the same color as thebackground.

Finally, you can run the simulation. Some simulations will be successful, and otherswill die out before they catch on. Have fun with it!

Section 7. Summary

In this tutorial, you learned how to use the JSEclipse plug-in for the Eclipse IDE toease JavaScript development. The plug-in provides capabilities such as codecompletion and code templates, and easier code organization and color-coding.

The tutorial also chronicled the creation of creatures that evolve with eachsuccessive generation, creating new values based on the old and bouncing aroundthe environment looking for mates.

ibm.com/developerWorks developerWorks®

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

Page 50: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Downloads

Description Name Size Download method

Source code os-eclipse-jseclipse.source.zip3KB HTTP

Information about download methods

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 50 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 51: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

Resources

Learn

• Find all about the Europa release of Eclipse in the developerWorks article "Awhirlwind tour of Eclipse Europa."

• Get an introduction to Eclipse and a peek at its colorful history in "Get started withthe Eclipse Platform."

• Read Simon Willison's "A (Re)-Introduction to JavaScript."

• Be sure to check out these: Tutorial: Introduction to JavaScript and Introduction toJavaScript from w3schools.com.

• David Nishimoto has a great example of Building a MultiDimensional Array inJavaScript.

• To see a more complex artificial ecosystem, check out Second Life's Svarga.

• Learn about artificial ecosystems in "Virtual Critters Thrive, Evolve in OnlineWorld" from National Geographic.

• Check out the "Recommended Eclipse reading list."

• Browse all the Eclipse content on developerWorks.

• New to Eclipse? Read the developerWorks article "Get started with EclipsePlatform" to learn its origin and architecture, and how to extend Eclipse withplug-ins.

• Expand your Eclipse skills by checking out IBM developerWorks' Eclipse projectresources.

• To listen to interesting interviews and discussions for software developers, checkout check out developerWorks podcasts.

• For an introduction to the Eclipse platform, see "Getting started with the EclipsePlatform."

• Stay current with developerWorks' Technical events and webcasts.

• Watch and learn about IBM and open source technologies and product functionswith the no-cost developerWorks On demand demos.

• Check out upcoming conferences, trade shows, webcasts, and other Eventsaround the world that are of interest to IBM open source developers.

• Visit the developerWorks Open source zone for extensive how-to information,tools, and project updates to help you develop with open source technologies and

ibm.com/developerWorks developerWorks®

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

Page 52: Building JavaScript applications with JSEclipse...provides many important features to aid in the development of JavaScript applications. JSEclipse gives you the same ease of use Eclipse

use them with IBM's products.

Get products and technologies

• Check out the latest Eclipse technology downloads at IBM alphaWorks.

• Download Eclipse Platform and other projects from the Eclipse Foundation.

• Download IBM product evaluation versions, and get your hands on applicationdevelopment tools and middleware products from DB2®, Lotus®, Rational®,Tivoli®, and WebSphere®.

• Innovate your next open source development project with IBM trial software,available for download or on DVD.

Discuss

• The Eclipse Platform newsgroups should be your first stop to discuss questionsregarding Eclipse. (Selecting this will launch your default Usenet news readerapplication and open eclipse.platform.)

• The Eclipse newsgroups has many resources for people interested in using andextending Eclipse.

• Participate in developerWorks blogs and get involved in the developerWorkscommunity.

About the author

Nicholas ChaseNo bio.

developerWorks® ibm.com/developerWorks

Building JavaScript applications with JSEclipsePage 52 of 52 © Copyright IBM Corporation 1994, 2008. All rights reserved.