-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathBMInterfaceGame.php
More file actions
1745 lines (1585 loc) · 59.3 KB
/
BMInterfaceGame.php
File metadata and controls
1745 lines (1585 loc) · 59.3 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
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* BMInterfaceGame: interface between GUI and BMGame for all game-related requests
*
* @author james
*/
/**
* This class deals with communication between the UI, the game code, and the database
*/
class BMInterfaceGame extends BMInterface {
/**
* Create a game
*
* @param array $playerIdArray
* @param array $buttonNameArray
* @param int $maxWins
* @param string $description
* @param int|NULL $previousGameId
* @param int|NULL $currentPlayerId
* @param bool $autoAccept
* @param array $customRecipeArray
* @return array|NULL
*/
public function create_game(
array $playerIdArray,
array $buttonNameArray,
$maxWins = 3,
$description = '',
$previousGameId = NULL,
$currentPlayerId = NULL,
$autoAccept = TRUE,
array $customRecipeArray = array()
) {
$isValidInfo =
$this->validate_game_info(
$playerIdArray,
$maxWins,
$previousGameId,
$buttonNameArray,
$customRecipeArray
);
if (!$isValidInfo) {
return NULL;
}
$buttonIdArray = $this->retrieve_button_ids($playerIdArray, $buttonNameArray);
if (is_null($buttonIdArray)) {
return NULL;
}
try {
if (!isset($currentPlayerId)) {
throw new LogicException(
"$currentPlayerId must be set"
);
}
$gameId = $this->insert_new_game(
$playerIdArray,
$maxWins,
$description,
$previousGameId,
$currentPlayerId
);
foreach ($playerIdArray as $position => $playerId) {
$hasAcceptedGame = ($playerId === $currentPlayerId) ||
$autoAccept ||
$this->retrieve_player_autoaccept($playerId);
$this->add_player_to_new_game(
$gameId,
$playerId,
$buttonIdArray[$position],
$position,
$hasAcceptedGame
);
}
$this->set_random_button_flags($gameId, $buttonNameArray);
if (!$this->set_custom_recipes($gameId, $buttonNameArray, $customRecipeArray)) {
return NULL;
}
// update game state to latest possible
$game = $this->load_game($gameId, NULL, TRUE);
$prevState = $game->gameState;
if (!($game instanceof BMGame)) {
throw new UnexpectedValueException(
"Could not load newly-created game $gameId"
);
}
$game->log_action(
'create_game',
0,
array(
'creatorId' => $currentPlayerId,
)
);
if ($previousGameId) {
$chatNotice = '[i]Continued from [game=' . $previousGameId . '][i]';
$game->add_chat(-1, $chatNotice);
}
$this->save_game($game, $prevState);
$this->set_message("Game $gameId created successfully.");
return array('gameId' => $gameId);
} catch (Exception $e) {
$this->set_message('Game create failed: ' . $e->getMessage());
error_log(
'Caught exception in BMInterface::create_game: ' .
$e->getMessage()
);
return NULL;
}
}
/**
* Insert a new game
*
* @param array $playerIdArray
* @param int $maxWins
* @param string $description
* @param int|NULL $previousGameId
* @param int|NULL $creatorId
* @return int|NULL
*/
protected function insert_new_game(
array $playerIdArray,
$maxWins = 3,
$description = '',
$previousGameId = NULL,
$creatorId = NULL
) {
try {
// create basic game details
$query = 'INSERT INTO game '.
' (status_id, '.
' n_players, '.
' n_target_wins, '.
' n_recent_passes, '.
' creator_id, '.
' start_time, '.
' description, '.
' previous_game_id) '.
'VALUES '.
' ((SELECT id FROM game_status WHERE name = :status), '.
' :n_players, '.
' :n_target_wins, '.
' :n_recent_passes, '.
' :creator_id, '.
' FROM_UNIXTIME(:start_time), '.
' :description, '.
' :previous_game_id)';
$parameters = array(':status' => 'OPEN',
':n_players' => count($playerIdArray),
':n_target_wins' => $maxWins,
':n_recent_passes' => 0,
':creator_id' => $creatorId,
':start_time' => time(),
':description' => $description,
':previous_game_id' => $previousGameId);
self::$db->update($query, $parameters);
$gameId = self::$db->select_single_value('SELECT LAST_INSERT_ID()', array(), 'int');
return $gameId;
} catch (Exception $e) {
$this->set_message('Game create failed: ' . $e->getMessage());
error_log(
'Caught exception in BMInterface::insert_new_game: ' .
$e->getMessage()
);
return NULL;
}
}
/**
* Add player to new game
*
* @param int $gameId
* @param int $playerId
* @param int $buttonId
* @param int $position
* @param bool $hasAccepted
*/
protected function add_player_to_new_game($gameId, $playerId, $buttonId, $position, $hasAccepted) {
// add info to game_player_map
$query = 'INSERT INTO game_player_map '.
'(game_id, player_id, button_id, position, has_player_accepted) '.
'VALUES '.
'(:game_id, :player_id, :button_id, :position, :has_player_accepted)';
$parameters = array(':game_id' => $gameId,
':player_id' => $playerId,
':button_id' => $buttonId,
':position' => $position,
':has_player_accepted' => $hasAccepted);
self::$db->update($query, $parameters);
}
/**
* Set flags indicating whether each button has been chosen randomly
*
* @param int $gameId
* @param array $buttonNameArray
*/
protected function set_random_button_flags($gameId, array $buttonNameArray) {
foreach ($buttonNameArray as $position => $buttonName) {
if ('__random' == $buttonName) {
$query = 'UPDATE game_player_map '.
'SET is_button_random = 1 '.
'WHERE game_id = :game_id '.
'AND position = :position;';
$parameters = array(':game_id' => $gameId,
':position' => $position);
self::$db->update($query, $parameters);
}
}
}
/**
* Set custom recipes
*
* @param int $gameId
* @param array $buttonNameArray
* @param array $customRecipeArray
*/
protected function set_custom_recipes(
$gameId,
array $buttonNameArray,
array $customRecipeArray
) {
if (!in_array('CustomBM', $buttonNameArray)) {
return TRUE;
}
if (empty($customRecipeArray)) {
return FALSE;
}
// james: the custom recipe has theoretically already been checked for validity
// in create_game()->validate_game_info(), but we include it here again in case
// we call set_custom_recipes() from somewhere else
if (!$this->are_custom_recipes_valid($buttonNameArray, $customRecipeArray)) {
return FALSE;
}
foreach ($buttonNameArray as $position => $buttonName) {
if ('CustomBM' == $buttonName) {
$query = 'UPDATE game_player_map '.
'SET alt_recipe = :custom_recipe '.
'WHERE game_id = :game_id '.
'AND position = :position;';
$parameters = array(':custom_recipe' => trim($customRecipeArray[$position]),
':game_id' => $gameId,
':position' => $position);
self::$db->update($query, $parameters);
}
}
return TRUE;
}
protected function are_custom_recipes_valid(
array $buttonNameArray,
array $customRecipeArray
) {
foreach ($buttonNameArray as $position => $buttonName) {
if ('CustomBM' == $buttonName) {
if ($this->get_config('site_type') != 'development') {
$this->set_message('Custom recipes can only be used on development sites.');
return FALSE;
}
if (empty($customRecipeArray)) {
$this->set_message('customRecipeArray must be supplied');
return FALSE;
}
$customRecipe = trim($customRecipeArray[$position]);
if (empty($customRecipe)) {
$this->set_message('Custom recipe cannot be empty.');
return FALSE;
}
$tempButton = new BMButton;
try {
$tempButton->load($customRecipe, 'CustomBM', TRUE, TRUE, TRUE);
} catch (BMExceptionDieRecipe $e) {
$eInner = $e;
while ($eInner->getPrevious()) {
$eInner = $eInner->getPrevious();
}
$this->set_message($eInner->getMessage());
return FALSE;
} catch (BMExceptionButtonRecipe $e) {
$eInner = $e;
while ($eInner->getPrevious()) {
$eInner = $eInner->getPrevious();
}
$this->set_message($eInner->getMessage());
return FALSE;
} catch (InvalidArgumentException $e) {
$this->set_message('Custom recipe ' . $customRecipe .
' is invalid.');
return FALSE;
} catch (Exception $e) {
return FALSE;
}
if ($tempButton->hasUnimplementedSkill) {
$this->set_message('Custom recipe ' . $customRecipe .
' is not allowed to contain unimplemented skills.');
return FALSE;
}
}
}
return TRUE;
}
/**
* Validate game parameters for a new game
*
* @param array $playerIdArray
* @param int $maxWins
* @param int|NULL $previousGameId
* @return bool
*/
protected function validate_game_info(
array $playerIdArray,
$maxWins,
$previousGameId,
array $buttonNameArray,
array $customRecipeArray
) {
if (!$this->validate_player_id_array($playerIdArray)) {
return FALSE;
}
if (FALSE ===
filter_var(
$maxWins,
FILTER_VALIDATE_INT,
array('options'=>
array('min_range' => 1,
'max_range' => 5))
)) {
$this->set_message('Game create failed because the maximum number of wins was invalid.');
return FALSE;
}
// Check that players match those from previous game, if specified
$arePreviousPlayersValid =
$this->validate_previous_game_players($previousGameId, $playerIdArray);
if (!$arePreviousPlayersValid) {
return FALSE;
}
// check that the first button has been specified
if (empty($buttonNameArray[0])) {
$this->set_message("The first button needs to be set.");
return FALSE;
}
if (!$this->are_custom_recipes_valid($buttonNameArray, $customRecipeArray)) {
return FALSE;
}
return TRUE;
}
/**
* Validate player ID array that required players are specified, unique, and valid
*
* @param array $playerIdArray
* @return bool
*/
protected function validate_player_id_array(array $playerIdArray) {
// check that the game has at least two players
if (count($playerIdArray) < 2) {
$this->set_message('Game create failed because there are not enough players.');
return FALSE;
}
// check that the first player has been specified
if (is_null($playerIdArray[0])) {
$this->set_message('Game create failed because the first player was not specified.');
return FALSE;
}
$areAllPlayersPresent = TRUE;
// check for the possibility of unspecified players
foreach ($playerIdArray as $playerId) {
if (is_null($playerId)) {
$areAllPlayersPresent = FALSE;
}
}
// check for nonunique player ids
if ($areAllPlayersPresent &&
count(array_flip($playerIdArray)) < count($playerIdArray)) {
$this->set_message('Game create failed because a player has been selected more than once.');
return FALSE;
}
foreach ($playerIdArray as $playerId) {
if (!(is_null($playerId) || is_int($playerId))) {
$this->set_message('Game create failed because player ID is not valid.');
return FALSE;
}
}
return TRUE;
}
/**
* Validate that the players in the previous game were the same as the current game
*
* @param int $previousGameId
* @param array $playerIdArray
* @return bool
*/
protected function validate_previous_game_players($previousGameId, array $playerIdArray) {
// If there was no previous game, then there's nothing to worry about
if ($previousGameId == NULL) {
return TRUE;
}
try {
$query =
'SELECT pm.player_id, s.name AS status ' .
'FROM game g ' .
'INNER JOIN game_player_map pm ON pm.game_id = g.id ' .
'INNER JOIN game_status s ON s.id = g.status_id ' .
'WHERE g.id = :previous_game_id;';
$parameters = array(':previous_game_id' => $previousGameId);
$columnReturnTypes = array(
'player_id' => 'int',
'status' => 'str',
);
$rows = self::$db->select_rows($query, $parameters, $columnReturnTypes);
$previousPlayerIds = array();
foreach ($rows as $row) {
if (($row['status'] != 'COMPLETE') &&
($row['status'] != 'CANCELLED')) {
$this->set_message(
'Game create failed because the previous game has not been completed yet.'
);
return FALSE;
}
$previousPlayerIds[] = $row['player_id'];
}
if (count($previousPlayerIds) == 0) {
$this->set_message(
'Game create failed because the previous game was not found.'
);
return FALSE;
}
foreach ($playerIdArray as $newPlayerId) {
if (!in_array($newPlayerId, $previousPlayerIds)) {
$this->set_message(
'Game create failed because the previous game does not contain the same players.'
);
return FALSE;
}
}
foreach ($previousPlayerIds as $oldPlayerId) {
if (!in_array($oldPlayerId, $playerIdArray)) {
$this->set_message(
'Game create failed because the previous game does not contain the same players.'
);
return FALSE;
}
}
return TRUE;
} catch (Exception $e) {
error_log(
'Caught exception in BMInterface::validate_previous_game_players: ' .
$e->getMessage()
);
$this->set_message('Game create failed because of an error.');
return FALSE;
}
}
/**
* Retrieve button IDs
*
* @param array $playerIdArray
* @param array $buttonNameArray
* @return array
*/
protected function retrieve_button_ids($playerIdArray, $buttonNameArray) {
$buttonIdArray = array();
foreach (array_keys($playerIdArray) as $position) {
// get button ID
$buttonName = $buttonNameArray[$position];
if ('__random' == $buttonName) {
$buttonIdArray[] = NULL;
} elseif (!empty($buttonName)) {
try {
$query = 'SELECT id FROM button '.
'WHERE name = :button_name';
$parameters = array(':button_name' => $buttonName);
$buttonIdArray[] = self::$db->select_single_value($query, $parameters, 'int');
} catch (BMExceptionDatabase $e) {
$this->set_message('Game create failed because a button name was not valid.');
return NULL;
} catch (Exception $e) {
error_log(
'Caught exception in BMInterface::retrieve_button_ids: ' .
$e->getMessage()
);
return NULL;
}
} else {
$buttonIdArray[] = NULL;
}
}
return $buttonIdArray;
}
/**
* Retrieve the autoaccept setting for a player
*
* @param int $playerId
* @return bool
*/
protected function retrieve_player_autoaccept($playerId) {
try {
$query = 'SELECT autoaccept FROM player '.
'WHERE id = :player_id';
$parameters = array(':player_id' => $playerId);
return self::$db->select_single_value($query, $parameters, 'bool');
} catch (BMExceptionDatabase $e) {
$this->set_message('Game create failed because a player id was not valid.');
return NULL;
}
}
/**
* Save decision about whether or not to join a game
*
* @param int $playerId
* @param int $gameId
* @param string $decision
* @return bool
*/
public function save_join_game_decision($playerId, $gameId, $decision) {
if (('accept' != $decision) && ('reject' != $decision)) {
$this->set_message('decision must be either accept or reject');
return;
}
$game = $this->load_game($gameId);
$prevState = $game->gameState;
if (BMGameState::CHOOSE_JOIN_GAME != $game->gameState) {
if (('reject' == $decision) &&
($playerId == $game->playerArray[0]->playerId)) {
$decision = 'withdraw';
}
$this->set_message(
'Your decision to ' .
$decision .
' the game failed because the game has been updated ' .
'since you loaded the page'
);
return;
}
$playerIdx = array_search($playerId, $game->playerIdArray);
if ($playerIdx !== FALSE) {
$player = $game->playerArray[$playerIdx];
$player->waitingOnAction = FALSE;
$decisionFlag = ('accept' == $decision);
$player->hasPlayerAcceptedGame = $decisionFlag;
} elseif (($playerId === $game->creatorId) &&
('reject' === $decision)) {
foreach ($game->playerArray as $player) {
$player->waitingOnAction = FALSE;
$decisionFlag = FALSE;
}
} else {
return;
}
if (!$decisionFlag) {
$game->gameState = BMGameState::CANCELLED;
}
$this->save_game($game, $prevState);
if ($decisionFlag) {
$this->set_message("Joined game $gameId");
} elseif ($playerIdx !== FALSE) {
$this->set_message("Rejected game $gameId");
} else {
$this->set_message("Cancelled game $gameId");
}
return TRUE;
}
/**
* Join an open game
*
* @param int $currentPlayerId
* @param int $gameId
* @return bool
*/
public function join_open_game($currentPlayerId, $gameId) {
try {
$game = $this->load_game($gameId);
// check that there are still unspecified players and
// that the player is not already part of the game
$emptyPlayerIdx = NULL;
$isPlayerPartOfGame = FALSE;
foreach ($game->playerArray as $playerIdx => $player) {
if (is_null($player->playerId) && is_null($emptyPlayerIdx)) {
$emptyPlayerIdx = $playerIdx;
} elseif ($currentPlayerId == $player->playerId) {
$isPlayerPartOfGame = TRUE;
break;
}
}
if ($isPlayerPartOfGame) {
$this->set_message('You are already playing in this game.');
return FALSE;
}
if (is_null($emptyPlayerIdx)) {
$this->set_message('No empty player slots in game '.$gameId.'.');
return FALSE;
}
$query = 'UPDATE game_player_map SET player_id = :player_id '.
'WHERE game_id = :game_id '.
'AND position = :position';
$parameters = array(':game_id' => $gameId,
':player_id' => $currentPlayerId,
':position' => $emptyPlayerIdx);
self::$db->update($query, $parameters);
$query = 'UPDATE game SET start_time = FROM_UNIXTIME(:start_time) '.
'WHERE id = :id';
$parameters = array(':start_time' => time(),
':id' => $gameId);
self::$db->update($query, $parameters);
$game = $this->load_game($gameId);
$prevState = $game->gameState;
$player = $game->playerArray[$emptyPlayerIdx];
$player->hasPlayerAcceptedGame = TRUE;
$this->save_game($game, $prevState);
$this->set_message('Successfully joined game ' . $gameId);
return TRUE;
} catch (Exception $e) {
error_log(
"Caught exception in BMInterface::join_open_game: ".
$e->getMessage()
);
$this->set_message('Internal error while joining open game');
}
}
/**
* Cancel an open game
*
* @param int $currentPlayerId
* @param int $gameId
* @return bool
*/
public function cancel_open_game($currentPlayerId, $gameId) {
try {
$game = $this->load_game($gameId);
$prevState = $game->gameState;
// check that the current player is involved in this game
$isPlayerInThisGame = ($game->playerArray[0]->playerId == $currentPlayerId);
if (!$isPlayerInThisGame) {
$this->set_message('You are not involved in this game.');
return FALSE;
}
// check that the game state is appropriate
if ($game->gameState == BMGameState::CANCELLED) {
$this->set_message('This game has already been cancelled.');
return FALSE;
}
if ($game->gameState > BMGameState::CHOOSE_JOIN_GAME) {
$this->set_message('This game has already started.');
return FALSE;
}
$game->gameState = BMGameState::CANCELLED;
$this->save_game($game, $prevState);
$this->set_message("Successfully cancelled game $gameId");
return TRUE;
} catch (Exception $e) {
error_log(
"Caught exception in BMInterface::cancel_open_game: ".
$e->getMessage()
);
$this->set_message('Internal error while cancelling open game');
}
}
/**
* Select a button
*
* @param int $playerId
* @param int $gameId
* @param string $buttonName
* @return bool
*/
public function select_button(
$playerId,
$gameId,
$buttonName
) {
try {
if (empty($buttonName)) {
return FALSE;
}
$game = $this->load_game($gameId);
$playerIdx = array_search($playerId, $game->playerIdArray);
if (FALSE === $playerIdx) {
$this->set_message('Player is not a participant in game.');
return FALSE;
}
if (!is_null($game->playerArray[$playerIdx]->button)) {
$this->set_message('Button has already been selected.');
return FALSE;
}
if ('__random' == $buttonName) {
$query = 'UPDATE game_player_map SET is_button_random = 1 '.
'WHERE game_id = :game_id '.
'AND player_id = :player_id';
$parameters = array(':game_id' => $gameId,
':player_id' => $playerId);
self::$db->update($query, $parameters);
} else {
try {
$query = 'SELECT id FROM button '.
'WHERE name = :button_name';
$parameters = array(':button_name' => $buttonName);
$buttonId = self::$db->select_single_value($query, $parameters, 'int');
} catch (BMExceptionDatabase $e) {
$this->set_message('Button select failed because button name was not valid.');
return FALSE;
}
$query = 'UPDATE game_player_map SET button_id = :button_id '.
'WHERE game_id = :game_id '.
'AND player_id = :player_id';
$parameters = array(':game_id' => $gameId,
':player_id' => $playerId,
':button_id' => $buttonId);
self::$db->update($query, $parameters);
}
$query = 'UPDATE game SET start_time = FROM_UNIXTIME(:start_time) '.
'WHERE id = :id';
$parameters = array(':start_time' => time(),
':id' => $gameId);
self::$db->update($query, $parameters);
$game = $this->load_game($gameId);
$prevState = $game->gameState;
$this->save_game($game, $prevState);
return TRUE;
} catch (Exception $e) {
error_log(
"Caught exception in BMInterface::select_button: ".
$e->getMessage()
);
$this->set_message('Internal error while selecting button');
}
}
/**
* Submit swing and option values
*
* @param int $playerId
* @param int $gameId
* @param int $roundNumber
* @param array $swingValueArray
* @param array $optionValueArray
* @return bool
*/
public function submit_die_values(
$playerId,
$gameId,
$roundNumber,
$swingValueArray,
$optionValueArray
) {
try {
$game = $this->load_game($gameId);
$prevState = $game->gameState;
$currentPlayerIdx = array_search($playerId, $game->playerIdArray);
// check that the timestamp and the game state are correct, and that
// the die values still need to be set
if (!$this->is_action_current(
$game,
BMGameState::SPECIFY_DICE,
'ignore',
$roundNumber,
$playerId
)) {
$this->set_message('Dice sizes no longer need to be set');
return NULL;
}
$isSwingSetSuccessful = $this->set_swing_values($swingValueArray, $currentPlayerIdx, $game);
if (!$isSwingSetSuccessful) {
return NULL;
}
$this->set_option_values($optionValueArray, $currentPlayerIdx, $game);
// Create the action log entries for choosing die values
// now, so they will happen before any initiative actions.
// If the swing/option selection is unsuccessful,
// save_game() won't be called, so this action log entry
// will simply be dropped.
$swingLogArray = array();
foreach ($swingValueArray as $swingType => $swingValue) {
$swingLogArray[] = array(
'swingType' => $swingType,
'swingValue' => $swingValue,
);
}
$optionLogArray = array();
foreach ($optionValueArray as $dieIdx => $optionValue) {
$dieRecipe = $game->playerArray[$currentPlayerIdx]->activeDieArray[$dieIdx]->recipe;
$optionLogArray[] = array(
'recipe' => $dieRecipe,
'optionValue' => $optionValue,
);
}
$game->log_action(
'choose_die_values',
$game->playerArray[$currentPlayerIdx]->playerId,
array(
'roundNumber' => $game->roundNumber,
'swingValues' => $swingLogArray,
'optionValues' => $optionLogArray,
)
);
$game->proceed_to_next_user_action();
// check for successful swing value set
if ((FALSE == $game->playerArray[$currentPlayerIdx]->waitingOnAction) ||
($game->gameState > BMGameState::SPECIFY_DICE) ||
($game->roundNumber > $roundNumber)) {
$this->save_game($game, $prevState);
$this->set_message('Successfully set die sizes');
return TRUE;
} else {
if ($game->message) {
$this->set_message($game->message);
} else {
$this->set_message('Failed to set die sizes');
}
return NULL;
}
} catch (Exception $e) {
error_log(
'Caught exception in BMInterface::submit_die_values: ' .
$e->getMessage()
);
$this->set_message('Internal error while setting die sizes');
}
}
/**
* Set swing values
*
* @param array $swingValueArray
* @param int $currentPlayerIdx
* @param BMGame $game
* @return bool
*/
protected function set_swing_values($swingValueArray, $currentPlayerIdx, $game) {
$player = $game->playerArray[$currentPlayerIdx];
$player->swingValueArray = $swingValueArray;
$swingRequestArray = $player->swingRequestArray;
if (is_array($swingRequestArray)) {
$swingRequested = array_keys($player->swingRequestArray);
sort($swingRequested);
} else {
$swingRequested = array();
}
if (is_array($swingValueArray)) {
$swingSubmitted = array_keys($swingValueArray);
sort($swingSubmitted);
} else {
$swingSubmitted = array();
}
$isSwingSetSuccessful = ($swingRequested == $swingSubmitted);
if (!$isSwingSetSuccessful) {
$this->set_message('Wrong swing values submitted: expected ' . implode(',', $swingRequested));
}
return $isSwingSetSuccessful;
}
/**
* Set option values
*
* @param array $optionValueArray
* @param int $currentPlayerIdx
* @param BMGame $game
*/
protected function set_option_values($optionValueArray, $currentPlayerIdx, $game) {
if (is_array($optionValueArray)) {
$player = $game->playerArray[$currentPlayerIdx];
foreach ($optionValueArray as $dieIdx => $optionValue) {
$player->optValueArray[$dieIdx] = $optionValue;
}
}
}
/**
* Submit a turn
*
* @param array $args
* @return bool
*
* $args contains the following parameters:
* int playerId
* int game
* int roundNumber
* int Timestamp
* array dieSelectStatus
* string attackType
* int attackerIdx
* int defenderIdx
* string chat
* array turboSizeArray
*/
public function submit_turn($args) {
try {
$game = $this->load_game($args['game']);
$prevState = $game->gameState;
if (!$this->is_action_current(
$game,
BMGameState::START_TURN,
$args['timestamp'],
$args['roundNumber'],
$args['playerId']
)) {
$this->set_message('It is not your turn to attack right now');
return NULL;
}
$attackers = array();
$defenders = array();
$attackerDieIdx = array();
$defenderDieIdx = array();
$this->retrieve_dice_in_attack(
$game,
$args,
$attackers,
$defenders,
$attackerDieIdx,
$defenderDieIdx