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:
- We need a place to instantiate our game
- 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:
- Part 1 - Introduction
- Part 2 - Creating a Scene
- Part 3 - Controller Input
- Part 4 - Game Loop
- Part 5 - Game Factory (you are here)
- Part 6 - Main Menu
- Part 7 - Model
- Part 8 - Game Scene
- Part 9 - Finalizing The Game
Let’s add the GameFactory class which will do those tasks for us:
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:
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.
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.