DEV Community

Cover image for Lessons Learned: Adding ChatGPT to a Tic-Tac-Toe Game in Next.js
Jeffrey Nwankwo
Jeffrey Nwankwo

Posted on

Lessons Learned: Adding ChatGPT to a Tic-Tac-Toe Game in Next.js

Ever since ChatGPT showed up at our doorstep, we've been seeing a ton of cool apps popping up left and right. And now with the API out, the possibilities are endless!

Just the other day, I whipped up this super fun and addictive Tic-Tac-Toe game using Next.js. It's got all sorts of sound effects and animations that make it feel like you're really in the game. Give it a try.

Check it out here: https://tic-tac-toe-five-pi.vercel.app/

Aside from the cool animations and sound effects, I also spent quite some time working on the game logic to make it as efficient as possible. Playing against the computer (which I programmed to be my assistant) is already fun, but then I had an idea: what if the opponent was ChatGPT itself? Pretty neat, right?

The game logic is based on an array with 9 elements (0-8) representing the state of the board. Each element can hold either the player's or computer's symbol, or be null, indicating an empty spot. With this in mind, I thought it'd be cool to pass the board's state to the OpenAPI Completion Endpoint and have AI suggest its next move by returning the index where it should place its symbol.

Tic-Tac-Toe Game

It was a great idea, and technically it almost worked, but unfortunately, the implementation had some flaws. Firstly, allowing the AI to suggest the next move meant making requests to the endpoint every time, which was very slow and inefficient. After a few attempts, the response I received was "Too many requests," which essentially broke the game and ruined the fun.

Secondly, when you sign up for OpenAI's APIs, you receive free credits (about $18), which had already expired in my case. Upgrading to a paid plan wasn't feasible, as releasing the app would mean thousands of requests being made.

However, the game logic I created is pretty solid, and I believe the AI would suggest the same moves as the logic does. So, in the end, I decided to go with my own logic.šŸ˜Ž. No questions asked!

Do you see what I see? This could be huge for the world of gaming. In the near future, instead of writing complex game logic, developers could simply enable AI to compete against players. Just imagine playing your favorite game against a well-built AI opponent. Trust me, you'll be crushed! šŸ˜‚ The possibilities are endless, and we're just scratching the surface. This AI revolution is here to stay.

Thanks for reading, folks! Don't forget to follow me on Twitter.

And if you're interested in a detailed guide on how I built the Tic-Tac-Toe game in Next.js, let me know in the comments!

Top comments (0)