Kotlin Game Development: Game Factory

We already have a set of components for controlling the game loop, drawing on a screen and processing the input events so why do we need something else? There are two key things that are still missing:

  1. We need a place to instantiate our game
  2. Our game needs a window so we have to provide it

This is the fifth part of the “Kotlin Game Development” series and it’s better if you read it in chronological order:

  1. Part 1 - Introduction
  2. Part 2 - Creating a Scene
  3. Part 3 - Controller Input
  4. Part 4 - Game Loop
  5. Part 5 - Game Factory (you are here)
  6. Part 6 - Main Menu
  7. Part 7 - Model
  8. Part 8 - Game Scene
  9. Part 9 - Finalizing The Game

Let’s add the GameFactory class which will do those tasks for us:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.bubelov.snake.engine

import java.awt.Dimension
import javax.swing.WindowConstants
import java.awt.BorderLayout
import javax.swing.JFrame

object GameFactory {
    fun create(screenSize: Dimension): Game {
        val game = Game(screenSize)

        JFrame().apply {
            isResizable = false
            isVisible = true

            layout = BorderLayout()
            add(game)
            pack()

            defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
            setLocationRelativeTo(null)
        }

        game.createBufferStrategy(2)
        game.requestFocus()
        return game
    }
}

How Does It Work?

The only input argument we get is the screen size. It can vary from game to game so we shouldn’t hard code the screen size in order to make this factory reusable.

Our game can’t appear on the screen if there is no window to host it. The code above uses a JFrame to create the game window. We should also make sure that the game is visible and that the window is not resizable by default. The only line that seems a bit odd is setLocationRelativeTo(null) and it simply means that we want our game window to be placed right in the center of a computer screen.

The last step is to create a buffer strategy and request the input focus so our game can receive the input events from a keyboard.

Launching A Game

Let’s create a new file and call it Main.kt which will serve as an entry point to our game. Here is the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package com.bubelov.snake

import com.bubelov.snake.engine.GameFactory
import com.bubelov.snake.scene.MainMenuScene
import java.awt.Dimension

fun main(args: Array<String>) {
    val screenSize = Dimension(660, 660)
    val game = GameFactory.create(screenSize)
    game.play()
}

Now we can launch our game engine and see if it works so feel free to do it. You should see the empty white window in the center of your screen.

What’s Next

Our game engine is up and running and that means we can start using it. Our next goal is to create a simple scene to demonstrate how to draw on the screen and handle user input.