Pairing multiple images in javascript (with multiple options for each) - javascript

Edit: Since I'm just planning my approach to the project, I have no code to show for it. My question is more about how i could approach the problem (arrays, objects or if there are smarter ways to do it) than about the actual code. Since I'm pretty new Im looking for a "way in" how I could tackle the project and look at tutorials.
(Since I'm pretty new to coding I'm trying to solidify the basics of html/css/js by building my own projects. With this project my problem is finding my way in, since I struggle with finding the correct mechanics, so I cant find any tutorials because i dont know where to start)
The project
I'm trying to build a project which pairs 3 images ("background", "base" and "addition"), starting from one which is selected.
For example: I'm selecting in image with the "background" woods and it will pair it with a small river as "base" and foxes as "addition".
If the user doesn't like the pairing, he can click a btn and it will pair the same selected image (in this case the wood) with other two compatible images (for example: a mossy stone and squirrels).
However: it wouldn pair my selected image, which in this case is a wood with a desert floor and dolphins.
The user also could start by selecting a "addition", for example a crab, which will be paired with a beach and smaller pebbles.
The problem
I'm pretty sure that the main focus with this project should be on arrays.
I thought i could do 3 arrays (one for the background, one for the base and one for the addition) and from there just pair random values from the different arrays. However, should i make 3 arrays for every probability or is there a way I could filter the pairs I want and the pairs i dont want?
An other approach i thought of was to let every image in the array be an object, so that i can assign attributes (for example: climate, color, sea level..) to the objects and filter them based on that.
In this case however I'm struggling with the code to first filter the correct pairings and then select a random pairing from those which were selected.
Every bit of help is appreciated,
thank you!

Related

Managing and searching through millions of integers/coordinates in Javascript

I have an array of RGB value integers/whole numbers, ranging from 0 to 255. Eight Different lists.
For example one list has 8,349,042 values in it. OR 2,783,014 RGB sets of three.
The core objective is the user selects a pixel in an image.
That pixel's (R,G,B) value is grabbed and searched for within these lists. It exists in one of these lists, as all the lists together contain all the possible RGB combinations (16,777,216)
I'm trying to figure out what's the best way to store and search through these values.
again: these values don't change, they are hard coded lists(see Bullet Point below), with a known range.
The search query would be at minimum 3 times every event which would be every 10-30 seconds or so if the user was spamming.
OR Best case scenario, if the storage and search technique is fast enough I would like to: run the search on every pixel in an image (of maybe 800 x 600 or smaller resolutions) to have more data to play with. If I run into any memory limitations, I plan to work with it and use it as restrictions for my game design.
I used Javascript to generate these lists, going through and assigning each value based on how close it was to a base color.
[maybe unimportant how I made these lists]
I first assigned black and white RGB lists based on hard numeric limitations, then the rest of the RGB values were looped through and assigned to their closest base colors, red, yellow, cyan, green, blue and magenta. If there was a tie in distance I gave it to currently shortest list to try to keep it somewhat balanced. I may try to optimize this later and generate a new list, but not during runtime, just raw data.
I saved the results in hard text, and they are currently stored as a text that I can dump into large array.
At first I was trying to store the data as a JSON file along with my scripts. But I struggled to read the data and save it to an array. I ran into issues with using fetch and async and not being able to have the array where I needed it. Testing with console.log(arr) and getting undefined. I'm guessing because it wasn't loaded yet.
I can just paste it hard coded into the array but it's ginormous and I know there has to be a better way.
Also, hearing about differences in arrays vs sets vs objects
and different searching techniques within them.
Most of them seemed to be more tactful for multi variable arrays like name and age and location databases.
Since my data is all numeric I was thinking it could be a more bit/byte based approach?
I was reading some things on trees and hashs, bit crunching encryption?
Trees seemed nice for quicker searching as I could try to assign each branch of the tree to each R, G and B of the value, but I would also need to figure out how to convert my Giant single list of numbers into that, it also could be just the search type and that may depend on how I store the data.
I also struggled to understand the difference between front end and back end. I believe everything I've tried would be considered front end as I'm only testing my code in a browser.
I was pointed towards Node for backend but got lost in trying to get the console to run things.
I'm willing to give any of these things a try but I don't want to go down a path and find out it can't do what I want, or not optimally enough, like a server burden, or user burden with waiting too long or unable to do things because of user data security, requiring the user to do something more than just load the game, permissives wise.
SO I'm hoping someone can give me suggestions on what I should pursue so I can knuckle down and have a better focus on what I need to learn to be well versed and best tackle problem.
EDIT: Simplified question: In Javascript, I have an array of 2 million (x,y,z) numbers. What's the best way to search that array for a specific (x,y,z) value?
Would it be better to store the data in a different format than an array for constant searches?
I'm not certain I've understood the overall goal here but have a suggestion to consider if you are trying to assign a predetermined value to some (almost random as it is picked as a pixel colour from an image) rgb number set.
I assume the list/dictionary you have made allocates some value to each rgb number set and that it can be regenerated or reformatted if needed.
There are a maximum of 16,777,216 rgba values (256^3). Javascript arrays can have up to 2^32-2 (almost 4.3 billion) elements. Therefore the suggestion is to reformat your dictionary to be a 3-dimensional array where each dimension is indexed 0-255. The array can be declared and assigned as an array literal in a regular js script (text file) like colourDictionary= [[[val0]..[val255]]..[[]..[]],...[[val0]..[val255]]..[[]..[]]]; and each value accessed arithmetically in constant time using the pixel values as colourDictionary[r][g][b]
To be useful without writing lines to cater for missing values, your gaps (you mention a list of 8,349,042, around half the available number combinations) could be filled with the values of nearest neighbours.
Apologies if I've missed the point.

Poker hand generator and evaluator

I'm sure this topic has been covered to bits, but I've spent hours trying to work something out and I can't find enough resources that explain the process. Please note, I am new to JS and still relying on tutorials and code snippets to write code. I'm still not confident enough to write code from complete scratch.
THE GOAL:
In JavaScript, 'draw' 5 random cards
Evaluate the cards' rank among all possible hands
Return a score from a Variable min/max, based on the rank of the card, unless it's less than a pair.
Lastly, be able to draw a RANDOM hand based on rank (less than, more than, or exactly) EG. Return a hand that is of rank 100 or smaller. (could bring back 100 different hands)
Eg. While Min-Max score is 10-30. If a royal flush comes out, return 30 (best hand means best score). If low Two Pair (6H 6D 2C 2H 5S) comes out return 13. If high Two Pair (AH AD QC QH 5S), return 14. Etc.
[Those are probably not accurate scores but you get the drift]
My Research results:
Random Draw: Many applications have achieved this. My favorite so far has been this tutorial:
http://www.informit.com/library/content.aspx?b=STY_JavaScript_24_hours&seqNum=229
it is quite simple and gets the result, however does not offer a full evaluation, only by category (pair, two pair, three of a kind etc). I need an evaluation that would be able to give a higher score to the superior of two hand that have two pairs.
Evaluators: This got a bit confusing. I found a very basic evaluator, that uses javascript: http://jsfiddle.net/subskybox/r4mSF/ but it was too basic. Doesn't give me a complete rank. I found this one too: https://github.com/chenosaurus/poker-evaluator which uses the Two Plus Two algorithm and a lookup table. Now, it sounds really good, but I'm terribly confused as to how to install it on into my website, or how to use it. It says: to install: npm install poker-evaluator, which I never heard of before.
Convert rating to score: Should be fairly easy maths. Perhaps: thisRank/maxRank*(MaxScore-MinScore)+MinScore
Draw hand by rank: Haven't seen any way of doing this anywhere. Wouldn't mind seeing some examples or ideas. I'm not sure this can be done with the Two Plus Two poker-evaluator. It's more like the reverse process.
Now, it feels like I'm getting close with all this, but I'm not a 100% sure how to compile this completely. I feel like I could use the code I found in section 1, and the Two Plus Two poker-evaluator to achieve what I need. I would love to it if you could shed a light on the 'npm install', if I'm going in the right direction, or if you know other methods I could achieve the same thing.
Please don't tell me I have to try doing it myself first, because I really don't know how to do this from scratch without a little guidance.
I will post another beginner's advice :
Write the algorithm of what you want to achieve in pseudo-code (e.g., words that are easy for you to read). If the algorithm is not clear in your head before you start coding it is not going to get clearer by itself. You are not able to write code : it is fine; you hope to write a program without having a detailed low-level vision of every one of its steps : it is not. At least that is how I see things.
Example of pseudo-code that I would write for this case:
1-
create card deck
loop on number of cards to be drawn
-generate random integer and remove corresponding card from card deck
-add drawn card to hand
end loop
2-
check if hand is highest figure and associate rating
else check if hand is 2nd highest and associate rating
else...
OR
get data with all possible hands and search for this hand to retrieve score...
(see github repo)
3-
I did not get 3-
4- If you have data with all hands and their value, you just have
to search this data by value instead of searching by hand like in 2-
Second, looking for code snippets on github is a good idea; read the javascript files in the projects which interest you and understand what they do. I think you will need to install node.js for that particular project, because it is used to import the lookup table. Just download the javascript files and include them in your project...do not forget to credit/thank the author.
Third, your question is not about a precise difficulty : it is a question about how to start programming stuff when you never did it before. I do not think stackoverflow is the right place for this, but I still answered your question because after all, this is also a help forum. My last advice would be to find a good book / tutorial; in every good book there is a sample project to follow in which you develop a complete program and will teach you the basics.
P.S.: if you are really interested, don't give up because programming can be hard but it is also very rewarding to see stuff work...

Sorting a list without a counter

This is currently just conseptual, but it bothers my brain.
If I have a list of items - in my mind it's a HTML/JS implementation, but that's just because I'm a visual thinker ;)
I want to use drag and drop to sort this list, with the aim of storing the new order when I'm done. Is there a way to do this without numbering the items, and then updating the number of the dropped item + every single item that follows it? Isn't that very inefficient?
As far as performance goes, changing the numbering of the elements is nothing next to actually rendering the transition (while you're dragging an element), so no, it's not inefficient.
You can use a doubly linked list in order to minmize the amount of operations needed to change the order of the collection.
I would recommend using a JavaScript framework to do the job.
KnockoutJS should fit your needs (from the website):
Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.
If you left gaps in the numbers, you could probably do it efficiently -- for instance, let the first element be 10, the second be 20, the third 30, etc. Then when you drag something in front of the second one and after the first, call it 15 (or something).
Rather than incrementing numbers every time, you'd only have to do it if you ran out of space. At the end, you could just order the objects by lowest number.
Not including any code here, because this is a conceptual question.
You have to have a number for every element in the list anyway, since they have to have a Total Ordering among themselves to be represented as a list.
If you don't expect the number of elements in the list to be large, a Bubble Sort should work very well for you.

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/

Can anyone recommend a well performing interface to allow the user to organize a large number of items in HTML?

Currently for "group" management you can click the name of the group in a list of available groups and it will take you to a page with two side by side multi-select list boxes. Between the two list boxes are Add and Remove buttons. You select all the "users" from the left list and click 'Add' and they will appear in the right list, and vice versa. This works fairly well for a small amount of data.
The problem lies when you start having thousands of users. Not only is it difficult and time consuming to search through (despite having a 'filter' at the top that will narrow results based on a string), but you will eventually reach a point where your computer's power and the number of list items apex and the whole browser starts to lag horrendously.
Is there a better interface idea for managing this? Or are there any well known tricks to make it perform better and/or be easier to use when there are many 'items' in the lists?
Implement an Ajax function that hooks on keydown and checks the characters the user has typed into the search/filter box so far (server-side). When the search results drop below 50, push those to the browser for display.
Alternatively, you can use a jQuery UI Autocomplete plugin, and set the minimum number of characters to 3 to trigger the search. This will limit the number of list items that are pushed to the browser.
I would get away from using the native list box in your browser and implement a solution in HTML/CSS using lists or tables (depending on your needs). Then you can use JavaScript and AJAX to pull only the subset of data you need. Watch the user's actions and pull the next 50 records before they actually get to them. That will give the illusion of all of the records being loaded at runtime.
The iPhone does this kind of thing to preserve memory for it's TableViews. I would take that idea and apply it to your case.
I'd say you hit the nail on the head with the word 'filter'. I'm not the hugest fan of parallel multi-selects like what you are describing, but that is almost beside the point, whatever UX element you use, you are going to run into a problem given thousands of items. Thus, filtering. Filtering with a search string is a fine solution, but I suspect searching by name is not the fastest way to get to the users that the admin here wants. What else do you know about the users? How are they grouped.
For example, if these users were students at a highschool, we would know some meta-data about them: What grade are they in? How old are they? What stream of studies are they in? What is their GPA? ... providing filtering on these pieces of metadata is one way of limiting the number of students available at a time. If you have too many to start with, and it is causing performance problems, consider just limiting them, have a button to load more, and only show 100 at a time.
Update: the last point here is essentially what Jesse is proposing below.

Categories