FastAPI for a Simple Game

     Since I've been having fun with FastAPI, I decided to build an API for a simple game I learned about while studying my textbook for my Advanced Algorithms course. The game is described as two players attempting to move their pieces from one side of the grid to the opposite side. One player moves from the top to the bottom, the other from the left to the right. A piece can move forward one space into an empty space, or it can hop over one empty piece. Once a player's pieces have moved all the way over to the opposite end of the board, that player wins. The author of my textbook said this game was played on a table in a diner using sugar packets, so I decided to call my game 'Packet Swap'.

    Anyway, since I wanted to use FastAPI, the logic is in Python. I found what I thought was a pretty good solution by describing the board as a dictionary of tuple keys and strings describing the object in that location. Using tuples as the keys let me do some simple math on on my tuple when I wanted to find out if a piece could move where it wanted to. Depending on which player's turn it is, I decide if I need to check horizontally or vertically (since pieces can only move right or down).

    The API is where my seemingly elegant solution met some hard times, as I didn't realize that JSON doesn't like working with dictionaries that contain tuples. I tried several things, from turning the dictionary into a string to trying to convert each of the tuple keys into a string. The issue with that is that as I tried to iterate through my keys the size would change when I replaced the key. Ultimately instead of passing an entire object into JSON, I now have a global game board that I don't bother passing into my JSON. I'll admit it isn't the best solution but for now it will let me continue with my project.

    FastAPI is great because all of this logic is now accessed with a 32 line API and only three methods (and a bunch of background libraries working magic). The API will return a string of the board that can be printed, and will receive a tuple of the piece to be moved when a player takes their turn. Other than that, the tuple simply reaches out to my game logic to actually manage the game state. Eventually I will build a front-end for this game and make it playable, and maybe even get it working so multiple people can play across a network. You can check out the code here!

 

Comments

Popular posts from this blog

API's in C#

Using WebRTC to build a videophone in React and TypeScript

Reviewing WPF and MVVM