-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsend-msg.php
More file actions
60 lines (50 loc) · 1.52 KB
/
send-msg.php
File metadata and controls
60 lines (50 loc) · 1.52 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
<?php
declare(strict_types=1);
/**
* Custom Msg + `Cmd::send` — dispatch a self-defined message into
* the runtime to drive state transitions out-of-band from the
* input loop.
*
* php examples/send-msg.php
*
* Press space to schedule a tick that pings the model 1 sec later.
* Press 'q' to quit.
*/
require __DIR__ . '/../vendor/autoload.php';
use SugarCraft\Core\Cmd;
use SugarCraft\Core\KeyType;
use SugarCraft\Core\Model;
use SugarCraft\Core\Msg;
use SugarCraft\Core\Msg\KeyMsg;
use SugarCraft\Core\Program;
final class PingMsg implements Msg
{
public function __construct(public readonly int $count) {}
}
final class SendMsg implements Model
{
public function __construct(public readonly int $pings = 0) {}
public function init(): ?\Closure { return null; }
public function update(Msg $msg): array
{
if ($msg instanceof KeyMsg) {
if ($msg->type === KeyType::Char && $msg->rune === 'q') {
return [$this, Cmd::quit()];
}
if ($msg->type === KeyType::Space) {
// Schedule a delayed ping.
$next = $this->pings + 1;
return [$this, Cmd::tick(1.0, static fn (): Msg => new PingMsg($next))];
}
}
if ($msg instanceof PingMsg) {
return [new self($msg->count), null];
}
return [$this, null];
}
public function view(): string
{
return "Pings: {$this->pings}\n\n(space to schedule, q to quit)\n";
}
}
(new Program(new SendMsg()))->run();