DEV Community

Cover image for Kotlin short recipes: Generating a chessboard for a console game
Vic Shóstak
Vic Shóstak

Posted on

Kotlin short recipes: Generating a chessboard for a console game

Introduction

Hello, DEV friends! 👋

This series of a really short (but useful) articles will aim at a general demonstration of how the Kotlin 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! 👇

📝 Table of contents

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:

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

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

Project structure

The structure of the project (game) will be as Kotlin idiomatic 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

↑ Table of contents

Create the UI package

To improve reusability, let's immediately put some UI elements into the Kotlin's built-in enum class:

// ./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")
}
Enter fullscreen mode Exit fullscreen mode

Okay, move on to the rendering engine itself.

😉 By the way, I'll use a wonderful Kotlin data classes 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! 👇

// ./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}")
    }
}
Enter fullscreen mode Exit fullscreen mode

1️⃣ : To simplify, we will expand our array with the function mapIndexed(), 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() function. And then just output the result using the joinToString() function, which specifies the string translation (\n), as an element separator.

↑ Table of contents

Create the entry point

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

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

import ui.Board

fun main() {
    val board = Board("Let's play Chess!")
    board.draw()
}
Enter fullscreen mode Exit fullscreen mode

💡 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 (Shift + Ctrl + R) and 💥 BOOM 💥 everything works the way we wanted it to:

result

↑ Table of contents

Learn Kotlin

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

Then come to JetBrains Academy, 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

Photos and videos by

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 support me by donating at LiberaPay. Each donation will be used to write new articles and develop non-profit open-source projects for the community.

Support author at LiberaPay

Discussion (2)

Collapse
mariusty profile image
mariusty

Wanna more game-related articles :)

Collapse
koddr profile image
Vic Shóstak Author

As you wish! 😉