Showing posts with label coding. Show all posts
Showing posts with label coding. Show all posts

Wednesday, 24 May 2017

You Won't BELIEVE what I found in the new Spiderman : Homecoming trailer!

Note that I like to pander about, talking about whatever comes to mind, if you want to get straight to the analysis scroll down till you see the code.

I found decorative computer code. There, now send me an angry comment for the clickbait and be on your way, Internet stranger.
(But pls remember to tweet how angry you are and don't forget to link this and Google Plus this (I don't judge you for using that) and Facebook and send this to all your friends! Email if you have too! Or -gasp- talk to your friends about this!)
....
plz
....
 i hvae no raeders
....
I am broken inside
...
 :'(
....

Anyway here's Spidey's suit given to him by Tony

(Image courtesy of Sony, screencapped from the Youtube trailer, (98027 views as of writing) all of these are from there, don't sue me please :(  
 I'm also pretty sure it's legal for me to use this under fair use as long as I don't use it in it's entirety for educational purposes or something like that, so there's that. Sorry for rambling, readers. Wait I thought I have no readers?)

Looks pretty cool, apparently the red and blue isn't painted on but is emitted through the suit. Handy
for changing colour schemes and logos in the future without having to come up with the old "Upgraded suit" cliche.

Looks like the entire suit is a circuit. And guess what, it's programmable too!



Anyways here is the code, presumably in-universe written by Tony Stark. I believe this is the first time we see his actual code on-screen in the MCU.



So, either Tony left some code for Spidey to play with (but he blocked out most of it with "The Training Wheel Protocol", wow Tony. Just. Wow.).

I heavily suspect there is more code at the top and bottom, but the screen is scrolled somewhere in the middle of the code. That also explains the "boxAnchor + offset" meaningless code at the bottom, it's not fully displayed and maybe it's a typo or something.

If someone could identify the language used (assuming it's a real language), I would appreciate it. Right now my theory is....Javascript? I honestly have no clue.

So let's take a look at the code. I've written down for you, the non-existent reader's, convenience

MODEM BACKUP
boxTopLeft = box.toComp([0,0]);
boxBottomRight = box.toComp([box.width,box.height]);
boxAnchor = box.toComp(box.anchorPoint); xRatio = deltaX/distanceEdge;

deltaVec = sub(targetPos,boxAnchor);
deltaX = deltaVec[0];
deltaY = deltaVex[1];
xRatio = 1;
yRatio = 1;

if (deltaX>0)
{
    //target is right of anchorPoint
    xDistanceToEdge = boxTopLeft[0] - boxAnchor[0];
    xRatio = deltaX / xDistanceToEdge;
}

else if (deltaX<0)
{
    xDistanceToEdge = boxTopLeft[0] - boxAnchor[0];
    xRatio = deltaX / xDistanceToEdge;
}

if (deltaY>0)
{
    //target is below anchorPoint
    yDistanceToEdge = boxBottomRight[1] - boxAnchor[1];
    yRatio = deltaY / yDistanceToEdge;
}

else if (deltaY<0)
{
    yDistanceToEdge = boxTopLeft[1] - boxAnchor[1];
    yRatio = deltaY / yDistanceToEdge;
}

ratio = (xRatio>yRatio) ? xRatio:yRatio;
offset = div(deltaVec,ratio);
boxAnchor + offset

.;
MYCONFIGPROGRAM,SH
CREATE_SAMPLE_FILES,SH            BLURRY
./BACKUP:
DAVINCIPROGRAM.SH POWER.NEURAL.;     BLURRY
# FIND -INAME "POWER.NEURAL.1"

So yeah. Sorry I can't read the super blurred out section on the left.
Tony Stark has some really buggy code.By the way if you want, look at the picture you can see his style of writing code, the positioning of brackets and the like. Just an interesting observation, a man's style of writing is as expressive as his walking gait and personality in my opinion.

So at first glance, I think it's definitely something to do with geometry as evidenced by all the coordinates of Xs and Ys and Vectors.

Now I was too lazy to actually read the code, so I made up 2 hypotheses as to what it could be
  1. Detection for where to shoot web (it was mentioned there was 576 possible web shooter combinations in the trailer)
  2. Spidey's Heads Up Display GUI
Yes. Spiderman does have a HUD like Iron Man.



Honestly I like him better independent. Ah well it's a kick-ass cool suit.

I ruled out the first theory because  it seemed to simple for pattern recognition and the like.For some daft reason, I also ruled it out because of the lack of a 'z' coordinate in the real world. Only a little later did I realise that cameras on the suit (if there are any) would capture in 2d hence the lack of a z coordinate.

So it's likely to be used somewhere in Spiderman's HUD.

But what is it actually?

it seems to have an input a deltaVec 2d coordinate, a bounding box which I assume contains the deltaVec (it makes sense), and the target 2d coordinate I assume is away from the box.


(Yeah, sorry I didn't have my tablet at the time and now I'm too lazy)

First off it calculates the ratio between a) distance between the delta and the side of the box (in the direction of the target) b) distance between the input and the target.
Rinse and repeat for all possible cases for both x and y (4 cases, calculate X for left and right, calculate Y for up and down).

Note within a note : It may seem there are cleaner ways to do this with less code (i.e: taking the absolute value only so that eliminates
the need for if statements), but after some thinking, the code provided is actually the most readable way of doing this.

It seems to target the higher ratio first, that is, the one with a further distance to target and smaller distance to side of box,
then divide the delta vector by that "bigger" ratio.
What I don't get is why it chooses the "bigger" ratio for dividing *both* x and y coordinates in the vector. it would make more sense
for

offset = div(deltaVec[0],xRatio);
offset = div(deltaVec[1],yRatio);

where deltaVec[0] and deltaVec[1] are the x and y coordinate respectively.
THIS would have created a still weird but totally slightly more logical normalization.
No idea why it does what it does. Hit me up with a comment if you have a theory and definitely contact me if you managed crack the whole thing wide open and figured out what it does.

For the curious wondering what a normalization is, Wolfram Alpha defines it as so:
The normalized vector of x is a vector in the same direction but with norm (length) 1.
 This is used in conjunction with targetCoordinates-playerCoordinates to get the direction vector to move and multiply that with a speed float instead to control the speed. So a player from (0,0) to enemy (3,3) would give (3-0,3-0) and thus (3,3) as the direction (northeast). So That's is essentially moving (1,1) at a speed of 3 units per second. What normalising does is take the (3,3) and makes it into a (1,1) but the ratios must still be the same (3:3 is equal to 1:1)

Yes I understand the so-called "normalization"  does not have a unit length of 1. I'm still fairly sure the ratios are still the same though. I have no idea why or how they Tony did it like this. Genius level code obfuscation?

Hit me up with a comment if I got normalization completely wrong.
Be as harsh as you want, I have no emotions.

Hit me up with a comment if I got spelling errors.
Be as harsh as you want, I have no emotions.

Hit me up with a comment if you want to talk.
Be as harsh as you want, I have no emotions.

Side-thoughts:
The script "DAVINCIPROGRAM.SH POWER.NEURAL.;" seems to indicate a shell script named after Leonardo Da Vinci. The word Neural, which I first read as Neutral (assuming like as in Live, Neutral, Earth/Ground) but upon reinspection it is most definitely Neural. This word, along with the word Da Vinci, leads me to believe that this is a shell script for activating a Artificial Neural Network (Artificial Intelligence) for pattern finding in the real world through cameras to estimate where best to shoot those webs. Keep in mind this is a long shot and just a not-very-useful movie-wise theory which will likely never get verified (or debuked).

What the heck is "xRatio = deltaX/distanceEdge;" for?
xRatio gets reassigned a few lines later without ever being used.
Perhaps out of the reach of the screen we could not see it was being used for something though.
Why that weird ugly style of coding for someone of the likes of Tony Stark? I do not know.

All in all I was impressed with how they handled the code in the trailer. It might not be the perfect code, but honestly it's good enough for just a quick glance even by a coder.It visually feels interesting while not falling into the trope of having animated ASCII art and colourful GUIS all over the place with an deliberately attention-seeking "Look at me I'm a computer genius look at these random 0s and 1s and scrolling of texts in a green font" type of code. It even seems to be doing something, something related to the suit without ever mentioning "Spider" or something in the code, though I still for the life of me do not know what that something is.

But then again, fools know nothing.
(that was supposed to be a profound endin-

Sunday, 8 January 2017

Adventures in pathfinding (and more!)

Looking at my to-do list, I realised I haven't done any projects with pathfinding yet. "Whelp, I better get to it then".

Although my original goal was to create a Pacman clone, I find the code too bloated to work with. More on this later in the article.

This article was aimed to non coders but it slowly turned into something a bit more complex....Just ignore the parts you don't understand. I try to use as much non confusing terminology as possible.

Also keep in mind I wrote this around midnight while I was very sleep deprived. And apparently blogspot hates me because it keeps glitching out on me.

What is Pathfinding?

"Pathfinding...is the plotting, by a computer application, of the shortest route between two points." - Wikipedia.

It is typically used in video games to find the points an enemy would need to move to get to the player (i.e: Pacman). Here, the two 'points' are x and y coordinates. Pathfinding itself however is not bound to 2d Cartesian planes. For example, it could be bound to a 3d space to find the route from one point in 3d space and another. Another example, which is what is typically used in 3d video games, is to create a navigation mesh, or navmesh, a polygon where each edge is connected to another navmesh.


Algorithms

There are plenty of pathfinding algorithms out there, Djikstra's algorithm, A* algorithm, Breadth first search, etc.

I will be concentrating on Breadth first search, Greedy Best first search, and A*.

The reason why is because I find the level of difficulty in implementing those to be in ascending order, so I could code the former and add on to it for the next algorithm.

Coding language

Now was the time to decide what language to use. I considered C++, Python and Javascript with HTML5 to work with. Each had their pros and cons.

C++

Pros:

I am familiar with the language.

Cons:

Bad for quick prototyping, making small changes (which would be inevitable seeing as this is my first time implementing pathfinding algorithm) would require long compilation times.

Python

Pros:

Good for quick prototyping, because it is an interpreted language.

Cons:
I personally don't like Python.


And so I decided to go with Javascript, or more specifically, ECMAScript6, because I wanted to have classes and OOP capabilities. At the time it seemed like a good idea.....

Tile Editor

So I needed somewhere to design the level maze.
Now obviously I am too lazy to write my own tile editor, so I went with Tiled. Search it up, I don't want to link to it. It exported to a JSON file which played nicely with the Javascript code.

How it works

First off, the Breadth first search algorithm. What this basically does it is to "visit" to all directly adjacent nodes from the destination goal, and repeat the process for every adjacent node until it reaches the goal.  From there, it backtracks to get the route. Think of it like you want it to traverse as evenly as possible in all directions. You never wander too far off in one direction, each step you take, you  go back and go one step forward in all the other directions.

What is a node you ask? Well in this case, it's just the position in the game. The x and y coordinate combined.


Pseudocode 
  
BFS
Args: Destination position, Current position
Nodes.push(x);

FOR x in adjacent(Current)
      x->parent = Current
      BFS(Destination, x)

After a few iterations, it would look something like this (the white square is the enemy and I am the red square) 

  Funny how it looks like a ship, right?

Greedy Best first search

GBFS
Args: Destination position, Current position
FOR x in adjacent(current position)
       x->parent = current
      x->score   =  distance(Destination,x)
      GBFS(Destination position, Nodes.GetLowestScore())

So it favours the one which, according to the distance function, is the closest path. This sometimes leads to false alarms though, because you may traverse so far near to the destination only to find it is blocked.

A*
Args: Destination position, Current position
FOR x in adjacent(current position)
       x->parent = current
      x->score   =  distance(Destination,x) + x->parent->score
      GBFS(Destination position, Nodes.GetLowestScore())
 
A* uses the distance from the starting point in addition to the distance to the destination .

Both A* and Greedy Best first search worked the same in my level....

Here is a random screenshot of me trying to find a bug
What is happening is that my code "visits" every adjacent node, assigns a parent, and repeats itself with the next node. A nice way I found out for debugging was to use a "Blob", which is something like an internal file, to gather the debugging information,set the MIME type to a text file, and use it to create a blob:// url, which would make a downloadable text file. Otherwise I would have to keep going to the Inspect Element console to check for debugging info, which was very inconvenient.

Other Stuff

Views

This was also my first time implementing "View"s, allowing me to zoom in/out as well as to "follow"
the player. Surprisingly, it was not that difficult. I had a ProjectionScale multiply every speed variable and size variables, and as for the Viewport, I simply added two variables, scrollx and scrolly, to determine where in the screen to go to.

Here's a screenshot of a bug I thought was interesting early on in the development.

Code maintainability

I'm sure it's more of my less than impressive coding skills at fault, but I found difficulty in maintaining the code. In javascript, there are no "private" fields for classes (there are techniques to simulate this however, but I didn't implement that) making everything very cluttered.

Oh? There's something wrong with my m_collisionRect, let me add breakpoints to every place that is modified in Player.js.

"Two hours of debugging later.."

Oh! so I actually modified Player's collision rect in the GameplayScene file instead as a quick fix! Well... That's two hours of my life I'm never getting back.

In addition to that, being a C++ kinda guy, I felt very uncomfortable doing what I assume is copying everything whenever I pass it to a function instead of being able to pass it as a reference. I even miss having pointers!

In future, if I were to use Javascript for HTML5 games, I would firstly go to a good site to re-learn Javascript. Then I would ignore everything OOP and simply use vanilla Javascript, perhaps with the Phaser library. (Google it, I don't want to link.)

5 Steps to Polishing it

At some point in the future, I would polish up the code and then turn it into a real pacman game. Turning it into a real pacman game shouldn't be too difficult, just add the pellets and more ghosts enemies. Interestingly, the ghosts in the original Pacman had very specific characteristics. The red one would follow you directly behind, the pink one would try to cut off your paths by going in front of you. The orange one is stupid and moves randomly. Finally, the blue one would alternate between the other three. On top of all this, the ghosts would periodically all at the same time move to the four corners of the game.

Back to my tech demo thing,

First off, adding title screens and pause menus. This gives the first impression on the player instead of just launching them into a game.

Second, Animation, animation, animation. Moving objects are aesthetically pleasing for our eyes. Having a mostly stationary game like mine leads to boring visuals.

Third, Bright colours! Same idea as above. Makes it nicer to look at.

Fourth, smaller levels! While the one I did was okay for testing the pathfinding algorithm, smaller, nicely designed levels gives it a more "compact" feel as well as reducing the player's concentration on unnecessary lengths of tiles. This also everything to be a bit bigger, which is good because you don't have to squint your eyes.

Fifth, Music and SFX! An often underappreciated trait. The music needs to follow the mood of the game, and not be too short and repetitive. Appropriate sound effects are also very powerful in being more immersive. This is, besides the graphics, the main way of "rewarding"  the player for doing such actions such as collecting a pellet or defeating a ghost. The sound (and flashy colours) is what makes the experience all the more addictive!

Conclusion

Well, I can conclude I am very bad at coding efficiently and completing goals. My time management also needs improving, there was a time I forgot all about this project and only continued on it yesterday. But the important thing is I learned how to implement pathfinding algorithms and can concentrate more on the code design patterns next time instead of "quickly prototyping" the algorithm and making a mess of the code in the progress due to me having "temporary quick fixes" which then escalates to the universe blowing up. Okay, maybe not the universe, but the code base will definitely be messed up and if I didn't use a repository, I could lose weeks worth of code.

Also it's very important now I can brag tell people I know how pathfinding algorithms work and go into detail of the inner workings.

Thursday, 27 October 2016

10 ways to make boring articles fun!

Upon browsing Reddit, I found an interesting subreddit called SubredditSimulator. This subreddit consisted of bots which simulated redditors by collecting the data on various subreddits. The bots were powered by Markov chains , along with some other artificial intelligence algorithms for determining the topic. Naturally, I had to try implement this myself for fun.

Oh yeah, the topic is clickbait by the way, you won't be reading boring articles. You'll be making fun of them. Mocking them. Partronising them. Ha ha. Silly lil boring articles. (Don't you dare run the end program on this article. This article is fun.)

SubredditSimulator essentially is a smart Parody generator


"Parody generators are computer programs which generate text that is syntactically correct, but usually meaningless..."

What I created is closer to what is known as Disassociated Press.

"Dissociated press is a parody generator (a computer program that generates nonsensical text). The generated text is based on another text using the Markov chain technique." 


Additionally, for testing purposes, I decided to make it so that my program could also generate random names based on the same technique.

It is also interesting to note that this could possibly be used to generate plausible sounding text that could bypass spam filters.

To start with, I'd need a few things.
  1. Database of names OR and article
  2. A C++ compiler (C++ being my language of choice)
 My C++ compiler was MSVC's compiler. I got a database of common female American names from wikipedia, here.  As for the article, I got one about accounting from the New York Times website from July 2016.
PS: Don't click the link. If you click the link they'll be able to trace me down. Copy and paste it but DO NOT CLICK the link.

http://www.nytimes.com/2016/07/24/business/a-profit-bump-for-companies-and-tax-transparency-for-investors.html?rref=collection%2Ftimestopic%2FAccounting%20and%20Accountants&action=click&contentCollection=timestopics&region=stream&module=stream_unit&version=latest&contentPlacement=1&pgtype=collection&_r=0

Extremely boring, right? (So sorry editor of NYT if you're reading this D: , your articles are way better than mine)

Technical stuff

 Okay, okay, I know it'll be boring to some of you, but there's bound to be that one nerd who's into this kind of thing.
According to Wikipedia, "a process satisfies the Markov property if one can make predictions for the future of the process based solely on its present state". What does this mean? Well, it basically means that something has a Markov property if you can 'guess' what the next state will be.
Let's say that you have a list of names :-
  • James
  • John
  • Joseph
By looking at the data we can figure out that the letter 'J' is once followed by 'a' and twice followed by 'o'.  Thus, we can conclude that there is a 2 out of 3 chances of 'J' being followed by the letter 'o' and 1 out of 3 chances that 'J' is followed by the letter 'a'. The process then repeats itself ('a' is followed by 'm' 1 out of 1 times, so it is a 100% chance of being followed by m, etc.)

Current     Next    Occurrences          Chances
   J               a                1                  1/3 = 33.34%
   J               o                2                  2/3 = 66.64%
                               Sum = 3

Current     Next    Occurrences          Chances
   a               m                1                  1/1 = 100%
                               Sum = 1
...

While not entirely accurate, it could generate plausible sounding names.

Results

Here are some of my favourite unique names my program spewed out after eating up the common female names from Wikipedia.
  • Maletra
  • Parue
  • Tictinnda
  • Sucticicalerilliamintindonely
  • Mintiy
  • Chillla
  • Isa
  • Lula
  • Andia
  • Zophlamma
  • Eminarty
  • Dinaelie
And some sentences after processing the NYT article. Honestly, I can't even tell the difference
  • Utilities granted the options were Companies' tax benefit.
  • So to light by the world of being 40 percent, it anticipated; this tax rate may be under the balance sheet," he said.
  • The shift makes the costs and it has changed.
  • "Some companies now pay."
  • "Some companies are going to light by the fewest options," Equilar said.
  • Then you don't know about this proposal is what the greatest impact at far below their earnings.
  • Employee stock options at a company's net profits and are therefore rosier than they would add 20 cents a company's balance sheet," he said.
  • According to deduct from its financial statements made it in the company actually pays.
  • It simply shifts the change will give investors a company's financial filing indicates that is dull?
Well, that was a fun weekend project. If you're wondering where the program is, my code is crap and I'm too scared of being bullied by the elite coding gurus of the web for my bad practices. If I release my program without source code, then the elite coding gurus will bully me into releasing it. Maybe I'll send it for a code review and then release it or maybe I'll release it when I'm not feeling like a chicken. Peace out.
PS: If you liked my post, please leave me a comment, or share this post, or recommend it to Google. I would really really appreciate it! :)
And if you didn't like it.... Send me a comment! I will definitely listen to your feedback! :)