Wednesday, May 14, 2014

JavaScript and Java: Side-by-Side Comparison

[UPDATED 5/15/14: Tweaked a couple things in the Java code]

Currently translating my maze-generating code from JavaScript to Java.  Here's the original code in JavaScript:

var room=new Array();
var size=100

for (x=2;x<size;x+=2)
{for (y=2;y<size;y+=2)

 {room[x+(y*size)]=" ";
   var r=Math.floor(Math.random()*4);
   if (r==0 && x<size-2) {room[x+1+(y*size)]=  " ";}
   if (r==1 && x>02)     {room[x-1+(y*size)]=  " ";}
   if (r==2 && y<size-2) {room[x+((y+1)*size)]=" ";}
   if (r==3 && y>02)     {room[x+((y-1)*size)]=" ";}
   if (r==0 && x==size-2){room[x-1+(y*size)]=  " ";}
   if (r==1 && x==02)    {room[x+1+(y*size)]=  " ";}
   if (r==2 && y==size-2){room[x+((y-1)*size)]=" ";}
   if (r==3 && y==02)    {room[x+((y+1)*size)]=" ";}
  }
}


And here's the same code in Java:

int size = 100;
int[][] room = new int[size][size];
for (int x=2;x<size;x+=2)
{for (int y=2;y<size;y+=2)
  {room[x][y]=1;
    int r = 1; //haven't looked up the code for random numbers yet!
    if (r==0 && x<size-2) {room[x+1][y]=1;}
    if (r==1 && x>02)     {room[x-1][y]=1;}
    if (r==2 && y<size-2) {room[x][y+1]=1;}
    if (r==3 && y>02)     {room[x][y-1]=1;}
    if (r==0 && x==size-2){room[x-1][y]=1;}
    if (r==1 && x==02)    {room[x+1][y]=1;}
    if (r==2 && y==size-2){room[x][y-1]=1;}
    if (r==3 && y==02)    {room[x][y+1]=1;}
  }
}


The maze code works by 1) filling a grid with walls, 2) making every other space of every other row an open space (or, if you divided the maze into 2x2 squares, it would be the fourth quadrant of every square), and then 3) using random numbers to connect those spaces.

As you'll notice, the code hasn't actually changed all that much.  The biggest and most obvious change is declaring variables. In JavaScript, you need only use var, and you don't need to declare the variables in for statements.  In Java, variables are typed, meaning that you must declare what a variable will be used for at the time you declare it.

The other two changes may not have been strictly necessary.  The first is the change to double arrays (not supported in JavaScript).  As you can see, the double array makes reading code much easier then the multiplying required in the JavaScript code.  The second change was from strings to integers.  This has mostly to do with the fact that in the game the code was originally from, the map code could contain many different characters besides just walls and spaces.  In the penguin game, we will only be checking for walls or spaces, so it was more efficient to use numbers. Come to think of it, I may actually change them to Booleans - true on/off numbers.

Next time: Python to Java!

No comments:

Post a Comment