28 March 2012

CMT3313 - Week 5 Post - XML...The Basics

XML Definition Tag
XML stands for Extensible Markup Language and was created in 1996 with joint efforts by the W3 Consortium and Sun Microsystems.
As you might have noticed, XML is a Markup Language just like HTML, but the difference is XML is extensible, meaning there is no limitation on what element tags you can use. Element tags can be called what ever you like, as long as the syntax adheres to the rules of XML.


While I am mentioning the syntax of XML, I would like to point out that it is very strict for security and performance purposes. Some of these rules are:

  • Every element must be represented with and opening and closing tag.
  • Every parent element must contain the same child elements.
  • Every attribute value must be surrounded with double quotes.
  • XML is strictly case sensitive (if it wasn't, it would be 50% slower).
  • An XML file must have a single Root element.
But what does XML actually do?
Well...Basically XML doesn't do anything really, it alone, will not display anything in the browser or carry out any processing.
XML is actually a data structure, designed to store data in a self-descriptive way and transport it.
To create an XML file, you don't require any special software or IDE, all you need is a simple text editor and save the file format as ".XML".
So you might be wondering, what does its syntax look like then! What you can see below is a simple example of an XML file:

<?xml version="1.0"?>
<playerList>
<user type="developer">
<name>Clifford Grech</name>
<score>20</score>
<rank>2</rank>
<lastBeatenBy>Rebecca Scerri</lastBeatenBy>
</user>
<user>
<name>Wayne Grech</name>
<score>15</score>
<rank>3</rank>
<lastBeatenBy>Clifford Grech</lastBeatenBy>
</user>
<user>
<name>Rebecca Scerri</name>
<score>25</score>
<rank>1</rank>
<lastBeatenBy>null</lastBeatenBy>
</user>
</playerList>

In the XML code above, the first line simply explains to the browser that this is XML version 1.0, the rest is the actual XML code and as you can see, we have a root element tag named 'playerList', which has 3 child elements named 'user'. 
These 'user' elements are also parent elements as each and every one of them has the following set of child elements; 'name','score','rank' and 'lastBeatenBy'. 
But as you may have noticed the first 'user' element has an attribute called 'type' and a value has been assigned to this. Attributes don't follow the same rule of elements, meaning if one parent element has an attribute, the others don't have to have the same attribute. This is a good way to store extra information in an element.

You will be able to see more use of XML in my later posts as I will be using it to store the necessary information to implement; login and scoring functionality in my paper tossing game, which I wrote about in previous posts.

CMT3313 - Week 4 Post - JavaScript Interpreter

Interpreter
In this post I will write about the JavaScript Interpreter, its advantages and disadvantages and also carry out a small test on multiple browsers to see how they interpret the JavaScript code.


JavaScript Interpreted
JavaScript, unlike server-side programming languages is not compiled all at one go and then executed once. Instead it is interpreted line-by-line and executed immediately. This does make the overall execution slower than complied applications, but on the other hand, just imagine every JavaScript code present in a site being compiled on the user's machine every time he/she visits the site (don't forget, JavaScript is a client-side language). It would make the viewers' experience dreadful, as compiling all the JavaScript code at one time would certainly take a few moments! So there's one of the nice aspects of using an interpreter for a client-side language.


Some might say that compiled languages are better, because you only have to compile it once on one machine to produce a compiled version, which you can run on many other machines. With JavaScript being interpreted, it's true you have to compile it every time you which to run it and to do so, the machine you or the users who will be running the JavaScript application must have the interpreter installed on it, but not to worry, as today's internet browsers all have JavaScript interpreters embedded in them, so all you need is an Internet browser and this is normally installed on every machine by default.


One disadvantage which personally bugs me a bit is the fact that the JavaScript source code is available for everyone to see, sure you can store all the code in a separate file from the HTML, but still, if anyone has access to the hosting server, he/she wouldn't have any trouble looking at your code. But hay look on the bright side! At least your code could teach someone some new things.


Testing How the Interpreter Works


So I was thinking, if JavaScript is interpreted line-by-line and executed on the fly, I think it must be of crucial importance where to place communicating functions and the best way to know for sure is try it out!



<html>
     <head>
           <title>Test JS Interpreter</title>
           <script type="text/javascript">
                  //This statement calls the 'caller()' function before it is defined
                  caller();


                  //This function calls the 'receiver()' function before it is defined
                  function caller(){
                       try{
                              var blnCall = true;
                              receiver(blnCall);
                       }catch(err){
                              alert(err);
                       }
                  }

                  function receiver(blnCallRequest){
                        if(blnCallRequest){
                                alert("Receiver Responds to Caller");
                        }
                  }
           </script>
   </head>
   <body>
           <h1>Testing JavaScript Interpreter</h1>
   </body>
</html>


The simple code above consists of an HTML page with a heading and two JavaScript functions; 'caller()' and 'receiver()' and a statement at the beginning which calls the caller() function.
The 'caller()' function passes a boolean variable to the 'receiver()' function. This in turn will check if the received boolean is true and if so displays a message box.


As you can see, the 'receiver()' function is defined below the 'caller()' function, this means that when the interpreter, interprets the line of code which calls the 'receiver()' function and tries to execute it, an error should occur as the interpreter hasn't yet interpreted the line which defines the 'receiver()' function and the same goes at the start of the script with the statement calling the 'caller()' function. Please note that at this point the information I have given is what I think should happen, I have not tested this out yet so lets start by first testing it using Google Chrome, then Mozilla Firefox and finally Internet Explorer 9.


Google Chrome Result:


Google Chrome Test: Works
Mozilla Firefox Result:


Mozilla Firefox Test: Works


Internet Explorer 9:


Internet Explorer 9 Test: Works


Would you look at that! It still worked, but why did this happen?


Findings
After carrying out some research on how most JavaScript interpreters work I found out that the interpreter doesn't necessarily interpret one line and execute it. Instead it can interpret all or portions of the JavaScript code and store it in memory, ready to be executed all at once. This is why the code above worked regardless!


The following is an explanation available on Will Bontrager's article about JavaScript Tutorial Part1:


"Interpreted language" means when it loads a page, the browser's interpreter uses the original source code and translates it into machine language. The translation is stored in the browser's memory ready to run all or portions of it as appropriate. When the browser window gets ready to load a different web page, the previous page's translated JavaScript is discarded.

24 March 2012

CMT3313 - Week 3 Post - JavaScript Technology in General

Hi there, in this post I am going to explain a bit about JavaScript technology. If you read my previous posts about the simple web based game I did, you should have noticed that I accomplished it by using JavaScript. 
But what is JavaScript? Where did it come from? And how is it so popular among web developers?
These three questions; the what, where and how are your best way to learn more in life and in this post I will be answering them for you!


What is JavaScript?
JavaScript is a client-side scripting language, this means it is interpreted on the web page viewer's browser. Today's major Web Browsers all support JavaScript, therefore you can be rest assured that your JavaScript code will work on the client's machine if JavaScript is enabled (It is by default).


But why is it used you may be asking your self, well the answer is simple, JavaScript is the easiest way to provide dynamic user-interaction to web pages, without having to send loads of HTTP Requests to the host server and without having to refresh the whole page just to make a change to the displayed web page.
This means, that unlike other server-side technologies used for web interaction, such as JSP(Java Server Pages), JavaScript can dynamically change parts of the web page the user is viewing at the client-side without having to refreshing the page.


Where did JavaScript come from? 
So it's time for a bit of history then! 
The language was developed by Brendan Eich when he was hired by Netscape to develop it for them in-order to make their support for Java applets more accessible to non-Java programmers and web designers.
The language was first called 'LiveScript', to reflect its dynamic nature, but for marketing purposes it got renamed to JavaScript.
In 1995, Netscape and Sun Microsystems jointly launched the new language and termed it a "compliment" to HTML and Java.


From an early start, developers started to use JavaScript to manipulate images and page content, instead of controlling Java applets. Thus changing the web from just static pages to dynamically interactive interfaces.
But unfortunately, JavaScript's advantages of not requiring a compiler to run, being overly easy to use, having impressive cross-platform compatibility and the issue of multiple JavaScript books for non-programmers made experienced developers snob it and describe it as a toy, which ended up overshadowing its full potential.


None the less, JavaScript was being used out there and Microsoft responded with its VBScript and later with JScript, starting a browser war!
This eventually led to a nightmare for cross-browser compatability, forcing Microsoft, Netscape and other browser companies to work with the World Wide Web Consortium (W3C) in-order to achieve a standard, cross-browser compatible Document Object Model (DOM).


How is it so popular among web developers?
Today, now that almost all browsers use W3C's standard DOM, JavaScript has grown into a powerful scripting language, containing the best features of:

  • Perl
    • associative arrays
    • loosely typed variables
    • regular expressions
  • Java 
    • clean syntax
    • objects and classes
    • highly evolved date, math, and string libraries 


To code in JavaScript, you don't need any special software either, a simple application such as Notepad is enough, all you have to do when you're ready from creating your functions is save the file format to '.js' in-order to identify it as a JavaScript file and import it into your HTML file by using the <script> tag.
JavaScript can also be embedded within the HTML its self, both within the <head> element or within the <body> element. But it is good practice to separate your JavaScript code for the sake of easy re-usability in other web pages.

Now, as you might have realised, all these advantages are what made JavaScript the most popular scripting language used on the web.

What other purpose could JavaScript be used for?
Well, seeing that internet connectivity is available almost everywhere we go nowadays and devices capable of connecting to the internet are always getting smaller and lighter, I would think that if a touch-screen device, such as an IPad, gets installed into public vehicles, we could store all of our favourite songs, videos, pictures and documents in the cloud and then use JavaScript's dynamic nature to create a web interface which is personalized to every user's liking and would access our private on-line libraries and allow us to either playback our music, view our favourite pictures or even touch-up a business proposal presentation while being driven along.
This system could also be used as a safety feature in private vehicles which would work in the background by making use of the device's location detection functionality to calculate the speed the vehicle is going and if the speed is excessive, JavaScript's dynamic capabilities can be used to change the interface's look to an alarming one, indicating to the driver that he/she should slow down.

Other Links
For me to create this post, I researched the information from the following post:

20 March 2012

Coursework 1: JavaScript Animation Game– Post 4

In this post I will explain how I decided to implement the following tasks to the paper tossing game I have created while writing this blog:
  1. Provide the user with control of the throwing power
  2. Make the paper ball roll while moving through the air
Provide the user with control of the throwing power

In my last post on this subject I explained how I took the value containing the middle of the game area and tweaked it in-order to alter the shooting angle. This I found this to be a simple solution, so for me to implement a control on the shooting power, I decided to do the same but on the y-axis this time.

As I had stated in my second post on this subject, I stored a value of 250 in my global 'middleY' variable and used it in the calculation of the 'yPaces' value. I had also stated that I stored 250 and not 200, to amplify the upwards movement of the paper ball, so as you might have already figured out, altering the value of this variable would replicate different levels of throwing power.

As a control interface I added another <SELECT> element and stored nine different <OPTION> element within it, each representing a different power level, like so:

Power:<select id="powerSelector" title="Power">
                <option value="225">80 psi</option>
                <option value="150">70 psi</option>
                <option value="75">60 psi</option>
                <option value="25">50 psi</option>
                <option value="0">40 psi</option>
                <option value="-25">30 psi</option>
                <option value="-75">20 psi</option>
                <option value="-150">10 psi</option>
                <option value="-225">0 psi</option> 
</select>

Just like in my previous post, I gave the <SELECT> element a unique identifier, so I could later reference it and to alter my 'middleY' variable a gave each <OPTION> element a value attribute with different amounts. These amounts will be later used to increment or decrement my variable.

The next step was to alter once more my 'throwPaper()' function to connect this new user control to my JavaScript code. So, I referenced the newly created <SELECT> element via the document.getElementById() function, passing "powerSelector" as a parameter and stored its selected value by calling the object's value attribute and stored it in local variable 'power'. Once I have this object in memory I retrieved the selected value and increment it to the original value in global variable 'middleY'.

//gets the selected power and tweaks the middleY virtual poiter
//in-order to replicate a change of power
var power = document.getElementById('powerSelector').value;
middleY = middleY+parseInt(power);

I placed this code before the calculation of the yPaces and now, thanks to the altered 'middleY' variable, the throwing power can be adjusted by the user.

Make the paper ball roll while moving through the air

To make my paper ball roll I used a simple solution of making 16 copies in total, of the paper ball image and each one is rotated clockwise 22.5 degrees or 1/16 of a revolution (You could make more copies, each one rotating less than this amount for a smoother and quicker rotation).


Now that I have my paper ball copies, if I flick through them in sequential order I could see that the paper ball is rolling and this is what I decided to implement in my game.


To do this I had to change my paper ball's image continuously and sequentially in a loop, while the ball is moving and what better way to do this other than taking advantage of the loop which already exists in my application...That's right! I'm referring to the 'motion' interval that gets started when the user clicks on the Throw button.


The 'motion' interval calls my 'move()' function every 40 milliseconds and I want my paper to rotate while it is moving, therefore I had to implement this image changing code here. But this rotation feature can be classified as a function on its own, therefore I decided to create another function called 'rotatePaper()' and instead of implementing the code inside the 'move()' function, I simply call my new function.


To keep track of what image is currently being displayed I declared a global variable called 'paperImgCounter' and initialize it immediately with a value of 1. Below is the code in the 'rotatePaper()' function: 


function rotatePaper(){
     try{
           if(paperImgCounter !=17){
                 paperImgCounter = paperImgCounter +1;
           }else{
                 paperImgCounter = 1;
           }
           switch(paperImgCounter){
                 case 1:
                          myPaper.src = "paper1.jpg";
                          break ;

                 case 2:
                          myPaper.src = "paper2.jpg";
                          break ;

                 case 3:
                          myPaper.src = "paper3.jpg";
                          break ;

                 case 4:
                          myPaper.src = "paper4.jpg";
                          break ;

                 case 5:
                          myPaper.src = "paper5.jpg";
                          break ;

                 case 6:
                          myPaper.src = "paper6.jpg";
                          break ;

                 case 7:
                          myPaper.src = "paper7.jpg";
                          break ;

                 case 8:
                          myPaper.src = "paper8.jpg";
                          break ;

                 case 9:
                          myPaper.src = "paper9.jpg";
                          break ;

                 case 10:
                          myPaper.src = "paper10.jpg";
                          break ;

                 case 11:
                          myPaper.src = "paper11.jpg";
                          break ;

                 case 12:
                          myPaper.src = "paper12.jpg";
                          break ;

                 case 13:
                          myPaper.src = "paper13.jpg";
                          break ;

                 case 14:
                          myPaper.src = "paper14.jpg";
                          break ;

                 case 15:
                          myPaper.src = "paper15.jpg";
                          break ;

                 case 16:
                          myPaper.src = "paper16.jpg";
                          break ;
                 default:
                          paperImgCounter = 1;
                          myPaper.src = "paper1.jpg";
           }
     }catch(err){
           alert(err);
     }
}


What the above code does is first check if the 'paperImgCounter' has not reached 17. If it didn't, it increments it by 1, else it re-sets the counter to 1. Then a switch case statement changes the paper object's image according to the value in the counter.


The result of this code is represented by the image below:


Rotation of the paper ball during movement.
Conclusion


As much as I enjoyed this coursework, that's it for this blog subject, as a recap of what was carried out in the past four posts:

  1. Make an image move on screen.
  2. Identify the user’s browser screen size.
  3. Make the image go back to its starting position.
  4. Disable any important controls programmatically while the animation is in process.
  5. Make the paper go up and then back down.
  6. Collision detection.
  7. Provide the user with control of the shooting angle.
  8. Provide the user with control of the shooting power.
  9. Make the paper ball roll while moving in the air.
    In the near future I would like to improve this application by 
  • Implementing a function which works out a quadratic equation and returns the coordinates in-order to make the paper travel in an arch.
  • Use GIF files for the paper ball image, without the white space around it, so I could set a background image to the game area.
  • Replace the drop-down user controls with a pointer location function which would be used for the shooting direction and power, depending on how far the pointer is from the bottom left corner.
    I hope you found my posts helpful or interesting in any way. 
    
    Thanks for reading,

    Goodbye :)

17 March 2012

Coursework 1: JavaScript Animation Game– Post 3

In my last post I wrote about how:
  • I made my object move upwards, reach a certain point and then back down.
  • Disable and re-enable HTML elements when a particular event gets triggered.
Today I will explain how I managed to implement collision detection and how I provided the user with a way to alter the throwing angle of my paper ball.

Changing the angle with user input

For this web application to become a game, it must have some sort of user input, therefore I decided to give the user two options to change to course of the paper ball; The angle which the object will be thrown and the force, but in this post I will only explain how to change the angle and will talk about the force in my next post.

As I pointed out in my first post, It's best to start out simple and then elaborate, so as an input method for the angle I used a simple drop down list with pre-defined angles from which the user can choose one. To implement this drop down list in HTML I used the standard <SELECT> element tag and inserted <OPTION> elements between its open and close tags like so:

Angle:<select id="angleSelector" title="Angle">
            <option value="-250">80 deg</option>
            <option value="-200">70 deg</option>
            <option value="-150">60 deg</option>
            <option value="-100">50 deg</option>
            <option value="0">45 deg</option>
            <option value="100">40 deg</option>
            <option value="150">30 deg</option>
            <option value="200">20 deg</option>
            <option value="250">10 deg</option>
<select>



In the above HTML code I am declaring a Select element and assigning its unique identification attribute to "angleSelector" in-order to be able to reference it through JavaScript later on and its title attribute to "Angle", this value will display in a tool-tip box when the mouse pointer hovers over this drop down list.

Between the Select element's open and close tags, I inserted an Option element for every angle value I wanted to be in the list. As you may have noticed I assigned each Option element a positive or negative number in their value attribute. I will explain the purpose of this value attribute soon enough.

So now I have an input method for the shooting angle, but I still have to connect this control to my JavaScript code. To do so I first had to decide where and when I should retrieve the selected value and how to use it in-order to alter the angle of my paper.
The obvious choice of when to retrieve the selected angle is when the Throw button is pressed and that event calls my 'throwPaper()' function which I mentioned in my previous posts.

But what to do with the selected angle?

In-order for the angle to change I decided that the easiest way was to tweak the 'middleX' value, thus effecting the 'yPaces' calculation I mentioned in my previous blog, therefore altering the upwards movement of the paper ball.

How altering the 'middleX' value effects the shooting angle.
In the above image, the dotted lines represent the 'middleX' value and the straight lines represent the respective course of the paper ball. Notice how the angle of the red lines is much higher than the angle of the blue lines, because the 'middleX' value is closer to the left.

This is where the Option element's value attribute comes in! I add or reduce this value from the 'middleX' value and thus replicating what is illustrated in the image above.

N.B. - This method has a serious drawback though, because the 'middleX'
         value is dynamically calculated according to the user's screen width,
         while the values retrieved from the <SELECT> element are static. This
         means that the angles will vary according to the user's screen width.
         
         To solve this issue, you could calculate the ratio of the user's screen
         width against a predefined amount, say 100 pixels, and use this ratio
         on the retrieved value from the <SELECT> element. This way you would
         dynamically calculate the amount of pixels to deduct or add to the 
         'middleX' value as well.
  
Collision Detection

So, up to now its been interesting making my object move on screen and changing the shooting angle, but what is the point of being able to throw a paper ball in different angles, when there is noting to aim at?
Therefore I added another object on screen, this time a paper basket, called it 'bin' and gave it a width of 100 pixels and a height of 150 pixels.

<img id="bin" src="bin.jpg" alt="Image Not Found" style="width: 100px;height: 150px"/>

In the 'start()' function I reference this object and place it at the furthest corner on the right. Keeping in mind that each user might have different screen widths, I also dynamically calculated this position by using the retrieved screen width stored in 'screenW'.

//calculate and store the position of the bin
binXLocation = ((screenW-40)-140);

//gets the bin image and stores it as an object in myBin
myBin=document.getElementById('bin');
myBin.style.position='relative';
myBin.style.left=binXLocation+'px';
myBin.style.top='0px';

Now that my bin is in place, the next step was to implement collision detection and to do that I started out by defining the possible collision points and differentiating them from each other, like the image below illustrates:

Different Collision Points

After defining the collision points, I altered my 'move()' function to detect where the paper ball is, every time the function is called.

//gets the paper location on the x-axis
var paperXLocation = parseInt(myPaper.style.left);
//gets the paper location on the y-axis 
var paperYLocation = parseInt(myPaper.style.top);

Then I used a combination of conditions to determine whether the paper ball touches any of the collision points I had defined and if so, displays a message box with a respective message to the touched area. 
Below is the code containing these conditions:

//still have moves available
if(availableMoves > 0){
if(paperYLocation>=-20){
clearInterval(motion);
alert("Not far enough!");
}else if(paperYLocation>=-125 && paperXLocation>((screenW-40)/2) &&
                    paperXLocation>=binXLocation){
clearInterval(motion);
alert("So close...yet so FAR!!")
}else if(paperYLocation>=-150 && paperXLocation>binXLocation){
clearInterval(motion);
alert("Dunk! YOU WIN!!!");
}else{
if(paperXLocation<middleX){//paper goes up
                        //move paper up
myPaper.style.top = parseInt(myPaper.style.top) - yPaces+'px';
}else{//paper goes down
                        //move paper down
myPaper.style.top = parseInt(myPaper.style.top) + yPaces+'px';
}
                        //move paper right
myPaper.style.left = parseInt(myPaper.style.left) + xPaces + 'px';
}
availableMoves--;
}else{//no more moves left
clearInterval(motion);
if(paperYLocation<-20 && paperXLocation<binXLocation){//the paper is still in mid-air
//available moves ran out and the paper is still in mid-air,
//therefore get it to the ground!
//Set a new interval which calls the landPaper() function every 40 milliseconds
landMotion = setInterval(landPaper,40);
}else if(paperYLocation>=-150 && paperXLocation>binXLocation){//dunk
alert("Dunk! YOU WIN!!!");
}else if(paperYLocation<-150 && paperXLocation>binXLocation){//overshoot
alert("Over Shoot!");
}else if(paperYLocation>=-20){//not far enough
alert("Not far enough!");
}
}

That's it for today's post, hope you found it interesting and helpful. If you have any questions or suggestions, please leave them in the comments section and I will do my best to respond.
In my next post I will discuss how to provide the user with control of the shooting power and make the paper ball roll while moving in the air.

14 March 2012

Coursework 1: JavaScript Animation Game– Post 2


In my last post regarding JavaScript animation I explained how to:
  • Make an image move on screen by using JavaScript
  • Identify the user’s browser screen size
  • Make the image go back to its original position

Today I will start by simply adding how I managed to disable and enable HTML objects programmatically and then continue by explaining how I made my paper object go up and then back down, in-order to simulate a throw.

Disable any important controls programmatically while the animation is in process

While your animation is in process, you may want to disable some HTML objects to prevent the user from using them and later re-enable them when it’s safe to do so. I decided that I want to disable the ‘Throw’ button while the paper is moving, in-order to prevent the user from re-sending the throw command and re-enabling it when the user clicks on the ‘Restart’ button.

To do so I had to set the ‘Throw’ button’s name attribute, so I could reference it in my JavaScript code.


<input name="btnThrow" type="button" value="Throw" onclick="throwPaper();" />

To do so I had to do some research on how to access the ‘disabled’ attribute of an HTML element and I found my answer at CodeToad, so this is what you have to do:

1.   Place your element in an HTML form (<form></form>) as this will only work on elements within the form tags. (N.B. – You have to set the form’s name attribute in-order to reference it).

2.   Set the element’s name attribute, as I did with my ‘Throw’ button.



<form name="MainForm">
   <input name="btnThrow" type="button" value="Throw" onclick="throwPaper();" />
</form>

3.  Reference the element using the values you given in the name attributes like so:


//disables the 'Throw' button
document.MainForm.btnThrow.disabled=true;

4.  Now you want this code to be executed when a certain event takes place, so I’m just going to insert it in the function the ‘Throw’ button calls when clicked, which is ‘throwPaper()’.

To re-enable the element is just a simple matter of changing the Boolean value from “true” to “false” like so:



//makes sure the 'Throw' button is enabled   
document.MainForm.btnThrow.disabled=false;

Again, you want to execute this code when a certain event occurs, so I just put it in my ‘start()’ function, as this is called by the ‘Reset’ button when clicked on.

So there you go, now you know a way how to programmatically disable and enable HTML form elements

Make the paper go up and then back down

Up till now I have managed to get my paper to go in a straight line, but want to be able to throw it into a bin, therefore I need to make it go up and at some point get back down. To do this I could implement a function which works out a quadratic equation and passes the exact coordinates to my ‘move()’ function, this would make my paper ball travel in a perfect arch rather than a straight line, I could also make the quadratic equation function receive parameters to simulate different angles and force, but to keep matters simple I thought of a different way which I will now explain.

My paper ball is set to move 10 pixels to the right, every time I call the function ‘move()’, now if I make it go up a number of pixels, while still maintaining the movement to the right, my paper ball would move diagonally from the bottom-left of the screen to the top-right, thus simulating lift. But my paper ball can’t just keep on going upwards, I mean common it’s a paper ball…not a helium balloon!

So at some point I want to stop moving it upwards and start moving it downwards. To identify this position I started out by establishing a position of where I want my paper to land and that was the bottom-right corner. So I used the browser’s screen width, which is now being stored in a global variable called ‘screenW’ thanks to the ‘getScreenSize()’ function I mentioned earlier, deducted 40 pixels from it in-order to compensate for the table and div elements’ borders, divided it in half and stored it in a global variable named ‘middleX’, as this point is the middle of the x-coordinate range.


//determines the middleX value
middleX = ((screenW-40)/2);    

I placed this calculation in the 'start()' function as I don't need to calculate this position every time I shoot. Now that I have the point where I want my paper ball to start dropping down, naturally I now need to establish the middle of the y-coordinate range so I declared a global variable called ‘middleY’ and stored a value of 250 (N.B. - The height of the game area will be 400 pixels,  you might be thinking that 250 isn’t the middle of the y-coordinate range, but I did this to amplify the upwards movement, as I will explain shortly)

But I still haven’t decided how much I am going to raise up the paper ball every time I call the ‘move()’ function. To work this out, I divide the value in ‘middleY’ with the value in ‘middleX’, multiply them with the amount of pixels the paper will move to the right (which I have now stored in a global variable called ‘Xpaces)and multiply the answer with 2, in-order to make the paper ball reach the maximum height possible. 


//calculate the yPaces
yPaces = ((middleY/middleX)*xPaces)*2;


I have now established this value and stored it in a global variable called ‘Ypaces’, but it is important to think a bit where to carry out this summation. If I placed it in the ‘move()’ function my application would still work, but this would also mean that the user’s machine will work out this summation every time the this function is called (with a screen width of 1240 pixels and an X pace of 10 pixels, that would amount to 124 times) and that results to wasted processing power and bad performance. So I decided to place it in the ‘throwPaper()’ function, this way the summation is carried out only once and the value is stored globally so it can be reached from within the ‘move()’ function.

Once I have established the amount of upward pixels my paper should move and the point in which it should start to come down, all I have left to do is  make the necessary changes in my ‘move()’ function like so:


//checks the number of available moves left.
//if moves are still available, move the paper.
//else stop the interval.
function move(){
     //get paper's current location
     var paperXLocation = parseInt(myPaper.style.left);
     if(availableMoves > 0){//still have moves available
           if(paperXLocation<middleX){//paper goes up
                 myPaper.style.top = parseInt(myPaper.style.top) - yPaces+'px';//move paper up
           }else{//paper goes down
                 myPaper.style.top = parseInt(myPaper.style.top) + yPaces+'px';//move paper down
           }
           myPaper.style.left = parseInt(myPaper.style.left) + xPaces + 'px';//move paper right
     }else{//no more moves left
           availableMoves--;
     }
}

What I am doing here is:
1.       Get the paper’s current location.
2.       Check if there are any available moves left.
a.       If moves are still available:
                                                   i.      Check if the paper has reached the point of going down
                                          1.       If not, move the paper up yPaces
                                                    2.       Else, move the paper down yPaces
                                                   ii.      Move the paper to the right xPaces
b.      Else, stop the motion interval.
3.       Reduce the amount of available moves by 1.


The image below illustrates the progress so far for today:


This post describes how the 'Throw' button is disabled/re-enabled and how
 I made the paper ball go up and down while still moving to the right.



That’s it for now, in my next post I will discuss how I handle collision detection and how I provide the user with a way to change the shooting angle. Hope you enjoyed reading this post.