Kotlin short recipes: Generating a chessboard for a console game
Tags: kotlin, gamedev, showdev, tutorial
Published: 2021-12-29 09:35:54

## Introduction

Hello, DEV friends! 👋

This series of a really short (_but useful_) articles will aim at a general demonstration of how the [Kotlin](https://kotlinlang.org/docs/getting-started.html) language can elegantly solve many of the (_non-_)trivial problems.

> 🔥 Disclaimer: The purpose of this article is to show the essence of the solution, not to dive into the subject in detail. For a deeper dive, links to the Kotlin documentation pages will be left.

Yes, let's do it! 👇

<a name="toc"></a>
### 📝 Table of contents

- [The result of our efforts](#the-result-of-our-efforts)
- [Project structure](#project-structure)
- [Create the UI package](#create-the-ui-package)
- [Create the entry point](#create-the-entry-point)
- [Learn Kotlin](#learn-kotlin)

<a name="#the-result-of-our-efforts"></a>
## The result of our efforts

Let's go backwards. This will help you better understand what we will be trying to get out of this. 

I chose a game of chess to show you how to work with repetitive elements and draw a console UI for your projects (or even games). This is what the result of our program will look like:

```console
Let's play Chess!
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   | 8
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   | 7
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   | 6
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   | 5
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   | 4
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   | 3
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   | 2
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   | 1
+---+---+---+---+---+---+---+---+
  a   b   c   d   e   f   g   h
```

As you may notice, the numbers are on the right, not on the left, as many people have used to. This is because it is much easier to position elements in a line-by-line printout. 

> ☝️ If you don't like it that much, you can always change just one line of code (_which I'll show below_). That will be your homework! That's it, yeah.

[↑ Table of contents](#toc)

<a name="#project-structure"></a>
## Project structure

The structure of the project (game) will be as Kotlin [idiomatic](https://kotlinlang.org/docs/idioms.html) as possible. 

As always, the entry point will be in `Main.kt`. All UI elements and the drawing class itself in the `ui` package:

![project structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aibm4u2ng3bz484z8sfy.png)

[↑ Table of contents](#toc)

<a name="#create-the-ui-package"></a>
## Create the UI package

To improve reusability, let's immediately put some UI elements into the Kotlin's built-in [enum class](https://kotlinlang.org/docs/enum-classes.html):

```kotlin
// ./src/main/kotlin/ui/Element.kt

package ui

enum class Element(val view: String) {
    EMPTY_CELL(" "),
    DIVIDER("+---+---+---+---+---+---+---+---+"),
    ALPHABETICAL_INDEXES("a   b   c   d   e   f   g   h")
}
```

Okay, move on to the rendering engine itself. 

> 😉 By the way, I'll use a wonderful Kotlin [data classes](https://kotlinlang.org/docs/data-classes.html) for it.

So, let's create an array-structure with the given number of rows and cells and display the entire assembled UI via `println()` in our `draw()` method.

Sounds like a plan, let's do it! 👇

```kotlin
// ./src/main/kotlin/ui/Board.kt

package ui

data class Board(val title: String) {
    // Array for building the board:
    private val board = Array(8) { Array(8) { Element.EMPTY_CELL } }

    // Function for forming and drawing the board with
    fun draw() {
        // 1️⃣
        val boardAsString = board.mapIndexed { index, row ->
            val cells = row.joinToString(" | ") { it.view }
            "| $cells | ${index + 1}\n${Element.DIVIDER}"
        }

        println(title) // print game's title
        println(Element.DIVIDER) // print starting divider

        // 2️⃣
        println(boardAsString.reversed().joinToString("\n"))

        // print ending string with left padding
        println("  ${Element.ALPHABETICAL_INDEXES}")
    }
}
```

1️⃣ : To simplify, we will expand our array with the function [mapIndexed()](https://kotlinlang.org/docs/collection-transformations.html#map), where each element will be a string with an already prepared UI.

2️⃣ : To display line numbering reverse, we use Kotlin's built-in [reversed()](https://kotlinlang.org/docs/collection-ordering.html#reverse-order) function. And then just output the result using the [joinToString()](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/join-to-string.html) function, which specifies the string translation (`\n`), as an element separator.

[↑ Table of contents](#toc)

<a name="#create-the-entry-point"></a>
## Create the entry point

And, finally, let's create an entry point of our console game (`Main.kt`):

```kotlin
// ./src/main/kotlin/Main.kt

import ui.Board

fun main() {
    val board = Board("Let's play Chess!")
    board.draw()
}
```

> 💡 You can give your playing field any name you want. Just add it to the primary constructor of the `Board` data class.

Run our program (<kbd>Shift</kbd> + <kbd>Ctrl</kbd> + <kbd>R</kbd>) and 💥 BOOM 💥 everything works the way we wanted it to:

![result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/quf5uhy4u022hcxr9ezc.png)

[↑ Table of contents](#toc)

<a name="#learn-kotlin"></a>
## Learn Kotlin

Do you want to learn Kotlin? 👩‍🎓 👨‍🎓

Then come to [JetBrains Academy](https://hyperskill.org/join/9e07b927f), where there is a free basic course in this language for free! There you will find both theoretical part and many practical tasks of any level of complexity.

[↑ Table of contents](#toc)

<a name=""></a>
## Photos and videos by

- Kotlin mascot authors https://kotlinlang.org/docs/kotlin-mascot.html
- Vic Shóstak https://github.com/koddr

<a name=""></a>
## P.S.

If you want more articles (like this) on this blog, then post a comment below and subscribe to me. Thanks! 😻

And of course, you can help me make developers' lives even better! Just connect to one of my projects as a contributor. It's easy!

My projects that need your help (and stars) 👇

- 🔥 [gowebly][gowebly_url]: A next-generation CLI tool for easily build amazing web applications with Go on the backend, using htmx & hyperscript and the most popular atomic/utility-first CSS frameworks on the frontend.
- ✨ [create-go-app][cgapp_url]: Create a new production-ready project with Go backend, frontend and deploy automation by running one CLI command.
- 🏃 [yatr][yatr_url]: Yet Another Task Runner allows you to organize and automate your routine operations that you normally do in Makefile (or else) for each project.
- 📚 [gosl][gosl_url]: The Go Snippet Library provides snippets collection for working with routine operations in your Go programs with a super user-friendly API and the most efficient performance.
- 🏄‍♂️ [csv2api][csv2api_url]: The parser reads the CSV file with the raw data, filters the records, identifies fields to be changed, and sends a request to update the data to the specified endpoint of your REST API.
- 🚴 [json2csv][json2csv_url]: The parser can read given folder with JSON files, filtering and qualifying input data with intent & stop words dictionaries and save results to CSV files by given chunk size.

<!-- Footer links -->

[gowebly_url]: https://github.com/gowebly
[cgapp_url]: https://github.com/create-go-app
[yatr_url]: https://github.com/koddr/yatr
[gosl_url]: https://github.com/koddr/gosl
[csv2api_url]: https://github.com/koddr/csv2api
[json2csv_url]: https://github.com/koddr/json2csv