-
Notifications
You must be signed in to change notification settings - Fork 0
/
kingdombuilder.game.php
517 lines (457 loc) · 17.1 KB
/
kingdombuilder.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
<?php
/**
*------
* BGA framework: © Gregory Isabelli <gisabelli@boardgamearena.com> & Emmanuel Colin <ecolin@boardgamearena.com>
* KingdomBuilder implementation : © Timothée Pecatte tim.pecatte@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.
* -----
*
* KingdomBuilder.game.php
*
* This is the main file for your game logic.
*
* In this PHP file, you are going to defines the rules of the game.
*
*/
require_once APP_GAMEMODULE_PATH . 'module/table/table.game.php';
require_once 'modules/constants.inc.php';
require_once 'modules/KingdomBuilderBoard.class.php';
require_once 'modules/KingdomBuilderCards.class.php';
require_once 'modules/KingdomBuilderObjective.class.php';
require_once 'modules/KingdomBuilderLog.class.php';
require_once 'modules/KingdomBuilderPlayerManager.class.php';
class kingdombuilder extends Table
{
public function __construct()
{
parent::__construct();
self::initGameStateLabels([
'optionSetup' => OPTION_SETUP,
'optionRunningScores' => OPTION_RUNNING_SCORES,
'optionLords' => OPTION_DISABLE_LORDS,
'nomads' => OPTION_NOMADS_EXPANSION,
'currentRound' => CURRENT_ROUND,
'firstPlayer' => FIRST_PLAYER,
]);
// Initialize logger, board and cards
$this->log = new KingdomBuilderLog($this);
$this->board = new KingdomBuilderBoard($this);
$this->cards = new KingdomBuilderCards($this);
$this->playerManager = new KingdomBuilderPlayerManager($this);
$this->locationManager = new KingdomBuilderLocationManager($this);
}
protected function getGameName()
{
return 'kingdombuilder';
}
public function isNomads()
{
return self::getGameStateValue('nomads') == ENABLED;
}
/*
* setupNewGame:
* This method is called only once, when a new game is launched.
* params:
* - array $players
* - mixed $options
*/
protected function setupNewGame($players, $options = [])
{
// Initialize board and cards
$optionSetup = intval(self::getGameStateValue('optionSetup'));
$optionLords = intval(self::getGameStateValue('optionLords'));
$this->board->setupNewGame($optionSetup);
$this->cards->setupNewGame($players, $optionSetup, $optionLords);
// Init stats
$this->log->initStats($players);
// Initialize players (and settlements)
$this->playerManager->setupNewGame($players);
// Active first player to play
$pId = $this->activeNextPlayer();
self::setGameStateInitialValue('firstPlayer', $pId);
self::setGameStateInitialValue('currentRound', 0);
}
/*
* 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 and when a player refreshes the game page (F5)
*/
protected function getAllDatas()
{
$currentPlayerId = self::getCurrentPlayerId();
$data = [
'objectives' => $this->cards->getUiData(),
'board' => $this->board->getUiData(),
'fplayers' => $this->playerManager->getUiData($currentPlayerId),
'firstPlayer' => self::getGamestateValue('firstPlayer'),
'cancelMoveIds' => $this->log->getCancelMoveIds(),
'locations' => $this->locationManager->getUiData(),
];
if (intval(self::getGameStateValue('optionRunningScores')) == ENABLED) {
$data['players'] = self::getCollectionFromDB(
'SELECT player_id id, player_no no, player_name name, player_color color, player_score score FROM player'
);
}
return $data;
}
/*
* getGameProgression:
* Compute and return the current game progression approximation
* This method is called each time we are in a game state with the "updateGameProgression" property set to true
*/
public function getGameProgression()
{
$m = 40;
foreach ($this->playerManager->getPlayers() as $player) {
$m = min($m, $player->getSettlementsInHand());
}
return ((int) (40 - $m) * 100) / 40;
}
////////////////////////////////////////////////
//////////// Next player / Win ////////////
////////////////////////////////////////////////
/*
* stNextPlayer: go to next player
*/
public function stNextPlayer()
{
$pId = $this->activeNextPlayer();
self::giveExtraTime($pId);
$player = $this->playerManager->getPlayer();
self::giveExtraTime(
$pId,
count($player->getPlayableTilesInHand()) * 20
);
if (self::getGamestateValue('firstPlayer') == $pId) {
$n = (int) self::getGamestateValue('currentRound') + 1;
self::setGamestateValue('currentRound', $n);
if ($this->log->isLastTurn()) {
$this->gamestate->nextState('endgame');
return;
}
}
$this->gamestate->nextState('start');
}
/*
* stStartOfTurn: called at the beggining of each player turn
*/
public function stStartOfTurn()
{
$this->log->startTurn();
$this->playerManager->getPlayer()->startOfTurn();
$this->gamestate->nextState('build');
}
/*
* stEndOfTurn: called at the end of each player turn
*/
public function stEndOfTurn()
{
$this->playerManager->getPlayer()->endOfTurn();
if (intval(self::getGameStateValue('optionRunningScores')) == ENABLED) {
$scores = [];
foreach ($this->playerManager->getPlayers() as $player) {
$score = 0;
foreach ($this->cards->getObjectives() as $objective) {
$score += $objective->getScoring($player->getId());
}
$scores[$player->getId()] = $score;
self::DbQuery(
"UPDATE player SET player_score = {$score} WHERE player_id='{$player->getId()}'"
);
}
$this->notifyAllPlayers('updateScores', '', [
'scores' => $scores,
]);
}
$this->gamestate->nextState('next');
}
public function stScoringEnd()
{
// Reset scores
self::DbQuery('UPDATE player SET player_score = 0');
$scores = [];
foreach ($this->playerManager->getPlayers() as $player) {
$scores[$player->getId()] = 0;
}
$this->notifyAllPlayers('updateScores', '', ['scores' => $scores]);
// Header line
$headers = [''];
foreach ($this->playerManager->getPlayers() as $player) {
$headers[] = [
'str' => '${player_name}',
'args' => ['player_name' => $player->getName()],
'type' => 'header',
];
}
$table = [$headers];
// Objectives
foreach ($this->cards->getObjectives() as $objective) {
$table[] = $objective->scoringEnd();
}
// Total
$totals = [['str' => clienttranslate('Total'), 'args' => []]];
foreach ($this->playerManager->getPlayers() as $player) {
$totals[] = $player->getScore();
}
$table[] = $totals;
$this->notifyAllPlayers('tableWindow', '', [
'id' => 'finalScoring',
'title' => clienttranslate('Final scores'),
'table' => $table,
'closing' => clienttranslate('End of game'),
]);
// TODO : tie breaker
$this->gamestate->nextState('endgame');
}
/////////////////////////////////////////
/////////////////////////////////////////
///////////// Build ///////////////
/////////////////////////////////////////
/////////////////////////////////////////
/*
* Generic function that return the set of hexes available to build onto
*/
public function argPlayerBuildAux($terrain = null)
{
$player = $this->playerManager->getPlayer();
$terrain = $terrain ?? $player->getTerrain();
$tiles = $player->getPlayableTilesInHand();
$location = $this->locationManager->getActiveLocation();
$nbr = count($this->log->getLastBuilds());
return [
'i18n' => ['terrainName', 'tileName'],
'terrain' => $terrain,
'terrainName' => $this->terrainNames[$terrain],
'hexes' => $this->board->getAvailableHexes($terrain),
'cancelable' => $this->log->getLastActions() != null,
'nbr' => '(' . ($nbr + 1) . '/3)',
'tiles' => $nbr == 0 && is_null($location) ? $tiles : [],
'tileName' => is_null($location) ? '' : $location->getName(),
];
}
/*
* argPlayerBuild: give the list of accessible unnocupied spaces for builds
*/
public function argPlayerBuild()
{
// Not using a tile => classic build
if (is_null($this->locationManager->getActiveLocation())) {
return $this->argPlayerBuildAux();
} else {
return $this->locationManager->argPlayerBuild();
}
}
/*
* Build : build a settlement
*/
public function playerBuild($pos)
{
// Check if work is possible
self::checkAction('build');
$arg = $this->argPlayerBuild();
if (!in_array($pos, $arg['hexes'])) {
throw new BgaUserException(_('You cannot build here'));
}
$player = $this->playerManager->getPlayer();
$player->build($pos);
$this->stateAfterWork();
}
/*
* stateAfterWork: according to number of settlement builds, either build again or end turn
*/
public function stateAfterWork()
{
$player = $this->playerManager->getPlayer();
$nextState =
count($this->log->getLastBuilds()) == 3 ||
$player->getSettlementsInHand() == 0
? 'done'
: 'build';
if (
$nextState == 'done' &&
count($player->getPlayableTilesInHand()) > 0
) {
$nextState = 'useTile';
}
$this->gamestate->nextState($nextState);
}
////////////////////////////////////////
////////////////////////////////////////
/////////// UseTile //////////////
////////////////////////////////////////
////////////////////////////////////////
public function argUseTile()
{
return [
'tiles' => $this->playerManager
->getPlayer()
->getPlayableTilesInHand(),
'skippable' => true,
'cancelable' => true,
];
}
/*
* skip: called when a player decide to skip the use of tile
*/
public function skip()
{
$this->gamestate->nextState('skip');
}
/*
* useTile: called when a player decide to a tile location
*/
public function useTile($tileId)
{
$tiles = array_map(function ($tile) {
return $tile['id'];
}, $this->playerManager->getPlayer()->getPlayableTilesInHand());
if (!in_array($tileId, $tiles)) {
throw new \feException("You can't use that tile");
}
$nbr = count($this->log->getLastBuilds());
$location = $this->locationManager->getActiveLocation();
$state = $this->gamestate->state_id();
if ($state == ST_BUILD && $nbr != 0 && is_null($location)) {
throw new \feException(
"You can't use a tile in the middle of your mandatory action"
);
}
$location = $this->locationManager->getActiveLocation();
if (is_null($location)) {
$this->gamestate->nextState(
$this->locationManager->useTile($tileId)
);
}
}
/*
* argPlayerMove: give the list of settlements that can move
*/
public function argPlayerMove()
{
$arg = $this->locationManager->argPlayerMove();
return $arg;
}
/*
* Move : move a settlement
*/
public function playerMove($from, $to)
{
// Check if work is possible
self::checkAction('move');
$arg = $this->argPlayerMove();
if (!in_array($from, $arg['hexes'])) {
throw new BgaUserException(_('You cannot move this settlement'));
}
$arg2 = $this->locationManager->argPlayerMoveTarget($from);
if (!in_array($to, $arg2['hexes'])) {
throw new BgaUserException(
_('You cannot move this settlement here')
);
}
$player = $this->playerManager->getPlayer();
$player->move($from, $to);
$this->stateAfterWork();
}
////////////////////////////////////////
////////////////////////////////////////
///////// Undo/restart/confirm ////////
////////////////////////////////////////
////////////////////////////////////////
/*
* undoAction: called when a player decide to undo last action
*/
public function undoAction()
{
self::checkAction('undoAction');
if ($this->log->getLastActions() == null) {
throw new BgaUserException(_('You have nothing to cancel'));
}
// Undo the action
$moveIds = $this->log->cancelLastAction();
self::notifyAllPlayers(
'cancel',
clienttranslate('${player_name} undo their last action'),
[
'player_name' => self::getActivePlayerName(),
'moveIds' => $moveIds,
'board' => $this->board->getUiData(),
'fplayers' => $this->playerManager->getUiData(
self::getCurrentPlayerId()
),
]
);
$this->stateAfterWork();
}
/*
* restartTurn: called when a player decide to go back at the beggining of the turn
*/
public function restartTurn()
{
self::checkAction('restartTurn');
if ($this->log->getLastActions() == null) {
throw new BgaUserException(_('You have nothing to cancel'));
}
// Undo the turn
$moveIds = $this->log->cancelTurn();
self::notifyAllPlayers(
'cancel',
clienttranslate('${player_name} restarts their turn'),
[
'player_name' => self::getActivePlayerName(),
'moveIds' => $moveIds,
'board' => $this->board->getUiData(),
'fplayers' => $this->playerManager->getUiData(
self::getCurrentPlayerId()
),
]
);
$this->gamestate->nextState('restartTurn');
}
/*
* confirmTurn: called whenever a player confirm their turn
*/
public function confirmTurn()
{
$this->gamestate->nextState('confirm');
}
////////////////////////////////////
//////////// 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
*/
public function zombieTurn($state, $activePlayer)
{
if (array_key_exists('zombiePass', $state['transitions'])) {
$this->playerManager->eliminate($activePlayer);
$this->gamestate->nextState('zombiePass');
} else {
throw new BgaVisibleSystemException(
'Zombie player ' .
$activePlayer .
' stuck in unexpected state ' .
$state['name']
);
}
}
/////////////////////////////////////
////////// DB upgrade ///////////
/////////////////////////////////////
// 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.
/////////////////////////////////////
/*
* upgradeTableDb
* - int $from_version : 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
*/
public function upgradeTableDb($from_version)
{
}
}