Using OOP to reduce code and make it reusable - javascript

I am creating an application and I have a question about the way in which I go about making it.
You will be able to choose a number which determines the passage of time in minutes for two identical circles. (Separate buttons are created for incrementing and decrementing time for each circle)
As the time passes, the first circle fills up until the countdown for the first circle reaches 0 minutes.
Now a second identical circle will start the countdown and to fill up also based on the initial time you had given to it.
I have linked all the appropriate DOM elements(the circle, the buttons for incrementing/decrementing time) to the functions and event handlers written for the first circle and it runs perfectly. The second circle is essentially the exact same thing, except that it has a different button element for it's events and of course it is a different circle.
If I copy and paste all my code and just change the variables and function names associated with circle 1 to new ones for circle 2 it would work perfectly. That seems very repetitive and I'm sure there is a better way to go about this.
What comes to my mind is OOP. So instead of saying circle1 OR circle2 should fill up when I press this button, I can just say THIS circle fills up, when I press THIS button associated with each circle. Am I right in my thinking ? Is OOP the answer to my question here?

If you can get it to work with code duplication, that's a great start. What you have to do then is called refactoring:
Look for parts of the code which are exactly repeated, and if possible extract them into one function.
Then look for the parts of the code where you are doing things like var1 and var2, and think about ways to abstract that repetition in either a loop over an array, a generator function, or OOP class & instance patterns.
As you go along you will notice that your code will be functionally the same, but much easier to reason about and read.
Also don't be afraid of re-starting from a blank file!

Related

Routing algorithm for drawing non-intersecting lines

I'm working on a flowchart system in JS, that allows the user to click on one element followed by another, and the program inserts an arrow connecting them. For this, I need a line-drawing algorithm which meets the following criteria:
Only straight lines/90deg turns
Guaranteed to take an efficient route, such that...
... it can take into consideration other lines (as it cannot intersect) - e.g, if I insert one line, and then another, it is able to draw the second without having to rearrange the first, or take a wildly inefficient route to get to its destination to avoid the first line.
If you know any algorithms which fit the bill (I've only found ones that match just one or at most two of the criteria), I'd be interested; also, if there's a JS implementation I can steal then please link that too.
Some notes:
Time complexity does not matter, as long as the result is aesthetically pleasant
There can be multiple lines originating from or entering one element. This is to allow for loopbacks/subroutines.
Lines can go on top of each other, just not perpendicularly across one another.
Examples:
image 1
I click on one element...
image 2
... and then on another, which then inserts the arrow between them.
image 3
If I continue this, I expect to get a linear sequence, with the arrows inserted automagically.
image 4
Alternatively, I can make use of multiple inputs/outputs to get a more closed chart, generating a more complex result.
image 5
I should be able to do this in any order to get the same result.

Animation of features in OpenLayers3

I was curious about the possibilities of animating features in OpenLayers3.
I'm very aware of the examples presented here
http://openlayers.org/en/v3.0.0/examples/animation.html and here
https://gis.stackexchange.com/questions/26546/openlayers-animation-examples-and-algorithms
However, the official examples for OL3 don't quite fit my needs.
Let's assume that I have a layer (geojson for instance) that has a "time" column with lots and lots of time values.
I'd like to implement something like a slider that adds/removes features (or changes their style) depending on the user's actions.
The thing is that there are some APIs that might be able to do that, but they seem to be outdated (code examples were still working with ol2).
Do you have any suggestions on how to build a simple animation slider with OL3?
EDIT: It doesn't necessarily have to be proper animation. A possibility that came to my mind is changing the style of a layer whenever the slider is moved. Still no clue though on how to realise that.
This image illustrates what I have in mind:
EDIT: My current approach is to have a slider, that triggers code everytime it is moved. I somehow try do change the layer style dynamically, but I still haven't gotten a viable result.
Ok. I've come up with a solution myself. It's not really a full-fledged animation, but it works for me.
Basically what I do is that I load a wfs-layer to my map.
Now, here is the trick:
When I do that, I simply sort the time-values of the features one by one and add every feature with the time value of 1 to one layer, every feature with a time value of 2 to another and so and so forth.
This basically does the trick. The rest is simple.
Next step is that I implement a slider that ranges from 1 (the lowest time value) to whatever the highest time value is. Everytime the slider is moved it triggers an event that finds out to which time value the slider is set to and then adds/removes the corresponding layers.
So, if the slider is set to 5. It will add every layer from 1 to 5 to the map and remove every other layer. Again, this is not really an animation, but it does work in my case.
If anyone comes up with another possible solution, please post it here. I'd appreciate it.
(Btw, this is what my solution looks like in action:)
EDIT: I can now also confirm that it is possible to build "proper" animations with this approach. I simply built a js-function that includes multiple "setTimeout"s to time when a layer is added and added a play button that triggers this function. This amounts to an animation that visualises the growth from t=1 to tmax.

Board game in javascript, sync questions card

I'm developing a board game in javascript and I'm almost solved all conditionals and iterations but I still have one problem: it's a game in which you roll the dice and then your pawn moves, and when your pawn reaches certain place on the board, it's supposed to show up a card with questions.
That card is actually a html div, and I just hide and show it by using a .css file.
The thing is, it's "firing" just after I roll the dice, and I can't figure out how to syncronize it with the pawn movements, in order to make it show up when the pawn actually reaches that board section.
The pawn is just an image, and I'm "calling" it using jQuery like this: $("#bluePawn") and then I use an animate function in javascript to make it "move" over the board.
That function receives 4 parameters, which are: the DOM object to move (the pawn as I've referred to before), the pawn's current position on the board, how many spaces to move, and a true/false flag.
I hope this can be more illustrative if I show you the piece of code that issues the movement.
The places where the pawns can be placed and over which they can move, are "marked" on the board with pixel coordinates, included in an associative array
I tried to include an example code but wasn't able to indent it properly.
If you know how long it will take the guy to move you can use setTimeout() to wait the proper length before triggering the card (or a jQuery animate delay.
If you don't know the exact time it will take you should look into callback functions. Trigger the function to show the card (by removing or hiding a css class) AFTER you move the pawns.
This is a generic answer to a generic question without code :)

HTML5 Canvas game has bug where first puzzle piece changes to a different piece when clicked on?

I think I just need a fresh set of eyes on this game I'm working on.
It's a sliding image puzzle (where you split an image into pieces and display them back in a random order, I then remove a single piece of the puzzle and the user has to click on each puzzle piece to move it around and thus put the image back together)
The full code is here: https://github.com/Integralist/HTML5-Image-Slider-Game
The bug I'm having is on the first puzzle piece you move, if you click it again - when it moves back to the position it just came from - the puzzle piece changes to a different piece (in one instance I noticed that it was changing to the puzzle piece that is removed to initiate the game, but that might just be coincidence).
At first I thought the issue was with the setInterval method which is asynchronous (I was thinking that because I'm inside a loop maybe the reference loop iteration was getting messed up, but I'm now passing in the relevant iteration into the setInterval and the issue still occurs so it can't be that).
UPDATE:
I still think the problem is something to do with the setInterval. The main issue is when we start drawing the image onto the canvas the original x/y co-ordinates obviously have changed from what we expect them to be. I've noticed that the object which holds the co-ordinates for the puzzle piece we want to move is incorrect when we click on the same puzzle piece to move it back into the position it was just in. I noticed the drawnOnCanvasX/Y properties are different to what they should be, and that they now match the x/y co-ordinates of the empty_space variable? The fact that this doesn't happen all the time makes me think that the setInterval is not passing through the correct object from the loop into the function that executes on the interval?
Any help appreciated.
The problem was because I hadn't removed a particular item from the randomised Array.
For the game to work I needed to remove 1 puzzle piece, this allows the other pieces to have a space they can be moved into. Problem was that I had clearRect the piece I wanted but not actually removed it from the Array. So when I was looping through to find an item in the Array that had those exact X/Y co-ordinates it was finding the puzzle piece item that should have been removed (and because the piece that is removed is chosen randomly that's why sometimes that piece would be found via the loop first, and other times the correct piece would be found).
Christ that was painful.

Dynamically creating objects and clicking one of the objects

I asked another version of this question on the gamedev.SE site earlier today but figured I could get better answers here. Also reformulated the question some. I hope this is okay couldn't find anything prohibiting it in the FAQ
I'm playing around with making a puzzle game, haven't done that much before I run into my first problem.
Question a) Basically, I want to create a certain amount of the same object/function (a ball). But the objects will be created dynamically (since the amount of balls could range from 3 to 25), preferably with a for loop pushing the different balls to an array.
However I'm not experienced enough to figure out a good way to do this.
Also, once I have my array of balls on the canvas, I want to be able to select one of the balls.
Question b) How do I know/determine which ball in the array was clicked?
Is a simple for loop enough and accessing the objects with [i]?
I made a jsFiddle example of what I want with 1 ball (you need to click the orange ball to select, then you can move it around by clicking anywhere on the canvas).
This is what I want to do, but with more balls, and the amount of balls is not specified (deciding the amount part i got covered). How could I solve this in a easy way?
Help appreciated.
Using a for loop is fine for your object generation.
As for detecting when you click an object in the canvas, this tutorial might help. It appears there is no built-in feature for tracking objects in your canvas - you simply do manual hit detection based on the common pixels under your mouse and object
Hope that helps
Paper.js has great DOM model, and out of the box ability to click and select items
http://paperjs.org/tutorials/project-items/transforming-items/
hit testing:
http://paperjs.org/examples/hit-testing/

Categories