-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmoonBot.js
589 lines (506 loc) · 25.4 KB
/
moonBot.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
require('dotenv').config();
const { telegramEventMessages } = require('./eventMessages');
const { OperationCode } = require('./gameRules');
const EngineEvents = require('./engineEvents');
const EngineCommands = require('./engineCommands');
const { sprintf } = require('sprintf-js');
const TelegramBot = require('node-telegram-bot-api');
const { concatMap, map } = require('rxjs/operators');
const { partition, Subject } = require('rxjs');
const keyBoards = require('./telegramKeyboard');
const { Rules, GameEventType } = require('./gameRules');
const { Ok, Err, nullable } = require('pratica');
//main flow
//keeping simple https://xkcd.com/974/
const showStateEvent = Symbol.for("SHOW_GAME_STATE");
const Store = require('./store/storeContainer'); //redis store recommended for production
const commandStream = new Subject();
const Game = require('./moonGame')(Store);
const gameEventStream = Game.EventStream;
const eventStreams = eventSubscriptions(gameEventStream);
const statistics = require('./statistics/statistics')(gameEventStream);
const recorder = require('./recorder/recorder')(commandStream);
const bot = telegramBot();
configureTelegramBot(bot);
//end main flow
function telegramBot() {
const token = process.env.MOON_BOT_TOKEN;
const useWebHook = process.env.MOON_BOT_USE_WEBHOOK;
const public_url = process.env.MOON_BOT_PUBLIC_URL;
const public_port = process.env.MOON_BOT_PUBLIC_PORT;
const bind_port = process.env.MOON_BOT_BIND_PORT;
const bind_host = process.env.MOON_BOT_BIND_HOST_IP;
let initBot;
if (useWebHook) {
initBot = () => {
const options = {
webHook: {
bind_port,
bind_host
}
};
const bot = new TelegramBot(token, options);
bot.setWebHook(`${public_url}:${public_port}/bot${token}`);
return bot;
};
}
else {
initBot = () => {
const options = {
polling: true
};
return new TelegramBot(token, options);
};
}
return initBot();
}
function eventSubscriptions(eventStream) {
/*
* Obtain game event stream and subscribe for behavior
*/
function notify(messageData) {
const notifyMessage = () => sendMessage(messageData.playerId, messageData.chatId, messageData.message, messageData.keyBoard);
const notifyGameState = () => sendGameStatus(messageData.playerId, messageData.chatId, messageData.gameState);
return messageData.sendStatus ? notifyGameState() : notifyMessage();
}
function toMessage(event) {
const shouldBeFixKb = () => event.gameEvent && event.gameEvent.eventType === GameEventType.Ok;
return {
playerId: event.playerId,
chatId: event.gameState.id,
message: event.gameEvent ? telegramEventMessages[event.gameEvent.eventType] : telegramEventMessages[event.eventType],
keyBoard: shouldBeFixKb() ? keyBoards.fixKeyBoard(event.gameState.errors) : undefined,
gameState: event.gameState,
sendStatus: event.eventType === showStateEvent
};
}
//isolate events to react in a different way on each
[numBitsMissedEvents, restOfEvents] = partition(eventStream, event => event.eventType === EngineEvents.gameNumBitsMissed);
[numBugsMissedEvents, restOfEvents] = partition(restOfEvents, event => event.eventType === EngineEvents.gameNumBugsMissed);
[maxEnergyMissedEvents, restOfEvents] = partition(restOfEvents, event => event.eventType === EngineEvents.gameMaxEnergyMissed);
[useEventsMissedEvents, restOfEvents] = partition(restOfEvents, event => event.eventType === EngineEvents.gameUseEventsMissed);
[noGameInstanceEvents, restOfEvents] = partition(restOfEvents, event => event.eventType === EngineEvents.gameNotCreated);
[fixOperationApplied, restOfEvents] = partition(restOfEvents, event => event.eventType === EngineEvents.fixOperationApplied);
//on event send inlinekeyboard asking for num of bits
numBitsMissedEvents.subscribe({
next(event) {
return sendMessage(event.playerId, event.gameId, telegramEventMessages[event.eventType], keyBoards.numBitsKeyboard());
}
});
//on event send inlinekeyboard asking for num of bugs
numBugsMissedEvents.subscribe({
next(event) {
return sendMessage(event.playerId, event.gameId, telegramEventMessages[event.eventType], keyBoards.numBugsKeyboard(event.numBits));
}
});
//on event send inlinekeyboard asking for max energy value
maxEnergyMissedEvents.subscribe({
next(event) {
return sendMessage(event.playerId, event.gameId, telegramEventMessages[event.eventType], keyBoards.maxEnergyKeyboard(event.numBits, event.numBugs));
}
});
//on event send inlinekeyboard asking for use game events or not
useEventsMissedEvents.subscribe({
next(event) {
return sendMessage(event.playerId, event.gameId, telegramEventMessages[event.eventType], keyBoards.useEventsKeyboard(event.numBits, event.numBugs, event.maxEnergy));
}
});
//on events where there is not game instance
noGameInstanceEvents.subscribe({
next(event) {
return sendMessage(event.playerId, event.gameId, telegramEventMessages[event.eventType]);
}
});
//send message and send gameState
fixOperationApplied.subscribe({
next(event) {
commandStream.next({ type: EngineCommands.applyFix, gameId: event.gameState.id, gameUUID: event.gameState.uuid, playerId: event.playerId, error: event.error });
return sendMessage(event.playerId, event.gameState.id, telegramEventMessages[event.eventType]).
then(() => sendGameStatus(event.playerId, event.gameState.id, event.gameState));
}
});
/*react on the rest of the events
concatMap creates a observable for each async execution and subscribe to it before continue to the next async execution
this ensures the order of the messages sent to the chat.*/
restOfEvents.pipe(map(toMessage)).pipe(concatMap(messageData => notify(messageData))).subscribe();
return {
numBitsMissedEvents,
numBugsMissedEvents,
maxEnergyMissedEvents,
useEventsMissedEvents,
noGameInstanceEvents,
fixOperationApplied,
restOfEvents
};
}
function configureTelegramBot(bot) {
//configure bot behavior with regExp
bot.onText(/^\/start$/, InitConversationRequest);
bot.onText(/^\/creategame$/, CreateGameRequest);
bot.on('callback_query', inlineCallbackParser);
bot.onText(/^\/joingame$/, JoinGameRequest);
bot.onText(/^\/leavegame$/, LeaveGameRequest);
bot.onText(/^\/startgame$/, StartGameRequest);
bot.onText(/^\/status$/, StatusGameRequest);
bot.onText(/^\/endturn$/, EndTurnRequest);
bot.onText(/^\/cancelgame$/, CancellGameRequest);
bot.onText(/^\/help$/, HelpRequest);
bot.onText(/^\/rules$/, RulesRequest);
bot.onText(/^\/operations$/, OperationListRequest);
bot.onText(/^\/(inc|INC) ([A-D]|[a-d])$/, IncRequest);
bot.onText(/^\/(dec|DEC) ([A-D]|[a-d])$/, DecRequest);
bot.onText(/^\/(rol|ROL) ([A-D]|[a-d])$/, RolRequest);
bot.onText(/^\/(ror|ROR) ([A-D]|[a-d])$/, RorRequest);
bot.onText(/^\/(mov|MOV) ([A-D]|[a-d]) ([A-D]|[a-d])$/, MovRequest);
bot.onText(/^\/(not|NOT) ([A-D]|[a-d])$/, NotRequest);
bot.onText(/^\/(or|OR) ([A-D]|[a-d]) ([A-D]|[a-d])$/, OrRequest);
bot.onText(/^\/(and|AND) ([A-D]|[a-d]) ([A-D]|[a-d])$/, AndRequest);
bot.onText(/^\/(xor|XOR) ([A-D]|[a-d]) ([A-D]|[a-d])$/, XorRequest);
bot.onText(/^\/(add|ADD) ([A-D]|[a-d]) ([A-D]|[a-d])$/, AddRequest);
bot.onText(/^\/(sub|SUB) ([A-D]|[a-d]) ([A-D]|[a-d])$/, SubRequest);
bot.onText(/^\/(nor|NOR) ([A-D]|[a-d]) ([A-D]|[a-d])$/, NorRequest);
bot.onText(/^\/(nand|NAND) ([A-D]|[a-d]) ([A-D]|[a-d])$/, NandRequest);
bot.onText(/^\/(nxor|NXOR) ([A-D]|[a-d]) ([A-D]|[a-d])$/, NxorRequest);
function InitConversationRequest(msg) {
return bot.sendMessage(msg.chat.id, welcome_message(msg));
}
function CreateGameRequest(msg) {
return Game.CreateGame(msg.chat.id, msg.from.username);
}
//handle inline keyboard responses
function inlineCallbackParser(callbackQuery) {
let args = new Array();
args.push(callbackQuery.message.chat.id); //gameId
args.push(callbackQuery.from.username); //playerId
args = args.concat(callbackQuery.data.split(" "));
const isFix = () => args[2] === "fix"
? Ok(args[2])
: Err(args[2]);
isFix() //[gameId, playerId, fix, B]
.cata({
Ok: _ => Game.FixError.apply(Game, args),
Err: () => Game.CreateGame.apply(Game, args)
});
return bot.answerCallbackQuery(callbackQuery.id); //just finish the callback; the job will be done on missed events subscriptions
}
function JoinGameRequest(msg) {
return Game.JoinGame(msg.chat.id, msg.from.username); //will raise events
}
function LeaveGameRequest(msg) {
return Game.LeaveGame(msg.chat.id, msg.from.username); //will raise events
}
async function StartGameRequest(msg) {
(await Game.StartGame(msg.chat.id, msg.from.username))
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.startGame, gameUUID: gameState.uuid, playerId: msg.from.username, gameState });
},
Nothing: () => { }
});
}
async function StatusGameRequest(msg) {
(await Game.StatusGame(msg.chat.id, msg.from.username))
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
},
Nothing: () => { }
});
}
async function EndTurnRequest(msg) {
(await Game.EndPlayerTurn(msg.chat.id, msg.from.username))
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.endTurn, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username });
},
Nothing: () => { }
});
}
async function CancellGameRequest(msg) {
(await Game.CancelGame(msg.chat.id, msg.from.username))
.cata({
Just: gameState => {
commandStream.next({ type: EngineCommands.cancelGame, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username });
},
Nothing: () => { }
});
}
function HelpRequest(msg) {
return sendMessage(msg.from.username, msg.chat.id, help_message);
}
function RulesRequest(msg) {
return sendMessage(msg.from.username, msg.chat.id, rules_message);
}
function OperationListRequest(msg) {
return sendMessage(msg.from.username, msg.chat.id, opList_message);
}
//partial applied funcions to provide naming context makes this more readable
const ExecuteIncOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.inc);
const ExecuteDecOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.dec);
const ExecuteRolOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.rol);
const ExecuteRorOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.ror);
const ExecuteMovOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.mov);
const ExecuteNotOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.not);
const ExecuteOrOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.or);
const ExecuteAndOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.and);
const ExecuteXorOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.xor);
const ExecuteAddOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.add);
const ExecuteSubOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.sub);
const ExecuteNorOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.nor);
const ExecuteNandOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.nand);
const ExecuteNxorOperation = Game.ExecuteBitOperation.bind(Game, OperationCode.nxor);
async function IncRequest(msg, match) {
(await ExecuteIncOperation(msg.chat.id, msg.from.username, match[2].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.inc, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function DecRequest(msg, match) {
(await ExecuteDecOperation(msg.chat.id, msg.from.username, match[2].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.dec, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function RolRequest(msg, match) {
(await ExecuteRolOperation(msg.chat.id, msg.from.username, match[2].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.rol, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function RorRequest(msg, match) {
(await ExecuteRorOperation(msg.chat.id, msg.from.username, match[2].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.ror, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function MovRequest(msg, match) {
(await ExecuteMovOperation(msg.chat.id, msg.from.username, match[2].toUpperCase(), match[3].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.mov, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function NotRequest(msg, match) {
(await ExecuteNotOperation(msg.chat.id, msg.from.username, match[2].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.not, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function OrRequest(msg, match) {
(await ExecuteOrOperation(msg.chat.id, msg.from.username, match[2].toUpperCase(), match[3].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.or, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function AndRequest(msg, match) {
(await ExecuteAndOperation(msg.chat.id, msg.from.username, match[2].toUpperCase(), match[3].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.and, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function XorRequest(msg, match) {
(await ExecuteXorOperation(msg.chat.id, msg.from.username, match[2].toUpperCase(), match[3].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.xor, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function AddRequest(msg, match) {
(await ExecuteAddOperation(msg.chat.id, msg.from.username, match[2].toUpperCase(), match[3].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.add, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function SubRequest(msg, match) {
(await ExecuteSubOperation(msg.chat.id, msg.from.username, match[2].toUpperCase(), match[3].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.sub, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function NorRequest(msg, match) {
(await ExecuteNorOperation(msg.chat.id, msg.from.username, match[2].toUpperCase(), match[3].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.nor, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function NandRequest(msg, match) {
(await ExecuteNandOperation(msg.chat.id, msg.from.username, match[2].toUpperCase(), match[3].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.nand, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
async function NxorRequest(msg, match) {
(await ExecuteNxorOperation(msg.chat.id, msg.from.username, match[2].toUpperCase(), match[3].toUpperCase())) //use the partial applied functions above
.cata({
Just: gameState => {
gameEventStream.next({ eventType: showStateEvent, gameId: msg.chat.id, playerId: msg.from.username, gameState });
commandStream.next({ type: EngineCommands.applyOperation, gameId: gameState.id, gameUUID: gameState.uuid, playerId: msg.from.username, operation: OperationCode.nxor, target1: match[2].toUpperCase(), target2: undefined });
},
Nothing: () => { }
});
}
}
//gameState to telegram message
function buildStatusMessage(gameState) {
if (!gameState) { return null; }
const lockedRegister = (hasError) => hasError ? "\u{274C}" : "";
const lockedOperation = (hasError) => hasError ? "\u{274C}" : "\u{2705}";
const playerTurn = () => gameState.playerList[gameState.playerTurn].name;
const eneryLeft = () => gameState.playerList[gameState.playerTurn].energy;
const currentObjetive = () => gameState.currentObjetive.value.toString(2).padStart(gameState.numBits, "0".repeat(gameState.numBits));
const registerA = () => gameState.registers.A.toString(2).padStart(gameState.numBits, "0".repeat(gameState.numBits));
const registerB = () => gameState.registers.B.toString(2).padStart(gameState.numBits, "0".repeat(gameState.numBits));
const registerC = () => gameState.registers.C.toString(2).padStart(gameState.numBits, "0".repeat(gameState.numBits));
const registerD = () => gameState.registers.D.toString(2).padStart(gameState.numBits, "0".repeat(gameState.numBits));
const objetivesLeft = () => gameState.objetives.length;
const unresolved = () => gameState.unresolved;
const maxUnresolved = () => Rules.MaxUnresolvedValue - gameState.bugsFound;
return `\`\`\`
\u{1F5A5}
$> \u{1F468}\u{200D}\u{1F680} turn: ${playerTurn()}
$> ${eneryLeft()} \u{1F50B} left
$> Objetive:
-> ${currentObjetive()}
-----------------
A: ${registerA()}
-----------------
B: ${registerB()} ${lockedRegister(gameState.errors.B)}
-----------------
C: ${registerC()} ${lockedRegister(gameState.errors.C)}
-----------------
D: ${registerD()} ${lockedRegister(gameState.errors.D)}
-----------------
$> Instruction status:
ROL: ${lockedOperation(gameState.errors.ROL)}
NOT: ${lockedOperation(gameState.errors.NOT)}
XOR: ${lockedOperation(gameState.errors.XOR)}
$> \u{1F41E} found: ${gameState.bugsFound}
$> Objetive slot: ${unresolved()}/${maxUnresolved()}
$> Objetives in queue: ${objetivesLeft()}
$> man\`\`\` /operations`;
}
//send message if not null or undefined
function sendMessage(playerId, chatId, message, keyboard) {
if (!message) { return Promise.resolve(); }
return bot.sendMessage(chatId, sprintf(message, playerId), { parse_mode: "Markdown", reply_markup: keyboard });
}
//send game status if not null or undefined
function sendGameStatus(playerId, chatId, gameState) {
if (!gameState) { return Promise.resolve(); }
return sendMessage(playerId, chatId, buildStatusMessage(gameState));
}
function welcome_message(msg) {
return `Hello ${msg.from.username}.
You can check the /rules or /creategame and start playing in solo mode.
Add me to a group if you want to play with friends.
You can use /help to see all available commands.`;
}
const help_message =
`/rules - Shows a link about the game and pdf rules.
/creategame - Create a new game.
/joingame - Join into a created game. You can not join into a started game.
/leavegame - Player leaves the game. If last player leaves, the game is cancelled.
/startgame - Start the first round of a created game. Once started, no players can join it.
/status - Shows the current game status like player turn, player energy, current objetive, register values, unresolved objetives queue and objetives left.
/operations - Shows the list of register operations and its energy cost.
/endturn - Player ends the current turn.
/cancelgame - Cancel the created game. It can not be resumed.
/help - Shows this command list.
/inc - How to use: "/inc B".
/dec - How to use: "/dec B".
/rol - How to use: "/rol B".
/ror - How to use: "/ror B".
/mov - How to use: "/mov A C". Register A will be modified.
/not - How to use: "/not D".
/or - How to use: "/or C B". Register C will be modified.
/and - How to use: "/and C B". Register C will be modified.
/xor - How to use: "/xor C B". Register C will be modified.
/add - How to use: "/add C B". Register C will be modified.
/sub - How to use: "/sub C B". Register C will be modified.
/nor - How to use: "/nor C B". Register C will be modified.
/nand - How to use: "/nand C B". Register C will be modified.
/nxor - How to use: "/xor C B". Register C will be modified.`;
const rules_message =
`[What is moon (1110011)?](http://compus.deusto.es/moon/)\n
[Rule book](http://tiny.cc/moonboardgame-en)`;
const opList_message =
`
\`\`\`
Operation Target Cost
--------- ------ ----
inc 1 Reg 2 \u{1F50B}
dec 1 Reg 2 \u{1F50B}
rol 1 Reg 1 \u{1F50B}
ror 1 Reg 1 \u{1F50B}
mov 2 Reg 1 \u{1F50B}
not 1 Reg 1 \u{1F50B}
or 2 Reg 0.5\u{1F50B}
and 2 Reg 0.5\u{1F50B}
xor 2 Reg 0.5\u{1F50B}
add 2 Reg 1.5\u{1F50B}
sub 2 Reg 1.5\u{1F50B}
nor 2 Reg 1 \u{1F50B}
nand 2 Reg 1 \u{1F50B}
nxor 2 Reg 1 \u{1F50B}
All 2 register operations store the result in the first register.
"or A B" will modify register A.
"mov A B" will copy register B value into register A.\`\`\``;
process.on('SIGINT', async function () {
commandStream.complete();
await Game.Quit();
await statistics.quit();
await recorder.quit();
process.exit(0);
});