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);
Game
and write any code in them. And the game engine itself will call them when the user presses the mouse buttons.
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.onMouseRightClick(int x, int y)
- Called when the right mouse button is clicked. Works similar to the methodonMouseLeftClick(int x, int y)
.
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);
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.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).
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 theonTurnTimer()
. An infinite number of times until the timer is turned off. How to use the timer?
-
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 methodonTurn()
every timeMs milliseconds. -
Redefine the onTurn(int) method.
To do this, you must declare a method
void onTurn(int step)
in a class that inherits from classGame
. 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, ...). -
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()
. -
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 callsonTurn()
will change.
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:
GO TO FULL VERSION