Build your own Serverless tic tac toe AI using Node.js and (a little bit of) Machine Learning
WIFI
Reactor
Open123!
cd CityJS-Workshop
yarn
yarn run dev
Setup
git clone https://github.com/<YOURREPO!>/CityJS-Workshop.git
Intros
Hew Ingram
@hewingram
beapplied.com
Thomas Ankcorn
@thomasankcorn
BAE Systems AI
LNUG
A friendly monthly meetup for people using Node.js for fun or profit.
lnug.org
We are Software Engineers... not data scientists
Important caveat
cd CityJS-Workshop
yarn
yarn run dev
git clone https://github.com/<YOURREPO!>/CityJS-Workshop.git
Setup
Let's deploy your fork of the app to netlify.com
- Quickly Deploy to their global CDN
- Deploy golang or node.js functions as a service
- Super simple
- Great developer experience
Deployment
Step 1 - adding an endpoint
In
src-functions/test.js
add
exports.handler = function(event, context, callback) {
console.log('hello world')
callback(null, {
statusCode: 200,
body: "Hello, World"
});
}
Netlify will build this into an endpoint available at
/test
Step 2 - make the endpoint mildly interesting
The board is stored as an array of length 9
Is stored as:
[1, -1, 0, 1, 1, 0, -1, 0, 0]
Try making the endpoint return back the "next move" (but lets just make the next move be the first available space)
Step 3 - training the neural network
Machine learning made SUPER simple
yarn add brain.js
Step 3 - training the neural network
const net = new brain.NeuralNetwork();
net.train([{input: { r: 0.03, g: 0.7, b: 0.5 }, output: { black: 1 }},
{input: { r: 0.16, g: 0.09, b: 0.2 }, output: { white: 1 }},
{input: { r: 0.5, g: 0.5, b: 1.0 }, output: { white: 1 }}]);
const output = net.run({ r: 1, g: 0.4, b: 0 });
Step 4 - make your endpoint return a better next move
exports.handler = function(event, context, callback) {
const board = JSON.parse(event.body)
const output = net.run(board);
callback(null, {
statusCode: 200,
body: output
});
}
<div @click="things">
I do things when clicked
</div>
Step 5 - make the mode toggle do something
Hook a function up to the click event
modeSwitch() {
this.resetGame()
this.mode = this.mode === "2Player" ? "ai" : "2Player"
}
Define a toggle function
BUT the data isn't there!
export async function getAIMove(board) {
return post('/.netlify/functions/neuralNet', board);
}
Step 6 - get the next move from the backend
Call the endpoint
handleClick: function(position) {
...
if(this.mode === 'ai'){
// do cool AI stuff
}
if(this.win()) {
return
}
this.$emit("turnSwitch");
}
}
Modify the handleClick function to use it
Step 7 - revel in the powerful AI you've created
Or.... not
Workshop
By hewingram
Workshop
- 180