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

Section "Games" on JavaRush: Event Handling

Published in the Random EN group
“Games” from JavaRush 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 and the game is ready. You can share it on social networks and invite friends to play. ChapterIn this material we will talk in detail about methods of event processing 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 Game, and 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 you click the left mouse button. As arguments, it receives the coordinates of the cell of the playing field 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 you right-click. Works similar to the method onMouseLeftClick(int x, int y).
Example of using methods:

import com.javarush.engine.cell.Color;
import com.javarush.engine.cell.Game;
import com.javarush.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 occur 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 itself will call them when the user presses or releases a keyboard key.
  1. onKeyPress (Key key)— called when any keyboard key 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 keyboard key is released. The key argument takes the value of the corresponding key (or Key.UNKNOWN).
Example of using methods:

import com.javarush.engine.cell.Color;
import com.javarush.engine.cell.Game;
import com.javarush.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 accept 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 clicked the Pause button
Key.SPACE The 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 except the ones listed above

3. Working with the timer

Many games take place in real time, meaning that even if the user does nothing, the events in the game are still executed. So that you can implement such games, we have added timer functionality to the game engine. It works something like this: you turn on the timer and set the time period after which it should go off. 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. 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. We override the onTurn(int) method.

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

  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 simpler: call setTurnTimer(int timeMs)again, with a new value, and the time between calls onTurn()will change.

Example:

import com.javarush.engine.cell.Color;
import com.javarush.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 created a field of 3x3 cells. Then we turned on a timer that will call the method every half second onTurn(). Every half second the color of the cell will change, but its content will not change. After 50 seconds the color will stop changing. 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