DEV Community

Adrian Foong
Adrian Foong

Posted on

Tic Tac Toe Fight!

Once upon an internship, the company I was with brought all the programming interns together to participate in a fun little challenge: writing an AI to play Connect 4 against each other. Or maybe it was Tic Tac Toe? I can't really remember the details. All I recall is that it was a ton of fun and I wanted to recreate that experience!

So, here it is: T3F

Tic Tac Toe

This is a pretty simple Tic Tac Toe game where you get to play with humans, or one of the built in AIs (there are only 2 very simple ones right now πŸ˜…). But the part I like the most is the part where you can pit your custom AI against a friend's!

Tic Tac Toe - Custom

The AI is just a function that takes in the game state and returns the position you want to play on. In order for the game to talk to your AI however, we need to put it on a server - which is a great use case for a serverless function!

There are many cloud providers that offer serverless functions, but probably the easiest way to get started is to use Netlify Functions. Kent C. Dodds already has a great blog post on how to get started with Netlify Functions, so I won't go into how to create one.

Here's an example of a custom AI:
Custom AI

This function parses the request body to get the game state object, and then returns the position of the first item in the cells array that does not have a playerId (the next unoccupied cell). Yours can be a lot more sophisticated than this! Feel free to take this example and make it your own. The game state sent to the function and the expected output are described more fully in the info box that appears below the player setup screen.

Here's a demo of two different AIs playing against each other:
Game Example

Let me know if you decide to check it out. Feel free to share your feedback, games and even custom AI for others to play against!

Here's the (very messy) repo if you're interested 😁.

Top comments (0)