-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmagicmaze.game.php
956 lines (839 loc) · 36.1 KB
/
magicmaze.game.php
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
<?php
/**
*------
* BGA framework: © Gregory Isabelli <gisabelli@boardgamearena.com> & Emmanuel Colin <ecolin@boardgamearena.com>
* MagicMaze implementation : © Patrick Xia <patrick.xia@gmail.com>
*
* This code has been produced on the BGA studio platform for use on http://boardgamearena.com.
* See http://en.boardgamearena.com/#!doc/Studio for more information.
* -----
*/
require_once(APP_GAMEMODULE_PATH . 'module/table/table.game.php');
require_once('modules/mm-playerability.php');
require_once('modules/mm-sql.php');
require_once('modules/mm-util.php');
// Be nice to the players: let them overshoot their timers by a tiny bit.
define('TIMER_SLOP', 4);
class MagicMaze extends Table {
// tile_id -> x -> y -> {"walls", "escalator", "properties"}
protected $tileinfo = array();
public function __construct() {
parent::__construct();
self::initGameStateLabels(array(
'timer_deadline_micros' => 10,
'num_flips' => 11,
'mage_status' => 12,
'attention_pawn' => 13,
'explore_status' => 14,
'tiles_remain' => 15,
'option_time_limit' => 100,
'option_tile_set' => 102,
));
}
protected function getGameName() {
// Used for translations and stuff. Please do not modify.
return 'magicmaze';
}
/*
setupNewGame:
This method is called only once, when a new game is launched.
In this method, you must setup the game according to the game rules, so that
the game is ready to be played.
*/
protected function setupNewGame($players, $options = array()) {
$gameinfos = self::getGameinfos();
$default_colors = $gameinfos['player_colors'];
// Create players
// (This is boilerplate from the template).
$sql = 'INSERT INTO player (player_id, player_color, player_canal, player_name, player_avatar) VALUES ';
$values = array();
foreach ($players as $player_id => $player) {
$color = array_shift($default_colors);
$values[] = "('" . $player_id . "','$color','" . $player['player_canal'] . "','" . addslashes($player['player_name']) . "','" . addslashes($player['player_avatar']) . "')";
}
$sql .= implode(',', $values);
self::DbQuery($sql);
$tiles = getTileset(self::getGameStateValue('option_tile_set'));
shuffle($tiles);
$sql = 'insert into tiles (tile_id, tile_order) values ';
for ($i = 0; $i < count($tiles); ++$i) {
if ($i != 0) {
$sql .= ',';
}
$sql .= "($tiles[$i], $i)";
}
self::DbQuery($sql);
if (in_array(0, $tiles)) {
$this->createTile(0, 0, 0, 0, false);
} else {
$this->createTile(1, 0, 0, 0, false);
}
self::reattributeColorsBasedOnPreferences($players, $gameinfos['player_colors']);
self::reloadPlayersBasicInfos();
$spawns = array(array(1,1), array(1,2), array(2,1), array(2,2));
shuffle($spawns);
for ($i = 0; $i < 4; $i++) {
$x = $spawns[$i][0];
$y = $spawns[$i][1];
$sql = "insert into tokens (token_id, position_x, position_y) values ($i, $x, $y)";
self::DbQuery($sql);
}
/************ Start the game initialization *****/
// Init global values with their initial values
self::setGameStateInitialValue('timer_deadline_micros', -1);
self::setGameStateInitialValue('num_flips', 0);
self::setGameStateInitialValue('mage_status', 0);
self::setGameStateInitialValue('attention_pawn', -1);
self::setGameStateInitialValue('explore_status', 0);
self::setGameStateInitialValue('tiles_remain', count($tiles) - 1);
self::initStat('table', 'actions_number', 0);
self::initStat('table', 'tiles_explored', 0);
self::initStat('table', 'timer_flips', 0);
self::initStat('player', 'actions_number', 0);
$this->gamestate->setAllPlayersMultiactive();
/************ End of the game initialization *****/
}
/*
getAllDatas:
Gather all informations about current game situation (visible by the current player).
The method is called each time the game interface is displayed to a player, ie:
_ when the game starts
_ when a player refreshes the game page (F5)
*/
protected function getAllDatas() {
$result = array();
$current_player_id = self::getCurrentPlayerId();
// Get information about players
$result['players'] = self::loadPlayersBasicInfos();
$sql = 'select tile_id tile_id, position_x, position_y, rotation from tiles where placed';
$result['tiles'] = self::getCollectionFromDb($sql);
$sql = 'select token_id, position_x, position_y, locked from tokens';
$result['tokens'] = self::getCollectionFromDb($sql);
foreach ($result['tokens'] as $token_id => $values) {
if ($values['locked']) {
$result['next_tile'] = array();
$result['next_tile']['tile_id'] = $this->nextAvailableTile();
break;
}
}
// TODO: We can lower the roundtrips here but this is only on a full load...
$sql = "select position_x, position_y, token_id from properties where property = 'warp'";
$result['properties']['warp'] = self::getObjectListFromDB($sql);
$sql = "select position_x, position_y, token_id from properties where property = 'explore'";
$result['properties']['explore'] = self::getObjectListFromDB($sql);
$sql = "select position_x, position_y, token_id from properties where property = 'crystal'";
$result['properties']['crystal'] = self::getObjectListFromDB($sql);
$sql = "select position_x, position_y, token_id from properties where property = 'used'";
$result['properties']['used'] = self::getObjectListFromDB($sql);
$sql = "select old_x, old_y, new_x, new_y from escalators";
$result['properties']['escalator'] = self::getObjectListFromDB($sql);
$result['flips'] = self::getGameStateValue('num_flips');
$result['tiles_remain'] = self::getGameStateValue('tiles_remain');
$result['mage_status'] = self::getGameStateValue('mage_status');
$deadline = floatval(self::getGameStateValue('timer_deadline_micros'));
if ($deadline !== -1.) {
// Subtract three seconds here because getAllDatas() is part of some complicated
// handling loop on the PHP side where by the time the client gets the deadline
// it is stale. The client will request the new deadline on load via userRefreshDeadline.
$result['time_left'] = $deadline - microtime(true) - 3.0;
}
$attention = intval(self::getGameStateValue('attention_pawn'));
if ($attention !== -1) {
$result['attention_pawn'] = $attention;
}
return $result;
}
public function checkOk($action) {
$players = array_filter(self::loadPlayersBasicInfos(), function ($player) {
return !$player['player_zombie'];
});
$allowable = getRoles(
count($players),
$players[self::getCurrentPlayerId()]['player_no'],
self::getGameStateValue('num_flips')
);
if (strpos($allowable, $action) === false) {
throw new BgaUserException(self::_("you don't have that ability"));
}
self::incStat(1, 'actions_number');
self::incStat(1, 'actions_number', self::getCurrentPlayerId());
}
/*
getGameProgression:
Compute and return the current game progression.
The number returned must be an integer beween 0 (=the game just started) and
100 (= the game is finished or almost finished).
This method is called each time we are in a game state with the "updateGameProgression" property set to true
(see states.inc.php)
*/
public function getGameProgression() {
return intval(self::getGameStateValue('num_flips')) * 25;
}
//////////////////////////////////////////////////////////////////////////////
//////////// Utility functions
////////////
public function populateTileInfo() {
if (count($this->tileinfo) > 0) {
return;
}
require_once('modules/mm-tiles.php');
$this->tileinfo = MM_TILEINFO;
}
public function generateConnectionsForTile($tile_id, $x_coord, $y_coord, $rotation) {
$this->populateTileInfo();
$ret = array();
$tileToGrid = function ($x, $y) {
throw new Exception('invalid rotation');
};
$invTileToGrid = $tileToGrid;
$rotWalls = $tileToGrid;
switch ($rotation) {
case 0:
$tileToGrid = function ($x, $y) {
return array($x, $y);
};
$invTileToGrid = $tileToGrid;
$rotWalls = function ($str) {
return $str;
};
break;
case 90:
$tileToGrid = function ($x, $y) {
return array($y, 3 - $x);
};
$invTileToGrid = function ($x, $y) {
return array(3 - $y, $x);
};
$rotWalls = function ($str) {
return strtr($str, 'NESWnesw', 'ESWNeswn');
};
break;
case 180:
$tileToGrid = function ($x, $y) {
return array(3 - $x, 3 - $y);
};
$invTileToGrid = $tileToGrid;
$rotWalls = function ($str) {
return strtr($str, 'NESWnesw', 'SWNEswne');
};
break;
case -90:
case 270:
$tileToGrid = function ($x, $y) {
return array(3 - $y, $x);
};
$invTileToGrid = function ($x, $y) {
return array($y, 3 - $x);
};
$rotWalls = function ($str) {
return strtr($str, 'NESWnesw', 'WNESwnes');
};
break;
}
$escalatorstring = '';
$wallstring = '';
$propertystring = '';
for ($i = 0; $i < 4; ++$i) {
for ($j = 0; $j < 4; ++$j) {
$coord = $tileToGrid($i, $j);
$tile = $this->tileinfo[$tile_id][$coord[0]][$coord[1]];
$walls = $rotWalls($tile['walls']);
$oldx = $x_coord + $i;
$oldy = $y_coord + $j;
// gyop
for ($k = 0; $k < strlen($walls); ++$k) {
$dir = $walls[$k];
$dx = 0;
$dy = 0;
switch (strtoupper($dir)) {
case 'N':
$dx = 0;
$dy = -1;
break;
case 'S':
$dx = 0;
$dy = 1;
break;
case 'E':
$dx = 1;
$dy = 0;
break;
case 'W':
$dx = -1;
$dy = 0;
break;
default:
throw new Exception('assert: invalid direction');
}
if (strlen($wallstring) !== 0) {
$wallstring .= ',';
}
$newx = $oldx + $dx;
$newy = $oldy + $dy;
// TODO: figure out if we should write both
$is_dwarf = (($dir === strtoupper($dir)) ? 0 : 1);
$wallstring .= "($oldx, $oldy, $newx, $newy, $is_dwarf),";
$wallstring .= "($newx, $newy, $oldx, $oldy, $is_dwarf)";
}
if (strlen($tile['escalator']) > 0) {
if (strlen($escalatorstring) !== 0) {
$escalatorstring .= ',';
}
$esclx = intval($tile['escalator'][0]);
$escly = intval($tile['escalator'][1]);
$tfnew = $invTileToGrid($esclx, $escly);
$newx = $x_coord + $tfnew[0];
$newy = $y_coord + $tfnew[1];
$escalatorstring .= "($oldx, $oldy, $newx, $newy),";
$escalatorstring .= "($newx, $newy, $oldx, $oldy)";
$ret['escalator'][] = array(
'old_x' => $oldx,
'old_y' => $oldy,
'new_x' => $newx,
'new_y' => $newy,
);
}
if (strlen($tile['properties']) > 0) {
if (strlen($propertystring) !== 0) {
$propertystring .= ',';
}
// goyp
$color = 'NULL';
$type = '';
$lookup = array(
'g' => 0,
'o' => 1,
'y' => 2,
'p' => 3,
);
if (array_key_exists($tile['properties'][0], $lookup)) {
$color = $lookup[$tile['properties'][0]];
$type = substr($tile['properties'], 1);
} else {
$type = $tile['properties'];
}
$ret[$type][] = array(
'position_x' => $oldx,
'position_y' => $oldy,
'token_id' => $color,
);
$propertystring .= "($oldx, $oldy, $color, '$type')";
}
}
}
self::DbQuery("insert ignore into walls values $wallstring");
if (strlen($escalatorstring) > 0) {
self::DbQuery("insert ignore into escalators values $escalatorstring");
}
if (strlen($propertystring) > 0) {
self::DbQuery("insert into properties values $propertystring");
}
return $ret;
}
//////////////////////////////////////////////////////////////////////////////
//////////// Player actions
////////////
public function userRefreshDeadline() {
$deadline = self::checkDeadline(false);
if ($deadline === false || $deadline === -1.) {
return;
}
$this->notifyPlayer(
self::getCurrentPlayerId(),
'newDeadline',
'',
array(
'time_left' => $deadline - microtime(true),
)
);
}
public function setAttentionPawn($id) {
$this->checkAction('move');
self::setGameStateValue('attention_pawn', $id);
$players = self::loadPlayersBasicInfos();
self::notifyAllPlayers('attention', clienttranslate('Player ${player_name} is asked to pay attention by ${src_player}'), array(
'player_id' => $id,
'player_name' => $players[$id]['player_name'],
'src_player' => self::getCurrentPlayerName(),
));
}
public function nextAvailableTile() {
$sql = 'select tile_id from tiles where not placed order by tile_order limit 1 for update';
$nextId = self::getObjectFromDb($sql);
if (!$nextId) {
return -1;
}
return $nextId['tile_id'];
}
public function tileCoords($tile_id) {
$sql = 'select position_x, position_y from tiles where tile_id = ' . $tile_id;
$res = self::getNonEmptyObjectFromDb($sql);
return array($res['position_x'], $res['position_y']);
}
public function informNextTile() {
$next = $this->nextAvailableTile();
if ($next === -1) {
return false;
}
self::notifyAllPlayers('nextTile', '', array(
'tile_id' => $next,
'mage_status' => self::getGameStateValue('mage_status'),
));
return true;
}
public function attemptWizExplore() {
self::DbQuery(wizExploreQuery());
if (self::DbAffectedRow() === 0) {
return false;
}
self::setGameStateValue('mage_status', 1);
return true;
}
public function attemptExplore($tokenId) {
$this->checkAction('move');
$this->checkOk('H');
// TODO: write test cases for whether or not we transition states properly
// with a wizexplore while an elf is standing at an explore
$this->gamestate->nextState('move');
// TODO: this kind of sucks UI wise, display a little "locked" icon
// TODO: clicking twice on explore should place
// This needs to be before informNextTile because we need the correct mageStatus in there...
$mageStatusChanged = false;
if (isMage($tokenId)) {
if ($this->attemptWizExplore()) {
$mageStatusChanged = true;
}
}
if (!$this->informNextTile()) {
throw new BgaUserException(self::_('there are no tiles left!'));
}
if ($mageStatusChanged) {
return;
}
if (intval(self::getGameStateValue('mage_status')) !== 0) {
throw new BgaUserException(self::_('you are already exploring with the mage. click where you would like the tile.'));
}
if (intval(self::getGameStateValue('explore_status')) === 1) {
$res = self::getObjectFromDb(findLockedTokenQuery($tokenId));
if (!$res) {
throw new BgaUserException(self::_('that token was not on an explore space when you started the explore action'));
}
$this->placeTileFrom($res['tile_id'], $res['position_x'], $res['position_y'], true);
return;
}
self::setGameStateValue('explore_status', 1);
self::DbQuery(exploreAllEligibleQuery());
if (self::DbAffectedRow() === 0) {
throw new BgaUserException(self::_("can't explore: no eligible explorations"));
}
if (self::DbAffectedRow() === 1) {
$res = self::getNonEmptyObjectFromDb(findLockedTokensQuery());
if (intval($tokenId) !== intval($res['token_id'])) {
throw new BgaUserException(self::_("can't explore: that token is not on an explore space"));
}
if (isElf($res['token_id'])) {
$this->gamestate->nextState('talk');
}
$this->placeTileFrom($res['tile_id'], $res['position_x'], $res['position_y'], true);
}
}
public function setDeadline($newDeadline) {
self::setGameStateValue('timer_deadline_micros', $newDeadline);
}
public function checkDeadline($shouldStart) {
$deadline = floatval(self::getGameStateValue('timer_deadline_micros'));
if ($deadline === -1.) {
if ($shouldStart) {
$this->gamestate->nextState('startTimer');
$deadline = microtime(true) + getTimerValue(self::getGameStateValue('option_time_limit'));
$this->setDeadline($deadline);
$this->notifyAllPlayers('newDeadline', clienttranslate('Timer started!'), array(
'flips' => self::getGameStateValue('num_flips'),
'time_left' => $deadline - microtime(true),
));
}
} elseif (microtime(true) > $deadline + TIMER_SLOP) {
$this->gamestate->nextState('lose');
$this->notifyAllPlayers('message', clienttranslate('Oh no! You ran out of time.'), array());
return false;
}
return $deadline;
}
public function attemptWarp($x, $y) {
$this->checkAction('warp');
$this->checkOk('P');
self::DbQuery(warpToLocationQuery($x, $y));
if (self::DbAffectedRow() === 0) {
throw new BgaUserException(self::_("you can't warp there"));
}
if ($this->checkDeadline(true) === false) {
return;
}
// TODO: timestamp this
$sql = "select token_id, position_x, position_y from tokens where position_x = $x and position_y = $y";
$res = self::getNonEmptyObjectFromDb($sql);
$this->gamestate->nextState('warp');
self::notifyAllPlayers('tokenMoved', clienttranslate('${player_name} warps the ${token_name}'), array(
'i18n' => array('token_name'),
'token_id' => $res['token_id'],
'token_name' => tokenName($res['token_id']),
'player_name' => self::getCurrentPlayerName(),
'position_x' => $res['position_x'],
'position_y' => $res['position_y'],
));
}
public function attemptEscalator($token_id) {
$this->checkAction('move');
$this->checkOk('R');
$res = self::DbQuery(updateEscalatorQuery($token_id));
if (self::DbAffectedRow() === 0) {
throw new BgaUserException(self::_('invalid escalator operation'));
}
if ($this->checkDeadline(true) === false) {
return;
}
$sql = "select position_x, position_y from tokens where token_id = $token_id";
$res = self::getNonEmptyObjectFromDb($sql);
$this->gamestate->nextState('move');
self::notifyAllPlayers('tokenMoved', clienttranslate('${player_name} moves the ${token_name} along an escalator'), array(
'i18n' => array('token_name'),
'token_id' => $token_id,
'token_name' => tokenName($token_id),
'player_name' => self::getCurrentPlayerName(),
'position_x' => $res['position_x'],
'position_y' => $res['position_y'],
));
}
public function attemptMove($token_id, $x, $y, $keepMoving) {
$this->delayedNotification = null;
$res = $this->moveImpl($token_id, $x, $y);
if (is_null($res)) {
return;
}
while ($keepMoving) {
// Edge case: if we've won, we can't move any further, and
// the checkAction won't throw a BgaUserException...
if (!$this->checkAction('move', false)) {
break;
}
// It's likely to run into a wall after this happens, but
// just in case somebody adds a new map where this isn't
// the case...
if ($this->delayedNotification !== null) {
break;
}
try {
$newRes = $this->moveImpl($token_id, $x, $y);
$res = $newRes;
} catch (BgaUserException $e) {
$keepMoving = false;
}
}
// XXX conflicts, need a lot better than this (possibly timestamp the
// insertions).
self::notifyAllPlayers('tokenMoved', clienttranslate('${player_name} moves the ${token_name}'), array(
'i18n' => array('token_name'),
'token_id' => $token_id,
'token_name' => tokenName($token_id),
'player_name' => self::getCurrentPlayerName(),
'position_x' => $res['position_x'],
'position_y' => $res['position_y'],
));
if ($this->delayedNotification !== null) {
self::notifyAllPlayers(
...$this->delayedNotification
);
}
}
// Only useful in the middle of moves.
public function delayedNotifyAllPlayers($type, $msg, $args) {
$this->delayedNotification = array($type, $msg, $args);
}
// If we want to be nicer to the players, we can add a function findMoves($newx, $newy) that
// returns the token_id and $x, $y that can move there given the current player state.
// Then take a wrapper function, call it, and abort if ambiguous. Then call moveImpl.
public function moveImpl($token_id, $x, $y) {
$changedState = false;
$this->checkAction('move');
// TODO: the move should be a string and we should not parse this nonsense
// (legacy of how this was developed)
switch ($x . $y) {
case '-10':
$this->checkOk('W');
break;
case '10':
$this->checkOk('E');
break;
case '01':
$this->checkOk('S');
break;
case '0-1':
$this->checkOk('N');
break;
default:
throw new BgaUserException(self::_('received invalid move'));
}
$sql = 'select token_id, position_x, position_y from tokens for update';
//$allPositions = self::getNonEmptyCollectionFromDB($sql);
$res = self::DbQuery($sql);
$others = array();
$oldx = -9999;
$oldy = -9999;
while ($row = $res->fetch_row()) {
if ($row[0] == $token_id) {
$oldx = $row[1];
$oldy = $row[2];
} else {
$others[getKey($row[1], $row[2])] = 1;
}
}
$res->close();
if ($this->checkDeadline(true) === false) {
return null;
}
$newx = $oldx + $x;
$newy = $oldy + $y;
if (array_key_exists(getKey($newx, $newy), $others)) {
throw new BgaUserException(self::_("can't move there: another pawn is already there"));
}
$sql = "update tokens set position_x = $newx, position_y = $newy where " .
"token_id = $token_id";
$dwarfexclusion = ((isDwarf($token_id)) ? 'and not dwarf' : '');
$wallrestriction = ' and not exists '
. "(select 1 from walls where old_x = $oldx and old_y = $oldy and new_x = $newx and new_y = $newy $dwarfexclusion) ";
$tilerestriction = ' and exists '
. "(select 1 from tiles where $newx - position_x between 0 and 3 and $newy - position_y between 0 and 3) ";
$lockrestriction = ' and not locked ';
$res = self::DbQuery("$sql $wallrestriction $tilerestriction $lockrestriction");
if (self::DbAffectedRow() === 0) {
throw new BgaUserException(self::_("you can't move there"));
}
$target = ($this->checkAction('steal', false) ? 'item' : 'exit');
self::DbQuery(checkVictoryConditionQuery($target));
// TODO maybe move this logic down and refactor it out of here...
if (self::DbAffectedRow() === 4) {
if ($this->checkAction('steal', false)) {
$this->delayedNotifyAllPlayers('message', clienttranslate('The items have been stolen! Escape!'), array());
$this->gamestate->nextState('steal');
$changedState = true;
} else {
self::DbQuery('update player set player_score = 1');
$this->gamestate->nextState('win');
$changedState = true;
$this->delayedNotifyAllPlayers('message', clienttranslate('Congratulations!'), array());
}
}
// XXX roundtrips
$res = self::getNonEmptyObjectFromDb(getTokenInfoQuery($token_id));
if ($res['property'] === 'timer') {
self::DbQuery(attemptConsumeTimerQuery($res['position_x'], $res['position_y']));
if (self::DbAffectedRow() === 0) {
throw new BgaUserException(self::_("can't move there: security cameras"));
}
$newDeadline = 2 * microtime(true) -
self::getGameStateValue('timer_deadline_micros') +
getTimerValue(self::getGameStateValue('option_time_limit'));
$this->setDeadline($newDeadline);
self::notifyAllPlayers('newUsed', '', array(
'x' => $res['position_x'],
'y' => $res['position_y'],
'token_id' => $res['token_id'],
));
$this->gamestate->nextState('talk');
$changedState = true;
$this->delayedNotifyAllPlayers('newDeadline', clienttranslate('timer flipped!'), array(
'flips' => self::incGameStateValue('num_flips', 1),
'time_left' => $newDeadline - microtime(true),
));
self::incStat(1, 'timer_flips');
} elseif (isBarbarian($res['token_id']) && $res['property'] === 'camera') {
self::DbQuery(attemptConsumeCameraQuery($res['position_x'], $res['position_y']));
self::notifyAllPlayers('newUsed', '', array(
'x' => $res['position_x'],
'y' => $res['position_y'],
'token_id' => $res['token_id'],
));
}
if (!$changedState) {
$this->gamestate->nextState('move');
}
return $res;
}
public function placeTileFrom($tile_id, $x, $y, $is_absolute = false) {
// TODO: Maybe we shouldn't directly call here
$this->checkAction('move');
$this->checkOk('H');
self::incStat(1, 'tiles_explored');
$this->gamestate->nextState('move');
$coords = $this->tileCoords($tile_id);
if ($is_absolute) {
$x -= $coords[0];
$y -= $coords[1];
}
// x, y in relative coordinates
$nextId = $this->nextAvailableTile();
if ($nextId === -1) {
throw new BgaUserException(self::_('there are no tiles left!'));
}
// Only valid exit tiles are at
// 20 (no rotation)
// 32 (90 degree rotation)
// 13 (180 degree rotation)
// 01 (-90 degree rotation)
// 00 10 20 30
// 01 11 21 31
// 02 12 22 32
// 03 13 23 33
$rotations = array(
'20' => 0,
'32' => 90,
'13' => 180,
'01' => -90,
);
$dx = array(
'20' => array(1, -4),
'32' => array(4, +1),
'13' => array(-1, +4),
'01' => array(-4, -1),
);
$key = $x . $y;
if (!array_key_exists($key, $rotations)) {
throw new BgaUserException(self::_('no valid action at that cell'));
}
$oldx = $coords[0] + $x;
$oldy = $coords[1] + $y;
$newx = $coords[0] + $dx[$key][0];
$newy = $coords[1] + $dx[$key][1];
$rotation = $rotations[$key];
$drawNew = false;
$mageStatus = intval(self::getGameStateValue('mage_status'));
if ($mageStatus === 0) {
$tokenId = self::getObjectFromDb(getTokenExploringQuery($oldx, $oldy));
if (!$tokenId) {
throw new BgaUserException(self::_("you can't place a tile there"));
}
if (isElf($tokenId['token_id'])) {
$this->gamestate->nextState('talk');
}
} elseif ($mageStatus === 1) {
// TODO: allow user to opt out? I don't know why they would...
$drawNew = true;
self::setGameStateValue('mage_status', 2);
} else {
self::DbQuery(consumeMageTileQuery());
$res = self::getNonEmptyObjectFromDb(findConsumedMageTileQuery());
self::notifyAllPlayers('newUsed', '', array(
'x' => $res['position_x'],
'y' => $res['position_y'],
'token_id' => MAGE_ID,
));
self::setGameStateValue('mage_status', 0);
}
$this->createTile($nextId, $newx, $newy, $rotation);
if ($drawNew) {
// TODO We don't end up sending a "used" notification to the client for
// the half-used crystal ball, which is a bit weird. We should somehow unify
// the bottom two paths above.
if (!$this->informNextTile()) {
$drawNew = false;
}
}
if (!$drawNew) {
self::setGameStateValue('explore_status', 0);
self::DbQuery('update tokens set locked = false, dummy = false');
}
}
public function createTile($nextId, $newx, $newy, $rotation, $notify = true) {
self::DbQuery(placeTileQuery($nextId, $newx, $newy, $rotation));
if (self::DbAffectedRow() === 0) {
throw new BgaUserException(self::_("you can't create a tile there"));
}
// TODO: tell the client to stop allowing clicks too
$clickables = $this->generateConnectionsForTile($nextId, $newx, $newy, $rotation);
self::DbQuery(deleteUnneededExplores($nextId));
if ($notify) {
$tilesRemain = self::getGameStateValue('tiles_remain');
$tilesRemain--;
self::setGameStateValue('tiles_remain', $tilesRemain);
self::notifyAllPlayers('tileAdded',
clienttranslate('${player_name} explores. ${tiles_remain} tile(s) are left.'),
array(
'player_name' => self::getCurrentPlayerName(),
'tile_id' => $nextId,
'tiles_remain' => $tilesRemain,
'position_x' => $newx,
'position_y' => $newy,
'rotation' => $rotation,
'clickables' => $clickables,
'mage_status' => self::getGameStateValue('mage_status'),
));
}
}
//////////////////////////////////////////////////////////////////////////////
//////////// Zombie
////////////
/*
zombieTurn:
This method is called each time it is the turn of a player who has quit the game (= "zombie" player).
You can do whatever you want in order to make sure the turn of this player ends appropriately
(ex: pass).
Important: your zombie code will be called when the player leaves the game. This action is triggered
from the main site and propagated to the gameserver from a server, not from a browser.
As a consequence, there is no current player associated to this action. In your zombieTurn function,
you must _never_ use getCurrentPlayerId() or getCurrentPlayerName(), otherwise it will fail with a "Not logged" error message.
*/
public function zombieTurn($state, $active_player) {
$statename = $state['name'];
if ($state['type'] === 'multipleactiveplayer') {
// Make sure player is in a non blocking status for role turn
$this->gamestate->setPlayerNonMultiactive($active_player, '');
$players = self::loadPlayersBasicInfos();
self::notifyAllPlayers('newZombie', '', array(
'players' => $players,
));
return;
}
throw new feException('Zombie mode not supported at this game state: ' . $statename);
}
// states
public function stGiveTime() {
// There are four available timers.
$maxTime = 5 * (TIMER_SLOP + getTimerValue(self::getGameStateValue('option_time_limit')));
self::DbQuery(giveReflexionTime($maxTime));
$this->gamestate->nextState('');
}
///////////////////////////////////////////////////////////////////////////////////:
////////// DB upgrade
//////////
/*
upgradeTableDb:
You don't have to care about this until your game has been published on BGA.
Once your game is on BGA, this method is called everytime the system detects a game running with your old
Database scheme.
In this case, if you change your Database scheme, you just have to apply the needed changes in order to
update the game database and allow the game to continue to run with your new version.
*/
public function upgradeTableDb($from_version) {
// $from_version is the current version of this game database, in numerical form.
// For example, if the game was running with a release of your game named "140430-1345",
// $from_version is equal to 1404301345
// Example:
// if( $from_version <= 1404301345 )
// {
// // ! important ! Use DBPREFIX_<table_name> for all tables
//
// $sql = "ALTER TABLE DBPREFIX_xxxxxxx ....";
// self::applyDbUpgradeToAllDB( $sql );
// }
// if( $from_version <= 1405061421 )
// {
// // ! important ! Use DBPREFIX_<table_name> for all tables
//
// $sql = "CREATE TABLE DBPREFIX_xxxxxxx ....";
// self::applyDbUpgradeToAllDB( $sql );
// }
// // Please add your future database scheme changes here
//
//
}
}