Programing

Iterating through properties of a JavaScript Object with the “For In” loop

Posted in Geekdom, Programing, Web Development on January 16th, 2012 by Jarred – Comments Off on Iterating through properties of a JavaScript Object with the “For In” loop

As I have mentioned before I am a novice self taught programmer and I often come across little problems that take me quite a while to figure them out. I like to post them here so I can come back and remember how I solved the problem and also so hopefully others can benefit from my struggles. I came access one of these said problems this weekend trying to iterate through a object in JavaScript using a “for in” loop. I understood the looping mechanism quite well, however getting the syntax to work for me through me for a loop.

 

Incorrect (This is how I would assume it would work)

 for (var x in someObject.someProperty)

{
newVar = someObject.someProperty.x.anotherProperty;
}

This is how I got it to work

 for (var x in someObject.someProperty)

{
newVar = someObject.someProperty[x].anotherProperty;
}

You will notice you cant use .x to access the property the loop is currently processing,  you must use the [x] In truth I do not understand why this is so if anybody out there cares to enlighten me that would be appreciated. Either way hopefully this might save some frustration.

PHP code snippet to put mySQL query results into a 2 dimensional array

Posted in Geekdom, Programing, Web Development on December 16th, 2011 by Jarred – Comments Off on PHP code snippet to put mySQL query results into a 2 dimensional array

More often then not when I am are working with a mySQL database using PHP I want to put my results into a 2 dimensional array. A while back I found a snippet of code that very effectively does this. However, I am constantly digging through old projects trying to remember/find the piece the code that does this, So I figured I would post it here for reference. The code is only one line and will put the results of a mySQL query ($mySQLresults) into a 2 dimensional array.

 

while(($resultArray[] = @mysql_fetch_assoc($mySQLresults)) || array_pop($resultArray));

 

 

 

Source http://php.net/manual/en/function.mysql-fetch-assoc.php

Free 2 Column Webpage Template with Sticky Footer

Posted in Programing, Web Development on November 25th, 2011 by Jarred – Comments Off on Free 2 Column Webpage Template with Sticky Footer

Here is my first installment for my recent “Do more, Write Less” initiative I started for myself. I find myself constantly rewriting the same basic building blocks for my webpages and figure its about time to create a template that I can reuse to save myself time. I will post my code snippits here to not only archive them for my own use but also provided them to my visitors for free to try and help attract more traffic to my blog.

This is a free template for a webpage with a two column layout with a header and footer. This layout is very common and is used widely on the web. The template is just a basic building block for a web page and can be customized to however you see fit. One of the trickier things I find myself having to figure out over and over again is the sticky footer. This has also been included in the template and should work in all browsers. I have also included the basic template for the CSS which should probably be pasted into an external style sheet for bigger sites.  This template is free to use in any way you like and can be used for personal, commercial, or any other type of project.  Let me know if you find anything that does not work. Right click on the link below to download the free template (You may have to view source and then copy/past the HTML into a new file if your browser will not download the HTML file).

Free Website Template 2 Columns with Sticky Footer

Sources: http://ryanfait.com/resources/footer-stick-to-bottom-of-page/

 

 

HTML5 Audio Is Here (Sorta)

Posted in Programing, Web Development on September 8th, 2011 by Jarred – Comments Off on HTML5 Audio Is Here (Sorta)

Figuring out how to implement a pure HTML5 Audio solution for my game was quite a chore. I found countless threads and post complaining that audio support is just not there yet and that the best thing to do is use flash based solutions (like the SoundManager 2 script). However, I found other information which lead me to believe it could be done. After much searching and trial and error I figured out something that would work and that would preload the sounds before the game would start. My ultimate solution was pure HMTL5 without the use of a script and used a variety of techniques I gleaned from reading others posts and blogs(mostly stackoverflow).

Here is how I did it:

First I load all the game sounds using HTML audio elements in the body of my page. You have to provide at least a .mp3 file and a .ogg file to be compatible with most browsers. Also, If you plan on doing multi-shot sounds (sounds that can be played overlapping themselves such as a rapid fire gun sound in a game) you will have to load multiple instance of them into separate audio elements (Many of my sounds have 5 or 6 instances of themselves)

<audio id=”gun_sound_1″ preload=”auto”>
<source src=”sounds/gun.mp3″ type=”audio/mpeg” />
<source src=”sounds/gun.ogg” type=”audio/ogg” />
</audio>
<audio id=”gun_sound_2″ preload=”auto”>
<source src=”sounds/gun.mp3″ type=”audio/mpeg” />
<source src=”sounds/gun.ogg” type=”audio/ogg” />
</audio>
<audio id=”gun_sound_3″ preload=”auto”>
<source src=”sounds/gun.mp3″ type=”audio/mpeg” />
<source src=”sounds/gun.ogg” type=”audio/ogg” />
</audio>

Secondly the JavaScript

//Create a counter for the sound
gunSound_counter = 1

//Variable holding the number of audio elements that exist
gunSound_maxNumber = 3;

function playSound_html5(soundName)
{
//Add the counter suffix
soundToPlay = soundName+gunSound_counter;

//Play The Sound
audioElement = document.getElementById(soundToPlay);
audioElement.play();

// For Multi-Shot sounds Increment the counter. If counter is at the max reset to one
if (gunSound_counter >= gunSound_maxNumber)
gunSound_counter = 1;
else
gunSound_counter++;
}

Now when ever I want to play the sound I just call the playSound function and pass it a string with the name of the sound I want to play (without the number suffix).

playSound_html5(‘gun_sound_’);

I am pretty sure there is likely more eloquent ways to do this, but hopefully this can help you get a good start.

Update: Upon reading this it now looks like the SoundManager 2 now offers support (beta) for HTML5 audio. Looks like I will have to check this out on my next game cause sound really was just a pain.

 

Some of the sources I used:
http://stackoverflow.com/questions/1933969/sound-effects-in-javascript-html5
http://stackoverflow.com/questions/2741493/how-do-you-detect-html5-video-events
http://stackoverflow.com/questions/6312714/adding-event-listener-to-audio-html5-tag-in-javascript
http://stackoverflow.com/questions/3566967/how-to-stop-audio-played-by-audio-tag-of-html5
http://diveintohtml5.org/everything.html
http://www.webdeveloper.com/forum/showthread.php?t=194442
http://www.broken-links.com/2009/10/06/building-html5-video-controls-with-javascript/
http://bioinfornetics.blogspot.com/2011/02/how-to-resetrestart-position-of-html5.html

AsteroidsInc is ready to go

Posted in Entrepreneurship, Programing, Web Development on August 1st, 2011 by Jarred – 1 Comment


Well at long last I think I am finally ready to release my first game. Check it out at AsteroidsInc.com

 The game was programed entirely in JavaScript using the HTML5 canvas and audio objects. It should require no plugins to play (looks like safari may require quicktime). This was pretty much the first game I have ever programed and I learned a lot and did lots of stuff wrong the first time around (and most likely still have a lot of stuff not quite right). If I write another one it should go a lot smoother. If you play it and have any feedback or find any bugs please let me know.

 At the outset I had even grander designs for the game, but I decided to try and simplify the design so that I could get the game to a releasable state sooner. As it was this beast took me several months of my free time to complete. I estimate it has probably taken me around 200 hours total from start to finish (next time I will try and keep better track of the time).

 So if you refer to my post here on how I plan on accomplishing my goal this marks the completion of step one and two (at least for my first project). I hopefully have created something useful which will attract Visitors & Links.

 Now I plan on trying to figure out the most efficient way to monetize the game and start generating some passive income from it. I am aware that it will likely be a challenge and may not be a simple task to do, but I am determined to see this through. I will keep the graph on the upper right hand corner of the blog updated to track my progress.

Safari not liking the HTML5 Audio

Posted in All, Programing, Web Development on July 30th, 2011 by Jarred – 1 Comment

 Well this one threw me for a loop….

 I never use Safari, but in an attempt to make my latest HTML5 Game compatible in all the major browsers I downloaded the PC version of Safari to do some testing and trouble shooting to see if it would work. The game worked well in Chrome, Firefox, and I.E. so I assumed it would just work in Safari. But no, to my surprise it started throwing the following error every time I tried playing one of the audio elements.

 TypeError: ‘undefined’ is not a function (evaluating ‘audioElement.play()’)

 After much frustration I came across a post which indicated that HTML5 audio and video tags will not work in Safari without QuickTime. So much for HTML5 not requiring any plug-ins. I installed QuickTime and to my dismay Safari was now giving me the following error when I tried to start it up.

This application has failed to start because QTCF.dll was not found. Re-installing the application may fix this problem.

After trying to reinstall the the browser (this did not work) I found the QTCF.dll file in the Program Files/QuickTime/QTsystem made a copy of it and put it in Windows/System32. This solve the problem and Safari now started up. I was able to load my game with no more errors playing the audio objects. Safari seemed to handle the canvas object fairly well (although the frame rate on seems to be fairly poor).

Source: http://happyworm.com

Source: http://answers.yahoo.com/question/index?qid=20090912133753AAM60Ur

Free Animated explosion on transparent background

Posted in Geekdom, Programing on July 5th, 2011 by Jarred – 1 Comment

While creating my first game I came across the need for some sprite sized explosion animations. I tried multiple times to draw them myself, however I just couldn’t get them to look right. So I turned to the web to see if I could find some royalty free explosion animations that I could use in my game. After a little searching I found several suitable sprite sheets like the one below on http://www.positech.co.uk/content/explosion/explosiongenerator.html (The website also features a free explosion generator program to make more).

The animation however was on a sprite sheet that had a solid background and I needed a transparent background. So, I took the time to cut them out using an alpha layer and then saved them to individual files. I have upload the cutout files as I figure it is likely others might find them useful. The below file includes a photoshop file with all the different frames of the explosion on different layers as well as all of the frames of the explosion separated into individual .png files with transparent backgrounds. These images are royalty free so please feel free to use them any way you like.

Download animation with transparent background

UPDATE: Couple more free animated explosions can be found here

explosion_animation_sheet

Include an “or” Operator in a JavaScript Switch Statement

Posted in Programing, Web Development on July 4th, 2011 by Jarred – Comments Off on Include an “or” Operator in a JavaScript Switch Statement

I came across a situation where I needed a switch statement in JavaScript to do the exact same thing in multiple cases. For example:

switch (varAnimal)
{
   case ‘dog’:
   sameFunction();
   break;

   case ‘cat’:
   sameFunction();
   break;

   case ‘bird’:
   sameFunction();
   break;
}

While the above code works, if you have a long list of variables it is highly inefficient. To solve the problem I initially tried to use an “or” operator to try and test for the different values as you would do in an “if” statement. For example:

switch (varAnimal)
{
   case ‘dog’ || ‘cat’ || ‘bird’:
   sameFunction();
   break;
}

However this didn’t work. I found on a forum the below method which appears to accomplish what I was trying to do. It essentially lets you use an “or” operator to test for multiple cases which can save a lot of typing. For example:

switch (varAnimal)
{
   case ‘dog’: case ‘cat’: case ‘bird’:
   sameFunction();
   break;
}

Source: http://www.webdeveloper.com/forum/showthread.php?t=191879

How to find the length of an associative array in JavaScript

Posted in Programing, Web Development on June 26th, 2011 by Jarred – Comments Off on How to find the length of an associative array in JavaScript

So this little tidbit took me a bit by surprise. The .length property does not work on associative arrays in JavaScript. It will return zero no matter how many elements are in the array. Below is a script I found that will correctly return the length of a JavaScript associative array.

 

associativeArrayLength = function(obj)
{
    var size = 0, key;
    for (key in obj)
        {
        if (obj.hasOwnProperty(key)) size++;
        }
    return size;
};

 

Source: http://stackoverflow.com/questions/5223/length-of-javascript-associative-array

Select random element from a Javascript Array

Posted in Programing, Web Development on June 25th, 2011 by Jarred – Comments Off on Select random element from a Javascript Array

Need to select a random element from a javascript array? The process is fairly straightforward but I was not clever enough to figure it out on my own. First take a random number with Math.random() [which will return a random number between 0 and 1] then multiply this number by the length of the array. You then need to use Math.floor to round the number down to the nearest whole number and voila… you have a random element number. All of this can be included in the square brackets of the array to make more condensed/easy to read code.

For Example

randomElement = testArray[Math.floor(Math.random()*testArray.length)];

 

 

Source: http://www.webmasterworld.com/forum91/2245.htm