Output a Colorful Chessboard

Difficulty: ★ ★ ★ ☆

Text mode need not be so dreary when it comes to generating a game of chess. You have several options, all of which stink to varying degrees.

The worst is shown in Figure 1, which is something I concocted in a brutal attempt to create an ugly text mode chessboard. I’m sure some vintage mainframe in the 1970s forced users to endure playing chess on such a thing. Yikes.

text mode chessboard

Figure 1. What could be a potential chess game on a terminal back in 1974.

Better is to use color to fashion a light, friendly version of a text mode chessboard. I covered ASNI color text output in a post from earlier this year. You could use such techniques to generate output such as shown in Figure 2.

colorful ANSI chessboard

Figure 1. A better text mode chessboard created with ANSI color output.

Your challenge for this month’s Exercise is to write code that generates the chessboard in Figure 2 as output. This task may seem trivial, but the difficultly level rises because the grid shows alternating colors. When you first write your code, you may see a striped pattern, not a grid. Extra decisions are required to output a grid.

As mentioned earlier, refer to the ANSI color Lessons for details on color output in C. The two codes/colors I use are defined in my solution as:

#define COLOR_WHITE "\x1b[30;47m"
#define COLOR_CYAN "\x1b[30;46m"

Both set black text in the foreground, but white and cyan colors for the background, as lovingly shown in Figure 2.

Please try this exercise on your own before you check out my solution. This code is used in later posts to generate chessboard output for my Knight Moves series of lessons.

Leave a Reply