Menu

1 / 10

Unbeatable Tic-Tac-Toe AI: 7 Rules in Java

DEV Community: java·Hitesh Patel·19 days ago
#kvieF2w1
#devtojava#devto#dev#cell#fork
Long article (1936 words) — no AI summary yet.
Reading 0:00
15s threshold

My first bot picked squares at random. I beat it in 3 moves.

I'm working through LLD problems, and tic-tac-toe was the third one I picked. Building it for two players was the easy part. Then I added a bot, and it hooked me for days. Every time I beat it, I added a new rule. Every time I added a rule, I found a new way to beat it. This went on until one day I just... couldn't win anymore. Only draws.

This post isn't about the board, the turns or undo (that part is boring, trust me). It's about how the bot thinks . Let's see how I made it.

How the bot is wired

Before the levels, one thing you need to know: the bot doesn't have one big brain. It has a list of small brains , and it asks them one by one.

public interface BotStrategy { Cell makeMove ( Board board , Player player ) ; }

Enter fullscreen mode

Exit fullscreen mode

Each strategy either returns a cell ("I've got this") or null ("not my job, ask the next guy").…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.