Posts

Showing posts from June, 2015

The Snake Game

Image
This time we're going to look at the elegant algorithm behind the classic Snake game. # Definition First, we need a 2D grid and some constants to label the blocks, which are described bellow: HEAD follows input or block directions creates BODY blocks BODY represents the body of the snake TAIL follows block directions changes  TAIL  to  VOID changes BODY to TAIL FOOD suspends  TAIL  actions VOID represents an empty block Initially, the grid is created with all the blocks labeled as   VOID . # Illustration After we have the 2D grid, we need to create the snake itself and the food source. Currently, the snake has no BODY , only the HEAD and the TAIL , both with a left (⬅) direction specified: FOOD HEAD ⬅ TAIL ⬅

Image auto-cropper

Image
Back to image territory, to prove again that the 2D land is awesome. :-) In this post we're going to talk about image cropping and how to do this generically for any background color, even for backgrounds that have variations of the same color. # Finding the background color First, we need an algorithm to detect the background color, then we need to find where the background ends in all four parts of the image. The background color detection is the simplest part. We can take a pixel from one corner of the image and assume that this is the background color. To validate or invalidate this assumption, we have to test each edge of the image, pixel by pixel, to see if all pixels are about the same color. A clever way is by sampling pixels in larger steps and spiraling-in slowly until we checked all the pixels from a given row or column. For example, if we have a row of 100 pixels wide, the steps that we'll take in order to check all the edge pixels, are