In an earlier post, I shared a couple of fundamental search and navigation algorithms. You can read it here. In this blog post, I’ll share a fun implementation, a gamification using one of the algorithms. The premise is simple: We have a seeker (depicted by a bandit) whose objective is to find a target (a bag of money) in a given space. There’s also an obstacle (depicted by a police car) in that space. If he finds the money, he bags it and wins. If he runs into the obstacle first, he loses. The starting position of the seeker, target, and the obstacle are randomly placed each time we run the script. After each run, user is prompted to run again or quit. User can continue to play indefinitely, or decide to quit the game. When user decides not to run again, a summary of the session is shown in the shell output (bottom of the game widget) that includes the number of sessions run, percentage of win vs loss (for example: Sims:5 | wins %: 40.00 | losses %: 60.00
)
. Let’s take a closer look.
Sample clip 1 of a session:
Sample clip 2 of a session:
You can also play a smaller version of the game using a 5×5 grid below directly from this page. Click on Run on the widget below.
About the Code:
This is written in Python and uses tkinter library and PIL (pillow) library for GUI and image manipulation. The algorithm I’m using here is BFS, but with a twist for gamification. Without a twist, the algorithm would make the seeker always explore the space strictly according to the algorithm, which quickly would become predictable and boring. So, there’s a random factor involved which makes the seeker make some unpredictable moves, not necessarily always finding the shortest path to the target. In fact, the seeker is not at all informed of the locations of the target or the obstacle until it actually encounters them. The design uses object-oriented approach with the entire core script based on a GridGame class which has its properties (for the canvas/grid, seeker, target, obstacle, tiles or cells) and methods (functions to control each object, navigation of the seeker, graphics, and overall flow of the program). The data structure is a double-queue (“deque”) to keep track of and update the cells (each cell position is an item in the queue) that are explored, unexplored, and control the seeker’s navigation path. The grid size can be of any size by changing one line of code to specify the desired dimension. With a few lines of additional code, it can also have multiple obstacles and different types of targets.
I hope this was educational and interesting. You can get the full source code from my Patreon shop here (secure transaction).
Related: