When I first began my research for my paper “Bots Trained to Play Like a Human Are More Fun,” I had no idea how deep the neural network rabbit hole would go. The idea was simple: train bots that mimic human behavior in games, not just to win—but to play like us. What started as a weekend experiment quickly turned into late nights debugging Java code, trying to get my own custom neural network to converge. Eventually, I discovered brain.js, a lightweight neural network library for JavaScript, and my life (and my experiments) became much easier. In this post on how to build neural network in JavaScript with Brain.js I’ll share that journey — from manually crafting neural networks in Java to building efficient, human-like AI bots using brain.js. You’ll get detailed explanations, real-world code samples, and insights into the most common challenges faced when training neural networks.
What Is brain.js?
brain.js is an open-source JavaScript library that makes building, training, and running neural networks accessible and fast. It runs in both Node.js and browsers, meaning you can train AI models directly in your web apps — no Python or heavy frameworks needed.
Originally developed to bring neural network capabilities to front-end developers, brain.js simplifies deep learning by providing intuitive APIs while still leveraging GPU acceleration through GPU.js.
You can think of brain.js as the “entry-level TensorFlow” for JavaScript — designed to get you experimenting quickly without the boilerplate.
Install brain.js:
npm install brain.js
BashOr include it in your HTML:
<script src="https://unpkg.com/brain.js"></script>
BashMy journey: From Java Neural Nets to brain.js
When I began developing bots for my research, I wrote my first neural network from scratch in Java — defining neurons, layers, activation functions, and manually tweaking weights.
Here’s a glimpse of what that looked like:
public class Neuron {
double[] weights;
double bias;
double output;
public Neuron(int inputCount) {
weights = new double[inputCount];
for (int i = 0; i < inputCount; i++) {
weights[i] = Math.random() - 0.5;
}
bias = Math.random() - 0.5;
}
public double activate(double[] inputs) {
double sum = bias;
for (int i = 0; i < inputs.length; i++) {
sum += weights[i] * inputs[i];
}
output = 1 / (1 + Math.exp(-sum)); // sigmoid activation
return output;
}
}
JavaScriptBuilding networks layer by layer gave me a strong understanding of how forward propagation and backpropagation work. But scaling that into something usable for real-time gaming bots was… painful.
That’s when I found brain.js, which abstracts all that math and provides a clean API — perfect for experimentation.
Build neural network in JavaScript with Brain.js
Let’s rebuild that same network using brain.js.
We’ll create a neural network that learns a simple input-output relationship — something foundational before moving into human-like gameplay prediction.
Example: Predicting Player Reactions
const brain = require('brain.js');
// Create a new neural network
const net = new brain.NeuralNetwork({
hiddenLayers: [3] // you can tune the number of layers
});
// Training data — input (situation), output (reaction)
net.train([
{ input: { distance: 0.1 }, output: { jump: 1 } },
{ input: { distance: 0.5 }, output: { jump: 0 } },
{ input: { distance: 0.2 }, output: { jump: 1 } },
{ input: { distance: 0.9 }, output: { jump: 0 } },
]);
// Predict new outcome
const output = net.run({ distance: 0.15 });
console.log(output); // -> { jump: ~0.9 }
JavaScriptIn this example, we’re simulating a bot learning when to jump based on the distance from an obstacle — a primitive version of human-like reaction timing.
Training Bots to “Play Like a Human”
In my paper, I focused on creating bots that don’t just play optimally but rather exhibit imperfect, human-like decision-making.
By analyzing player data — time delays, hesitation, overcorrections — we can feed those metrics into the training set. The neural network then begins to mimic those tendencies.
For example:
net.train([
{ input: { distance: 0.1, hesitation: 0.05 }, output: { jump: 1 } },
{ input: { distance: 0.5, hesitation: 0.3 }, output: { jump: 0 } },
{ input: { distance: 0.3, hesitation: 0.2 }, output: { jump: 0.8 } },
]);
JavaScriptWhen you run predictions, you get more nuanced, human-like outputs — not binary yes/no results.
This is a great foundation for AI-powered gaming agents or behavioral simulation bots that feel more natural in gameplay.
Common Challenges When Building Neural Networks
Whether you’re building neural networks in Java, Python, or JavaScript, the same challenges often appear:
- Overfitting – When your neural network memorizes training data rather than generalizing it.
Solution: Use varied and diverse training data, apply dropout or noise.* - Poor Convergence – The network doesn’t learn effectively because of bad learning rates or activation functions.
Solution: Experiment with different configurations; brain.js allows quick tuning.* - Data Normalization – Raw data must be scaled between 0 and 1 for optimal training.
Solution: Always preprocess your data.* - Insufficient Training – Small datasets often lead to poor performance.
Solution: Augment or generate synthetic data.* - Debugging the “Black Box” – Understanding why a neural network makes a certain decision can be hard.
Solution: Log intermediate outputs and visualize training error rates.*
Why Use brain.js in 2025?
- Runs in the browser — perfect for web-based AI demos or educational projects.
- GPU accelerated — leverages your GPU for faster training.
- Simple API — build functional networks with just a few lines of code.
- Lightweight — no need for heavy Python environments.
If your goal is to experiment, prototype, or teach neural network concepts, brain.js is a perfect tool.
Going Further: Recurrent Networks in brain.js
brain.js also supports Recurrent Neural Networks (RNNs) for sequence data — ideal for tasks like predicting player moves, chat responses, or time-series data.
const net = new brain.recurrent.LSTM();
net.train([
{ input: "jump", output: "run" },
{ input: "run", output: "slide" },
{ input: "slide", output: "jump" }
]);
console.log(net.run("jump")); // -> "run"
JavaScriptThis kind of sequential prediction is exactly what powers behavioral modeling in bots that respond to player patterns.
Final Thoughts
Building my own neural network in Java was a valuable lesson — it taught me what’s happening under the hood. But moving to brain.js opened up a world of rapid prototyping, experimentation, and visual learning.
If your goal is to build AI that feels human, or to teach neural networks interactively in JavaScript, brain.js is the bridge between deep learning theory and fun, hands-on coding.
In the end, AI doesn’t have to be cold and robotic. With the right tools, we can build bots that think (and play) just a little more like us.
While you are here, maybe try one of my apps for the iPhone.
Snap! I was there on the App Store
Also, have a read of some of my other posts
The use of AI in recruitment & HireVue – My Day To-Do
How to unit test react-redux app – My Day To-Do (mydaytodo.com)
Playwright for end-to-end UI testing: A Complete Guide – My Day To-Do
0 Comments