forked from kestasjk/webDiplomacy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.php
executable file
·780 lines (664 loc) · 19.2 KB
/
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
<?php
/*
Copyright (C) 2004-2010 Kestas J. Kuliukas
This file is part of webDiplomacy.
webDiplomacy is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
webDiplomacy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with webDiplomacy. If not, see <http://www.gnu.org/licenses/>.
*/
require_once(l_r('lib/variant.php'));
require_once(l_r('objects/members.php'));
require_once(l_r('objects/scoringsystem.php'));
/**
* Prints data on a game, and loads and manages the collections of members which this game contains.
* Most used to display the summary, when not loaded as processGame
*
* @package Base
* @subpackage Game
*/
class Game
{
public static function mapType()
{
if ( isset($_REQUEST['largemap'] ) )
return 'large';
elseif ( isset($_REQUEST['mapType']) )
switch($_REQUEST['mapType'])
{
case 'large':
case 'xml':
case 'small':
case 'json':
return $_REQUEST['mapType'];
}
return (isset($_REQUEST['DATC'])?'large':'small');
}
public static function mapFilename($gameID, $turn, $mapType=false)
{
if( $mapType==false ) $mapType = self::mapType();
if( defined('DATC') )
$folder='datc/maps';
else
$folder=self::gameFolder($gameID);
$filename=$turn.'-'.$mapType.'.map';
return $folder.'/'.$filename;
}
public static function wipeCache($gameID, $turn=false)
{
$dir = self::gameFolder($gameID);
if( defined('DATC') )
libCache::wipeDir($dir, '*json*');
else
libCache::wipeDir($dir, ( $turn===false ? '*.*' : '*'.$turn.'-*.*'));
}
/**
* Create a tree-like folder for a game in a given base folder. e.g. gameFolder('../mapstore',12345)
* will return '../mapstore/123/12345', and make sure that that directory exists.
* This is used for storing maps, and orderlogs.
*
* @param $baseDirectory The base directory to write to
* @param $gameID The gameID
* @return string The game folder
*/
public static function gameFolder($gameID)
{
if( defined('DATC') )
return 'datc/maps';
else
return libCache::dirID('games',$gameID);
}
public static $validPhases = array('Pre-game', 'Diplomacy', 'Retreats', 'Builds', 'Finished');
/**
* The game ID
* @var int
*/
public $id;
public $variantID;
public $Variant;
/**
* The MD5 hash of the game's password
* @var string
*/
public $password;
/**
* The in-game turn, 0 = Spring 1919, 1 = Autumn 1919
* @var int
*/
public $turn;
/**
* The game phase: 'Pre-game', 'Diplomacy', 'Retreats', 'Builds', 'Finished'
* @var int
*/
public $phase;
public $attempts;
/**
* The deadline when the game must next be processed, a UNIX timestamp
* @var int
*/
public $processTime;
/**
* True if the game is private
* @var bool
*/
public $private;
/**
* The game's name
* @var string
*/
public $name;
/**
* The conditions under which the game ended; 'Won', 'No', 'Drawn'
* @var int
*/
public $gameOver;
/**
* The number of points in the pot
* @var int
*/
public $pot;
/**
* The number of minutes per phase, defaults to 1440(24 hours)
*
* @var int
*/
public $phaseMinutes;
/**
* The number of minutes per phase to switch to later. Defaults to $phaseMinutes.
*
* @var int
*/
public $nextPhaseMinutes;
/**
* The number of minutes after the game starts when $phaseMinutes is switched to $nextPhaseMinutes. Defaults to -1 (never).
* @var int
*/
public $phaseSwitchPeriod;
// Arrays of aggregate objects
/**
* An array of Member(/processMember) objects indexed by countryID
*/
public $Members;
/**
* An object of type ScoringSystem that provides the information needed to calculate game scores
* @var ScoringSystem
*/
public $Scoring;
/**
* Winner-takes-all/Points-per-supply-center
* @var string
*/
public $potType;
/**
* draw-votes-public/draw-votes-hidden
* @var string
*/
public $drawType;
/**
* Not-processing/Processing/Crashed/Paused
* @var string
*/
public $processStatus;
/**
* Only used if the game is paused; the amount of seconds remaining until the next turn once the pause is over
*
* @var int
*/
public $pauseTimeRemaining;
/**
* The minimum bet required to join the game; refreshed after each new turn, null if not joinable.
*
* @var int
*/
public $minimumBet;
/**
* Anonymous or not, Yes or No
*
* @var string
*/
public $anon;
/**
* Regular, PublicPressOnly, NoPress
*
* @var string
*/
public $pressType;
public $lockMode='';
/**
* Normal/Strict
* If Strict all players must have completed their orders before the game will proceed.
*/
public $missingPlayerPolicy;
/**
* The minimum value for Reliability Rating before a player can join this game
*/
public $minimumReliabilityRating;
public $civilDisorderInfo;
/**
* The number of allowed NMRs per player before they are set in Civil Disorder.
*/
public $excusedMissedTurns;
/**
* Is the game made of up members only, 1 member and bot(s), or mixed.
*/
public $playerTypes;
/**
* The time the game was started, a UNIX timestamp. Initialized as -1.
* @var int
*/
public $startTime;
/**
* User id of the game director or null if no director
* @var int|null
*/
public $directorUserID;
/**
* User id of the tournament director or null if no director
* @var int|null
*/
public $tournamentDirectorUserID;
/**
* User id of the co-tournament director or null if no director
* @var int|null
*/
public $tournamentCodirectorUserID;
/**
* @param int/array $gameData The game ID of the game to load, or the array of its database row
* @param string[optional] $lockMode The database locking phase to use; no locking by default
*/
public function __construct($gameData, $lockMode = NOLOCK)
{
$this->lockMode = $lockMode;
/* If a Game has already been loaded it gets moved out of the way
*
* We have to use $GLOBALS['Game'] instead of global $Game;, because global $Game; only
* creates a reference to the global, and unsetting it doesn't unset the global itself.
* Unsetting $GLOBALS['Game'] unsets the global itself, not just the local reference.
*/
unset($GLOBALS['Game']);
$GLOBALS['Game'] = $this;
if ( is_array($gameData) ) // && $lockMode == NOLOCK Sometimes a game record is fetched and locked before being constructed here
$this->loadRow($gameData);
else
{
if( is_array($gameData) )
$this->id = (int)$gameData['id'];
else
$this->id = (int) $gameData;
$this->load();
}
$this->loadMembers();
$this->loadCDs();
switch ($this->potType) {
case 'Points-per-supply-center':
$this->Scoring = new ScoringPPSC($this);
break;
case 'Winner-takes-all':
$this->Scoring = new ScoringWTA($this);
break;
case 'Unranked':
$this->Scoring = new ScoringUnranked($this);
break;
case 'Sum-of-squares':
$this->Scoring = new ScoringSoS($this);
break;
default:
trigger_error("Unknown pot type '".$this->potType."'");
break;
}
// TODO: Make this check work with variants properly
//if( !( defined("DATC") or $this->phase != "Diplomacy" or count($this->Members->ByID) == count($this->Variant->countries) ) )
// trigger_error("Game loaded incorrectly");
if( $this->processStatus=='Paused' )
{
if( (isset($this->processTime)||!is_null($this->processTime))
|| (!isset($this->pauseTimeRemaining) || is_null($this->pauseTimeRemaining) ))
trigger_error(l_t("Paused game timeout values incorrectly set."));
}
elseif( $this->processStatus!='Crashed' && (
( isset($this->pauseTimeRemaining)||!is_null($this->pauseTimeRemaining) )
|| ( !isset($this->processTime)||is_null($this->processTime) ) ) )
trigger_error(l_t("Not-paused game process-time values incorrectly set."));
}
private $isMemberInfoHidden;
/**
* Is the given user ID a director of this game, either game director, tournament director or tournament codirector
* @return boolean
*/
public function isDirector($userID)
{
return ($this->directorUserID != null && $this->directorUserID == $userID)
|| ($this->tournamentDirectorUserID != null && $this->tournamentDirectorUserID == $userID)
|| ($this->tournamentCodirectorUserID != null && $this->tournamentCodirectorUserID == $userID);
}
/**
* Should members be hidden for this game and this viewer?
*
* @return boolean
*/
public function isMemberInfoHidden()
{
global $User;
if ( !isset($this->isMemberInfoHidden) )
{
/*
* Members aren't hidden if either:
* - The game isn't anonymous
* - The game is finished
* - The user is a moderator who isn't in the game
*/
if ( $this->anon == 'No' || $this->phase == 'Finished' || $this->hasModeratorPowers())
{
$this->isMemberInfoHidden = false;
}
else
{
$this->isMemberInfoHidden = true;
}
}
return $this->isMemberInfoHidden;
}
public function getAlternatives(){
$alternatives = array();
$alternatives[] = $this->Variant->link();
$pressTypeMap = [
'NoPress' => 'No messaging',
'RulebookPress' => 'Rulebook press',
'PublicPressOnly' => 'Public messaging only',
];
if ( $pressType = $pressTypeMap[$this->pressType] ?? false ){
$alternatives[] = l_t( $pressType );
}
$playerTypeMap = [
'Mixed' => 'Fill with Bots',
'MemberVsBots' => 'Bot Game',
];
if( $playerType = $playerTypeMap[$this->playerTypes] ?? false ){
$alternatives[] = l_t( $playerType );
}
if( $this->anon == 'Yes' ){
$alternatives[] = l_t( 'Anonymous players' );
}
$alternatives[] = $this->Scoring->longName();
if( $this->drawType == 'draw-votes-hidden' ){
$alternatives[] = l_t( 'Hidden draw votes' );
}
if( $this->missingPlayerPolicy == 'Wait' ){
$alternatives[] = l_t( 'Wait for orders' );
}
return $alternatives;
}
/**
* This is a special case of isMemberInfoHidden that returns true if a moderator is seeing the member info (and a normal user wouldn't)
*
* @return boolean
*/
public function moderatorSeesMemberInfo()
{
global $User;
return (!($this->anon == 'No' || $this->phase == 'Finished') && $this->hasModeratorPowers());
}
public function hasModeratorPowers()
{
global $User;
return ($User->type['Moderator'] && !isset($this->Members->ByUserID[$User->id]));
}
function loadRow(array $row)
{
foreach( $row as $name=>$value )
{
$this->{$name} = $value;
}
// If there is a password the game is private
$this->private = isset($this->password);
$this->Variant = $GLOBALS['Variants'][$this->variantID];
}
function isClassicGame()
{
return $this->Variant->name == Config::$variants[1];
}
function watched()
{
global $DB, $User;
$row = $DB->sql_row('SELECT * from wD_WatchedGames WHERE gameID='.$this->id.' AND userID=' . $User->id);
return $row != false;
}
function watch()
{
global $DB, $User;
if (! $this->watched())
{
$DB->sql_put('INSERT INTO wD_WatchedGames (gameID, userID) VALUES ('.$this->id. ','.$User->id.')');
$DB->sql_put('COMMIT');
}
}
function unwatch()
{
global $DB, $User;
if ($this->watched())
{
$DB->sql_put('DELETE from wD_WatchedGames WHERE gameID='. $this->id . ' AND userID='. $User->id);// . $this->id . ' AND userID=' . $User->id);
$DB->sql_put('COMMIT');
}
}
function loadCDs()
{
global $DB;
$this->civilDisorderInfo = array();
$tabl = $DB->sql_tabl('SELECT userID, countryID, turn, SCCount from wD_CivilDisorders where gameID='. $this->id);
while ( $row = $DB->tabl_hash($tabl) )
{
$this->civilDisorderInfo[$row['userID']] = $row;
}
}
// Get a game row with all the expected columns etc, using the locking mode given
public static function fetchRow($gameID, $lockMode = NOLOCK)
{
global $DB;
return $DB->sql_hash("SELECT
g.id,
g.variantID,
LOWER(HEX(g.password)) as password,
g.turn,
g.phase,
g.processTime,
g.name,
g.gameOver,
g.attempts,
g.pot,
g.potType,
g.phaseMinutes,
g.phaseMinutesRB,
g.nextPhaseMinutes,
g.phaseSwitchPeriod,
g.processStatus,
g.pauseTimeRemaining,
g.minimumBet,
g.anon,
g.pressType,
g.missingPlayerPolicy,
g.drawType,
g.minimumReliabilityRating,
g.excusedMissedTurns,
g.playerTypes,
g.startTime,
g.directorUserID ,
t.directorID tournamentDirectorUserID,
t.coDirectorID tournamentCodirectorUserID
FROM wD_Games g
LEFT JOIN wD_TournamentGames tg ON g.id = tg.gameID
LEFT JOIN wD_Tournaments t ON t.id = tg.tournamentID
WHERE g.id=".$gameID.' '.$lockMode);
}
/**
* Reload the variables which are stored within this object specificially, ie everything
* except aggregates
*/
function load()
{
$row = self::fetchRow($this->id, $this->lockMode);
if ( $row === false || (! isset($row['id'])) || (! $row['id']) )
{
libHTML::error(l_t("Game not found; ensure a valid game ID has been given. Check that this game hasn't been canceled, you may have received a message about it on your <a href='index.php' class='light'>home page</a>."));
}
$this->loadRow($row);
}
/**
* Reload the Members array
*/
function loadMembers()
{
$this->Members = $this->Variant->Members($this);
}
function isJoinable()
{
global $User;
if( $this->Members->isJoined() ) return false;
if ( array_key_exists($User->id,$this->civilDisorderInfo) ) return false;
if( !$User->type['User'] ) return false;
switch($this->phase)
{
case 'Finished': return false;
case 'Pre-game':
if(count($this->Members->ByID)==count($this->Variant->countries))
return false;
elseif(is_null($this->minimumBet) || $User->points < $this->minimumBet )
return false;
else
return true;
default:
if(count($this->Members->ByStatus['Left'])==0)
return false;
elseif(is_null($this->minimumBet) || $User->points < $this->minimumBet )
return false;
else
return true;
}
}
/**
* A textual representation of the game over conditions
*
* @param bool[optional] $map Optional, false by default. If true the text will be without HTML, for the map
*
* @return string Either HTML or text depending on whether map.php is calling
*/
function gameovertxt($map=FALSE)
{
assert ('$this->gameOver != "No"');
switch($this->gameOver)
{
case 'Won':
foreach($this->Members->ByStatus['Won'] as $Winner);
return l_t('Game won by %s',($map ? $Winner->username : $Winner->profile_link() ));
case 'Drawn':
return l_t('Game drawn');
}
}
/**
* Return the in-game turn in text format. 0 = Spring 1901 , 1 = Autumn 1901, etc.
* It can use the Game object's turn, or a supplied $gdate
*
* @param int[optional] $turn If this optional parameter is not supplied the Game's turn is used
*
* @return string The game turn in text format
*/
function datetxt($turn = false)
{
if( $turn === false )
$turn = $this->turn;
return $this->Variant->turnAsDate($turn);
}
/**
* The Game's phase in textual format
*
* @return string
*/
function modetxt()
{
return $this->phase;
}
/**
* Check whether this game will be considered a "live" game.
* @return true if phase minutes are less than 60.
**/
function isLiveGame()
{
return $this->phaseMinutes < 60;
}
protected function getMissedTurnMinutes()
{
if ($this->phaseMinutesRB != -1) {
return $this->phaseMinutesRB;
}
else
{
return $this->phaseMinutes;
}
}
/**
* Return the total number of minutes for the current phase
*
* @return int
*/
protected function getCurPhaseMinutes()
{
if ($this->phaseMinutesRB != -1 && ($this->phase == "Retreats" || $this->phase == "Builds")) {
return $this->phaseMinutesRB;
}
else
{
return $this->phaseMinutes;
}
}
/**
* Return the minimum number of minutes for a phase.
* This should be used for calculating grace period.
*
* @return int
*/
protected function getMinPhaseMinutes()
{
if ($this->phaseMinutesRB != -1) {
return $this->phaseMinutesRB;
}
else
{
return $this->phaseMinutes;
}
}
/**
* Return the next process time in textual format, in terms of time remaining
*
* @return string
*/
function processTimetxt()
{
if ( $this->processTime < time() )
return l_t("Now");
else
return libTime::remainingText($this->processTime);
}
static function gamesCanProcess()
{
global $Misc;
static $gamesCanProcess;
if( !isset($gamesCanProcess) )
{
$gamesCanProcess=true;
if( defined('DATC') )
$gamesCanProcess = true;
elseif( $Misc->Panic )
$gamesCanProcess = false;
elseif( (time()-$Misc->LastProcessTime) > Config::$downtimeTriggerMinutes*60 )
$gamesCanProcess = false;
}
return $gamesCanProcess;
}
/**
* Do we need to be processed? Once locked this gives the final test that the game
* is ready to go through. Checks if either everyone is ready or the time is up,
* and always gives false if the game is finished.
*
* @return boolean
*/
function needsProcess()
{
global $Misc;
/*
* - Games are processing as normal
* - The game isn't finished
* - The game isn't crashed or paused
* - The game isn't in wait mode and missing a players completed moves
* - The game is either:
* - Out of time for the phase
* - Or either:
* - It's a normal order-related phase and everyone is ready to proceed
* - Or it's a pre-game phase and enough people have joined, and it's not a live game
*/
if( self::gamesCanProcess() && $this->phase!='Finished' && $this->processStatus=='Not-processing' &&
( $this->Members->isCompleted() || $this->missingPlayerPolicy!='Wait' ) && (
time() >= $this->processTime
|| ( ($this->phase!='Pre-game' && $this->Members->isReady() )
|| ($this->phase=='Pre-game' && count($this->Members->ByID)==count($this->Variant->countries) && !($this->isLiveGame()) ) )
)
)
return true;
else
return false;
}
/**
* Game name
* @return string
*/
function titleBarName()
{
return $this->name;
}
}
?>