Poker hand generator and evaluator - javascript

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...

Related

AI bot for a simple game

There is a relatively simple game with such rules:
There is a safe which needs to be unlocked.
Code to the safe is a 4 digits number without repetitions(1234, 4867, 1092, etc., code like 1231 isn't possible in this game).
The game gives 5 attempts to guess the right code.
Let's say I start a new game and on the first try I test code like 0123.
The game responds with 2-1. 2 means that code 0123 has 2 right numbers which I need to use in the final unlock code. 1 means that one of those 2 numbers is at the correct position already.
After this I have 4 more exact same steps where I try different codes based on the previous tested numbers and responses from the game.
The goal is to get final code, let's say 9135(based on the prev 0123 try) and response from the game needs to be 4-4(4 right numbers, 4 in place). The earlier it happens - better.
I know that this can be solved using combinatorics just by excluding some combinations but I don't know how to choose the most weighted combination for the next try and hope AI can do it better.
I'm a frontend developer and an absolute beginner in AI. I don't really understand how complex code will be to solve this problem and what effort it requires. I will really appreciate if you can explain to me and share some links/code examples(lang doesn't matter but would be good if it is JS or Python) of similar solved tasks, so I can solve my problem based on this.
Feel free to tell me if my explanation wasn't clear, I will try more simple words then:)
Thanks!
Your game sounds similar to Mastermind, only with numbers instead of colored pegs.
Googling "Mastermind AI" leads to e.g. this implementation using a genetic algorithm to solve Mastermind, which you could probably look at for inspiration.
While #AKX is correct that this is a variant of Mastermind, a genetic algorithm might not be the first place to look, as this is probably more complex that simpler approaches.
Donald Knuth is famous (among many other things) for working out a solution to the game. There is a good overview of this approach on the Puzzling Stack Exchange site, and if you look at the other answers on that question, there is also a discussion of how to code the solution.
In your case, the simple approach is to write a function that iterates from 0000 to 9999. These are all potential answers. But, when you iterate through the numbers you want to remove (1) all numbers with duplicate digits and (2) all numbers that are inconsistent with the guesses so far. Any other numbers can be put in an array or list storing potential answers. From these remaining numbers, you can just guess any number and then continue the process.
A more complicated approach would be to make the next guess using an algorithm similar to ID3 to try to find the guess that maximizes the information gain you get from the response. But, given how much information you get from each guess, this is unlikely to be needed.

Slot machine Random generator

so i saw this: https://www.quora.com/What-algorithm-do-slot-machines-use
How is acually these random numbers generated, and how are the acually translated further on?
i was planning to make a basic slot machine, but no idea where to start.
Well, i had an idea to use something like:
$randomNumber1 = rand(1,X);
for each slot, but that dont seem very effective,
How would i solve this?
By the way, here is one image from the link above, that conserns my issue.
edit: Would it be the same style functionality with a slot machine with 3x3 instead of 1x3 lines?
It depends on how realistic you want the slot machine to be. If you just want it to randomly pay out, then a simple r = rand(1,X) is fine. That's a good way to start because you can then prove that the mechanics of your game work: all the graphics and animations display correctly, the user interface controls work as expected, etc.
But a real slot machine doesn't just randomly display every possible combination. For example, if three sevens pays out more often than three cherries, then the slot machine is designed to show the three sevens much less frequently. After all, the goal of the slot machine is for the house to make money.
The math behind slot machines is quite involved: much too involved for a Stack Overflow answer. How you generate the random numbers, assuming you get a uniform distribution, is not a major concern compared to setting up your wheels to give a consistent payout.
My suggestion is that you use your built-in random number generator until you get your game working. Then, if you want it to work more like a real slot machine, type "slot machine math" into your favorite search engine, and start studying.
I would use the old tried-and-true Fisher-Yates shuffle algorithm for this. This question has a JavaScript implementation, and it can be used for slots like so:
let slotOptions = ["cherry", "seven", "bell", "bar"];
function play() {
return [shuffle(slotOptions), shuffle(slotOptions), shuffle(slotOptions)];
}
let [slot1, slot2, slot3] = play();
// do something with those slots here

How to create a dynamic graph for websites?

Hello,
I'm relatively new to the programming world and I was wondering how I would go about creating the following for a website I'm designing. I will use a random example as to not give my application away, but the process should be the same. I apologize ahead of time for the unrealistic values:
Say a civil engineer wants to come onto my website and figure out the mechanical stress at certain points on the Eiffel tower, lets say on the corner of the first/second observation deck (see Image). To make this more general, they want to vary values such as the height and base width of the tower to see how that affects the mechanical stress at those points.
Now, I can make the algorithm for calculating those stress values. My question is, how would a programmer go about creating this dynamic figure, such that the 'stress values' are shown on the image at distinct locations, and they change based off of the values of the user inputs + algorithm? My thoughts are the following:
Use HTML/CSS to place the images and design the webpage
Use JavaScript to take inputs, run the algorithm and calculate outputs. This would also make the dynamic changes on the image.
I have zero experience with JavaScript (I'm okay with HTML/CSS as I have built my own website before). I guess I'm hoping to be pointed in the right direction before I go off and start learning the wrong language for this application.
Bonus Challenge
While they're doing this, it would be nice to see a visual representation of the Eiffel tower change when the height and base area are changed. ie if you make the base way wider and the height much shorter, the bending in the midsection is going to be much more apparent. Obviously, this means I wouldn't be using a picture, but actually a vector-image model of the Eiffel tower that would change based off of the inputs. So what language and what libraries would one use to go about making this sort of things?
Thank you to anyone that can provide some insight on my issue. I really appreciate it!
Mike
Hello to integrate dynamic graph in a webpage there are two ways;
First you need to make your own graph library. For that you need to know SVG well to make a good looking graph.
Second, you can use any existing library. There are lot of open source libraries are there some of them are free to use also. To integrate graph using those libraries is not much difficult.
Some examples of graph generating library morris chart, c3.js etc. Google search 'll give you more detail idea.
As you said you have no idea about javascript so it will be a bit difficult at first for integrating graph. But 'll definitely much more easy to make your own graph library.

Grade Sudoku difficulty level

I am building a Sudoku game for fun, written in Javascript.
Everything works fine, board is generated completely with a single solution each time.
My only problem is, and this is what's keeping me from having my project released to public
is that I don't know how to grade my boards for difficulty levels. I've looked EVERYWHERE,
posted on forums, etc. I don't want to write the algorithms myself, thats not the point of this
project,and beside, they are too complex for me, as i am no mathematician.
The only thing i came close to was is this website that does grading via JSbut the problem is, the code is written in such a lousy undocumented, very ad-hoc manner,therefor cannot be borrowed...
I'll come to the point -Can anyone please point me to a place which offers a source code for Sudoku grading/rating?
Thanks
Update 22.6.11:
This is my Sudoku game, and I've implemented my own grading system which relies
on basic human logic solving techniques, so check it out.
I have considered this problem myself and the best I can do is to decide how difficult the puzzle is to solve by actually solving it and analyzing the game tree.
Initially:
Implement your solver using "human rules", not with algorithms unlikely to be used by human players. (An interesting problem in its own right.) Score each logical rule in your solver according to its difficulty for humans to use. Use values in the hundreds or larger so you have freedom to adjust the scores relative to each other.
Solve the puzzle. At each position:
Enumerate all new cells which can be logically deduced at the current game position.
The score of each deduction (completely solving one cell) is the score of the easiest rule that suffices to make that deduction.
EDIT: If more than one rule must be applied together, or one rule multiple times, to make a single deduction, track it as a single "compound" rule application. To score a compound, maybe use the minimum number of individual rule applications to solve a cell times the sum of the scores of each. (Considerably more mental effort is required for such deductions.) Calculating that minimum number of applications could be a CPU-intensive effort depending on your rules set. Any rule application that completely solves one or more cells should be rolled back before continuing to explore the position.
Exclude all deductions with a score higher than the minimum among all deductions. (The logic here is that the player will not perceive the harder ones, having perceived an easier one and taken it; and also, this promises to prune a lot of computation out of the decision process.)
The minimum score at the current position, divided by the number of "easiest" deductions (if many exist, finding one is easier) is the difficulty of that position. So if rule A is the easiest applicable rule with score 20 and can be applied in 4 cells, the position has score 5.
Choose one of the "easiest" deductions at random as your play and advance to the next game position. I suggest retaining only completely solved cells for the next position, passing no other state. This is wasteful of CPU of course, repeating computations already done, but the goal is to simulate human play.
The puzzle's overall difficulty is the sum of the scores of the positions in your path through the game tree.
EDIT: Alternative position score: Instead of completely excluding deductions using harder rules, calculate overall difficulty of each rule (or compound application) and choose the minimum. (The logic here is that if rule A has score 50 and rule B has score 400, and rule A can be applied in one cell but rule B can be applied in ten, then the position score is 40 because the player is more likely to spot one of the ten harder plays than the single easier one. But this would require you to compute all possibilities.)
EDIT: Alternative suggested by Briguy37: Include all deductions in the position score. Score each position as 1 / (1/d1 + 1/d2 + ...) where d1, d2, etc. are the individual deductions. (This basically computes "resistance to making any deduction" at a position given individual "deduction resistances" d1, d2, etc. But this would require you to compute all possibilities.)
Hopefully this scoring strategy will produce a metric for puzzles that increases as your subjective appraisal of difficulty increases. If it does not, then adjusting the scores of your rules (or your choice of heuristic from the above options) may achieve the desired correlation. Once you have achieved a consistent correlation between score and subjective experience, you should be able to judge what the numeric thresholds of "easy", "hard", etc. should be. And then you're done!
Donald Knuth studied the problem and came up with the Dancing Links algorithm for solving sudoku, and then rating the difficulty of them.
Google around, there are several implementations of the Dancing Links engine.
Perhaps you could grade the general "constrainedness" of a puzzle? Consider that a new puzzle (with only hints) might have a certain number of cells which can be determined simply by eliminating the values which it cannot contain. We could say these cells are "constrained" to a smaller number of possible values than the typical cell and the more highly constrained cells that exist the more progress one can make on the puzzle without guessing. (Here we consider the requirement for "guessing" to be what makes a puzzle hard.)
At some point, however, the player must start guessing and, again, the constrainedness of a cell is important because with fewer values to choose between for a given cell the easier it is to find the correct value (and increase the constrainedness of other cells).
Of course, I don't actually play Sudoku (I just enjoy writing games and solvers for it), so I have no idea if this is a valid metric, just thinking out loud =)
I have a simple solver that looks for only unique possibilities in rows, columns and squares. When it has solved the few cells solvable by this method, it then picks a remaining candidate tries it and sees if the simple solver then leads to either a solution or a cell empty of possibilities. In the first case the puzzle is solved, in the second, one possibility has shown to be infeasible and thus eliminated. In the third case, which leads to neither a final solution nor an infeasibility, no
deduction can be reached.
The primary result of cycling through this procedure is to eliminate possiblities until picking
a correct cell entry leads to a solution. So far this procedure has solved even the hardest
puzzles without fail. It solves without difficulty puzzles with multiple solutions. If the
trial candidates are picked a random, it will generate all possilbe solutions.
I then generate a difficulty for the puzzle based on the number of illegal candidates that must
be eliminated before the simple solver can find a solution.
I know that this is like guessing, but if simple logic can eliminated a possible candidate, then one
is closer to the final solution.
Mike
I've done this in the past.
The key is that you have to figure out which rules to use from a human logic perspective. The example you provide details a number of different human logic patterns as a list on the right-risde.
You actually need to solve the puzzle using these rules instead of computer rules (which can solve it in milliseconds using simple pattern replacement). Every time you change the board, you can start over from the 'easiest' pattern (say, single open boxes in a cell or row), and move down the chain until you find one the next logical 'rule' to use.
When scoring the sodoku, each methodology is assigned some point value, which you would add up for every field you needed to fill out. While 'single empty cell' might get a 0, 'XY Chain' might get 100. You tabulate all of the methods needed (and frequency) and you wind up with a final weighting. There are plenty of places that list expected values for those weightings, but they are all fairly empirical. You're trying to model human logic, so feel free to come up with your own weightings or enhance the system (if you really only use XY chains, the puzzle is probably easier than if it requires more advanced mechanisms).
You may also find that even though you have a unique sodoku, that it is unsolvable through human logic.
And also note that this is all far more CPU intensive than solving it in a standard, patterned way. Some years ago when I wrote my code, it was taking multiple (I forget exactly, but maybe even up to 15) seconds to solve some of the generated puzzles I'd created.
Assuming difficulty is directly proportional to the time it takes a user to solve the puzzle, here is an Artificially Intelligent solution that approaches the results of the ideal algorithm over time.
Randomly generate a fixed number of starting puzzle layouts, say 100.
Initially, offer a random difficulty section that let's a user play random puzzles from the available layouts.
Keep an average random solution time for each user. I would probably make a top 10/top X leaderboard for this to generate interest in playing random puzzles.
Keep an average solution time multiplier for each puzzle solution (if the user normally solves the puzzle in 5 minutes and solves it in 20 minutes, 4 should be figured in to the puzzles average solution time multiplier)
Once a puzzle has been played enough times to get a base difficulty for the puzzle, say 5 times, add that puzzle to your list of rated puzzles and add another randomly generated puzzle to your available puzzle layouts.
Note: You should keep the first puzzle in your random puzzles list so that you can get better and better statistics on it.
Once you have enough base-rated puzzles, say 50, allow users to access the "Rated Difficulty" portion of your application. The difficulty for each puzzle will be the average time multiplier for that puzzle.
Note: When users choose to play puzzles with rated difficulty, this should NOT affect the average random solution time or average solution time multiplier, unless you want to get into calculating weighted averages (otherwise if a user plays a lot of harder puzzles, their average time and time multipliers will be skewed).
Using the method above, a solution would be rated from 0 (already solved/no time to solve) to 1 (users will probably solve this puzzle in their average time) to 2 (users will probably take twice as long to solve this puzzle than their average time) to infinity (users will take forever to find a solution to this puzzle).

Jquery append using multiline

I have been working on a project that dynamically creates a javascript file using ASP.NET which is called from another site.
This jquery javascript file appends a div and fills it with a rather large HTML segment and in order to do that I need to turn the segment into a string like so:
$(document).ready(function(){
var html = "Giving this magazine such a lofty epithet may seem a bit presumptuous, but for a non scientifically trained outsider this magazine offers a fresh and challenging look at the fast paced world of science that doesn't shy away from humor and the use of terms and ideas that may require its readers to go online and define a term. And in some cases it may inspire the reader to pick up a book on science by such greats as Hawking and Greene in order to better grasp some of the concepts dealing with time, space and atoms. This magazine isn't dumbed down. It includes well placed and efficient illustrations to help explain some of the more abstract points. It is not designed in the way popular magazinea are, in so much as they only touch upon a topic in the simplest manner and then move on before the audience is lost. Yet this magazine keeps the attention of the reader by combining explanatory notes that help people with no background knowledge have some grasp of the topic and by using humor and well written articles to clearly make their points. <br />For a magazine with a serious and well researched list of topics having small cartoons the likes of the New Yorker shows how comfortable this magazine is with itself. From the moment I picked up this magazine for the first time I felt like every word I read mattered and was worth my time to read. (Not true of many other magazines) American Scientist may not have the audience of Discover or National Geographic, nor is it as accessible as said titles, but for those with a true interest in science willing to challenge themselves and commit to real learning this magazine may be a perfect fit. At $4.95 it is certainly worth it to pick a copy on the news stand and try it out."
$("#divname").append(html);
});
As you can see the segment will be pretty large and I have no way of knowing how big as it is generated dynamically from my database depending on the reviewID which is defined by the user in their request.
The html to be inserted into the div is a list of reviews and is generated using asp.net MVC by a repeater which loops through a list. (if that helps give you an idea of what I am doing).
Is there any way to turn this large segment into one string which can be inserted into the append script?
Thank You
Cross domain jquery json
http://docs.jquery.com/Release:jQuery_1.2/Ajax#Cross-Domain_getJSON_.28using_JSONP.29
Some ideas:
You can replace new lines with spaces and create a huge line. There shouldn't be a problem with it.
Use string concatenation. Split the string and lines and do:
var html = line1 +
line2 +
...
linen;
Make an Ajax call to fill the div:
$("#divname").load(service_url);
You need to create a service that will return the string.
In my opinion the 3rd option is better than the other ones.
Correct me if i'm wrong but i think everything between the starting and ending quotation marks would be considered part of that string no matter how many lines it has. Unless your string has got any quotation marks in itself, in which case it'll be better to do the equivalent of php's addslashes() function in ASP on your string, which should add a \ before all the " marks in the string.
Another idea can be to use Json to encode/decode the string.
i don't see what's wrong with just generating one big-ass long single-line string and appending it just like you are doing. period. done. Fancier isn't going to gain you anything.
Hide it else where on the page and populate the div with it when you need it?

Categories