-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathJoystick.php
More file actions
62 lines (55 loc) · 1.51 KB
/
Copy pathJoystick.php
File metadata and controls
62 lines (55 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
namespace DesignPatterns\Behavioral\Command;
/**
* Joystick represents a manipulator with few keys. When key is pressed on joystick the method of `Field` must be called.
* This class is completely decoupled from `Field` and it has no means to call its methods directly.
* Instead the joystick calls the appropriate methods of `Field` by means of `Command` objects.
*
* Corresponds to `Invoker` in the Command pattern.
*
* @author Vlad Riabchenko <contact@vria.eu>
*/
class Joystick
{
/**
* Available keys.
* Array that maps string requests "left", "right", etc. to commands LestCommand, RightCommand, etc.
*
* @var CommandInterface[]
*/
private $keyboard = [];
/**
* Command history
*
* @var array
*/
private $requests = [];
/**
* Add a new key to the joystick
*
* @param $key
* @param CommandInterface $command
*/
public function addKey($key, CommandInterface $command)
{
$this->keyboard[$key] = $command;
}
/**
* Press key, execute command
*
* @param string $key
*/
public function pressKey($key)
{
$this->requests[] = $key; // Save the request to history
$this->keyboard[$key]->move(); // Execute command
}
/**
* Undo last move
*/
public function undo()
{
$lastRequest = array_pop($this->requests); // get last key pressed, delete it from history of requests
$this->keyboard[$lastRequest]->moveBack(); // Undo command
}
}