JavaRush /Java Blog /Random EN /Section "Games" on JavaRush: Game engine

Section "Games" on JavaRush: Game engine

Published in the Random EN group
“Games” from JavaRush is a new section that contains large task-projects for writing popular computer games. Making them is easier than it seems: each project is divided into two dozen subtasks. By completing the tasks step by step, you will write your game, and then you can add unique “features” to it and share it with friends. ChapterThe games use the simple JavaRush game engine . In this article we will talk about its key features and what the process of writing a game looks like.
  1. Introduction
  2. Game initialization
  3. Creating a playing field
  4. Primitive program
  5. Working with the cells of the playing field
  6. Working with color
  7. Dialog boxes
  8. Utility Methods
  9. Game engine limitations

1. Introduction

There are three stages in the implementation of a computer game on the part of the developer:
  1. Initialization of the game is preparatory actions: setting the size and drawing of the playing field, creating and installing game objects in the initial position, as well as other actions that must be performed at the beginning of the game.

  2. Game process. This includes the movement of game objects, player actions, accounting for points earned, as well as other actions that must be performed at certain intervals or by pressing buttons.

  3. Ending the game. This includes stopping animations, reporting victory or defeat, and other actions that need to be performed at the end of the game.

2. Game initialization

Initializing the game consists of just two steps:

Step 1: create the main game class.

To develop your game based on the JavaRush game engine, you need to create a class and inherit it from the Game class (com.javarush.engine.cell.Game). This will give your class the ability to call methods on the game engine, and the ability for the engine to call your methods. Example:
import com.javarush.engine.cell.Game;

public class MySuperGame extends Game {
    ...
}

Step 2: override the initialize() method.

In this method, all the actions necessary to start the game will take place: creating the playing field, creating game objects, etc. You just need to declare this method in a class that inherits from the Game class . Example:
import com.javarush.engine.cell.Game;

public class MySuperGame extends Game {

    @Override
    public void initialize() {
        //  Тут выполняем все действия по инициализации игры и ее an objectов
    }
}
The initialize() method is an analogue of the main() method : it is where all the code written for the game begins to be executed.

3. Creating a playing field

Creating a playing field also consists of only two steps.

Step 1: divide the playing field into cells.

The entire playing field is divided into cells by the game engine. The minimum size is 3x3, the maximum is 100x100. The game screen has a constant size. It can be divided into different numbers of cells. For example, width 7 and height 9:
Chapter
Please note that cell numbering starts from the upper left corner. To set the size of the playing field, use the void setScreenSize(int width, int height) method . It sets the size of the playing field. It takes as parameters the number of cells horizontally (width) and vertically (height). It is usually called once when the game starts. Example:
import com.javarush.engine.cell.Game;

public class MySuperGame extends Game {

    @Override
    public void initialize() {
       //  задали размер поля 7x9 клеток
       setScreenSize(7, 9);
        ...
    }
}
When writing a game, you may need to get the current width and height of the playing field. The int getScreenWidth() and int getScreenHeight() methods are useful for this .

Step 2: Turn the grid on or off (optional).

If you don't like the black grid that separates the cells on the playing field, you can turn it off. The void showGrid(boolean isShow) method turns the grid separating cells on and off. By default, the grid is displayed. To turn it off, call this method with the false parameter:
showGrid(false);
Result:
Chapter
To turn the grid back on, call:
showGrid(true);

4. Primitive program

Example program:
public class MySuperGame extends Game {

    @Override
    public void initialize() {

        //  Создаем игровое поле 3x3 клетки
        setScreenSize(3, 3);
        //  Выключаем отображение сетки
        showGrid(false);
        //  Меняем фон центральной клетки на синий, и отображаем в ней “Х”
        setCellValueEx(1, 1, Color.BLUE, "X", Color.ORANGE, 50);
    }
}
In this example, the size of the playing field is set to 3x3, the grid display is turned off, and an orange half-cell sized “X” symbol is placed in the center on a blue background. This will be the first thing the player sees when starting the game.

5. Working with the cells of the playing field

The fact that we can divide the playing field into cells is great, but what can we do with the cells themselves? Each cell of the playing field can be set:
  • cell color (cell background color);
  • text (text or number);
  • text color;
  • text size as a percentage relative to the cell size.
Let's consider methods for working with cells of the playing field :
  1. void setCellColor(int x, int y, Color color) — sets the color of the cell with coordinates (x, y):

    setCellColor(0, 0, Color.RED);
    setCellColor(3, 6, Color.BLACK);
    setCellColor(6, 8, Color.NONE);

  2. Color getCellColor(int x, int y) - returns the color of the cell with coordinates (x, y):

    Color myColor = getCellColor(2, 0);

  3. void setCellValue(int x, int y, String value) - places the text value in the cell with coordinates (x, y):

    setCellValue(3, 3, "text");
    setCellValue(0, 8, "W");
    setCellValue(4, 1, "2222");
    setCellValue(6, 6, "");

  4. String getCellValue(int x, int y) - returns the text contained in the cell with coordinates (x, y):

    String s = getCellValue(3, 3);
    System.out.println(getCellValue(4, 1));

  5. void setCellTextSize(int x, int y, int size) - sets the size of the content in the cell with coordinates (x, y). size – text height as a percentage of the cell height:

    setCellTextSize(2 , 0, 70); //  70% высоты клетки

  6. int getCellTextSize(int x, int y) - returns the size of the content in the cell with coordinates (x, y):

    int size = getCellTextSize(2 , 0);

  7. void setCellNumber(int x, int y, int value) - places the number value in the cell with coordinates (x, y):

    setCellNumber(3, 3, 40);
    setCellNumber(0, 8, -8);
    setCellNumber(4, 1, 2222);
    setCellNumber(6, 6, 0);

  8. int getCellNumber(int x, int y) - returns the number contained in the cell with coordinates (x, y). If the cell does not contain a number, returns 0:

    int i = getCellNumber(3, 3);
    System.out.println(getCellNumber(4, 1));

  9. void setCellTextColor(int x, int y, Color color) — sets the color of the content (text) in the cell with coordinates (x, y):

    setCellTextColor(2, 1, Color.GREEN);
    setCellTextColor(0, 1, Color.NONE);

  10. Color getCellTextColor(int x, int y) - returns the color of the content (text) in a cell with coordinates (x, y):

    Color textColor = getCellTextColor(1, 3);
For convenience, there are several setCellValueEx() methods with different sets of parameters:
  1. void setCellValueEx(int ​​x, int y, Color cellColor, String value) — sets the cell with coordinates (x, y) background color cellColor and content value:

    setCellValueEx(0, 2, Color.BLUE, "56");

  2. void setCellValueEx(int ​​x, int y, Color cellColor, String value, Color textColor) — sets the cell with coordinates (x, y) background color cellColor, content value and content color textColor:

    setCellValueEx(0, 2, Color.BLACK, "56", Color.GREEN);

  3. void setCellValueEx(int ​​x, int y, Color cellColor, String value, Color textColor, int textSize); — sets the cell with coordinates (x, y) background color cellColor, content value, content color textColor and content size textSize:

    setCellValueEx(0, 2, Color.BLACK, "56", Color.GREEN, 70);

6. Working with color

Colors in the game engine are controlled by the Color enum , which contains unique values ​​for 148 colors. And also the special value NONE - absence of color. Example of working with color:
Color myColor = Color.WHITE;  //  переменной myColor присваивается белый цвет.
Color redColor = Color.RED; //  переменной redColor присваивается красный цвет.
Color blueColor = Color.BLUE; //  переменной blueColor присваивается синий цвет.
Sometimes you may want to get an array of all existing colors. To do this, use the values() method . For example:
//  переменной colors присваивается массив, содержащий все доступные цвета.
Color[] colors = Color.values();
Getting the color number in the palette is very simple:
Color color = Color.RED;
int redIndex = color.ordinal(); //  Номер красного цвета

int blueIndex = Color.BLUE.ordinal(); //  Номер синего цвета
You can also get a color by its number:
//  переменной color присваивается цвет с индексом 10 из enum Color.
Color color = Color.values()[10];

7. Dialog boxes

At the end of the game, the player must be informed of victory or defeat. There is a special method for this that displays a dialog box on the game screen:
void showMessageDialog(Color cellColor, String message, Color textColor, int textSize)
Here:
  • cellColor — background color of the dialog box;
  • message — message text;
  • textColor — message text color;
  • textSize — message text size.
The dialog closes by itself if the user presses the space bar.

8. Utility methods

Random numbers are often used when writing games. To make it easier to obtain random numbers, you can use scrap engine methods:
  1. int getRandomNumber(int max) - returns a random integer from 0 to (max–1) inclusive.

  2. int getRandomNumber(int min, int max) - returns a random integer from min to (max–1) inclusive.

9. Game engine limitations

To run games on the site, they are translated into JavaScript on the server. In this regard, some restrictions arise. In particular, when writing games using the JavaRush engine, you cannot work with files, nor use all methods of the System class , except currentTimeMillis() , setOut() , setErr() , arrayscopy() . You can also use the err and out fields . By violating these restrictions, the game, of course, can be compiled and run, but it will not be possible to publish. You also won't be able to publish a game with infinite loops. That's all! If you want to learn more about the Games section, here is some useful documentation that can help:
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION