DEV Community

Cover image for I Wanted to Build Something Using AI... So I Made a Ninja Game That Learns From You
Puneet Kumar Mishra for Necoz

Posted on

I Wanted to Build Something Using AI... So I Made a Ninja Game That Learns From You

Includes a live AI mind view showing decisions

Yo Developers!!

So, a few days ago, I was thinking about building something using AI.

I didn't want to make another chatbot or just integrate an API into a website. I wanted to build something where AI actually does something.

But I had a problem.

I didn't have any GPU, ML resources, or much knowledge about training AI models.

I wasn't even sure where to start.

So I did what most of us probably do when we have a random idea...

I asked ChatGPT. ๐Ÿ˜‚

I started asking it about different AI models, how their backend works, how they learn, and whether I could build something interesting without needing expensive resources.

That's when I came across Q-learning.

And somehow, this random exploration turned into a game.

Meet NinjaDuel!

๐ŸŽฎ Play it here: https://developerpuneet.github.io/NinjaDuel/
Github: https://github.com/DeveloperPuneet/NinjaDuel

Okay, how did I actually build it?

I didn't build the whole thing in one go. It was more like experimenting with different things and seeing what worked.

Here's how it happened.

1. Started with a basic game

First, I decided to make a simple ninja fighting game.

I started with the basics:

  • Player movement.
  • Basic attacks and fighting mechanics.
  • A simple background.
  • Keyboard controls using JavaScript.
  • Basic collision and movement logic.

Nothing fancy at this point.

I just wanted two characters to fight each other and have something playable and i made them... simple...

2. Then I gave it to DeepSeek...

Once I had the basic game working, I wanted to improve how it looked.

So I gave the project to DeepSeek and asked it to improve the UI.

AND BRO... ๐Ÿ˜ญ

It came up with a pretty insane-looking UI.

I genuinely liked what it created, so I kept that direction and continued improving the game.

This was the point where it started looking like an actual game instead of a random JavaScript experiment.

3. Discovered Q-learning through YouTube

Now came the interesting part.

I didn't want the opponent to just perform random attacks or follow a fixed pattern.

I wanted an opponent that could learn.

I started watching YouTube videos about reinforcement learning and Q-learning.

After watching a few tutorials, I understood the basic concept:

An AI agent observes a situation, takes an action, receives a reward, and updates what it has learned.

I decided to try implementing a basic structure of Q-learning myself.

I started thinking about:

  • What information should the AI observe?
  • What actions should it be allowed to take?
  • How should it receive rewards?
  • How should it remember what it learned?

I created a basic structure for this and then used Claude to help improve and refine the implementation.

Obviously, I had to experiment with it and connect the learning logic to the actual game mechanics.

And that's how the Q-learning-based opponent started taking shape.

Wait, how does the AI actually learn?

Let me explain the basic idea.

Q-learning is a reinforcement learning algorithm.

Imagine you're playing a game for the first time. You don't know which moves are good.

You try different actions.

Some work well, some don't.

You learn from those experiences.

Q-learning follows a similar idea.

There are four important things:

  • State: What is happening in the game right now?
  • Action: What can the AI do?
  • Reward: How useful was the result?
  • Q-value: How valuable is an action in a particular state?

The AI maintains a Q-table containing values for different state-action combinations.

After taking an action and receiving feedback, it updates those values.

The general Q-learning update equation is:

Q(s,a) = Q(s,a) + ฮฑ[r + ฮณ max Q(s',a') - Q(s,a)]

Don't worry if that looks complicated. The basic idea is that the AI updates its estimate of how good an action is based on the reward and what it expects to happen next.

How Q-learning is used in NinjaDuel

In NinjaDuel, the AI observes the combat situation, including things like:

  • Distance between the player and opponent.
  • Current combat situation.
  • Available actions.

Based on the current state, it chooses an action.

It can move, attack, block, jump, and perform other actions.

Afterward, it receives feedback and updates its Q-values.

With more matches, it can use its stored experience to make different decisions.

I also added two different AI modes:

1. Q-learning AI

Starts with an empty Q-table and learns through matches.

2. Pretrained Q-learning AI

Starts with existing practice values and continues learning while playing.

The learning data is saved using browser localStorage, so the AI can retain its learned values between visits.

How to play?

You can choose your opponent and jump straight into the fight.

Here are the controls:

Action Key
Move A / D or Arrow Keys
Jump W / Space / Up
Block / Parry S / Down
Quick Slash J / F
Heavy Slash K
Kick L
Shuriken U
Dash Strike I
Quick Attack Left Mouse Button
Pause / Resume P / Esc

Some extra controls

Key Function
Tab Toggle AI Mind View
0 Reset AI learning memory
M Open opponent selection
1 / 2 / 3 Change difficulty
R Rematch after knockout

One feature I particularly like is AI Mind View.

Press Tab during the game to see information about the AI's decision-making.

I wanted to make the AI learning process more visible rather than just having a mysterious opponent fighting in front of you.

What did I use?

The project is built using:

  • HTML
  • CSS
  • JavaScript
  • Canvas API
  • Q-learning-inspired reinforcement learning

I also added sound effects, particles, different attacks, difficulty levels, offline support, and PWA support.

And the interesting thing is that everything runs directly in the browser.

No external AI API, no GPU, and no model hosting required.

It's open source!

I have published the project on GitHub under the MIT License.

You can explore the code, try it, or contribute if you find something interesting.

๐ŸŽฎ Live Demo: https://developerpuneet.github.io/NinjaDuel/

๐Ÿ’ป GitHub Repository: https://github.com/DeveloperPuneet/NinjaDuel

What's next?

Honestly, this project started with a random question to ChatGPT.

Then I wrote some JavaScript, experimented with DeepSeek, learned Q-learning through YouTube tutorials, and used Claude to improve my implementation.

I didn't expect to end up with an entire playable game.

I'm still learning about reinforcement learning, so I'd genuinely love to hear suggestions from people who have worked with it.

What would you improve in the AI?

And what other interesting things can we build using Q-learning?

Also, try the game and tell me if you managed to defeat the AI. ๐Ÿ˜‚ also the learning data is stored in your device as cache

Thanks for reading!!

Top comments (26)

Collapse
 
ndcodes profile image
Nnamdi Felix Ibe Necoz •

Nice build, and for me the best is the AI Mind View. You made the decision visible which I think is more than most demos bother with.

What I'd add isn't in the algorithm. Right now, the only evidence it's learning is that the opponent feels harder, and you're learning too, so you can't separate the two. Play the agent against a fixed scripted opponent for a few hundred matches and plot the win rate.

And the localStorage learning is per browser and per device, so wrap the read in a try/catch. It can come back empty or throw in private browsing.

Collapse
 
puneetkumar2010 profile image
Puneet Kumar Mishra Necoz •

Thanks a lot for the detailed feedback! Really appreciate it. ๐Ÿ˜Š

Actually, before writing the post, I tested the AI myself. I played 29 matches against it, and it managed to win only 5 of them ๐Ÿ˜‚

But you're right, that's not really a proper way to measure its learning since I'm also getting better at the game while playing.

The fixed-opponent idea is interesting. I'll try running multiple matches against a scripted opponent and track the win rate to see how its performance changes over time.

And thanks for pointing out the localStorage edge case! I'll look into handling that as well.

Really appreciate you taking the time to check out the project and share these suggestions!

Collapse
 
ndcodes profile image
Nnamdi Felix Ibe Necoz •

Don't mention. I am bored now just finished my second series. And I had fun reading through your article.

Thread Thread
 
puneetkumar2010 profile image
Puneet Kumar Mishra Necoz •

Haha, glad you enjoyed reading it! And congrats on finishing your second series! What was it about? ๐Ÿ˜‚๐Ÿ˜‚๐Ÿคฃ๐Ÿคฃ

Thread Thread
 
ndcodes profile image
Nnamdi Felix Ibe Necoz •

100 Days of DevOps and Cloud. One lab a day for a hundred days, AWS, then Azure, with Ansible and Terraform near the end.

Working the tasks in labs was pretty easy. The writing was where I found out what I'd actually understood, which is why most of the posts ended up being about something that looked right and wasn't. I had to look at technical blogs, documentation, etc to get full insight into the tools and the expected results.

Day 100 went out this morning, so your post was good timing. ๐Ÿ˜„

Thread Thread
 
puneetkumar2010 profile image
Puneet Kumar Mishra Necoz •

Woah, 100 days straight?! That's some serious dedication! ๐Ÿ”ฅ Huge congratulations on completing the series!

And I totally get what you mean about writing revealing how much you've actually understood. It's one thing to get something working in a lab, but explaining why it works is a whole different challenge.

Thread Thread
 
ndcodes profile image
Nnamdi Felix Ibe Necoz •

Thank you, @puneetkumar2010. It was worth it.

Yes, that's the skill I'm developing: training myself to read deeply and to take an architect-level view of anything.

Thread Thread
 
puneetkumar2010 profile image
Puneet Kumar Mishra Necoz •

That's a really interesting skill to develop. I think it's easy to focus on just getting something to work, but understanding the bigger picture and why things work the way they do is a whole different level.

I'm still learning that myself through building projects. Definitely something worth working towards! ๐Ÿ˜„

Collapse
 
nyaomaru profile image
nyaomaru Necoz •

I didn't know about Q-learning! ๐Ÿ˜ธ๐Ÿ’š

It's fascinating how the opponent learns through playing against you. This could be a really interesting direction for the next generation of CPU opponents in games!

I'm interested in game development myself, so I'll definitely take some inspiration from your project!

By the way, I defeated your AI! ๐Ÿ˜น๐Ÿ†

win

Collapse
 
puneetkumar2010 profile image
Puneet Kumar Mishra Necoz •

Haha, you defeated it! ๐Ÿ˜‚๐Ÿ†

Yeah, in the beginning, the AI behaves pretty dumb. But I tested it for around 60โ€“70 matches, and now I'm seeing some interesting behaviour. It's started dodging my shurikens and kicks at the right moments. Before I land a heavy sword attack, it often moves back or interrupts its own action to avoid getting hit. That's the kind of improvement I wanted to see!

One thing to mention: its learning is mainly stored in your browser's local storage, so it learns from your matches on your device. If you play against my AI, it'll probably be much harder after you've played several matches with it. ๐Ÿ˜…

Actually, I've been thinking about trying Q-learning with a chatbot too. But then I wondered... would that even work? ๐Ÿ˜‚

Imagine:

User: How are you?

AI: Who are you? ๐Ÿ’€

I guess Q-learning could help a chatbot learn which responses or actions users prefer, but it probably wouldn't be enough on its own to understand and generate natural conversations. Still, it might be an interesting experiment!

I also like the idea of lightweight AI that can run on CPU-based devices, especially since GPUs can be pretty expensive.

Btw, what kind of project are you thinking of building with Q-learning? I'd love to hear your ideas! ๐Ÿ˜„

Collapse
 
nyaomaru profile image
nyaomaru Necoz •

Haha!! Maybe I should retire undefeated before your AI gets too strong! ๐Ÿ˜น๐Ÿ†

One idea I have is to let an AI-controlled character initially react to a boss's movements with random actions, then gradually learn which responses are most effective.

If the learning data can be stored on the client side using something like localStorage, there could be quite a lot of interesting possibilities without requiring expensive servers or GPUs!

I'd love to explore this further. Thanks for introducing me to Q-learning! ๐Ÿ˜ธ๐Ÿ’š

Thread Thread
 
puneetkumar2010 profile image
Puneet Kumar Mishra Necoz •

Haha, exactly! ๐Ÿ˜ I'm actually using client-side localStorage only to store the learning data. Haven't connected any database or external server to it. Everything runs entirely in the browser!

That's what makes experimenting with Q-learning so interesting without needing extra infrastructure.

Collapse
 
zarb450 profile image
Ameer Hamza •

Pretty Amazing. I tried it myself too, and while enjoying the game, I decided to test the learning capabilities by throwing the same attack again and again. At first, it lost again and again, but then it started blocking my attacks and started counterattacking.

That seems pretty amazing to me. In fact, I am also working on a project where I need AI to learn, and now I think I should also use Q-Learning there.

Collapse
 
puneetkumar2010 profile image
Puneet Kumar Mishra Necoz •

Yooo, that's awesome! ๐Ÿ˜‚๐Ÿ”ฅ The fact that you kept repeating the same attack and it eventually started blocking and counterattacking is exactly the kind of behaviour I wanted to see when building this.

And that's interesting about your project! Q-learning is definitely worth exploring if your AI needs to learn through actions and rewards.

Btw, is your project open source? I'd love to check it out! Also, what is it about? Is it a game or some kind of software? ๐Ÿ‘€

Collapse
 
zarb450 profile image
Ameer Hamza •

Yeah, my project is definitely open-source, but I am currently building it with my 2 other friends, as it is our Final Year Project. It will be a middle layer that will encounter every incoming request and check if it's a hacker or a normal person.

The AI part is that it will encounter the request, display it on the dashboard and check the behaviour and pattern of the user. If the AI can't decide, then the request will be sent to the human, he will check and then mark it either as a normal user or a hacker and the AI will then store that pattern in itself.

Thread Thread
 
puneetkumar2010 profile image
Puneet Kumar Mishra Necoz •

Ohh, now I get the idea! That's actually a really interesting project. ๐Ÿ‘€

So basically, you're building a security layer that monitors incoming requests, detects suspicious behaviour, and learns from human feedback whenever it isn't confident about a decision.

I especially like the human-in-the-loop part. It means the system can keep improving from patterns that humans identify.

Are you planning to use Q-learning for this, or are you exploring some other machine learning approach?

Also, would love to check out the GitHub repo once it's public! Good luck to you and your teammates with the final year project!

Thread Thread
 
zarb450 profile image
Ameer Hamza •

Thanks, there is no code at the moment because we are doing research on the attacks and the different kinds of attacks that hackers do.

The human part was added because we don't want the AI to handle everything, as it might start hallucinating.

Regarding th Q-learning, I am mainly interested in any Reinforcement learning type, since now, I have seen a demo of Q-learning, I will definitely discuss this with my teammates.

Thread Thread
 
puneetkumar2010 profile image
Puneet Kumar Mishra Necoz •

Ohh, now I get the idea! That's actually a really interesting project. ๐Ÿ‘€

So basically, you're building a security layer that monitors incoming requests, detects suspicious behaviour, and learns from human feedback whenever it isn't confident about a decision.

I especially like the human-in-the-loop part. It means the system can keep improving from patterns that humans identify.

Good luck to you and your teammates with the final year project!

Collapse
 
divya2009 profile image
Divya Necoz •

i like it :O

Collapse
 
puneetkumar2010 profile image
Puneet Kumar Mishra Necoz •

๐Ÿ˜Ž glad you liked it!!

Collapse
 
realdashiii profile image
realdashiii ( Ali ) •

Fellow game dev hereโ€”love how lightweight this is! Using Q-tables and browser storage to get adaptive enemy behavior without external servers is a great approach ๐Ÿ˜

Collapse
 
puneetkumar2010 profile image
Puneet Kumar Mishra Necoz •

Thanks! ๐Ÿ˜ Really wanted to keep it lightweight and fully client-side without depending on external servers. Glad to hear another game dev appreciates the approach!

Collapse
 
smtahosin profile image
S M Tahosin •

Hey Puneet! played two rounds just now, the ninja started reading my jump attacks by round three lol. closed the tab and came back later, it still remembered how i play. bit spooky haha. if i spam one combo does it just keep farming me? thanks :D

Collapse
 
paullovelace profile image
Paul Lovelace •

The AI Mind View is the bit I'd steal โ€” making the decision visible is what turns a demo into something you can actually learn from. The measurement problem ndcodes raised is the one that'd bug me though: you're getting better at the same time the AI is, so the win rate doesn't prove much either way. Have you tried freezing a Q-table snapshot and running it against a fresh random player for a hundred matches? That'd give you a baseline that doesn't move while you do.

Collapse
 
aheadkit profile image
AheadKit •

A game that adapts to the player is a much harder claim than a game that reacts to the player, and the difference is where I'd poke. In our own runs this week we asked a model a question five different ways with no documents at all, and it answered --no-cache five times out of five, because the flag was already in its head, not because it learned anything from the run. How do you tell, in your game, whether the ninja is actually adapting to how someone plays versus just repeating a pattern that already worked once?

Collapse
 
member_7c8c7e8d profile image
Max K. •

The live AI Mind View is what turns this from a fun browser game into a great reinforcement learning visualizer. For tabular Q-learning in localStorage, two small tweaks keep the opponent sharp without bloating the table: bucketing distances and cooldowns into coarse discrete bands, and decaying epsilon across rounds while keeping a small exploration floor around 0.05 so it still adapts when a player changes tactics mid-session. After your 29-match test run, roughly how many distinct states ended up stored in the Q-table?