JavaScript function explanation for Blackjack game - javascript

I have been working on this blackjack problem on learnstreet:
http://www.learnstreet.com/cg/simple/project/blackjack#get-hint
I am stuck on the last method getStrategy() - here's a description of how the task is to be completed:
"This method simulates the dealer's strategy, so that he knows when to hit and when to stand -- i.e., when to accept another draw from the deck and risk "going bust" and breaking 21, or stopping with the current hand and hoping his opponent will not beat his number.
This is a special function in that it returns an object that is a function itself. (How's that for crazy?) It accepts 'n', an integer score of the dealer's hand at which point the dealer's strategy is to hit or to stand. (Blackjack dealers usually take hits when his cards total less than 17 points, so n would be 17 in that case.)
What you need to return in this method should be in the form of "return function(currenthand){};" where you fill in what's inside the curly braces ({}). The current hand will be supplied to the function call, and you will need to write some logic where the dealer compares the current hand's points with 'n'."
LearnStreet implemented getSrategt() in this way:
function getstrategy(n) {
return function(currenthand) {
return (countpoints(currenthand) < n);
}
}
The getStrategy() method is called in the applyStrategy method like this:
/*
This function applies the strategy you define in getstrategy(n): DON'T CHANGE
*/
function applystrategy(hand, n) {
var strat = getstrategy(n);
return strat(hand);
}
Can anybody please explain to me why we are returning (countpoints(currenthand) < n)?

countpoints(currenthand) will return the number of points in the hand. n is 17, the number where, if the current points is less than, the dealer will take another hit. Basically, if current points is less than 17, keep playing, if it is equal to or greater, stop.

Related

How do I implement minimax with the chess.js node module

I'm currently working on creating a chess engine using chess.js, chessboard.js, and the minimax algorithm. I eventually want to implement alpha-beta, but for right now, I just want to get minimax to work. It seems like the computer is thinking, but it usually just does Nc6. If I move the pawn to d4, it usually takes with the knight, but sometimes it just moves the rook back and forth in the spot that was opened up by the knight. If there is nothing for the knight to take, the computer moves the Rook or some other pointless move. My best guess is that all of the moves are returning the same valuation, and so it just makes the first move in the array of possible moves, hence the top left rook being a prime target. I should note that part of my confusion is around the way a recursive function works, and most of the stuff I've found online about recursive functions leaves me more confused than when I started.
I'm using Express.js with the chessboard.js config in public/javascripts as a boardInit.js that's included in the index.ejs folder, and when the user makes a move, a Post request is sent to /moveVsComp. It sends it to the server, where the app.post function for /moveVsComp tells chess.js to make the move that the player made.
After the player move is recorded, the computer calls the computerMoveBlack function.
Function call in the post request:
let compMove = computerMoveBlack(3);
game.load(currentFen)
game.move(compMove)
res.status(200).send({snapback: false, fen: game.fen()})
computerMoveBlack Function:
function computerMoveBlack(depth) {
let bestMove = ['', 105];
for (let move of game.moves()) {
game.move(move)
let value = minimax(move, depth-1, false)
if (value < bestMove[1]) {
bestMove = [move, value]
}
game.undo()
}
console.log(bestMove[0])
return bestMove[0]
}
This function loops through all of the moves, and I was using this because it seemed like this was the best way to keep the best move instead of just returning a valuation of the current position.
Minimax Function:
function minimax(node, depth, maximizingPlayer) {
let value = maximizingPlayer ? -105 : 105
if (depth === 0 || game.game_over()) return getValuation()
if (maximizingPlayer) {
for (let move of game.moves()) {
game.move(move)
value = Math.max(value, minimax(move, depth-1, false))
game.undo()
}
return value
} else {
for (let move of game.moves()) {
game.move(move)
value = Math.min(value, minimax(move, depth-1, true))
game.undo()
}
return value
}
}
getValuation Function:
function getValuation() {
let evalString = game.fen().split(' ')[0];
let score = 0;
score += (evalString.split('r').length -1) * -5 || 0;
score += (evalString.split('b').length -1) * -3 || 0;
score += (evalString.split('n').length -1) * -3 || 0;
score += (evalString.split('q').length -1) * -9 || 0;
score += (evalString.split('p').length -1) * -1 || 0;
score += (evalString.split('R').length -1) * 5 || 0;
score += (evalString.split('N').length -1) * 3 || 0;
score += (evalString.split('B').length -1) * 3 || 0;
score += (evalString.split('Q').length -1) * 9 || 0;
score += (evalString.split('P').length -1) || 0;
return score;
}
I should note that I understand using a FEN in the valuation is very slow for this use case, but I'm not really sure what a better alternative would be.
Just as kind of a recap of the questions, I'm trying to figure out why it just makes the first move in the array every time, what is wrong with the format of my functions, and what a better way to get the valuation of a position is as opposed to string manipulation of the FEN.
I will point out a few suggestions below to help you on the way if you are just getting started. First I just want to say that you are probably right that all moves get the same score and therefore it picks the first possible move. Try to add some Piece Square Tables (PST) to your Evaluation function and see if it puts pieces on appropriate squares.
I would implement a Negamax function instead of Minimax. It is way easier to debug and you won't have to duplicate a lot of code when you later make more optimizations. Negamax is one of the standard chess algorithms.
It seems like you don't do the legal move generation yourself, do you know how the board is represented in the library that you use? Instead of using the FEN for evaluation you want to use the board (or bitboards) to be able to do more advanced evaluation (more on it further down).
The min/max value of -105/105 is not a good way to go. Use -inf and inf instead to not get into troubles later on.
Regarding the evaluation you normally use the board representation to figure out how pieces are placed and how they are working together. Chessprogramming.org is a great resource to read up on different evaluation concepts.
For your simple starting evaluation you could just start with counting up all the material score at the beginning of the game. Then you subtract corresponding piece value when a piece is captured since that is the only case where the score is changing. Now you are recalculating lots of things over and over which will be very slow.
If you want to add PST to the evaluation then you also want to add the piece value change for the moving piece depending on the old and new square. To try and sum up the evaluation:
Sum up all piece values at start-up of a game (with PST scores if you use them) and save it as e.g. whiteScore and blackScore
In your evaluation you subtract the piece value from the opponent if you capture a piece. Otherwise you keep score as is and return it as usual.
If using PST you change the own score based on the new location for the moved piece.
I hope it makes sense, let me know if you need any further help.

Recursive Reduce method in ES6 / Immutable

Hope this isn't too difficult a question without context, but here goes nothing. So, I inherited this code from someone, and I can't seem to get it to work!
We're making a Go game. We want to scan a set of pieces on the board and see if they're empty or not. An empty square is called a 'liberty'. Now, at the bottom of the function there we're creating a new 2D array 'visitedBoard' that keeps track of where we've scanned so far.
PROBLEM, the current implementation allows for liberties to be scanned twice! It only seems to be marking something as 'visited' in the board when it is either empty or another color (0), not when it's 1.
BTW, at the bottom - we're iterating through neighbors, which is a 4 item array of objects {row: 2, col: 3} and then recursively running it through this function.
Any assistance is helpful. I'm new to this functional / immutable business.
const getLiberties = function (board, point, color) {
if (board.get(point.row).get(point.col) === C.VISITED) {
return 0; // we already counted this point
} else if (board.get(point.row).get(point.col) === C.EMPTY) {
return 1; // point is a liberty
} else if (board.get(point.row).get(point.col) !== color) {
return 0; // point has an opposing stone in it
}
const neighbours = getNeighbours(board, point)
const visitedBoard = board.setIn([point.row, point.col], C.VISITED)
return neighbours.reduce(
(liberties, neighbour) => liberties + getLiberties(visitedBoard,
neighbour, color), 0)}
instead of .get(point.row).get(point.col) you can use .getIn([point.row, point.col])
inside reduce you always use same visitedBoard for all calls. You have to re-assign new value to variable after reduce callback call

Unbalanced binary tree not functioning properly. Node.Js

So I was solving a problem for class involving binary search and the algorithm I implemented to solve it worked fine but my hunch is that a slight gamble would be more effective given the parameters of the problem
The fictional town of HollyBroke, Fl is made up of a 30 x 30 block grid. The streets are named after the presidents of the United States and the avenues are numbered numerically. The infamous two-word arsonist is holding the town hostage. He selects a house every Saturday for destruction by fire and taunts the police department by challenging them to guess the location for each week’s crime. He will answer up 10 guesses with either a “yes”or a “no” answer during his very brief phone call right before he strikes the match. (He won’t stay on the line so the call can’t be trace.)
The city wants you to develop a program to provide a quick response when this notorious criminal calls.
The answer to that was easy enough to create an algorithm for but I thought a median-1/median+1 gamble would be more effective. My hunch is that more often than not I will arrive at the conclusion with one extra question to go allowing me to either ask a binary search question about the arsonist or if the game allowed it I would show up with police before the end of the call. If I don't outright solve it beforehand I would have a very small space to search after it was completed, like three or four blocks right next to each other,
This is my code for the "gambling" binary search.
`var array = [{"a":30,"b":30,"c":0}]
function findLower(input) {
var half = Math.floor(input/2);
if(0 == input%2)
return (half-1);
else
return (half);
};
function findUpper(input) {
var half = Math.floor(input/2);
if(input%2 == 0)
return (half+1);
else
return (half+1);
}
for (var i = 0; i <= 9; i++){
for (var z = array.length - 1; z >= 0; z--) {
if (array[z].c = i){
if (array[z].a>array[z].b)
array.push({"a":findLower(array[z].a),"b":array[z].b,"c":array[z].c + 1},{"a":findUpper(array[z].a),"b":array[z].b,"c":array[z].c + 1})
else
array.push({"a":array[z].a,"b":findLower(array[z].b),"c":array[z].c + 1},{"a":array[z].a,"b":findUpper(array[z].b),"c":array[z].c + 1})
}
};
}
console.log(array.length);`
Its coming up with an absurd array length given that it should be 2^10 +2^9 + 2^8 ..... = 2047
The program is coming up with an array length of 19683
And some of the arrays should most certainly not be 30*14 at node level 10 I'm sure the algorithm was set up properly. I've walked it through two levels by pen and paper and it seems like it should work properly.
Found it.
if (array[z].c = i){
should be
if (array[z].c == i){
its a conditional statement not declaring them equal
Also I was wrong. You only have about a 40% chance of successfully locating the house in 10 guesses.

Testing/validating/evaluating the outcome of every path in a function?

Disclaimer - I've tried finding an answer to this via google/stackoverflow, but I don't know how to define the problem (I don't know the proper term)
I have many small AI snippets such as what follows. There is an ._ai snippet (like below) per enemy type, with one function next() which is called by the finite state machine in the main game loop (fyi: the next function doesn't get called every update iteration, only when the enemy is shifted from the queue).
The question: How do I test every case (taking into account some enemy AI snippets might be more complex, having cases that may occur 1 in 1000 turns) and ensure the code is valid?
In the example below, if I added the line blabla/1 under count++, the error might not crop for a long time, as the Javascript interpreter won't catch the error until it hits that particular path. In compiled languages, adding garbage such as blabla/1 would be caught at compile time.
// AI Snippet
this._ai = (function(commands){
var count = 0;
return {
next: function(onDone, goodies, baddies) {
// If the internal counter reaches
// 2, launch a super attack and
// reset the count
if(count >= 2) {
commands.super(onDone);
count = 0;
}
else {
// If not performing the super attack
// there is a 50% chance of calling
// the `attack` command
if(chance(50)) {
var target = goodies[0];
commands.attack(onDone, target);
}
// Or a 50% chance of calling the
// `charge` command
else {
commands.charge(onDone);
count++;
}
}
}
};
})(this._commands);
I could rig the random generator to return a table of values from 0-n and run next 1000's of times against each number. I just don't feel like that is will concretely tell me every path is error free.
As you say, unit tests must test every path so you will be sure all works well.
But you should be able to decide which path the method will follow before calling it on your tests, so you're be able to know if the method behaviour is the expected one, and if there is any error.
So, for example, if there is a path that will be followed in only one of every 1000 executions, you shouldn't need to test all 0, 1, 2 ... 999 cases. You only one combination of results that behave distinctly.
For example, in the snippet shown you have these cases:
the counter has reached 2
the counter has not reached 2 and chance returns true
the counter has not reached 2 and chance returns false
One way to archieve this is taking control of the counter and of the chance method by mocking them.
If you want to know what happens when the counter has reached 2 and the next method is called, just pass a counter with 2 and call next. You don't need to reach 2 on the counter by really passing for all the code.
As for the randomizer, you don't need to try until the randomizer returns the value you want to test. Make it a mock and configure it to behave as you need for each case.
I hope this helps.

How to make a Simon Js game based on arrays?

Im writing a js simple simon game and im clueless on how to do it.
I know that :
I need to create two arrays, and a level(score) variable
A randomly generated number from 1 to 4 (inclusive) needs to be added
to the first array, When one of four buttons is pressed, the value
of it is added to the second array, if the second array is not the
same size or bigger than the first array. Each time a value is added
to the second array, check that the value is equal to the value in
the same position in the first array, if not, clear both arrays, and
set levelvar to 1, and alert "gameover" This means if you get one
wrong, you cannot continue. If the length of the second array
matches the level variable, add a random number to array one, clear
array two, increment levelvar.
But, I am clueless in aspect to the code.
My Jsfiddle :http://jsfiddle.net/jbWcG/2/
JS:
var x = []
var y = []
var levelvar = 1
document.getElementById("test").onclick= function() {
document.getElementById("test").innerHTML=x
};
document.getElementById("button1").onclick= function() {
x.push("Red")
};
document.getElementById("button2").onclick= function() {
x.push("Green")
};
document.getElementById("button3").onclick= function() {
x.push("Yellow")
};
document.getElementById("button4").onclick= function() {
x.push("Blue")
};
HTML:
<button id="button1">Red</button><br />
<button id="button2">Green</button><br />
<button id="button3">Yellow</button><br />
<button id="button4">Blue</button><br />
<p id="test">Click To see What you have clicked</p>
How would I make a two arrays see if a certain value is the same?
Lets say, that the generated array is : [1,2,3,4,1,2,3]
and i am at position 5 and i press 2, how would i check that the two numbers match?
Thanks in advance
The easiest way to check one at a time that position i of your array is x is
if (gen_arr[i] == x) {
// matches
} else {
// doesn't match
}
So if you conceptualize the flow of your game, you're going to want to, at each button press:
somehow keep track of which index they are on (maybe have a counter that increments with each button press)
checks if gen_arr[i] == x (and displays game over if it doesn't).
Alternatively, instead of keeping track of which index, you can call gen_array.shift() to get the first item in gen_array AND delete it from the array, in a flow kind of like this:
var gen_array = [1,2,3,4,1];
function press_button(button_pressed) {
var supposed_to_be = gen_array.shift();
// at this point, on the first call,
// supposed_to_be = 1, and gen_array = [2,3,4,1]
if (supposed_to_be != button_pressed) {
// game over!
} else {
// you survive for now!
if (gen_array.length() == 0) {
// gen_array is empty, they made it through the entire array
// game is won!
}
}
}
While that represents the general "what to check" at every step, using this verbatim is not recommended as it quickly leads to an unstructured game.
I recommend looking into things called "game state" diagrams, which are basically flow charts which have every "state" of the game -- which in your case, includes at least
"displaying" the pattern
waiting for button press
checking if button press is correct
game over
game won
And from each state, draw arrows on "how" to transition from one state to the next. You can do a google search to see examples.
Once you have a good game state diagram/flow chart, it's easier to break down your program into specific chunks and organize it better ... and you can usually then see exactly what you need to code and what is missing/what is not missing.

Categories