better living through python

An adventure in programming and recovery.

Good things can come from bad experiences

July 12, 2012

I received an email from the PhD student whose Bullying Study I participated in. The email was very nice, thanking me for my participation and providing me with a copy of her dissertation. She asked how I was and if things were going well. What you would expect, really.

I was totally caught off guard by my reaction. I almost started crying. Seeing the work she put into using our stories to understand and discuss what happens in women on women bullying. Not the amount of work, which after reading a majority of the dissertation was impressive (as dissertations should be), but that something was coming out of my experience, something besides my own recovery and self revelations.

You can tell your friends about horrible experiences you have, and they can hear you and be there for you and try to help as best they can. So rarely (and through no fault of theirs) do your friends go and attempt to make a major change in the world because of an experience you had. Most people try to change the world based on their own experiences, and I think that’s how things should be.

But here I did what I felt I could do. I told someone about what I experienced, hoping it might help in some way. I don’t feel like I could ever go and perform such a study myself. I’m still having issues letting go and I definitely haven’t forgiven my former boss yet. I don’t know when that will happen, but I know the sooner it does the sooner I can let go of everything that happened back then.
Here I was, staring at the computer screen, getting emotional because I was seeing my experience come to life. My experiences being…utilized, meaning something besides pain and anger. Just another step in recovery I guess.

Was this vindication? No, but it did somewhat satisfy my rage.

I’m hoping to get permission to post a copy of the dissertation to my blog, but until then I’ll just be referencing it. When and if I get a chance to post it I’ll probably talk a little about what the results were and what they mean to me.

A twinkle function, making stars better since 1929

July 11, 2012

No this post has nothing to do with the stock market crash. I’m just here to finish up my fancy starness. This function processes all the other functions I’ve since been explaining, and uses them to create my twinkle effect.

function twinkle(star, currenttime){
  var intensityred = intensity(star['duration'], 
  currenttime - star['creationtime'], star['delayred'], star['cycles'][0]); 
  var intensitygreen = intensity(star['duration'], 
  currenttime - star['creationtime'], star['delaygreen'], star['cycles'][1]); 
  var intensityblue = intensity(star['duration'], 
  currenttime - star['creationtime'], star['delayblue'], star['cycles'][2]);
  var rgb = hextorgb(star['background-color']); 
  var red = Math.floor(rgb[0] * intensityred);
  var green = Math.floor(rgb[1] * intensitygreen);
  var blue = Math.floor(((rgb[2] - 64) * intensityblue) + 64);
  return "rgb(" + red + "," + green + "," + blue + ")";     
}

To begin with twinkle() pulls in two variables, star and the currenttime. The currenttime is self explanatory, and the star we’ve discussed before (all the css values that correspond to be the star on the screen). Then the majority of this function simply creates variables.

The first three set the intensities of the different RGB values. The variable rgb converts the background color the star is originally set to from a hex value to rgb (as discussed in this entry). After this the actual rgb variable values (red, green, blue) are set and subsequently rounded down so that the browser can easily handle them.

The final value returned from this function is the rgb value, which is used in updatestar(). If you remember, updatestar() renders the various css values of the star. Basically now, instead of a basic hex color value designated as the background-color I use twinkle(). The colors update and we get the twinkle (pulsing) effect because updatestars() (which runs updatestar()) runs within the tick() function (which for the purposes of explanation runs 60 times a second). If you didn’t realize how much processing power your browser had yet, think about that for a while.

Adjusting some css color intensity using trigonometry

July 05, 2012

The next part of this javascript code, is the function intensity(). It calls four variables and is, in some ways, the more complicated of the functions (mathematically at least). The function itself is called within the twinkle() function, and sets the varying duration, age, delay and cycle of the color intensity of each star. Here is the function itself:

function intensity(duration, age, delay, cycle){
  if (age < delay){
    return 0;
  }else if (age < duration - delay){
    return (-1*Math.cos((age-delay)*2*cycle*Math.PI/(duration-delay*2)) + 1)/2;   
  }else{
    return 0;
  }
}

Although this function takes several values it only returns one; the new color intensity. Using two if blocks it first determines if the age of the star is less than the delay. The age of the star is the length of time the star has existed on the screen. The delay is the amount of time before this color shows up. Therefore as long as the delay is greater than the age of the star, the new color intensity will not appear as the functions returns zero.

Then comes the else if block. This block determines, that if the age of the star is greater than the duration (total life span of the star) minus the delay, then a new color intensity value will be returned. This color intensity is created based on the trig function listed here.

If neither of those two situations apply, then the function once again returns zero.

Late Posting Goodness

June 26, 2012

Today was definitely a day of tiredness. Recently I’ve been seeing a physical therapist to get my hip back into the correct locations in my hip sockets. While that’s still being figured out, there are other problems that were noted in my left ankle, more stuff to get fixed. I’m able to walk around and whatnot, but I think my left leg and hip is finally having to work normally again and it’s not happy about it.

Thus I get home from work and I’m rather tired with my day, simply because my left leg is so sore.

Good news, however, I’ve come up with a cool idea to add to my game. Nothing original, mind you, but still exciting for me. I’m going to add a charge bar like in Mortal Combat, so when it’s fully charged you can either hit a button and make all the ships on the screen explode, or they simply explode when you reach fully charge.

On top of that, I was Carmen Sandiego this past weekend at the local Supervillian Conference (read “a friend’s debaucherously fun birthday party”). Fun was had.

I did not have enough mental energy to program this evening, thus a non-programming related post.

Creating a time sensitive color shift with javascript

June 21, 2012

This was a rather difficult piece of code for me. I haven’t had a lot of practice using trigonometry within code before, so Robey had to help a fair deal with this.

I’ll start today by giving a brief description of what I wanted to have happen, the basics on how it was set up, and one of the simpler functions I created for this exercise.

At this point in my code, my stars will fade in and out while only remaining one color value. My hope was to have a kind of twinkle effect for my stars and to simulate that I was going to use a gradual color shift to emphasize it. To do this I had to create three new functions: twinkle(star, currenttime), intensity(duration, age, delay, cycle), and hextorgb(hex).

twinkle() is the most complex of the different functions, and will be discussed last. The main purpose of it is to take in all the values and information provided by the subsequent functions, and make them useful when the function itself is called in updatestar() (previously discussed, this function simply turns the js object into rendered css).

intensity() involves the trig and will be discussed later, but hextorgb() is the most basic one and what you’ll hear about today.

hextorgb() does basically what it’s name means, it converts hex color values into RGB color values.

function hextorgb(hex){
  var newhex = hex.slice(1);
  var red = newhex.slice(0,2);
  var green = newhex.slice(2,4);
  var blue = newhex.slice(4,6);
  var newred = parseInt(red, 16);  
  var newgreen = parseInt(green, 16);  
  var newblue = parseInt(blue, 16);  
  var rgb = [newred, newgreen, newblue];
  return rgb;
}

Most of this function is simply creating variables out of other variables. Using javascript’s version of slice, I cut up the hex value (example: #dded00) into the 3 different RGB values. For those who don’t know, RGB stands for Red, Green and Blue. The first two values in the hex color value represent Red (ex. dd), the next two green(ex. ed) and the last blue(ex. 00).

First I create a newhex value from the inputted hex value, because my original hex values were stored as strings starting with the hash sign. Therefore I start out by slicing that value from ‘#dded00’ to ‘dded00’.

Then I create new values from the first two, second two and last two digits in the hex, and thus identify a variable with it’s corresponding hex code. Then I use a js built in function called parseInt(), which takes a variable and converts it into a number using a set base during conversion. Here it takes our hex string values of, for example, red ‘dd’ and converts it into a number. It does this by using the base set provided, 16. Basically this says, instead of a base set of numbers that go from 1 to 10 (base 10), the base set goes from 1 to f (1,2,3,4,5,6,7,8,9,10,a,b,c,d,e,f). Taking the base set it converts it to base 10 integer.

The final step in this function is simply taking all the new RGB values, and putting them into an object which is returned from the function. Alright, it’s too hot in here and I want to go hiking. I’ll chat more next week.

Star management...much easier when coding

June 19, 2012

This last function runs the functions makestar() and updatestar() and manages all the stars created therefrom.

function updatestars(currenttime){
  var newstars = [];
  while (stars.length < 20) {
    var star = makestar(currenttime);
    stars.push(star); 
  }
  for (var i = 0; i < stars.length; i+=1){
    var star = stars[i];
    updatestar(star, i);
    if (star['duration'] > currenttime - star['creationtime']){
      newstars.push(star);
     }     
  }
  stars = newstars;
}

The only variable this function needs to run appropriately is a designation for the current time. Then the fun begins.

To start the function creates an empty object (in python this is known as a dictionary). Then a while loop runs, which adds a newly created star object (via the makestar() function) to the global object stars as long as the length of the global object is less than 20.

Then a for loop runs, which takes one of the values in the stars object and runs updatestar() on it. Then a check is run, to determine whether or not the star should still be visible based on the duration and and creationtime values stored in the object. If the duration of star visibility is greater than the currenttime listed in the game and the initial creationtime of the star, the star will be added to the newstars object and thus displayed on the screen. Basically that’s the age of the star.

Technically the stars are never specifically removed from the object, because javascript has what is known as ‘garbage collection’. The programming language was built in such a way that allows you to simply stop holding onto information. When you stop holding on to it, or collecting it, it’s handled by something written in the language itself. Anything more specific than that I can’t tell you…it’s something I’ll be learning more about another day I understand. Basically, once the duration is no longer greater than the currenttime minus the creationtime, (in other words the duration of the star is spent), the star will simply cease to exist within the code.

So far so good. Here is an image or what my current stars look like.

Spaceships with stars in the background

Updating the star css and jQuery data

June 14, 2012

The function from yesterday created an object that housed the information necessary to create the stars. Today’s function puts the star on the screen.

function updatestar(star, id){
  id = id + 1;
  $("#" + 'star' + id).css({
     'display':'block',
     'position': 'absolute',
     'right': star['right'] + '%',
     'top': star['top'] + '%',
     'height': star['height'],
     'width': star['height'],
     'background-color': star['background-color'],
     '-webkit-transform': 'rotate(' + star['rotation'] + 'deg)',
     '-moz-transform': 'rotate(' + star['rotation'] + 'deg)',
     '-o-transform': 'rotate(' + star['rotation'] + 'deg)',
     '-ms-transform': 'rotate(' + star['rotation'] + 'deg)',
     'transform': 'rotate(' + star['rotation'] + 'deg)',
     'opacity': star['opacity']
    });
}

My function updatestar(star, id) will take the star object created by the makestar() function (inputted here as the variable star) and an id. The id identifies which html div the star css info will go into.

Going from top to bottom, you can note how many of the css attributes have a corresponding key from the star object. There are only two that don’t, and they are the attributes that make the star actually display and determine it’s position. If you have any questions about how these aspects of css work, you can look it up on the Mozilla Developer Network website. W3schools is also helpful, but not nearly as comprehensive.

Creating twinkling stars with css and javascript

June 13, 2012

Once again, my other job has interfered with my ability to program. Great sadness I know. This is why I never posted yesterday, but I’m back again. Now on to more fun programming topics!

After assessing the flow of Science Fiction Tower Power, I was able to make background stars for my game. To make these stars I had to code some, what programmers call, ‘sprites’.

To begin I had to determine how I wanted my stars to act. This brainstorming session helped to me to pin down a fair amount of my parameters. I wanted them to show up randomly on the screen and fade in and out or twinkle. One of the more difficult things in programming is realizing that an idea of how you want things to act or look on the screen encompasses many more parameters than go into your imagination. By that I mean, you can imagine it, but programming it requires about 3 to 4 times more information to make it a reality.

To better explain this, I’ll show what information I had to create in order to make my sprites, or ‘stars’. First I created a function that would generate a randomized star.

function makestar(currenttime){
  var star = {
     'right': getRandomInt(0, 100), 
     'top': getRandomInt(0, 100),
     'height': getRandomInt(4, 8),
     'background-color': starcolors[getRandomInt(0, starcolors.length)],
     'rotation': 45,
     'opacity': 1.0,
     'duration': getRandomInt(7,15) * 1000,
     'creationtime': currenttime
  };
  return star;  
}

To randomize most of my variables I created getRandomInt(x,y). This is a basic function that takes in two variables and returns a random number in that designated the range of possible numbers. If I inputted 1 and 20 as my variables into getRandomInt(1,20), it would mean that this function could return any number from 1 through 20 when it runs.

This function creates a javascript object that I can access in my next function. As you read from top to bottom, you’ll see the css position descripters right and top to specify a random star location. The height of the star is created randomly (the width is the same size as the height, so I just take that result instead of repeating code).

To determine the background color I use the same getRandomInt() function, however I use it to grab a random entry in a list of various color hex values. I use a specific pallette of colors for the game so it provides consistency, but this way I can still allow for some variation in the small stars.

Lastly I identify the rotation of the star (actually a square turned 45 degrees, thus making it diamond in shape, a simple way to create a star image). Opacity is turned on full at 1.0. The duration sets how long the star is to remain visible on the screen, and the creationtime is when the star should first appear.

The next function updates the star’s css and jQuery information, and the third manages star creation and removal. I’ll chat about those next time. Also, we’re in the new office!! Photos to come here in the near future :)

Admitting when you're wrong

June 07, 2012

No one likes to do this…admitting you’re wrong can be humliating at times. But being unable to admit it prevents you from accomplishing so many important things.

I have a difficult time admitting I don’t understand code sometimes. Mostly it’s when I’m reviewing code I’ve written and Robey is helping me to analyze it. I sometimes get a bit red in the face about it, and it’s such a waste of time. If I had allowed myself to be more open minded about my own faults, I would have been able to move forward already.

When I talk about it with Robey, others, or just write about it here I realize how stupid it is. I’m human, I err. Add in that I’m learning how to code because I’m unexperienced at it just adds to the hilarity of it all. I don’t know what I’m doing but I can’t admit that I don’t know what I’m doing. I mean…that’s just dumb.

So, as you can see, this has been one of my major learning hurdles over the past year. Learning how to identify when I’m wrong and attempting to ignore it. The other part of this puzzle is, once I’ve realized I’m trying to ignore I’m wrong, learning to admit it without much emotional turmoil and being able to move on smoothly.

Learning how much of an issues this is within myself I’ve started to see other people with the same problem. It’s amazing just how many people have the same problem as I do. Oddly heartening.

Javascript Flow Chart

June 05, 2012

These past few work days I’ve been going through my code with a fine-tooth comb. Robey and I were partially looking at unneeded repetitions or code run unnecessarily. Mostly we were putting together a flow chart construction of how the functions interacted. This was done mainly for my benefit, so that I could more easily identify where any bugs might be located.

Science Fiction Tower Power basic flow chart

This process was incredibly helpful. It helped me to identify several lengthy areas that could be simply cut down by creating another function. There was also some code that I was able to simply strike out because it’s become obsolete based on other updates.

There were two bugs in particular that had been bothering me. The first bug occurred when the player attempted to submit a solution after the spaceship had collided with the world. When this happened the ‘kersplat’ image that normally would show up and slowly fade, now would remain until the next time a ship collided with the planet.

The awesome part about this first bug, was that it was rather difficult realizing what exactly was causing the effect, and so determining how to solve it took a bit. After some puzzling and a helpful Robey, we identified that is was caused by what I mentioned above. To solve this I ran my submitsolution() function begin with an if block. This if block identified whether or not the problem was visible, before it allowed a person to submit any information. Basically, it stopped allowing accidental answer submissions when the problem wasn’t visible.

The second bug occured when the player attempted to answer a problem but was unsuccessful and the ship ‘kersplatted’ (and a new ship was thus generated). The answer box would keep the old data the player had entered, therefore making it difficult for the player to answer the next problem without deleting the old numbers.

To solve this I simply used the .val() jQuery function. This function $().val() allows you to alter what appears in the input box in a variety of ways. Luckily I just wanted to make the submission box blank everytime a new ship was created. My end code was simply $(“#inputproblem” + problemnumber).val(””); This little bit of code is able to update any input box with an empty string.

But what was the most interesting discovery of this process? Learning that your naming conventions are incredibly important, especially in the beginning. You want your function to very easily tell you what it does. If you need to change things later, and then never rename your function accordingly, it can make reading your code that much harder. It’s already hard enough sometimes…why make it worse?

Links