JavaRush /Java Blog /Random EN /Section "Games" on JavaRush: Handling events

Section "Games" on JavaRush: Handling events

Published in the Random EN group
"Games" by CodeGym is a new section with interesting and large-scale tasks for creating your own versions of popular games. It's simple: each game project is divided into subtasks. Complete them one by one - the game is ready. You can share it on social networks and invite your friends to play. ChapterIn this article, we will talk in detail about the methods of handling events when writing games.

1. Working with the mouse

The game engine has two methods for working with the mouse:
  • void onMouseLeftClick(int x, int y);

  • void onMouseRightClick(int x, int y);
You simply declare these methods in the game class inherited from Gameand write any code in them. And the game engine itself will call them when the user presses the mouse buttons.
  1. onMouseLeftClick(int x, int y)- called by the engine when the left mouse button is clicked. As arguments, it receives the coordinates of the playing field cell where the click occurred. The top left cell has coordinates (0,0). To use this method, it must be overridden.

  2. onMouseRightClick(int x, int y)- Called when the right mouse button is clicked. Works similar to the method onMouseLeftClick(int x, int y).
An example of using methods:
import com.codegym.engine.cell.Color;
import com.codegym.engine.cell.Game;
import com.codegym.engine.cell.Key;

public class MySuperGame extends Game {
    @Override
    public void initialize() {
        // Устанавливаем размер игрового поля 3x3
        setScreenSize(3, 3);

        // Закрашиваем игровое поле белым цветом
        for (int x = 0; x < 3; x++) {
            for (int y = 0; y < 3; y++) {
                setCellColor(x, y, Color.WHITE);
            }
        }
    }

    @Override
    public void onMouseLeftClick(int x, int y) {
        // Ставим символ "X" в клетку по которой кликнули левой кнопкой мыши
        setCellValue(x, y, "X");
    }

    @Override
    public void onMouseRightClick(int x, int y) {
        // Очищаем клетку по которой кликнули правой кнопкой мыши
        setCellValue(x, y, "");
    }
}

2. Working with the keyboard

The game engine has two methods for working with the keyboard:
  • void onKeyPress(Key key);

  • void onKeyReleased(Key key);
If you want actions to be performed when the user presses a button on the keyboard, declare these methods in your game class that inherits from Game and write your code in them. The game engine will automatically call them when the user presses or releases a keyboard key.
  1. onKeyPress (Key key)Called when any key on the keyboard is pressed. The value of the pressed key (or Key.UNKNOWN) is passed to the method as the key argument.

  2. onKeyReleased (Key key)Called when any key on the keyboard is released. The key argument takes the value of the corresponding key (or Key.UNKNOWN).
An example of using methods:
import com.codegym.engine.cell.Color;
import com.codegym.engine.cell.Game;
import com.codegym.engine.cell.Key;

public class MySuperGame extends Game {
    @Override
    public void initialize() {
        // Устанавливаем размер игрового поля 3x3
        setScreenSize(3, 3);

        // Закрашиваем игровое поле белым цветом
        for (int x = 0; x < 3; x++) {
            for (int y = 0; y < 3; y++) {
                setCellColor(x, y, Color.WHITE);
            }
        }
    }

    @Override
    public void onKeyPress(Key key) {
        // При нажатии пробела, центральная клетка становится желтой
        if (key == Key.SPACE) {
            setCellColor(1, 1, Color.YELLOW);
        }
    }

    @Override
    public void onKeyReleased(Key key) {
        // При отпускании пробела, центральной клетке возвращается белый цвет
        if (key == Key.SPACE) {
            setCellColor(1, 1, Color.WHITE);
        }
    }
}
Important! In the current version of the engine, the Key type can only take a limited set of values ​​(9 pcs):
Meaning What the user clicked
Key.ENTER The user pressed the Enter button
Key.ESCAPE The user pressed the Esc button
Key.PAUSE The user pressed the Pause button
Key.SPACE User pressed Space
Key.LEFT The user pressed the Left Arrow
Key.RIGHT The user pressed the Right Arrow
Key.UP The user pressed the Up Arrow
Key DOWN The user pressed the Down Arrow
Key.UNKNOWN Any key other than the above

3. Working with a timer

Many games take place in real time, that is, even if the user does nothing, the events in the game are still being executed. To enable you to implement such games, we have added a timer to the game engine. It works like this: you turn on the timer and set the time interval after which it should work. For example, 500 milliseconds. After that, every half second, the Game Engine calls the onTurnTimer(). An infinite number of times until the timer is turned off. How to use the timer?
  1. We turn on the timer.

    There is a special method for this void setTurnTimer(int timeMs). As an argument, the method takes the duration of the interval between calls in milliseconds (1/1000 of a second). It is enough to call it once, and the game engine will start calling the method onTurn()every timeMs milliseconds.

  2. Redefine the onTurn(int) method.

    To do this, you must declare a method void onTurn(int step)in a class that inherits from class Game. This method will be called by the game engine. In this case, the engine will each time pass the sequence number of such a call to the method (1,2,3, ...).

  3. Turn off the timer.

    If the timer is no longer needed when, for example, the user has completed the game, it can be turned off. To do this, you just need to call the stopTurnTimer().

  4. Speed ​​up or change the timer.

    In some games, events are constantly speeding up, so it would be convenient to speed up our timer (reduce the time between calls). There is nothing easier: call setTurnTimer(int timeMs)again, with a new value, and the time between calls onTurn()will change.

Example:
import com.codegym.engine.cell.Color;
import com.codegym.engine.cell.Game;

public class MySuperGame extends Game {@Override
    public void initialize() {
    	// Создаем игровое поле 3x3 клетки
        setScreenSize(3, 3);
        showGrid(false);
        setCellValueEx(1, 1, Color.BLUE, "X", Color.ORANGE, 50);

        setTurnTimer(500);   //Включаем таймер, интервал между вызовами – 500мс.
    }

    @Override
    public void onTurn(int step) {
        if(step == 100) {
            stopTurnTimer();  // если прошло 100 тактов, выключаем таймер
        }

        if (step % 2 == 1) {
            // Если данный такт нечётный, установить клетке красный фон
            setCellColor(1, 1, Color.RED);
        } else {
            //если данный такт чётный, установить клетке синий фон
            setCellColor(1, 1, Color.BLUE);

        }
    }}
In this simple example, we have created a 3x3 box. Then we turned on a timer that will call the onTurn(). Every half second, the color of the cell will change, while its content will not change. After 50 seconds, the color will stop changing. That's all! If you'd like to learn more about the Games section, here's some helpful documentation to help you:
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION