Debian Codegraph @

src/game.cpp

raw
1 // Copyright © 2001-2004 Rob Kaper <[email protected]>,
2 // 2001 Erik Bourget <[email protected]>
3 // 2010-2015 Sylvain Rochet <[email protected]>
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // version 2 as published by the Free Software Foundation.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program; see the file COPYING. If not, see
16 // <http://www.gnu.org/licenses/>.
17
18 #include "config.h"
19
20 #define __USE_XOPEN
21 #include <stdarg.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <syslog.h>
25 #include <string.h>
26 #include <time.h>
27 #include <algorithm> // libstdc++ from the gcc 2.95 has no #include <algo> yet :(
28
29 #include <map>
30 #include <string>
31 #include <iostream>
32 #include <fstream>
33
34 #include <utf8.h>
35
36 #include "auction.h"
37 #include "card.h"
38 #include "cardgroup.h"
39 #include "debt.h"
40 #include "estate.h"
41 #include "estategroup.h"
42 #include "game.h"
43 #include "io.h"
44 #include "player.h"
45 #include "trade.h"
46 #include "display.h"
47
48 Game::Game(int id)
49 : GameObject(id, GGame), m_randomEngine(time(NULL))
50 {
51 m_status = Config;
52
53 m_startMoney = 0;
54 m_houses = 0;
55 m_hotels = 0;
56 m_master = m_pTurn = 0;
57 m_goEstate = 0;
58 m_gameType = m_bgColor = "";
59 m_isValid = m_pausedForDialog = false;
60 m_auction = 0;
61 m_auctionDebt = 0;
62 dice[0]=0;
63 dice[1]=0;
64
65 // addConfigOption( "test", "A test config option", "teststring" );
66 // addConfigOption( "test2", "An int test config option", 23 );
67 // addBoolConfigOption( "test3", "A bool test config option", true );
68
69 m_nextCardGroupId = m_nextEstateId = m_nextEstateGroupId = m_nextTradeId = m_nextAuctionId = 0;
70
71 addBoolConfigOption( "collectfines", "Free Parking collects fines", false, true );
72 addBoolConfigOption( "alwaysshuffle", "Always shuffle decks before taking a card", false, true );
73 addBoolConfigOption( "auctionsenabled", "Enable auctions", true, true );
74 addBoolConfigOption( "doublepassmoney", "Double pass money on exact landings", false, true );
75 addBoolConfigOption( "unlimitedhouses", "Bank provides unlimited amount of houses/hotels", false, true );
76 addBoolConfigOption( "norentinjail", "Players in Jail get no rent", false, true );
77 addBoolConfigOption( "allowestatesales", "Allow estates to be sold back to Bank", false, true );
78 addBoolConfigOption( "automatetax", "Automate tax decisions", false, true );
79 addBoolConfigOption( "allowspectators", "Allow spectators", true, true );
80 }
81
82 Game::~Game()
83 {
84 // We are responsible for the objects allocated
85 while (!m_cardGroups.empty()) { delete *m_cardGroups.begin(); m_cardGroups.erase(m_cardGroups.begin()); }
86 while (!m_debts.empty()) { delete *m_debts.begin(); m_debts.erase(m_debts.begin()); }
87 while (!m_estates.empty()) { delete *m_estates.begin(); m_estates.erase(m_estates.begin()); }
88 while (!m_estateGroups.empty()) { delete *m_estateGroups.begin(); m_estateGroups.erase(m_estateGroups.begin()); }
89 while (!m_trades.empty()) { delete *m_trades.begin(); m_trades.erase(m_trades.begin()); }
90 while (!m_configOptions.empty()) { delete *m_configOptions.begin(); m_configOptions.erase(m_configOptions.begin()); }
91
92 if (m_auction)
93 delete m_auction;
94 }
95
96 void Game::ioWrite(const char *fmt, ...)
97 {
98 int n, size = 256;
99 char *buf = new char[size];
100 static std::string ioStr;
101 va_list arg;
102
103 buf[0] = 0;
104
105 while (1)
106 {
107 va_start(arg, fmt);
108 n = vsnprintf(buf, size, fmt, arg);
109 va_end(arg);
110
111 if (n > -1 && n < size)
112 {
113 ioStr = buf;
114 delete[] buf;
115 ioWrite(ioStr);
116 return;
117 }
118
119 if (n > -1)
120 size = n+1;
121 else
122 size *= 2;
123
124 delete[] buf;
125 buf = new char[size];
126 }
127 }
128
129 void Game::ioWrite(const std::string data)
130 {
131 Player *pTmp = 0;
132 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end() && (pTmp = *it) ; ++it)
133 pTmp->ioWrite(data);
134 }
135
136 void Game::ioInfo(const char *data, ...)
137 {
138 va_list arg;
139 char buf[2048];
140
141 va_start(arg, data);
142 vsnprintf(buf, sizeof(buf)-1, data, arg);
143 va_end(arg);
144 buf[sizeof(buf)-1] = 0;
145
146 ioWrite("<monopd><msg type=\"info\" value=\"%s\"/></monopd>\n", buf);
147 }
148
149 void Game::ioInfo(const std::string data)
150 {
151 ioWrite("<monopd><msg type=\"info\" value=\"" + data + "\"/></monopd>\n");
152 }
153
154 void Game::ioError(const std::string data)
155 {
156 ioWrite("<monopd><msg type=\"error\" value=\"" + data + "\"/></monopd>\n");
157 }
158
159 void Game::loadGameType(const std::string &gameType)
160 {
161 if (m_gameType != gameType)
162 {
163 m_gameType = gameType;
164 loadConfig();
165
166 // Reset estates.. so that the first player joining won't get estateupdates until init
167 for (std::vector<Estate *>::iterator it = m_estates.begin(); it != m_estates.end() && (*it) ; ++it) {
168 (*it)->unsetPropertiesChanged();
169 }
170 }
171 }
172
173 void Game::loadConfig()
174 {
175 enum ConfigGroup { Board, EstateGroups, Estates, CardGroups, Cards, Other };
176 ConfigGroup configGroup = Other;
177 std::map<Estate *, int> payTargets;
178 EstateGroup *group = 0;
179 Estate *eTmp = 0;
180 CardGroup *cardGroup = 0;
181 Card *card = 0;
182 unsigned int goEstate = 0, nextCardId = 0;
183 int pos = 0;
184
185 std::string line, key, value;
186 std::string filename = std::string(MONOPD_DATADIR "/games/") + m_gameType + ".conf";
187
188 std::ifstream infile( filename.c_str() );
189 if ( infile.bad() )
190 return;
191
192 while (getline( infile, line, '\n')) {
193
194 if (!line.size() || line[0] == '#') {
195 continue;
196 }
197
198 if (!utf8::is_valid(line.begin(), line.end())) {
199 infile.close();
200 return;
201 }
202
203 if (line[0] == '<') {
204 value = line.substr( 1, line.size()-2 );
205 if ( value == "Board" )
206 configGroup = Board;
207 else if ( value == "EstateGroups" )
208 configGroup = EstateGroups;
209 else if ( value == "Estates" )
210 configGroup = Estates;
211 else if ( value == "Cards" )
212 configGroup = CardGroups;
213 else
214 configGroup = Other;
215
216 continue;
217 }
218
219 if (line[0] == '[') {
220 value = line.substr( 1, line.size()-2 );
221 if (configGroup == EstateGroups)
222 group = newGroup( value );
223 else if (configGroup == Estates)
224 eTmp = newEstate( value );
225 else if (configGroup == Cards && cardGroup)
226 card = cardGroup->newCard( nextCardId++, value );
227
228 continue;
229 }
230
231 pos = line.find( "=" );
232 if (pos == (int)std::string::npos) {
233 continue;
234 }
235
236 key = line.substr( 0, pos );
237 value = line.substr( pos+1 );
238
239 if (configGroup == Board) {
240 if ( key == "go" ) {
241 goEstate = atoi( value.c_str() );
242 } else if ( key == "bgcolor" ) {
243 m_bgColor = value;
244 }
245 }
246 else if (configGroup == EstateGroups) {
247 parseConfigEntry( group, key, value );
248 }
249 else if (configGroup == Estates) {
250 if ( key == "paytarget" ) {
251 payTargets[eTmp] = atoi( value.c_str() );
252 } else {
253 parseConfigEntry( eTmp, key, value );
254 }
255 }
256 else if (configGroup == CardGroups) {
257 if ( key == "groupname" ) {
258 cardGroup = newCardGroup( value );
259 configGroup = Cards;
260 }
261 }
262 else if (configGroup == Cards) {
263 if ( key == "groupname" ) {
264 cardGroup = newCardGroup( value );
265 } else {
266 parseConfigEntry( card, key, value );
267 }
268 }
269 else if ( key == "name" || key == "description") {
270 setProperty( key, value );
271 }
272 else if ( key == "minplayers" || key == "maxplayers" ) {
273 setProperty( key, atoi( value.c_str() ) );
274 }
275 else if ( key == "houses" ) {
276 m_houses = atoi( value.c_str() );
277 }
278 else if ( key == "hotels" ) {
279 m_hotels = atoi( value.c_str() );
280 }
281 else if ( key == "startmoney" ) {
282 m_startMoney = atoi( value.c_str() );
283 }
284 }
285 infile.close();
286
287 // Make sure defaults are within reasonable limits
288 if (getIntProperty("minplayers") < 2)
289 setProperty("minplayers", 2);
290 if (getIntProperty("maxplayers") < getIntProperty("minplayers"))
291 setProperty("maxplayers", getIntProperty("minplayers"));
292 else if (getIntProperty("maxplayers") > 32)
293 setProperty("maxplayers", 32);
294
295 // Go estate is required, defaults to first specified
296 if (!(m_goEstate = findEstate(goEstate)))
297 m_goEstate = findEstate(0);
298 if (!m_goEstate)
299 return;
300
301 // Fix defaults for estates
302 for (std::map<Estate *, int>::iterator it = payTargets.begin() ; it != payTargets.end() && (eTmp = (*it).first) ; it++)
303 eTmp->setPayTarget(findEstate((*it).second));
304 payTargets.clear();
305
306 eTmp = 0;
307 for (std::vector<Estate *>::iterator eIt = m_estates.begin() ; eIt != m_estates.end() && (eTmp = *eIt) ; eIt++)
308 {
309 if (!eTmp->hasIntProperty("mortgageprice"))
310 eTmp->setProperty("mortgageprice", (int)(eTmp->price()/2), this);
311 if (!eTmp->hasIntProperty("unmortgageprice"))
312 eTmp->setProperty("unmortgageprice", (int)((eTmp->price()/2)*1.1), this);
313 if (!eTmp->hasIntProperty("sellhouseprice"))
314 eTmp->setProperty("sellhouseprice", (int)(eTmp->housePrice()/2), this);
315 }
316
317 m_isValid = true;
318 }
319
320 void Game::parseConfigEntry(Estate *es, const std::string &key, const std::string &value)
321 {
322 if (!es)
323 return;
324
325 if ( key == "group" )
326 es->setEstateGroup( findGroup( value ) );
327 else if ( key == "color" || key == "bgcolor" || key == "icon" )
328 es->setProperty( key, value, this );
329 else if ( key == "price" || key == "mortgageprice" || key == "unmortgageprice" || key == "houseprice" || key == "sellhouseprice" ||
330 key == "payamount" || key == "passmoney" || key == "tax" || key == "taxpercentage"
331 )
332 es->setProperty( key, atoi( value.c_str() ), this );
333 else if ( key == "rent0" )
334 es->setRent(0, atoi( value.c_str() ) );
335 else if ( key == "rent1" )
336 es->setRent(1, atoi( value.c_str() ) );
337 else if ( key == "rent2" )
338 es->setRent(2, atoi( value.c_str() ) );
339 else if ( key == "rent3" )
340 es->setRent(3, atoi( value.c_str() ) );
341 else if ( key == "rent4" )
342 es->setRent(4, atoi( value.c_str() ) );
343 else if ( key == "rent5" )
344 es->setRent(5, atoi( value.c_str() ) );
345 else if ( key == "tojail" || key == "jail" )
346 es->setBoolProperty( key, atoi( value.c_str() ), this );
347 else if ( key == "takecard" )
348 es->setTakeCardGroup( findCardGroup( value ) );
349 }
350
351 void Game::parseConfigEntry(Card *card, const std::string &key, const std::string &value)
352 {
353 if (!card)
354 return;
355
356 if ( key == "canbeowned" )
357 card->setCanBeOwned( atoi( value.c_str() ) );
358 else if ( key == "pay" )
359 card->setPay( atoi( value.c_str() ) );
360 else if ( key == "payhouse" )
361 card->setPayHouse( atoi( value.c_str() ) );
362 else if ( key == "payhotel" )
363 card->setPayHotel( atoi( value.c_str() ) );
364 else if ( key == "payeach" )
365 card->setPayEach( atoi( value.c_str() ) );
366 else if ( key == "tojail" )
367 card->setToJail( atoi( value.c_str() ) );
368 else if ( key == "outofjail" )
369 card->setOutOfJail( atoi( value.c_str() ) );
370 else if ( key == "advance" )
371 card->setAdvance( atoi( value.c_str() ) );
372 else if ( key == "advanceto" )
373 card->setAdvanceTo( atoi( value.c_str() ) );
374 else if ( key == "advancetonextof" )
375 card->setAdvanceToNextOf( findGroup( value ) );
376 else if ( key == "rentmath" )
377 card->setRentMath( value );
378 }
379
380 void Game::parseConfigEntry(EstateGroup *group, const std::string &key, const std::string &value)
381 {
382 if (!group)
383 return;
384
385 if ( key == "price" )
386 group->setPrice( atoi( value.c_str() ) );
387 else if ( key == "houseprice" )
388 group->setHousePrice( atoi( value.c_str() ) );
389 else if ( key == "color" || key == "bgcolor" )
390 group->setProperty( key, value, this );
391 else if ( key == "rentmath" )
392 group->setRentMath( value );
393 else if ( key == "rentvar" )
394 group->setRentVar( value );
395 }
396
397 void Game::editConfiguration(Player *pInput, char *data)
398 {
399 if (pInput != m_master)
400 {
401 pInput->ioError("Only the master can edit the game configuration.");
402 return;
403 }
404
405 if (m_status != Config)
406 {
407 pInput->ioError("This game has already been started.");
408 return;
409 }
410
411 if (!strstr(data, ":"))
412 {
413 pInput->ioError("Invalid input for .gc, no separator after configId");
414 return;
415 }
416 int configId = atoi(strsep(&data, ":"));
417
418 GameObject *configOption = findConfigOption(configId);
419 if (!configOption)
420 {
421 pInput->ioError("No such configId: %d.", configId);
422 return;
423 }
424
425 std::string newValue = data;
426
427 if ( configOption->getStringProperty("type") == "string" )
428 configOption->setProperty( "value", newValue );
429 else if ( configOption->getStringProperty("type") == "int" )
430 configOption->setProperty( "value", atoi(newValue.c_str()) );
431 else if ( configOption->getStringProperty("type") == "bool" )
432 configOption->setBoolProperty( "value", atoi(newValue.c_str()) );
433 }
434
435 GameObject *Game::newConfigOption(const std::string &name, const std::string &description, bool editable)
436 {
437 GameObject *config = new GameObject( m_configOptions.size()+1 , ConfigOption, this);
438 m_configOptions.push_back(config);
439 config->setProperty("name", name, this);
440 config->setProperty("description", description, this);
441 config->setBoolProperty("edit", editable, this);
442 return config;
443 }
444
445 void Game::addConfigOption(const std::string &name, const std::string &description, const std::string &defaultValue, bool editable)
446 {
447 GameObject *config = newConfigOption(name, description, editable);
448 config->setProperty("type", "string", this);
449 config->setProperty("value", defaultValue, this);
450 }
451
452 void Game::addConfigOption(const std::string &name, const std::string &description, int defaultValue, bool editable)
453 {
454 GameObject *config = newConfigOption(name, description, editable);
455 config->setProperty("type", "int", this);
456 config->setProperty("value", defaultValue, this);
457 }
458
459 void Game::addBoolConfigOption(const std::string &name, const std::string &description, bool defaultValue, bool editable)
460 {
461 GameObject *config = newConfigOption(name, description, editable);
462 config->setProperty("type", "bool", this);
463 config->setBoolProperty("value", defaultValue, this);
464 }
465
466 GameObject *Game::findConfigOption(int configId)
467 {
468 for(std::vector<GameObject *>::iterator it = m_configOptions.begin(); it != m_configOptions.end() && (*it) ; ++it)
469 if ( (*it)->id() == configId )
470 return (*it);
471 return 0;
472 }
473
474 GameObject *Game::findConfigOption(const std::string &name)
475 {
476 for(std::vector<GameObject *>::iterator it = m_configOptions.begin(); it != m_configOptions.end() && (*it) ; ++it)
477 if ( (*it)->getStringProperty("name") == name )
478 return (*it);
479 return 0;
480 }
481
482 bool Game::getBoolConfigOption(const std::string &name)
483 {
484 GameObject *config = findConfigOption(name);
485 return (config && config->getBoolProperty("value"));
486 }
487
488 void Game::start(Player *pInput)
489 {
490 if (pInput != m_master)
491 {
492 pInput->ioError("Only the master can start a game.");
493 return;
494 }
495 if (m_status != Config)
496 {
497 pInput->ioError("This game has already been started.");
498 return;
499 }
500 int minPlayers = getIntProperty("minplayers");
501 if (players() < minPlayers)
502 {
503 pInput->ioError("This game requires at least %d players to be started.", minPlayers);
504 return;
505 }
506
507 // Update status.
508 sendStatus(Init);
509 // Add notification of game start.
510 m_status = Run;
511 setProperty("status", "run");
512
513 // Update whether players can join/watch.
514 setBoolProperty("canbejoined", false);
515 GameObject *config = findConfigOption("allowspectators");
516 if (config && config->getBoolProperty("value")) {
517 setBoolProperty("canbewatched", true);
518 }
519
520 // Shuffle players
521 std::shuffle(m_players.begin(), m_players.end(), m_randomEngine);
522
523 // Shuffle card decks.
524 CardGroup *cardGroup = 0;
525 for (std::vector<CardGroup *>::iterator it = m_cardGroups.begin() ; it != m_cardGroups.end() && (cardGroup = *it) ; ++it)
526 cardGroup->shuffleCards();
527
528 // Set all players at Go, give them money
529 Player *pTmp = 0;
530 int turnorder = 0;
531 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end() && (pTmp = *it) ; ++it)
532 {
533 pTmp->reset(false);
534 pTmp->setProperty("turnorder", ++turnorder, this);
535 pTmp->setEstate(m_goEstate);
536 pTmp->addMoney(m_startMoney);
537 }
538
539 // First turn
540 setProperty("turn", 1);
541
542 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end() && (pTmp = *it) ; ++it)
543 sendFullUpdate(pTmp);
544
545 Display display;
546 display.resetText();
547 display.resetEstate();
548 display.setText("Game started!");
549 sendDisplayMsg(&display);
550
551 // Turn goes to first player
552 m_pTurn = *m_players.begin();
553 m_pTurn->setTurn(true);
554 }
555
556 void Game::setTokenLocation(Player *pInput, unsigned int estateId)
557 {
558 if (!clientsMoving())
559 return;
560
561 Estate *estateLoc = findEstate(estateId);
562
563 if ( !estateLoc || !pInput->tokenLocation() || !m_pTurn->destination() || (pInput->tokenLocation() == estateLoc) )
564 return;
565
566 // printf("Game::setTokenLocation, P:%d PTL:%d EID:%d\n", pInput->id(), pInput->tokenLocation()->id(), estateId);
567
568 std::vector<Estate *>::iterator it;
569 // find current player estate
570 for (it = m_estates.begin(); it != m_estates.end(); it++) {
571 if (*it == pInput->tokenLocation()) {
572 // printf("Game::setTokenLocation, %d==PTL\n", (*it)->id());
573 it++;
574 break;
575 }
576 }
577
578 unsigned int money = 0;
579 while (1) {
580 if (it == m_estates.end()) {
581 // printf("Game::setTokenLocation, reloop\n");
582 it = m_estates.begin();
583 }
584 Estate *estate = *it;
585
586 if (estate->getIntProperty("passmoney")) {
587 // printf("Game::setTokenLocation, pass:%d\n", estate->id());
588 Display display;
589 display.setText("%s passes %s and gets %d.", m_pTurn->getStringProperty("name").c_str(), estate->getStringProperty("name").c_str(), estate->getIntProperty("passmoney"));
590 pInput->sendDisplayMsg(&display);
591 money += estate->getIntProperty("passmoney");
592 pInput->ioWrite("<monopd><playerupdate playerid=\"%d\" money=\"%d\"/></monopd>\n", m_pTurn->id(), m_pTurn->getIntProperty("money") + money);
593 }
594
595 if (estate == m_pTurn->destination()) {
596 // printf("Game::setTokenLocation, setPTL:0\n");
597 pInput->setTokenLocation(0); // Player is done moving
598 break;
599 }
600
601 if (estate == estateLoc) {
602 // printf("Game::setTokenLocation, setPTL:%d\n", estateId);
603 pInput->setTokenLocation(estate); // Player is not done moving
604 break;
605 }
606
607 it++;
608 }
609
610 // Find out if there are still clients busy with movement.
611 if (clientsMoving())
612 return;
613
614 // Land player!
615 landPlayer(m_pTurn, false);
616 // game might be ended if a player is bankrupt after landing (eg. could not pay rent), thus m_pTurn can be NULL here
617 if (m_pTurn) m_pTurn->endTurn();
618 }
619
620 void Game::tokenMovementTimeout()
621 {
622 // game might be ended if a player left while moving, thus m_pTurn can be NULL here
623 if (!m_pTurn) {
624 return;
625 }
626
627 if (!m_pTurn->destination()) {
628 return;
629 }
630
631 // Mark all clients as non moving.
632 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end(); ++it) {
633 if ((*it)->tokenLocation()) {
634 setTokenLocation(*it, m_pTurn->destination()->id());
635 }
636 }
637 }
638
639 unsigned int Game::auctionTimeout()
640 {
641 // game might be ended while an auction was in progress (eg. a player left), thus m_auction can be NULL here
642 if (!m_auction)
643 return 0;
644
645 printf("Game::auctionTimeout %d %d\n", m_id, m_auction->status());
646
647 m_auction->setStatus(m_auction->status() +1);
648 ioWrite("<monopd><auctionupdate auctionid=\"%d\" status=\"%d\"/></monopd>\n", m_auction->id(), m_auction->status());
649
650 if (m_auction->status() == Auction::Sold) {
651 printf("Game::auctionTimeout sold %d %d\n", m_id, m_auction->status());
652
653 Player *pBid = m_auction->highBidder();
654 int bid = m_auction->getIntProperty("highbid");
655
656 if (!pBid->payMoney(bid)) {
657 Display display;
658 display.setText("%s has to pay %d. Game paused, %s is not solvent. Player needs to raise %d in cash first.", pBid->getStringProperty("name").c_str(), bid, pBid->getStringProperty("name").c_str(), (bid - pBid->getIntProperty("money")));
659 sendDisplayMsg(&display);
660
661 m_auctionDebt = newDebt(pBid, 0, 0, bid);
662 return 0;
663 }
664
665 completeAuction();
666 m_pTurn->endTurn();
667 return 0;
668 }
669
670 return 4000;
671 }
672
673 void Game::newDebtToAll(Player *from, int amount)
674 {
675 Player *pTmp = 0;
676 for(std::vector<Player *>::iterator it = m_players.begin() ; it != m_players.end() && (pTmp = *it) ; ++it)
677 if (pTmp != from)
678 newDebt(from, pTmp, 0, amount);
679 }
680
681 Debt *Game::newDebt(Player *from, Player *toPlayer, Estate *toEstate, int amount)
682 {
683 if (from && (from->getBoolProperty("bankrupt") || from->getBoolProperty("spectator")))
684 return 0;
685 if (toPlayer && (toPlayer->getBoolProperty("bankrupt") || toPlayer->getBoolProperty("spectator")))
686 return 0;
687
688 Debt *d = new Debt(from, toPlayer, toEstate, amount);
689 m_debts.push_back(d);
690
691 if (amount > from->assets())
692 {
693 from->setBoolProperty("hasdebt", true);
694
695 Display display;
696 display.setText("%s is bankrupt!", from->getStringProperty("name").c_str());
697 sendDisplayMsg(&display, from);
698 display.resetButtons(); /* Player is bankrupt, removed declare bankruptcy button */
699 from->sendDisplayMsg(&display);
700
701 bankruptPlayer(from);
702 return 0;
703 }
704
705 if (!from->getBoolProperty("hasdebt")) {
706 from->setBoolProperty("hasdebt", true);
707 Display display;
708 display.addButton(".D", "Declare bankruptcy", true);
709 from->sendDisplayMsg(&display);
710 }
711 return d;
712 }
713
714 Debt *Game::findDebt(Player *p)
715 {
716 Debt *dTmp = 0;
717 for(std::vector<Debt *>::iterator it = m_debts.begin(); it != m_debts.end() && (dTmp = *it) ; ++it)
718 if (p == dTmp->from())
719 return dTmp;
720
721 return 0;
722 }
723
724 Debt *Game::findDebtByCreditor(Player *p)
725 {
726 Debt *dTmp = 0;
727 for(std::vector<Debt *>::iterator it = m_debts.begin(); it != m_debts.end() && (dTmp = *it) ; ++it)
728 if (p == dTmp->toPlayer())
729 return dTmp;
730
731 return 0;
732 }
733
734 void Game::delDebt(Debt *debt)
735 {
736 for(std::vector<Debt *>::iterator it = m_debts.begin(); it != m_debts.end(); ++it)
737 if (*it == debt)
738 {
739 m_debts.erase(it);
740 break;
741 }
742
743 if (debt == m_auctionDebt) {
744 m_auctionDebt = 0;
745 }
746
747 Player *pFrom = debt->from();
748 if ( !findDebt(pFrom) )
749 pFrom->setBoolProperty("hasdebt", false);
750
751 delete debt;
752 }
753
754 void Game::solveDebts(Player *pInput, const bool &verbose)
755 {
756 Debt *debt = findDebt(pInput);
757 if (!debt)
758 {
759 if (verbose)
760 ioError("You don't have any debts to pay off!");
761 return;
762 }
763
764 while ( (debt = findDebt(pInput)) )
765 {
766 if ( !solveDebt(debt) )
767 break;
768 }
769
770 if (unsigned int debts = m_debts.size()) {
771 Display display;
772 display.setText("There are still %d debts, game still paused.", debts);
773 sendDisplayMsg(&display);
774 }
775 else {
776 Display display;
777 display.setText("All debts are settled, game continues.");
778 sendDisplayMsg(&display, pInput);
779 display.resetButtons(); /* Remove declare bankruptcy button */
780 pInput->sendDisplayMsg(&display);
781
782 m_pTurn->endTurn();
783 }
784 }
785
786 bool Game::solveDebt( Debt *debt )
787 {
788 Player *pFrom = debt->from();
789 int payAmount = debt->amount();
790 if ( !(pFrom->payMoney(payAmount)) )
791 return false;
792
793 Player *pCreditor = 0;
794 Estate *eCreditor = 0;
795 if ((pCreditor = debt->toPlayer()))
796 pCreditor->addMoney(payAmount);
797 else if ( ( eCreditor = debt->toEstate() ) && getBoolConfigOption("collectfines") )
798 eCreditor->addMoney(payAmount);
799
800 Display display;
801 display.setText("%s pays off a %d debt to %s.", pFrom->getStringProperty("name").c_str(), debt->amount(), (pCreditor ? pCreditor->getStringProperty("name").c_str() : "Bank"));
802 sendDisplayMsg(&display);
803 delDebt(debt);
804 completeAuction();
805 return true;
806 }
807
808 void Game::enforceDebt(Player *pBroke, Debt *debt)
809 {
810 // Find creditors
811 Estate *eCreditor = debt ? debt->toEstate() : 0;
812 Player *pCreditor = debt ? debt->toPlayer() : 0;
813
814 // Give all cards to creditor or card stack
815 while (Card *card = pBroke->findFirstCard())
816 transferCard(card, pCreditor);
817
818 // Sell all houses on property
819 Estate *eTmp = 0;
820 for(std::vector<Estate *>::iterator it = m_estates.begin() ; it != m_estates.end() && (eTmp = *it) ; ++it)
821 {
822 if (pBroke == eTmp->owner())
823 {
824 // Sell houses
825 int eTmpHouses = eTmp->getIntProperty("houses");
826 if (eTmpHouses)
827 {
828 // Get money
829 int returnValue = eTmpHouses * eTmp->housePrice() / 2;
830 pBroke->addMoney(returnValue);
831
832 if (!getBoolConfigOption("unlimitedhouses"))
833 {
834 // Make houses available again
835 if ( eTmpHouses == 5 )
836 m_hotels++;
837 else
838 m_houses += eTmpHouses;
839 }
840 eTmp->setProperty("houses", 0);
841 }
842
843 // Transfer ownership to creditor
844 if (pCreditor)
845 transferEstate(eTmp, pCreditor);
846 else
847 {
848 eTmp->setBoolProperty("mortgaged", false);
849
850 // TODO: auction all estate when there is no pCreditor
851 transferEstate(eTmp, pCreditor);
852 }
853 // TODO: send estateupdate?
854 }
855 }
856
857 // Give all money to creditor
858 int payAmount = pBroke->getIntProperty("money");
859 pBroke->payMoney(payAmount);
860
861 if (pCreditor)
862 pCreditor->addMoney(payAmount);
863 else if (eCreditor && getBoolConfigOption("collectfines"))
864 eCreditor->addMoney(payAmount);
865
866 if (debt)
867 delDebt(debt);
868 }
869
870 void Game::newAuction(Player *pInput)
871 {
872 if (!getBoolConfigOption("auctionsenabled") || !totalAssets())
873 {
874 pInput->ioError("Auctions are not enabled.");
875 return;
876 }
877 if (!(pInput->getBoolProperty("canauction")))
878 {
879 pInput->ioError("You cannot auction anything at the moment.");
880 return;
881 }
882
883 Estate *estate = pInput->estate();
884
885 m_auction = new Auction();
886 m_auction->setEstate(estate);
887 m_auction->addToScope(this);
888
889 pInput->setBoolProperty("can_buyestate", false);
890 pInput->setBoolProperty("canauction", false);
891
892 Display display;
893 display.setText("%s chooses to auction %s.", pInput->getStringProperty("name").c_str(), estate->getStringProperty("name").c_str());
894 sendDisplayMsg(&display, pInput);
895 display.resetButtons(); /* Remove buy estate buttons: Buy, Auction, End Turn */
896 pInput->sendDisplayMsg(&display);
897
898 ioWrite("<monopd><auctionupdate auctionid=\"%d\" actor=\"%d\" estateid=\"%d\" status=\"0\"/></monopd>\n", m_auction->id(), pInput->id(), estate->id());
899 }
900
901 Auction *Game::auction()
902 {
903 return m_auction;
904 }
905
906 // Returns 0 on successful bid, 1 on error.
907 int Game::bidInAuction(Player *pInput, char *data)
908 {
909 if (!strstr(data, ":"))
910 {
911 pInput->ioError("Invalid input for .ab, no separator after auctionId");
912 return 1;
913 }
914 int auctionId = atoi(strsep(&data, ":"));
915 int bid = atoi(data);
916
917 if ( !m_auction || m_auction->id() != auctionId )
918 {
919 pInput->ioError("No such auctionId: %d.", auctionId);
920 return 1;
921 }
922
923 if (m_auction->status() == Auction::Sold) {
924 pInput->ioError( "You can no longer bid in auction %d.", auctionId );
925 return 1;
926 }
927
928 if (bid > pInput->assets())
929 {
930 pInput->ioError("You don't have %d.", bid);
931 return 1;
932 }
933
934 int highestBid = m_auction->getIntProperty("highbid");
935 if (bid <= highestBid)
936 {
937 pInput->ioError("Minimum bid is %d.", highestBid+1);
938 return 1;
939 }
940
941 m_auction->setHighBid(pInput, bid);
942 ioWrite("<monopd><auctionupdate auctionid=\"%d\" highbid=\"%d\" highbidder=\"%d\" status=\"%d\"/></monopd>\n", m_auction->id(), bid, pInput->id(), m_auction->status());
943 return 0;
944 }
945
946 void Game::newTrade(Player *pInput, unsigned int playerId)
947 {
948 Player *player = findPlayer(playerId);
949 if (!player) {
950 pInput->ioError("No such playerId: %d.", playerId);
951 return;
952 }
953 if (player == pInput) {
954 pInput->ioError("Trading with yourself?");
955 return;
956 }
957 if (player->getBoolProperty("bankrupt")) {
958 pInput->ioError("You cannot trade with bankrupt players.");
959 return;
960 }
961 if (player->getBoolProperty("spectator")) {
962 pInput->ioError("You cannot trade with spectators.");
963 return;
964 }
965
966 // Create a new trade between us and player
967 Trade *t = new Trade(pInput, player, m_nextTradeId++);
968 m_trades.push_back(t);
969 }
970
971 Trade *Game::findTrade(Player *_p)
972 {
973 Trade *tTmp = 0;
974 for(std::vector<Trade *>::iterator it = m_trades.begin(); it != m_trades.end() && (tTmp = *it) ; ++it)
975 if (tTmp->hasPlayer(_p))
976 return tTmp;
977
978 return 0;
979 }
980
981 Trade *Game::findTrade(int tradeId)
982 {
983 Trade *tTmp = 0;
984 for(std::vector<Trade *>::iterator it = m_trades.begin(); it != m_trades.end() && (tTmp = *it) ; ++it)
985 if (tradeId == tTmp->id()) return tTmp;
986
987 return 0;
988 }
989
990 void Game::delTrade(Trade *trade)
991 {
992 for(std::vector<Trade *>::iterator it = m_trades.begin(); it != m_trades.end(); ++it)
993 if (*it == trade)
994 {
995 delete trade;
996 m_trades.erase(it);
997 break;
998 }
999 }
1000
1001 void Game::acceptTrade(Player *pInput, char *data)
1002 {
1003 int tradeId = 0, revision = 0;
1004
1005 if (!strstr(data, ":"))
1006 {
1007 ioError("Invalid input for .Ta, no separator after tradeId");
1008 return;
1009 }
1010 tradeId = atoi(strsep(&data, ":"));
1011 revision = atoi(data);
1012
1013 Trade *trade = findTrade(tradeId);
1014 if (!trade)
1015 {
1016 pInput->ioError("No such tradeId: %d.", tradeId);
1017 return;
1018 }
1019 if ( !(trade->hasPlayer(pInput)) )
1020 {
1021 pInput->ioError("You are not part of trade %d.", tradeId);
1022 return;
1023 }
1024 if (revision != trade->getIntProperty("revision"))
1025 {
1026 pInput->ioError("Ignored accept for trade %d because it was changed.", tradeId);
1027 return;
1028 }
1029
1030 trade->setPlayerAccept(pInput, true);
1031
1032 if (trade->allAccept()) {
1033 completeTrade(trade);
1034 }
1035 }
1036
1037 void Game::rejectTrade(Player *pInput, unsigned int tradeId, const bool verbose)
1038 {
1039 Trade *trade = findTrade(tradeId);
1040 if (!trade)
1041 {
1042 if (verbose) {
1043 pInput->ioError("No such tradeId: %d.", tradeId);
1044 }
1045 return;
1046 }
1047
1048 if ( !(trade->hasPlayer(pInput)) )
1049 {
1050 if (verbose) {
1051 pInput->ioError("You are not part of trade %d.", tradeId);
1052 }
1053 return;
1054 }
1055
1056 ioWrite("<monopd><tradeupdate type=\"rejected\" tradeid=\"%d\" actor=\"%d\"/></monopd>\n", trade->id(), pInput->id());
1057 delTrade(trade);
1058 }
1059
1060 void Game::completeTrade(Trade *trade)
1061 {
1062 ioWrite("<monopd><tradeupdate tradeid=\"%d\" type=\"accepted\"/></monopd>\n", trade->id());
1063
1064 Player *pFrom, *pTo;
1065 GameObject *object;
1066 while((pTo = trade->firstTarget()))
1067 {
1068 Display display1, display2;
1069 pFrom = trade->firstFrom();
1070 object = trade->takeFirstObject();
1071 switch(object->type())
1072 {
1073 case GameObject::Money:
1074 unsigned int money;
1075 money = object->id();
1076 delete object; // was temporarily created to serve as trade object
1077 if (!pFrom->payMoney(money))
1078 {
1079 display2.setText("Game paused, %s owes %d to %s but is not solvent. Player needs to raise %d in cash first.", pFrom->getStringProperty("name").c_str(), money, pTo->getStringProperty("name").c_str(), (money - pFrom->getIntProperty("money")));
1080 sendDisplayMsg(&display2);
1081
1082 newDebt(pFrom, pTo, 0, money);
1083 }
1084 else
1085 pTo->addMoney(money);
1086
1087 display1.setText("%s gets %d from %s.", pTo->getStringProperty("name").c_str(), money, pFrom->getStringProperty("name").c_str());
1088 sendDisplayMsg(&display1);
1089 break;
1090 default:
1091 transferObject(object->type(), object->id(), pTo, true);
1092 }
1093 }
1094
1095 // Write "completed" to all players
1096 ioWrite("<monopd><tradeupdate tradeid=\"%d\" type=\"completed\"/></monopd>\n", trade->id());
1097
1098 // Solve debts for trade players
1099 Player *player = 0;
1100 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end() && (player = *it) ; ++it)
1101 if (trade->hasPlayer(player))
1102 solveDebts(player);
1103
1104 delTrade(trade);
1105 }
1106
1107 void Game::abortAuction()
1108 {
1109 if (!m_auction)
1110 return;
1111
1112 printf("Game::abortAuction()\n");
1113
1114 if (m_auction->status() != Auction::Sold) {
1115 ioWrite("<monopd><auctionupdate auctionid=\"%d\" status=\"%d\"/></monopd>\n", m_auction->id(), Auction::Sold);
1116 }
1117
1118 delete m_auction;
1119 m_auction = NULL;
1120 }
1121
1122 void Game::completeAuction()
1123 {
1124 if (!m_auction || m_auction->status() != Auction::Sold || m_auctionDebt)
1125 return;
1126
1127 printf("Game::completeAuction()\n");
1128
1129 Player *pBid = m_auction->highBidder();
1130 Estate *estate = m_auction->estate();
1131 transferEstate(estate, pBid);
1132
1133 Display display;
1134 display.setText("Purchased by %s in an auction for %d.", pBid->getStringProperty("name").c_str(), m_auction->getIntProperty("highbid"));
1135 sendDisplayMsg(&display);
1136
1137 delete m_auction;
1138 m_auction = NULL;
1139 }
1140
1141 void Game::sendDisplayMsg(Display *display, Player *except) {
1142 for (std::vector<Player *>::iterator pit = m_players.begin(); pit != m_players.end(); ++pit) {
1143 if (*pit != except) {
1144 (*pit)->sendDisplayMsg(display);
1145 }
1146 }
1147 }
1148
1149 void Game::sendMsgEstateUpdate(Estate *e)
1150 {
1151 Estate *eTmp = 0;
1152 Player *pTmp = 0;
1153 for (std::vector<Player *>::iterator pit = m_players.begin(); pit != m_players.end() && (pTmp = *pit) ; ++pit) {
1154 for(std::vector<Estate *>::iterator eit = m_estates.begin(); eit != m_estates.end() && (eTmp = *eit) ; ++eit) {
1155 if(eTmp->group() == e->group())
1156 pTmp->ioWrite("<monopd><estateupdate estateid=\"%d\" owner=\"%d\" can_toggle_mortgage=\"%d\" can_buy_houses=\"%d\" can_sell_houses=\"%d\"/></monopd>\n", eTmp->id(), (eTmp->owner() ? eTmp->owner()->id() : -1), eTmp->canToggleMortgage(pTmp), eTmp->canBuyHouses(pTmp), eTmp->canSellHouses(pTmp));
1157 }
1158 }
1159 }
1160
1161 EstateGroup *Game::newGroup(const std::string &name)
1162 {
1163 EstateGroup *group = new EstateGroup(m_nextEstateGroupId++, this, name);
1164 m_estateGroups.push_back(group);
1165 return group;
1166 }
1167
1168 EstateGroup *Game::findGroup(const std::string &name)
1169 {
1170 EstateGroup *group = 0;
1171 for(std::vector<EstateGroup *>::iterator it = m_estateGroups.begin(); it != m_estateGroups.end() && (group = *it) ; ++it)
1172 if (group->name() == name)
1173 return group;
1174
1175 return 0;
1176 }
1177
1178 unsigned int Game::estateGroupSize(EstateGroup *estateGroup)
1179 {
1180 unsigned int size = 0;
1181
1182 Estate *eTmp = 0;
1183 for(std::vector<Estate *>::iterator it = m_estates.begin(); it != m_estates.end() && (eTmp = *it) ; ++it)
1184 if (estateGroup == eTmp->group())
1185 size++;
1186
1187 return size;
1188 }
1189
1190 Estate *Game::newEstate(const std::string &name)
1191 {
1192 Estate *es = new Estate(m_nextEstateId++, &m_estates);
1193 m_estates.push_back(es);
1194
1195 // Set properties with game-wide scope
1196 es->setProperty("name", name, this);
1197 es->setProperty("houses", 0, this);
1198 es->setProperty("money", 0, this);
1199 es->setBoolProperty("mortgaged", false, this);
1200
1201 return es;
1202 }
1203
1204 Estate *Game::findEstate(int id)
1205 {
1206 if (id >= 0 && id < (int)m_estates.size())
1207 return m_estates[id];
1208 else
1209 return NULL;
1210 }
1211
1212 Estate *Game::findNextEstate(EstateGroup *group, Estate *startEstate)
1213 {
1214 std::vector<Estate *>::iterator it = m_estates.begin();
1215 if (startEstate) {
1216 for (; it != m_estates.end(); it++) {
1217 if (startEstate == *it) {
1218 break;
1219 }
1220 }
1221 }
1222 for (; it != m_estates.end(); it++) {
1223 if ((*it)->group() == group) {
1224 return *it;
1225 }
1226 }
1227 // reloop
1228 if (startEstate) {
1229 for (it = m_estates.begin(); it != m_estates.end(); it++) {
1230 if ((*it)->group() == group) {
1231 return *it;
1232 }
1233 }
1234 }
1235 return NULL;
1236 }
1237
1238 Estate *Game::findNextJailEstate(Estate *startEstate)
1239 {
1240 std::vector<Estate *>::iterator it = m_estates.begin();
1241 if (startEstate) {
1242 for (; it != m_estates.end(); it++) {
1243 if (startEstate == *it) {
1244 break;
1245 }
1246 }
1247 }
1248 for (; it != m_estates.end(); it++) {
1249 if ((*it)->getBoolProperty("jail")) {
1250 return *it;
1251 }
1252 }
1253 // reloop
1254 if (startEstate) {
1255 for (it = m_estates.begin(); it != m_estates.end(); it++) {
1256 if ((*it)->getBoolProperty("jail")) {
1257 return *it;
1258 }
1259 }
1260 }
1261 return NULL;
1262 }
1263
1264 void Game::transferEstate(Estate *estate, Player *player, const bool verbose)
1265 {
1266 if (estate->owner())
1267 {
1268 Trade *trade = 0;
1269 for(std::vector<Trade *>::iterator it = m_trades.begin(); it != m_trades.end() && (trade = *it) ; ++it)
1270 trade->delComponent(estate->type(), estate->id());
1271 }
1272
1273 estate->setOwner(player);
1274 sendMsgEstateUpdate(estate);
1275
1276 if (player && verbose) {
1277 Display display;
1278 display.setText("%s is now the owner of estate %s.", player->getStringProperty("name").c_str(), estate->getStringProperty("name").c_str());
1279 sendDisplayMsg(&display);
1280 }
1281 }
1282
1283 void Game::transferObject(const enum GameObject::Type type, unsigned int id, Player *player, const bool verbose)
1284 {
1285 switch(type)
1286 {
1287 case GameObject::GCard:
1288 transferCard(findCard(id), player, verbose);
1289 break;
1290 case GameObject::GEstate:
1291 transferEstate(findEstate(id), player, verbose);
1292 break;
1293 default:;
1294 }
1295 }
1296
1297 void Game::setPausedForDialog(const bool paused)
1298 {
1299 m_pausedForDialog = paused;
1300 }
1301
1302 bool Game::pausedForDialog()
1303 {
1304 return m_pausedForDialog;
1305 }
1306
1307 void Game::transferCard(Card *card, Player *player, const bool verbose)
1308 {
1309 Player *owner = card->owner();
1310 if (owner)
1311 {
1312 owner->takeCard(card);
1313 card->setOwner(0);
1314 Trade *trade = 0;
1315 for(std::vector<Trade *>::iterator it = m_trades.begin(); it != m_trades.end() && (trade = *it) ; ++it)
1316 trade->delComponent(card->type(), card->id());
1317 }
1318 else
1319 card->group()->popCard();
1320
1321 if (player)
1322 {
1323 player->addCard(card);
1324 card->setOwner(player);
1325 }
1326 else
1327 card->group()->pushCard(card);
1328
1329 ioWrite("<monopd><cardupdate cardid=\"%d\" title=\"%s\" owner=\"%d\"/></monopd>\n", card->id(), card->name().c_str(), card->owner() ? card->owner()->id() : -1);
1330 if (verbose) {
1331 Display display;
1332 display.setText("%s is now the owner of card %d.", player->getStringProperty("name").c_str(), card->id());
1333 sendDisplayMsg(&display);
1334 }
1335 }
1336
1337 CardGroup *Game::newCardGroup(const std::string name)
1338 {
1339 CardGroup *cardGroup = new CardGroup(m_nextCardGroupId++, this, name);
1340 m_cardGroups.push_back(cardGroup);
1341 return cardGroup;
1342 }
1343
1344 CardGroup *Game::findCardGroup(const std::string name)
1345 {
1346 CardGroup *cardGroup = 0;
1347 for(std::vector<CardGroup *>::iterator it = m_cardGroups.begin(); it != m_cardGroups.end(); ++it)
1348 if ((cardGroup = *it) && cardGroup->name() == name)
1349 return cardGroup;
1350
1351 return 0;
1352 }
1353
1354 Card *Game::findCard(unsigned int id)
1355 {
1356 Card *card = 0;
1357
1358 CardGroup *cardGroup = 0;
1359 for(std::vector<CardGroup *>::iterator it = m_cardGroups.begin(); it != m_cardGroups.end() && (cardGroup = *it) ; ++it)
1360 {
1361 card = cardGroup->findCard(id);
1362 if (card)
1363 return card;
1364 }
1365
1366 Player *player = 0;
1367 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end() && (player = *it) ; ++it)
1368 {
1369 card = player->findCard(id);
1370 if (card)
1371 return card;
1372 }
1373
1374 return 0;
1375 }
1376
1377 Player *Game::addPlayer(Player *p, const bool &isSpectator, const bool &isFirst)
1378 {
1379 m_players.push_back(p);
1380
1381 p->setGame(this);
1382 addToScope(p);
1383
1384 // Properties with game as scope
1385 p->setProperty("money", 0, this);
1386 p->setBoolProperty("bankrupt", false, this);
1387 p->setBoolProperty("jailed", false, this);
1388 p->setBoolProperty("hasturn", 0, this);
1389 p->setBoolProperty("spectator", isSpectator, this);
1390
1391 setProperty("players", players());
1392 if (players() == getBoolProperty("maxplayers")) {
1393 setBoolProperty("canbejoined", false);
1394 }
1395
1396 if (isFirst) {
1397 m_master = p;
1398 setProperty("master", p->id());
1399 }
1400
1401 // Properties with player as scope
1402 p->setProperty("doublecount", 0);
1403 p->setProperty("jailcount", 0);
1404 p->setBoolProperty("can_roll", false);
1405 p->setBoolProperty("canrollagain", false);
1406 p->setBoolProperty("can_buyestate", false);
1407 p->setBoolProperty("canauction", false);
1408 p->setBoolProperty("hasdebt", false);
1409 p->setBoolProperty("canusecard", false);
1410
1411 if (!isFirst) {
1412 if (m_status == Run) {
1413 sendStatus(Init, p);
1414 sendFullUpdate(p);
1415 sendStatus(Run, p);
1416 } else {
1417 sendFullUpdate(p);
1418 }
1419 }
1420
1421 return p;
1422 }
1423
1424 Player *Game::findPlayer(int playerId)
1425 {
1426 Player *pTmp = 0;
1427 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end() && (pTmp = *it) ; ++it)
1428 if (playerId == pTmp->id())
1429 return pTmp;
1430
1431 return 0;
1432 }
1433
1434 void Game::removePlayer(Player *p)
1435 {
1436 // note: m_pTurn is NULL when a game is finished
1437 if (p == m_pTurn) {
1438 // cancel any tax dialog
1439 m_pausedForDialog = false;
1440 // player left game during its turn, cancel any token movement
1441 setAllClientsMoving(0);
1442 // and update turn -before- removing player from players vector
1443 updateTurn();
1444 }
1445
1446 // Find player and erase from std::vector
1447 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end(); ++it)
1448 if (*it == p)
1449 {
1450 m_players.erase(it);
1451 break;
1452 }
1453
1454 // Do everything after player is removed from list, player doesn't need the resulting messages
1455 setProperty("players", players());
1456
1457 // If in Config, canbejoined might become true again
1458 if (m_status == Config) {
1459 if (players() < getBoolProperty("maxplayers"))
1460 setBoolProperty("canbejoined", true);
1461 }
1462 else if (m_status != End) {
1463 bankruptPlayer(p);
1464 }
1465
1466 p->setGame(0);
1467 removeFromScope(p);
1468
1469 if (p == m_master && m_players.size() > 0)
1470 {
1471 m_master = m_players[0];
1472 setProperty( "master", m_master->id() );
1473
1474 if (m_status == Config)
1475 sendConfiguration(m_master);
1476 }
1477 }
1478
1479 Player *Game::kickPlayer(Player *pInput, int playerId)
1480 {
1481 if ( pInput != m_master )
1482 {
1483 pInput->ioError("Only the master can kick players.");
1484 return 0;
1485 }
1486
1487 if ( m_status != Config )
1488 {
1489 pInput->ioError("You can only kick players during game configuration.");
1490 return 0;
1491 }
1492
1493 Player *player = findPlayer(playerId);
1494 if (!player)
1495 {
1496 pInput->ioError("No such playerId: %d.", playerId);
1497 return 0;
1498 }
1499
1500 return player;
1501 }
1502
1503 void Game::upgradePlayer(Player *pInput, int playerId)
1504 {
1505 if ( pInput != m_master )
1506 {
1507 pInput->ioError("Only the master can upgrade spectators.");
1508 return;
1509 }
1510
1511 if ( m_status != Run )
1512 {
1513 pInput->ioError("You can only upgrade spectators during a game in progress.");
1514 return;
1515 }
1516
1517 int maxPlayers = getIntProperty("maxplayers");
1518 if (players() >= maxPlayers)
1519 {
1520 pInput->ioError("This game already has the maximum of %d players.", maxPlayers);
1521 return;
1522 }
1523
1524 Player *player = findPlayer(playerId);
1525 if (!player)
1526 {
1527 pInput->ioError("No such playerId: %d.", playerId);
1528 return;
1529 }
1530
1531 if ( !player->getBoolProperty("spectator") )
1532 {
1533 pInput->ioError( "%s is not a spectator in this game.", player->name().c_str() );
1534 return;
1535 }
1536
1537 // Reset player and remove spectator property.
1538 player->reset(false);
1539
1540 int turnorder = 0;
1541 for (std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end(); ++it) {
1542 int to = (*it)->getIntProperty("turnorder");
1543 if (to > turnorder) {
1544 turnorder = to;
1545 }
1546 }
1547 player->setProperty("turnorder", turnorder+1, this);
1548
1549 // Find player and erase from std::vector
1550 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end(); ++it) {
1551 if (*it == player) {
1552 m_players.erase(it);
1553 break;
1554 }
1555 }
1556 // Reinsert player to std::vector
1557 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end(); ++it) {
1558 if ((*it)->getIntProperty("turnorder") == turnorder) {
1559 m_players.insert(it+1, player);
1560 break;
1561 }
1562 }
1563
1564 player->setEstate(m_goEstate);
1565 player->addMoney(m_startMoney);
1566 player->setBoolProperty("spectator", 0, this);
1567 setProperty("players", players());
1568
1569 ioInfo( "%s upgrades %s to a participating player.", pInput->name().c_str(), player->name().c_str() );
1570 }
1571
1572 unsigned int Game::playerAssets(Player *player)
1573 {
1574 unsigned int assets = player->getIntProperty("money");
1575 Estate *estate = 0;
1576 for(std::vector<Estate *>::iterator it = m_estates.begin(); it != m_estates.end() && (estate = *it) ; ++it)
1577 {
1578 if ( player == estate->owner() )
1579 {
1580 if (!estate->getBoolProperty("mortgaged"))
1581 {
1582 assets += estate->getIntProperty("mortgageprice");
1583 assets += ( estate->getIntProperty("houses") * estate->getIntProperty("sellhouseprice"));
1584 }
1585 }
1586 }
1587 return assets;
1588 }
1589
1590 void Game::updateTurn()
1591 {
1592 // Disable turn, roll and buy.
1593 m_pTurn->setTurn(false);
1594
1595 std::vector<Player *>::iterator it;
1596 // find current player
1597 for(it = m_players.begin(); it != m_players.end(); it++) {
1598 if (*it == m_pTurn) {
1599 it++;
1600 break;
1601 }
1602 }
1603
1604 // find next player
1605 while (1) {
1606 if (it == m_players.end()) {
1607 it = m_players.begin();
1608 setProperty("turn", getIntProperty("turn") +1);
1609 }
1610 Player *player = *it;
1611 if (!player->getBoolProperty("bankrupt") && !player->getBoolProperty("spectator")) {
1612 m_pTurn = player;
1613 break;
1614 }
1615 it++;
1616 }
1617
1618 // Set turn.
1619 Display display;
1620 display.setText("Turn goes to %s.", m_pTurn->getStringProperty("name").c_str());
1621 sendDisplayMsg(&display);
1622
1623 m_pTurn->setTurn(true);
1624 }
1625
1626 void Game::landPlayer(Player *pTurn, const bool directMove, const std::string &rentMath)
1627 {
1628 Estate *destination = pTurn->destination();
1629 if (destination) {
1630 std::vector<Estate *>::iterator it;
1631
1632 // find current player estate
1633 for (it = m_estates.begin(); it != m_estates.end(); it++) {
1634 if (*it == pTurn->estate()) {
1635 it++;
1636 break;
1637 }
1638 }
1639
1640 unsigned int money = 0;
1641 while (1) {
1642 if (it == m_estates.end()) {
1643 it = m_estates.begin();
1644 }
1645 Estate *estate = *it;
1646
1647 if (estate->getIntProperty("passmoney")) {
1648 money += estate->getIntProperty("passmoney");
1649 // Write incremental message for direct moves, token
1650 // confirmation or timeout didn't do it yet.
1651 if (directMove) {
1652 Display display;
1653 display.setText("%s passes %s and gets %d.", pTurn->getStringProperty("name").c_str(), estate->getStringProperty("name").c_str(), estate->getIntProperty("passmoney"));
1654 sendDisplayMsg(&display);
1655 }
1656 }
1657
1658 if (estate == destination) {
1659 break;
1660 }
1661
1662 it++;
1663 }
1664 pTurn->setEstate(destination);
1665 pTurn->setDestination(0);
1666
1667 // Store and write final data.
1668 pTurn->addMoney(money);
1669 }
1670
1671 // Hm, we wait for all tokens to have landed, this is exactly what we
1672 // were trying to avoid with async updates! So some of this stuff can be
1673 // sent earlier.
1674
1675 // What properties does the estate we are landing on have?
1676 Player *pOwner = 0;
1677 Estate *es = pTurn->estate();
1678
1679 if (getBoolConfigOption("doublepassmoney") && es->getIntProperty("passmoney"))
1680 {
1681 Display display;
1682 display.setText("%s lands on %s and gets %d.", pTurn->getStringProperty("name").c_str(), es->getStringProperty("name").c_str(), es->getIntProperty("passmoney"));
1683 display.setEstate(es);
1684 sendDisplayMsg(&display);
1685
1686 pTurn->addMoney(es->getIntProperty("passmoney"));
1687 }
1688 else {
1689 Display display;
1690 display.setText("%s lands on %s.", pTurn->getStringProperty("name").c_str(), es->getStringProperty("name").c_str());
1691 display.setEstate(es);
1692 sendDisplayMsg(&display);
1693 }
1694
1695 // toJail is really serious: if an estate has this property, all other
1696 // properties are ignored when landing it. TODO: Don't ignore and allow
1697 // weird combinations?
1698 if (es->getBoolProperty("tojail"))
1699 {
1700 if ( Estate *eTmp = findNextJailEstate(es) )
1701 pTurn->toJail(eTmp);
1702 else
1703 ioError("This gameboard does not have a jail estate.");
1704
1705 updateTurn();
1706 return;
1707 }
1708
1709 // Any estate can have a pot of gold. This is handled before all other
1710 // properties except toJail and works in combination with any of those
1711 // properties.
1712 if ( int estateMoney = es->getIntProperty("money") )
1713 {
1714 if ( estateMoney > 0)
1715 {
1716 // Good for you!
1717 pTurn->addMoney(estateMoney);
1718 es->setProperty("money", 0);
1719
1720 Display display;
1721 display.setText("%s gets %d from the fine pot.", pTurn->getStringProperty("name").c_str(), estateMoney);
1722 sendDisplayMsg(&display);
1723 }
1724 else
1725 {
1726 // Pay up!
1727 Estate * const ePayTarget = es->payTarget();
1728 if (!pTurn->payMoney(estateMoney))
1729 {
1730 // TODO: If we go into debt here, we'll never enter rent
1731 // calculation. But we'll need negative getIntProperty("money") piles for
1732 // Estates because that's basically what tax estates are.
1733 Display display;
1734 display.setText("%s has to pay %d but is not solvent. Game paused, %s is not solvent. Player needs to raise %d in cash first.", pTurn->getStringProperty("name").c_str(), estateMoney, pTurn->getStringProperty("name").c_str(), (estateMoney - pTurn->getIntProperty("money")));
1735 sendDisplayMsg(&display);
1736
1737 newDebt(pTurn, 0, ePayTarget, estateMoney);
1738 return;
1739 }
1740 else if (ePayTarget && getBoolConfigOption("collectfines"))
1741 ePayTarget->addMoney(estateMoney);
1742
1743 Display display;
1744 display.setText("%s pays %d.", pTurn->getStringProperty("name").c_str(), estateMoney);
1745 sendDisplayMsg(&display);
1746 }
1747 }
1748
1749 // Any estate can have taxes on them. This is handled before rent and purchase opportunities.
1750 // TODO: Merge with getIntProperty("money") stuff to avoid duplication?
1751 int tax = es->getIntProperty("tax"), taxPercentage = es->getIntProperty("taxpercentage");
1752
1753 if (tax || taxPercentage)
1754 {
1755 int payAmount = 0;
1756 if ( tax && taxPercentage )
1757 {
1758 GameObject *config = findConfigOption("automatetax");
1759 if (config && config->getBoolProperty("value") )
1760 {
1761 payAmount = tax;
1762 tax = (taxPercentage * pTurn->assets() / 100);
1763 if (tax < payAmount)
1764 payAmount = tax;
1765 }
1766 else
1767 {
1768 Display display1, display2;
1769
1770 display1.setText("%s must pay either %d or %d percent of his/her assets.", pTurn->getStringProperty("name").c_str(), tax, taxPercentage);
1771 sendDisplayMsg(&display1, pTurn);
1772
1773 display2.setText("Pay either %d or %d percent of your assets.", tax, taxPercentage);
1774 display2.addButton(".T$", std::string("Pay ") + itoa(tax), 1);\
1775 display2.addButton(".T%", std::string("Pay ") + itoa(taxPercentage) + " Percent", 1);
1776 pTurn->sendDisplayMsg(&display2);
1777
1778 // TODO: port this into a blocking bool in Display which we can check, will be more generic
1779 m_pausedForDialog = true;
1780 return;
1781 }
1782 }
1783 else
1784 payAmount = ( tax ? tax : (int)(taxPercentage * pTurn->assets() / 100 ) );
1785
1786 Estate * const ePayTarget = es->payTarget();
1787
1788 if (!pTurn->payMoney(payAmount))
1789 {
1790 // TODO: If we go into debt here, we'll never enter rent
1791 // calculation. So, estates with tax shouldn't be ownable
1792 // ever.
1793 Display display;
1794 display.setText("Game paused, %s owes %d but is not solvent. Player needs to raise %d in cash first.", pTurn->getStringProperty("name").c_str(), payAmount, (payAmount - pTurn->getIntProperty("money")));
1795 sendDisplayMsg(&display);
1796
1797 newDebt(pTurn, 0, ePayTarget, payAmount);
1798 return;
1799 }
1800 else if (ePayTarget && getBoolConfigOption("collectfines"))
1801 ePayTarget->addMoney(payAmount);
1802
1803 Display display;
1804 display.setText("%s pays %d.", pTurn->getStringProperty("name").c_str(), payAmount);
1805 sendDisplayMsg(&display);
1806 }
1807
1808 // Some estates have cards. Handle them before we do rent and purchasing.
1809 if ( CardGroup *cardGroup = es->takeCardGroup() )
1810 {
1811 if (getBoolConfigOption("alwaysshuffle"))
1812 cardGroup->shuffleCards();
1813
1814 giveCard(pTurn, cardGroup->nextCard());
1815 }
1816
1817 // Calculate rent for owned estates or offer them for sale.
1818 if ( es->canBeOwned() )
1819 {
1820 if ((pOwner = es->owner()))
1821 {
1822 // Owned.
1823
1824 if (pOwner == pTurn) {
1825 Display display;
1826 display.setText("%s already owns it.", pTurn->getStringProperty("name").c_str());
1827 sendDisplayMsg(&display);
1828 } else if (es->getBoolProperty("mortgaged")) {
1829 Display display;
1830 display.setText("%s pays no rent because it's mortgaged.", pTurn->getStringProperty("name").c_str());
1831 sendDisplayMsg(&display);
1832 } else if (getBoolConfigOption("norentinjail") && pOwner->getBoolProperty("jailed")) {
1833 Display display;
1834 display.setText("%s pays no rent because owner %s is in jail.", pTurn->getStringProperty("name").c_str(), pOwner->getStringProperty("name").c_str());
1835 sendDisplayMsg(&display);
1836 } else {
1837 // Pay payAmount owed.
1838 int payAmount = es->rent(pTurn, rentMath);
1839
1840 if (!pTurn->payMoney(payAmount))
1841 {
1842 Display display;
1843 display.setText("Game paused, %s owes %d to %s but is not solvent. Player needs to raise %d in cash first.", pTurn->getStringProperty("name").c_str(), payAmount, pOwner->getStringProperty("name").c_str(), (payAmount - pTurn->getIntProperty("money")));
1844 sendDisplayMsg(&display);
1845
1846 newDebt(pTurn, pOwner, 0, payAmount);
1847 return;
1848 }
1849 Display display;
1850 display.setText("%s pays %d rent to %s.", pTurn->getStringProperty("name").c_str(), payAmount, pOwner->getStringProperty("name").c_str());
1851 sendDisplayMsg(&display);
1852
1853 pOwner->addMoney(payAmount);
1854 }
1855 }
1856 else
1857 {
1858 // Unowned, thus for sale.
1859 pTurn->setBoolProperty("can_roll", false);
1860 pTurn->setBoolProperty("can_buyestate", true);
1861 pTurn->setBoolProperty("canauction", (getBoolConfigOption("auctionsenabled") && totalAssets()));
1862
1863 Display display;
1864 display.setText("For sale.");
1865 sendDisplayMsg(&display, pTurn);
1866 display.addButton(".eb", "Buy", 1);
1867 display.addButton(".ea", "Auction", (getBoolConfigOption("auctionsenabled") && totalAssets()));
1868 display.addButton(".E", "End Turn", !getBoolConfigOption("auctionsenabled"));
1869 pTurn->sendDisplayMsg(&display);
1870 return;
1871 }
1872 }
1873 }
1874
1875 void Game::giveCard(Player *pTurn, Card *card)
1876 {
1877 if (!card)
1878 {
1879 ioError(pTurn->name() + " should get a card, but there don't seem to be any available!");
1880 return;
1881 }
1882
1883 Display display;
1884 display.setText("%s", card->getStringProperty("name").c_str());
1885 sendDisplayMsg(&display);
1886
1887 // If canBeOwned, remove from stack and give to player. Card can still
1888 // have actions afterwards.
1889 if (card->canBeOwned())
1890 transferCard(card, pTurn);
1891
1892 // Actions
1893 if (card->toJail())
1894 {
1895 if ( Estate *eTmp = findNextJailEstate(pTurn->estate()) )
1896 pTurn->toJail(eTmp);
1897 else
1898 ioError("This gameboard does not have a jail estate.");
1899
1900 updateTurn();
1901 }
1902 else if (card->pay())
1903 {
1904 int payAmount = card->pay();
1905 Estate * const ePayTarget = pTurn->estate()->payTarget();
1906 if (payAmount > 0)
1907 {
1908 if (!pTurn->payMoney(payAmount))
1909 {
1910 Display display;
1911 display.setText("Game paused, %s owes %d but is not solvent. Player needs to raise %d in cash first.", pTurn->getStringProperty("name").c_str(), payAmount, (payAmount - pTurn->getIntProperty("money")));
1912 sendDisplayMsg(&display);
1913
1914 newDebt(pTurn, 0, ePayTarget, payAmount);
1915 }
1916 else if (ePayTarget && getBoolConfigOption("collectfines"))
1917 ePayTarget->addMoney(payAmount);
1918 }
1919 else if (payAmount < 0)
1920 pTurn->addMoney(-payAmount);
1921 }
1922 else if (card->payEach())
1923 {
1924 Player *pTmp = 0;
1925 int payAmount = 0;
1926 for (std::vector<Player *>::iterator it = m_players.begin() ; it != m_players.end() && (pTmp = *it) ; ++it)
1927 if (pTmp != pTurn && !pTmp->getBoolProperty("bankrupt") && !pTmp->getBoolProperty("spectator"))
1928 payAmount += card->payEach();
1929
1930 if (payAmount > 0)
1931 {
1932 if (!pTurn->payMoney(payAmount))
1933 {
1934 Display display;
1935 display.setText("Game paused, %s owes %d but is not solvent. Player needs to raise %d in cash first.", pTurn->getStringProperty("name").c_str(), payAmount, (payAmount - pTurn->getIntProperty("money")));
1936 sendDisplayMsg(&display);
1937
1938 newDebtToAll(pTurn, card->payEach());
1939 }
1940 else
1941 {
1942 for (std::vector<Player *>::iterator it = m_players.begin() ; it != m_players.end() && (pTmp = *it) ; ++it)
1943 if (pTmp != pTurn && !pTmp->getBoolProperty("bankrupt") && !pTmp->getBoolProperty("spectator"))
1944 pTmp->addMoney(card->payEach());
1945 }
1946 }
1947 else
1948 {
1949 payAmount = -(card->payEach());
1950 for (std::vector<Player *>::iterator it = m_players.begin() ; it != m_players.end() && (pTmp = *it) ; ++it)
1951 if (pTurn != pTmp && !pTmp->getBoolProperty("bankrupt") && !pTmp->getBoolProperty("spectator"))
1952 {
1953 if (!pTmp->payMoney(payAmount))
1954 {
1955 Display display;
1956 display.setText("Game paused, %s owes %d but is not solvent. Player needs to raise %d in cash first.", pTmp->getStringProperty("name").c_str(), payAmount, (payAmount - pTmp->getIntProperty("money")));
1957 sendDisplayMsg(&display);
1958
1959 newDebt(pTmp, pTurn, 0, payAmount);
1960 }
1961 else
1962 pTurn->addMoney(payAmount);
1963 }
1964 }
1965 }
1966 else if (card->payHouse() && card->payHotel())
1967 {
1968 int payAmount = 0;
1969
1970 Estate *eTmp = 0;
1971 for (std::vector<Estate *>::iterator eIt = m_estates.begin() ; eIt != m_estates.end() && (eTmp = *eIt) ; eIt++)
1972 {
1973 if (pTurn == eTmp->owner())
1974 {
1975 if (eTmp->getIntProperty("houses") == 5)
1976 payAmount += card->payHotel();
1977 else if (eTmp->getIntProperty("houses"))
1978 payAmount += (eTmp->getIntProperty("houses") * card->payHouse());
1979 }
1980 }
1981
1982 if (payAmount > 0)
1983 {
1984 Estate * const ePayTarget = pTurn->estate()->payTarget();
1985 if (!pTurn->payMoney(payAmount))
1986 {
1987 Display display;
1988 display.setText("Game paused, %s owes %d but is not solvent. Player needs to raise %d in cash first.", pTurn->getStringProperty("name").c_str(), payAmount, (payAmount - pTurn->getIntProperty("money")));
1989 sendDisplayMsg(&display);
1990
1991 newDebt(pTurn, 0, ePayTarget, payAmount);
1992 }
1993 else if (ePayTarget && getBoolConfigOption("collectfines"))
1994 ePayTarget->addMoney(payAmount);
1995 }
1996 else if (payAmount < 0)
1997 pTurn->addMoney(-payAmount);
1998 }
1999 else if (card->advance() || card->advanceTo()!=-1 || card->advanceToNextOf())
2000 {
2001 // Duplicated from cmd_roll. :-(
2002 if (card->advance())
2003 pTurn->advance(card->advance(), true);
2004 else if (card->advanceTo()!=-1)
2005 pTurn->advanceTo(card->advanceTo(), true);
2006 else if (EstateGroup *group = card->advanceToNextOf())
2007 {
2008 if (Estate *eTmp = findNextEstate(group, pTurn->estate()))
2009 pTurn->advanceTo(eTmp->id(), true);
2010 else
2011 ioError("Could not find next estate on gameboard.");
2012 }
2013 landPlayer(pTurn, true, card->rentMath());
2014 }
2015 }
2016
2017 void Game::declareBankrupt(Player *pInput)
2018 {
2019 Display display;
2020 display.setText("%s declares bankruptcy!", pInput->getStringProperty("name").c_str());
2021 sendDisplayMsg(&display, pInput);
2022 display.resetButtons(); /* Player declared bankruptcy, removed declare bankruptcy button */
2023 pInput->sendDisplayMsg(&display);
2024
2025 bankruptPlayer(pInput);
2026 }
2027
2028 void Game::bankruptPlayer(Player *pBroke)
2029 {
2030 if (pBroke->getBoolProperty("bankrupt") || pBroke->getBoolProperty("spectator"))
2031 return;
2032
2033 // abort any trade where this player is participating
2034 for (std::vector<Trade *>::iterator it = m_trades.begin(); it != m_trades.end() && (*it);) {
2035 unsigned int prevsize = m_trades.size();
2036 rejectTrade(pBroke, (*it)->id(), false);
2037 if (prevsize != m_trades.size()) {
2038 it = m_trades.begin();
2039 continue;
2040 }
2041 ++it;
2042 }
2043
2044 // highest bidder declared bankruptcy (or left)
2045 if (m_auction && m_auction->highBidder() == pBroke) {
2046 abortAuction();
2047 }
2048
2049 // Set bankrupt flag
2050 pBroke->setBoolProperty("bankrupt", true);
2051
2052 Debt *debt = 0;
2053 bool debtsWereSolved = false;
2054
2055 // Find debts we are creditor in and remove them
2056 while ((debt = findDebtByCreditor(pBroke)))
2057 {
2058 delDebt(debt);
2059 debtsWereSolved = true;
2060 }
2061
2062 // Find debts we are debitor in and pay them off
2063 while ((debt = findDebt(pBroke)))
2064 {
2065 enforceDebt(pBroke, debt);
2066 debtsWereSolved = true;
2067 }
2068
2069 // Player might still have assets, when he goes bankrupt without debts
2070 // (disconnection timeout), so we'll enforce giving assets to the Bank.
2071 enforceDebt(pBroke);
2072
2073 // Count active (non-bankrupt) players
2074 int activePlayers = 0;
2075 Player *pTmp = 0;
2076 Player *pWinner = 0;
2077 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end() && (pTmp = *it) ; ++it)
2078 if (pTmp && !pTmp->getBoolProperty("bankrupt") && !pTmp->getBoolProperty("spectator"))
2079 {
2080 activePlayers++;
2081 pWinner = pTmp;
2082 }
2083
2084 if (activePlayers == 1) {
2085 // a user who disconnect might end the game while an auction was running
2086 abortAuction();
2087 // game might be ended if a player left while a player was moving
2088 setAllClientsMoving(0);
2089
2090 m_status = End;
2091 setProperty("status", "end");
2092 syslog(LOG_INFO, "game %d ended: %s wins with a fortune of %d.", m_id, pWinner->name().c_str(), pWinner->assets());
2093 setBoolProperty("canbewatched", false);
2094
2095 Display display;
2096 display.resetButtons(); /* Reset any button, game might end if a player left while we were asked to buy an estate for example */
2097 display.setText("The game has ended! %s wins with a fortune of %d!", pWinner->getStringProperty("name").c_str(), pWinner->assets());
2098 display.addButton(".gx", "New Game", true);
2099 sendDisplayMsg(&display);
2100
2101 m_pTurn->setTurn(false);
2102 m_pTurn = NULL;
2103 return;
2104 }
2105
2106 if (m_debts.size()) {
2107 return;
2108 }
2109
2110 if (debtsWereSolved) {
2111 Display display;
2112 display.setText("All debts are settled, game continues.");
2113 sendDisplayMsg(&display);
2114 }
2115
2116 if (pBroke == m_pTurn) {
2117 updateTurn();
2118 return;
2119 }
2120
2121 // necessary when an auction bidder cannot pay and then declared bankruptcy
2122 m_pTurn->endTurn();
2123 }
2124
2125 int Game::totalAssets()
2126 {
2127 int assets = 0;
2128
2129 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end() && (*it) ; ++it)
2130 assets += (*it)->assets();
2131
2132 return assets;
2133 }
2134
2135 void Game::rollDice()
2136 {
2137 // TODO: decent dice display
2138 dice[0] = 1 + (int) (6.0 * rand()/(RAND_MAX + 1.0 ));
2139 dice[1] = 1 + (int) (6.0 * rand()/(RAND_MAX + 1.0 ));
2140 }
2141
2142 int Game::players(bool includeSpectators)
2143 {
2144 if (includeSpectators == true) {
2145 return (int)m_players.size();
2146 }
2147
2148 int count = 0;
2149 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end(); ++it) {
2150 if (!(*it)->getBoolProperty("spectator")) {
2151 count++;
2152 }
2153 }
2154 return count;
2155 }
2156
2157 int Game::debts()
2158 {
2159 return m_debts.size();
2160 }
2161
2162 unsigned int Game::clientsMoving()
2163 {
2164 unsigned int moving = 0;
2165 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end(); ++it) {
2166 if ((*it)->tokenLocation()) {
2167 moving++;
2168 }
2169 }
2170 return moving;
2171 }
2172
2173 void Game::setAllClientsMoving(Estate *estate)
2174 {
2175 for(std::vector<Player *>::iterator it = m_players.begin(); it != m_players.end(); ++it) {
2176 if ((*it)->socket()) {
2177 (*it)->setTokenLocation(estate);
2178 }
2179 }
2180 }
2181
2182 void Game::sendStatus(Status status, Player *p)
2183 {
2184 const char *s = "unknown";
2185
2186 switch(status) {
2187 case Config:
2188 s = "config";
2189 break;
2190 case Init:
2191 s = "init";
2192 break;
2193 case Run:
2194 s = "run";
2195 break;
2196 case End:
2197 s = "end";
2198 break;
2199 }
2200
2201 if (p) {
2202 p->ioWrite("<monopd><gameupdate gameid=\"%d\" status=\"%s\"/></monopd>\n", m_id, s);
2203 } else {
2204 ioWrite("<monopd><gameupdate gameid=\"%d\" status=\"%s\"/></monopd>\n", m_id, s);
2205 }
2206 }
2207
2208 void Game::sendEstateList(Player *p)
2209 {
2210 Estate *eTmp = 0;
2211 for(std::vector<Estate *>::iterator eIt = m_estates.begin(); eIt != m_estates.end() && (eTmp = *eIt) ; eIt++)
2212 {
2213 std::string bgColor = eTmp->getStringProperty("bgcolor");
2214 if (!bgColor.size())
2215 {
2216 EstateGroup *estateGroup = eTmp->group();
2217 if (estateGroup)
2218 bgColor = estateGroup->getStringProperty("bgcolor");
2219
2220 if (!bgColor.size())
2221 bgColor = m_bgColor;
2222 }
2223
2224 std::string color = eTmp->getStringProperty("color");
2225 if (!color.size())
2226 {
2227 EstateGroup *estateGroup = eTmp->group();
2228 if (estateGroup)
2229 color = estateGroup->getStringProperty("color");
2230 }
2231
2232 p->ioWrite("<estateupdate estateid=\"%d\" color=\"%s\" bgcolor=\"%s\" owner=\"%d\" houseprice=\"%d\" group=\"%d\" can_be_owned=\"%d\" can_toggle_mortgage=\"%d\" can_buy_houses=\"%d\" can_sell_houses=\"%d\" price=\"%d\" rent0=\"%d\" rent1=\"%d\" rent2=\"%d\" rent3=\"%d\" rent4=\"%d\" rent5=\"%d\"/>", eTmp->id(), color.c_str(), bgColor.c_str(), (eTmp->owner() ? eTmp->owner()->id() : -1), eTmp->housePrice(), eTmp->group() ? eTmp->group()->id() : -1, eTmp->canBeOwned(), eTmp->canToggleMortgage(p), eTmp->canBuyHouses(p), eTmp->canSellHouses(p), eTmp->price(), eTmp->rentByHouses(0), eTmp->rentByHouses(1), eTmp->rentByHouses(2), eTmp->rentByHouses(3), eTmp->rentByHouses(4), eTmp->rentByHouses(5));
2233 p->ioWrite(eTmp->oldXMLUpdate(p, true));
2234 }
2235 }
2236
2237 void Game::sendEstateGroupList(Player *p)
2238 {
2239 EstateGroup *egTmp = 0;
2240 for(std::vector<EstateGroup *>::iterator it = m_estateGroups.begin(); it != m_estateGroups.end() && (egTmp = *it) ; ++it)
2241 p->ioWrite("<estategroupupdate groupid=\"%d\" name=\"%s\"/>", egTmp->id(), egTmp->name().c_str());
2242 }
2243
2244 void Game::sendPlayerList(Player *pOut)
2245 {
2246 Player *pTmp = 0;
2247 for(std::vector<Player *>::iterator it = m_players.begin() ; it != m_players.end() && (pTmp = *it) ; ++it)
2248 {
2249 pOut->ioWrite("<playerupdate playerid=\"%d\" name=\"%s\" location=\"%d\" jailed=\"%d\" directmove=\"%d\" hasturn=\"%d\" can_roll=\"%d\" turnorder=\"%d\"/>", pTmp->id(), pTmp->name().c_str(), pTmp->getIntProperty("location"), pTmp->getBoolProperty("jailed"), 1, pTmp->getBoolProperty("hasturn"), pTmp->getBoolProperty("can_roll"), pTmp->getIntProperty("turnorder"));
2250 pOut->ioWrite(pTmp->oldXMLUpdate(pOut, true));
2251 }
2252 }
2253
2254 void Game::sendCardList(Player *pOut)
2255 {
2256 for(std::vector<Player *>::iterator it = m_players.begin() ; it != m_players.end() && (*it) ; ++it) {
2257 (*it)->sendCardList(pOut);
2258 }
2259 }
2260
2261 void Game::sendFullUpdate(Player *p)
2262 {
2263 if (m_status == Config) {
2264 sendConfiguration(p);
2265 return;
2266 }
2267
2268 p->ioWrite("<monopd>");
2269 sendPlayerList(p);
2270 sendEstateGroupList(p);
2271 sendEstateList(p);
2272 sendCardList(p);
2273 p->ioWrite("</monopd>\n");
2274 }
2275
2276 void Game::sendConfiguration(Player *p)
2277 {
2278 p->ioWrite("<monopd>");
2279 for(std::vector<GameObject *>::iterator it = m_configOptions.begin(); it != m_configOptions.end() && (*it) ; ++it)
2280 p->ioWrite( (*it)->oldXMLUpdate(p, true) );
2281 p->ioWrite("</monopd>\n");
2282 }
2283
2284 bool Game::sendChildXMLUpdate(Player *pOutput, bool updateEmpty)
2285 {
2286 // Send updates about all config options
2287 GameObject *configOption = 0;
2288 for(std::vector<GameObject *>::iterator it = m_configOptions.begin() ; it != m_configOptions.end() && (configOption = *it) ; ++it)
2289 {
2290 // .. but only when changed (and in property scope)
2291 std::string updateXML = configOption->oldXMLUpdate(pOutput);
2292 if (updateXML.size())
2293 {
2294 if (updateEmpty)
2295 {
2296 pOutput->ioWrite("<monopd>");
2297 updateEmpty = false;
2298 }
2299 pOutput->ioWrite("%s", updateXML.c_str());
2300 }
2301 }
2302
2303 // Send updates *about* all estates ..
2304 Estate *eUpdate = 0;
2305 for(std::vector<Estate *>::iterator uit = m_estates.begin(); uit != m_estates.end() && (eUpdate = *uit) ; ++uit)
2306 {
2307 // .. but only when changed (and in property scope)
2308 std::string updateXML = eUpdate->oldXMLUpdate(pOutput);
2309 if (updateXML.size())
2310 {
2311 if (updateEmpty)
2312 {
2313 pOutput->ioWrite("<monopd>");
2314 updateEmpty = false;
2315 }
2316 pOutput->ioWrite("%s", updateXML.c_str());
2317 }
2318 }
2319 return updateEmpty;
2320 }
2321
2322 void Game::unsetChildProperties()
2323 {
2324 // Reset config options ..
2325 for(std::vector<GameObject *>::iterator it = m_configOptions.begin(); it != m_configOptions.end() && (*it) ; ++it)
2326 (*it)->unsetPropertiesChanged();
2327
2328 // Reset estates ..
2329 for(std::vector<Estate *>::iterator it = m_estates.begin(); it != m_estates.end() && (*it) ; ++it)
2330 (*it)->unsetPropertiesChanged();
2331 }