File: player.c

package info (click to toggle)
freeciv 2.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 212,508 kB
  • sloc: ansic: 443,831; cpp: 29,541; sh: 7,982; makefile: 7,886; python: 1,933; xml: 945
file content (1798 lines) | stat: -rw-r--r-- 61,041 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
/***********************************************************************
 Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program 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.
***********************************************************************/

#ifdef HAVE_CONFIG_H
#include <fc_config.h>
#endif

/* utility */
#include "fcintl.h"
#include "log.h"
#include "mem.h"
#include "shared.h"
#include "support.h"

/* common */
#include "ai.h"
#include "city.h"
#include "fc_interface.h"
#include "featured_text.h"
#include "game.h"
#include "government.h"
#include "idex.h"
#include "improvement.h"
#include "map.h"
#include "research.h"
#include "rgbcolor.h"
#include "tech.h"
#include "traderoutes.h"
#include "unit.h"
#include "unitlist.h"
#include "vision.h"

#include "player.h"


struct player_slot {
  struct player *player;
};

static struct {
  struct player_slot *slots;
  int used_slots; /* number of used/allocated players in the player slots */
} player_slots;

static void player_defaults(struct player *pplayer);

static void player_diplstate_new(const struct player *plr1,
                                 const struct player *plr2);
static void player_diplstate_defaults(const struct player *plr1,
                                      const struct player *plr2);
static void player_diplstate_destroy(const struct player *plr1,
                                     const struct player *plr2);

/***************************************************************
  Return the diplomatic state that cancelling a pact will
  end up in.
***************************************************************/
enum diplstate_type cancel_pact_result(enum diplstate_type oldstate)
{
  switch(oldstate) {
  case DS_NO_CONTACT: /* possible if someone declares war on our ally */
  case DS_WAR: /* no change */
  case DS_ARMISTICE:
  case DS_CEASEFIRE:
  case DS_PEACE:
    return DS_WAR;
  case DS_ALLIANCE:
    return DS_ARMISTICE;
  case DS_TEAM: /* no change */
    return DS_TEAM;
  default:
    log_error("non-pact diplstate %d in cancel_pact_result", oldstate);
    return DS_WAR; /* arbitrary */
  }
}

/***************************************************************
  The senate may not allow you to break the treaty.  In this 
  case you must first dissolve the senate then you can break 
  it.  This is waived if you have statue of liberty since you 
  could easily just dissolve and then recreate it. 
***************************************************************/
enum dipl_reason pplayer_can_cancel_treaty(const struct player *p1, 
                                           const struct player *p2)
{
  enum diplstate_type ds = player_diplstate_get(p1, p2)->type;

  if (p1 == p2 || ds == DS_WAR || ds == DS_NO_CONTACT) {
    return DIPL_ERROR;
  }
  if (players_on_same_team(p1, p2)) {
    return DIPL_ERROR;
  }
  if (!p1->is_alive || !p2->is_alive) {
    return DIPL_ERROR;
  }
  if (player_diplstate_get(p1, p2)->has_reason_to_cancel == 0
      && get_player_bonus(p1, EFT_HAS_SENATE) > 0
      && get_player_bonus(p1, EFT_NO_ANARCHY) <= 0) {
    return DIPL_SENATE_BLOCKING;
  }
  return DIPL_OK;
}

/***************************************************************
  Returns true iff p1 can be in alliance with p2.

  Check that we are not at war with any of p2's allies. Note 
  that for an alliance to be made, we need to check this both 
  ways.

  The reason for this is to avoid the dread 'love-love-hate' 
  triad, in which p1 is allied to p2 is allied to p3 is at
  war with p1. These lead to strange situations.
***************************************************************/
static bool is_valid_alliance(const struct player *p1, 
                              const struct player *p2)
{
  players_iterate_alive(pplayer) {
    enum diplstate_type ds = player_diplstate_get(p1, pplayer)->type;

    if (pplayer != p1
        && pplayer != p2
        && ds == DS_WAR /* do not count 'never met' as war here */
        && pplayers_allied(p2, pplayer)) {
      return FALSE;
    }
  } players_iterate_alive_end;

  return TRUE;
}

/***************************************************************
  Returns true iff p1 can make given treaty with p2.

  We cannot regress in a treaty chain. So we cannot suggest
  'Peace' if we are in 'Alliance'. Then you have to cancel.

  For alliance there is only one condition: We are not at war 
  with any of p2's allies.
***************************************************************/
enum dipl_reason pplayer_can_make_treaty(const struct player *p1,
                                         const struct player *p2,
                                         enum diplstate_type treaty)
{
  enum diplstate_type existing = player_diplstate_get(p1, p2)->type;

  if (players_on_same_team(p1, p2)) {
    /* This includes the case p1 == p2 */
    return DIPL_ERROR;
  }
  if (get_player_bonus(p1, EFT_NO_DIPLOMACY) > 0
      || get_player_bonus(p2, EFT_NO_DIPLOMACY) > 0) {
    return DIPL_ERROR;
  }
  if (treaty == DS_WAR 
      || treaty == DS_NO_CONTACT 
      || treaty == DS_ARMISTICE 
      || treaty == DS_TEAM
      || treaty == DS_LAST) {
    return DIPL_ERROR; /* these are not negotiable treaties */
  }
  if (treaty == DS_CEASEFIRE && existing != DS_WAR) {
    return DIPL_ERROR; /* only available from war */
  }
  if (treaty == DS_PEACE 
      && (existing != DS_WAR && existing != DS_CEASEFIRE)) {
    return DIPL_ERROR;
  }
  if (treaty == DS_ALLIANCE) {
    if (!is_valid_alliance(p1, p2)) {
      /* Our war with a third party prevents entry to alliance. */
      return DIPL_ALLIANCE_PROBLEM_US;
    } else if (!is_valid_alliance(p2, p1)) {
      /* Their war with a third party prevents entry to alliance. */
      return DIPL_ALLIANCE_PROBLEM_THEM;
    }
  }
  /* this check must be last: */
  if (treaty == existing) {
    return DIPL_ERROR;
  }
  return DIPL_OK;
}

/***************************************************************
  Check if pplayer has an embassy with pplayer2.  We always have
  an embassy with ourselves.
***************************************************************/
bool player_has_embassy(const struct player *pplayer,
                        const struct player *pplayer2)
{
  return (pplayer == pplayer2
          || player_has_real_embassy(pplayer, pplayer2)
          || player_has_embassy_from_effect(pplayer, pplayer2));
}

/***************************************************************
  Returns whether pplayer has a real embassy with pplayer2,
  established from a diplomat, or through diplomatic meeting.
***************************************************************/
bool player_has_real_embassy(const struct player *pplayer,
                             const struct player *pplayer2)
{
  return BV_ISSET(pplayer->real_embassy, player_index(pplayer2));
}

/***************************************************************
  Returns whether pplayer has got embassy with pplayer2 thanks
  to an effect (e.g. Macro Polo Embassy).
***************************************************************/
bool player_has_embassy_from_effect(const struct player *pplayer,
                                    const struct player *pplayer2)
{
  return (get_player_bonus(pplayer, EFT_HAVE_EMBASSIES) > 0
          && !is_barbarian(pplayer2));
}

/****************************************************************************
  Return TRUE iff the given player owns the city.
****************************************************************************/
bool player_owns_city(const struct player *pplayer, const struct city *pcity)
{
  return (pcity && pplayer && city_owner(pcity) == pplayer);
}

/****************************************************************************
  Return TRUE iff the player can invade a particular tile (linked with
  borders and diplomatic states).
****************************************************************************/
bool player_can_invade_tile(const struct player *pplayer,
                            const struct tile *ptile)
{
  const struct player *ptile_owner = tile_owner(ptile);

  return (!ptile_owner
          || ptile_owner == pplayer
          || !players_non_invade(pplayer, ptile_owner));
}

/****************************************************************************
  Allocate new diplstate structure for tracking state between given two
  players.
****************************************************************************/
static void player_diplstate_new(const struct player *plr1,
                                 const struct player *plr2)
{
  struct player_diplstate *diplstate;

  fc_assert_ret(plr1 != NULL);
  fc_assert_ret(plr2 != NULL);

  const struct player_diplstate **diplstate_slot
    = plr1->diplstates + player_index(plr2);

  fc_assert_ret(*diplstate_slot == NULL);

  diplstate = fc_calloc(1, sizeof(*diplstate));
  *diplstate_slot = diplstate;
}

/****************************************************************************
  Set diplstate between given two players to default values.
****************************************************************************/
static void player_diplstate_defaults(const struct player *plr1,
                                      const struct player *plr2)
{
  struct player_diplstate *diplstate = player_diplstate_get(plr1, plr2);

  fc_assert_ret(diplstate != NULL);

  diplstate->type                 = DS_NO_CONTACT;
  diplstate->max_state            = DS_NO_CONTACT;
  diplstate->first_contact_turn   = 0;
  diplstate->turns_left           = 0;
  diplstate->has_reason_to_cancel = 0;
  diplstate->contact_turns_left   = 0;
  diplstate->auto_cancel_turn     = -1;
}


/***************************************************************
  Returns diplomatic state type between two players
***************************************************************/
struct player_diplstate *player_diplstate_get(const struct player *plr1,
                                              const struct player *plr2)
{
  fc_assert_ret_val(plr1 != NULL, NULL);
  fc_assert_ret_val(plr2 != NULL, NULL);

  const struct player_diplstate **diplstate_slot
    = plr1->diplstates + player_index(plr2);

  fc_assert_ret_val(*diplstate_slot != NULL, NULL);

  return (struct player_diplstate *) *diplstate_slot;
}

/****************************************************************************
  Free resources used by diplstate between given two players.
****************************************************************************/
static void player_diplstate_destroy(const struct player *plr1,
                                     const struct player *plr2)
{
  fc_assert_ret(plr1 != NULL);
  fc_assert_ret(plr2 != NULL);

  const struct player_diplstate **diplstate_slot
    = plr1->diplstates + player_index(plr2);

  if (*diplstate_slot != NULL) {
    free(player_diplstate_get(plr1, plr2));
  }

  *diplstate_slot = NULL;
}

/***************************************************************
  Initialise all player slots (= pointer to player pointers).
***************************************************************/
void player_slots_init(void)
{
  int i;

  /* Init player slots. */
  player_slots.slots = fc_calloc(player_slot_count(),
                                 sizeof(*player_slots.slots));
  /* Can't use the defined functions as the needed data will be
   * defined here. */
  for (i = 0; i < player_slot_count(); i++) {
    player_slots.slots[i].player = NULL;
  }
  player_slots.used_slots = 0;
}

/***************************************************************
  Return whether player slots are already initialized.
***************************************************************/
bool player_slots_initialised(void)
{
  return (player_slots.slots != NULL);
}

/***************************************************************
  Remove all player slots.
***************************************************************/
void player_slots_free(void)
{
  players_iterate(pplayer) {
    player_destroy(pplayer);
  } players_iterate_end;
  free(player_slots.slots);
  player_slots.slots = NULL;
  player_slots.used_slots = 0;
}

/****************************************************************************
  Returns the first player slot.
****************************************************************************/
struct player_slot *player_slot_first(void)
{
  return player_slots.slots;
}

/****************************************************************************
  Returns the next slot.
****************************************************************************/
struct player_slot *player_slot_next(struct player_slot *pslot)
{
  pslot++;
  return (pslot < player_slots.slots + player_slot_count() ? pslot : NULL);
}

/***************************************************************
  Returns the total number of player slots, i.e. the maximum
  number of players (including barbarians, etc.) that could ever
  exist at once.
***************************************************************/
int player_slot_count(void)
{
  return (MAX_NUM_PLAYER_SLOTS);
}

/****************************************************************************
  Returns the index of the player slot.
****************************************************************************/
int player_slot_index(const struct player_slot *pslot)
{
  fc_assert_ret_val(NULL != pslot, -1);

  return pslot - player_slots.slots;
}

/****************************************************************************
  Returns the team corresponding to the slot. If the slot is not used, it
  will return NULL. See also player_slot_is_used().
****************************************************************************/
struct player *player_slot_get_player(const struct player_slot *pslot)
{
  fc_assert_ret_val(NULL != pslot, NULL);

  return pslot->player;
}

/****************************************************************************
  Returns TRUE is this slot is "used" i.e. corresponds to a valid,
  initialized player that exists in the game.
****************************************************************************/
bool player_slot_is_used(const struct player_slot *pslot)
{
  fc_assert_ret_val(NULL != pslot, FALSE);

  /* No player slot available, if the game is not initialised. */
  if (!player_slots_initialised()) {
    return FALSE;
  }

  return NULL != pslot->player;
}

/****************************************************************************
  Return the possibly unused and uninitialized player slot.
****************************************************************************/
struct player_slot *player_slot_by_number(int player_id)
{
  if (!player_slots_initialised()
      || !(0 <= player_id && player_id < player_slot_count())) {
    return NULL;
  }

  return player_slots.slots + player_id;
}

/****************************************************************************
  Return the highest used player slot index.
****************************************************************************/
int player_slot_max_used_number(void)
{
  int max_pslot = 0;

  player_slots_iterate(pslot) {
    if (player_slot_is_used(pslot)) {
      max_pslot = player_slot_index(pslot);
    }
  } player_slots_iterate_end;

  return max_pslot;
}

/****************************************************************************
  Creates a new player for the slot. If slot is NULL, it will lookup to a
  free slot. If the slot already used, then just return the player.
****************************************************************************/
struct player *player_new(struct player_slot *pslot)
{
  struct player *pplayer;

  fc_assert_ret_val(player_slots_initialised(), NULL);

  if (NULL == pslot) {
    player_slots_iterate(aslot) {
      if (!player_slot_is_used(aslot)) {
        pslot = aslot;
        break;
      }
    } player_slots_iterate_end;

    fc_assert_ret_val(NULL != pslot, NULL);
  } else if (NULL != pslot->player) {
    return pslot->player;
  }

  /* Now create the player. */
  log_debug("Create player for slot %d.", player_slot_index(pslot));
  pplayer = fc_calloc(1, sizeof(*pplayer));
  pplayer->slot = pslot;
  pslot->player = pplayer;

  pplayer->diplstates = fc_calloc(player_slot_count(),
                                  sizeof(*pplayer->diplstates));
  player_slots_iterate(dslot) {
    const struct player_diplstate **diplstate_slot
      = pplayer->diplstates + player_slot_index(dslot);

    *diplstate_slot = NULL;
  } player_slots_iterate_end;

  players_iterate(aplayer) {
    /* Create diplomatic states for all other players. */
    player_diplstate_new(pplayer, aplayer);
    /* Create diplomatic state of this player. */
    if (aplayer != pplayer) {
      player_diplstate_new(aplayer, pplayer);
    }
  } players_iterate_end;

  /* Set default values. */
  player_defaults(pplayer);

  /* Increase number of players. */
  player_slots.used_slots++;

  return pplayer;
}

/****************************************************************************
  Set player structure to its default values.
  No initialisation to ruleset-dependent values should be done here.
****************************************************************************/
static void player_defaults(struct player *pplayer)
{
  int i;

  sz_strlcpy(pplayer->name, ANON_PLAYER_NAME);
  sz_strlcpy(pplayer->username, _(ANON_USER_NAME));
  pplayer->unassigned_user = TRUE;
  sz_strlcpy(pplayer->ranked_username, _(ANON_USER_NAME));
  pplayer->unassigned_ranked = TRUE;
  pplayer->user_turns = 0;
  pplayer->is_male = TRUE;
  pplayer->government = NULL;
  pplayer->target_government = NULL;
  pplayer->nation = NO_NATION_SELECTED;
  pplayer->team = NULL;
  pplayer->is_ready = FALSE;
  pplayer->nturns_idle = 0;
  pplayer->is_alive = TRUE;
  pplayer->turns_alive = 0;
  pplayer->is_winner = FALSE;
  pplayer->last_war_action = -1;
  pplayer->phase_done = FALSE;

  pplayer->revolution_finishes = -1;

  BV_CLR_ALL(pplayer->real_embassy);
  players_iterate(aplayer) {
    /* create diplomatic states for all other players */
    player_diplstate_defaults(pplayer, aplayer);
    /* create diplomatic state of this player */
    if (aplayer != pplayer) {
      player_diplstate_defaults(aplayer, pplayer);
    }
  } players_iterate_end;

  pplayer->style      = 0;
  pplayer->music_style = -1;          /* even getting value 0 triggers change */
  pplayer->cities = city_list_new();
  pplayer->units = unit_list_new();

  pplayer->economic.gold    = 0;
  pplayer->economic.tax     = PLAYER_DEFAULT_TAX_RATE;
  pplayer->economic.science = PLAYER_DEFAULT_SCIENCE_RATE;
  pplayer->economic.luxury  = PLAYER_DEFAULT_LUXURY_RATE;

  spaceship_init(&pplayer->spaceship);

  pplayer->ai_controlled = FALSE;
  pplayer->ai_common.skill_level = ai_level_invalid();
  pplayer->ai_common.fuzzy = 0;
  pplayer->ai_common.expand = 100;
  pplayer->ai_common.barbarian_type = NOT_A_BARBARIAN;
  player_slots_iterate(pslot) {
    pplayer->ai_common.love[player_slot_index(pslot)] = 1;
  } player_slots_iterate_end;
  pplayer->ai_common.traits = NULL;

  pplayer->ai = NULL;
  pplayer->was_created = FALSE;
  pplayer->savegame_ai_type_name = NULL;
  pplayer->random_name = TRUE;
  pplayer->is_connected = FALSE;
  pplayer->current_conn = NULL;
  pplayer->connections = conn_list_new();
  BV_CLR_ALL(pplayer->gives_shared_vision);
  for (i = 0; i < B_LAST; i++) {
    pplayer->wonders[i] = WONDER_NOT_BUILT;
  }

  pplayer->attribute_block.data = NULL;
  pplayer->attribute_block.length = 0;
  pplayer->attribute_block_buffer.data = NULL;
  pplayer->attribute_block_buffer.length = 0;

  pplayer->tile_known.vec = NULL;
  pplayer->tile_known.bits = 0;

  pplayer->rgb = NULL;

  memset(pplayer->multipliers, 0, sizeof(pplayer->multipliers));
  memset(pplayer->multipliers_target, 0, sizeof(pplayer->multipliers_target));

  /* pplayer->server is initialised in
      ./server/plrhand.c:server_player_init()
     and pplayer->client in
      ./client/climisc.c:client_player_init() */
}

/****************************************************************************
  Set the player's color.
  May be NULL in pregame.
****************************************************************************/
void player_set_color(struct player *pplayer,
                      const struct rgbcolor *prgbcolor)
{
  if (pplayer->rgb != NULL) {
    rgbcolor_destroy(pplayer->rgb);
    pplayer->rgb = NULL;
  }

  if (prgbcolor) {
    pplayer->rgb = rgbcolor_copy(prgbcolor);
  }
}

/****************************************************************************
  Clear all player data. If full is set, then the nation and the team will
  be cleared too.
****************************************************************************/
void player_clear(struct player *pplayer, bool full)
{
  bool client = !is_server();

  if (pplayer == NULL) {
    return;
  }

  if (pplayer->savegame_ai_type_name != NULL) {
    free(pplayer->savegame_ai_type_name);
    pplayer->savegame_ai_type_name = NULL;
  }

  /* Clears the attribute blocks. */
  if (pplayer->attribute_block.data) {
    free(pplayer->attribute_block.data);
    pplayer->attribute_block.data = NULL;
  }
  pplayer->attribute_block.length = 0;

  if (pplayer->attribute_block_buffer.data) {
    free(pplayer->attribute_block_buffer.data);
    pplayer->attribute_block_buffer.data = NULL;
  }
  pplayer->attribute_block_buffer.length = 0;

  /* Clears units and cities. */
  unit_list_iterate(pplayer->units, punit) {
    /* Unload all cargos. */
    unit_list_iterate(unit_transport_cargo(punit), pcargo) {
      unit_transport_unload(pcargo);
      if (client) {
        pcargo->client.transported_by = -1;
      }
    } unit_list_iterate_end;
    /* Unload the unit. */
    unit_transport_unload(punit);
    if (client) {
      punit->client.transported_by = -1;
    }

    game_remove_unit(punit);
  } unit_list_iterate_end;

  city_list_iterate(pplayer->cities, pcity) {
    game_remove_city(pcity);
  } city_list_iterate_end;

  if (full) {
    team_remove_player(pplayer);

    /* This comes last because log calls in the above functions
     * may use it. */
    if (pplayer->nation != NULL) {
      player_set_nation(pplayer, NULL);
    }
  }
}

/****************************************************************************
  Clear the ruleset dependent pointers of the player structure. Called by
  game_ruleset_free().
****************************************************************************/
void player_ruleset_close(struct player *pplayer)
{
  pplayer->government = NULL;
  pplayer->target_government = NULL;
  player_set_nation(pplayer, NULL);
  pplayer->style = NULL;
}

/****************************************************************************
  Destroys and remove a player from the game.
****************************************************************************/
void player_destroy(struct player *pplayer)
{
  struct player_slot *pslot;

  fc_assert_ret(NULL != pplayer);

  pslot = pplayer->slot;
  fc_assert(pslot->player == pplayer);

  /* Remove all that is game-dependent in the player structure. */
  player_clear(pplayer, TRUE);

  fc_assert(0 == unit_list_size(pplayer->units));
  unit_list_destroy(pplayer->units);
  fc_assert(0 == city_list_size(pplayer->cities));
  city_list_destroy(pplayer->cities);

  fc_assert(conn_list_size(pplayer->connections) == 0);
  conn_list_destroy(pplayer->connections);

  players_iterate(aplayer) {
    /* destroy the diplomatics states of this player with others ... */
    player_diplstate_destroy(pplayer, aplayer);
    /* and of others with this player. */
    if (aplayer != pplayer) {
      player_diplstate_destroy(aplayer, pplayer);
    }
  } players_iterate_end;
  free(pplayer->diplstates);

  /* Clear player color. */
  if (pplayer->rgb) {
    rgbcolor_destroy(pplayer->rgb);
  }

  dbv_free(&pplayer->tile_known);

  if (!is_server()) {
    vision_layer_iterate(v) {
      dbv_free(&pplayer->client.tile_vision[v]);
    } vision_layer_iterate_end;
  }

  free(pplayer);
  pslot->player = NULL;
  player_slots.used_slots--;
}

/**************************************************************************
  Return the number of players.
**************************************************************************/
int player_count(void)
{
  return player_slots.used_slots;
}

/**************************************************************************
  Return the player index.

  Currently same as player_number(), but indicates use as an array index.
  The array must be sized by player_slot_count() or MAX_NUM_PLAYER_SLOTS
  (player_count() *cannot* be used) and is likely to be sparse.
**************************************************************************/
int player_index(const struct player *pplayer)
{
  return player_number(pplayer);
}

/**************************************************************************
  Return the player index/number/id.
**************************************************************************/
int player_number(const struct player *pplayer)
{
  fc_assert_ret_val(NULL != pplayer, -1);
  return player_slot_index(pplayer->slot);
}

/**************************************************************************
  Return struct player pointer for the given player index.

  You can retrieve players that are not in the game (with IDs larger than
  player_count).  An out-of-range player request will return NULL.
**************************************************************************/
struct player *player_by_number(const int player_id)
{
  struct player_slot *pslot = player_slot_by_number(player_id);

  return (NULL != pslot ? player_slot_get_player(pslot) : NULL);
}

/****************************************************************************
  Set the player's nation to the given nation (may be NULL).  Returns TRUE
  iff there was a change.
  Doesn't check if the nation is legal wrt nationset.
****************************************************************************/
bool player_set_nation(struct player *pplayer, struct nation_type *pnation)
{
  if (pplayer->nation != pnation) {
    if (pplayer->nation) {
      fc_assert(pplayer->nation->player == pplayer);
      pplayer->nation->player = NULL;
    }
    if (pnation) {
      fc_assert(pnation->player == NULL);
      pnation->player = pplayer;
    }
    pplayer->nation = pnation;
    return TRUE;
  }
  return FALSE;
}

/***************************************************************
  Find player by given name.
***************************************************************/
struct player *player_by_name(const char *name)
{
  players_iterate(pplayer) {
    if (fc_strcasecmp(name, pplayer->name) == 0) {
      return pplayer;
    }
  } players_iterate_end;

  return NULL;
}

/**************************************************************************
  Return the leader name of the player.
**************************************************************************/
const char *player_name(const struct player *pplayer)
{
  if (!pplayer) {
    return NULL;
  }
  return pplayer->name;
}

/***************************************************************
  Find player by name, allowing unambigous prefix (ie abbreviation).
  Returns NULL if could not match, or if ambiguous or other
  problem, and fills *result with characterisation of match/non-match
  (see shared.[ch])
***************************************************************/
static const char *player_name_by_number(int i)
{
  struct player *pplayer;

  pplayer = player_by_number(i);
  return player_name(pplayer);
}

/***************************************************************
Find player by its name prefix
***************************************************************/
struct player *player_by_name_prefix(const char *name,
                                     enum m_pre_result *result)
{
  int ind;

  *result = match_prefix(player_name_by_number,
                         player_slot_count(), MAX_LEN_NAME - 1,
                         fc_strncasequotecmp, effectivestrlenquote,
                         name, &ind);

  if (*result < M_PRE_AMBIGUOUS) {
    return player_by_number(ind);
  } else {
    return NULL;
  }
}

/***************************************************************
 Find player by its user name (not player/leader name)
***************************************************************/
struct player *player_by_user(const char *name)
{
  players_iterate(pplayer) {
    if (fc_strcasecmp(name, pplayer->username) == 0) {
      return pplayer;
    }
  } players_iterate_end;

  return NULL;
}

/*************************************************************************
  "Age" of the player: number of turns spent alive since created.
**************************************************************************/
int player_age(const struct player *pplayer)
{
  fc_assert_ret_val(pplayer != NULL, 0);
  return pplayer->turns_alive;
}

/*************************************************************************
  Check if pplayer could see all units on ptile if it had units.

  See can_player_see_unit_at() for rules about when an unit is visible.
**************************************************************************/
bool can_player_see_hypotetic_units_at(const struct player *pplayer,
                                       const struct tile *ptile)
{
  struct city *pcity;

  /* Can't see invisible units. */
  if (!fc_funcs->player_tile_vision_get(ptile, pplayer, V_INVIS)) {
    return FALSE;
  }

  /* Can't see city units. */
  pcity = tile_city(ptile);
  if (pcity && !can_player_see_units_in_city(pplayer, pcity)
      && unit_list_size(ptile->units) > 0) {
    return FALSE;
  }

  /* Can't see non allied units in transports. */
  unit_list_iterate(ptile->units, punit) {
    if (unit_type_get(punit)->transport_capacity > 0
        && unit_owner(punit) != pplayer) {

      /* An ally could transport a non ally */
      if (unit_list_size(punit->transporting) > 0) {
        return FALSE;
      }
    }
  } unit_list_iterate_end;

  return TRUE;
}

/****************************************************************************
  Checks if a unit can be seen by pplayer at (x,y).
  A player can see a unit if he:
  (a) can see the tile AND
  (b) can see the unit at the tile (i.e. unit not invisible at this tile) AND
  (c) the unit is outside a city OR in an allied city AND
  (d) the unit isn't in a transporter, or we are allied AND
  (e) the unit isn't in a transporter, or we can see the transporter
****************************************************************************/
bool can_player_see_unit_at(const struct player *pplayer,
			    const struct unit *punit,
                            const struct tile *ptile,
                            bool is_transported)
{
  struct city *pcity;

  /* If the player can't even see the tile... */
  if (TILE_KNOWN_SEEN != tile_get_known(ptile, pplayer)) {
    return FALSE;
  }

  /* Don't show non-allied units that are in transports.  This is logical
   * because allied transports can also contain our units.  Shared vision
   * isn't taken into account. */
  if (is_transported && unit_owner(punit) != pplayer
      && !pplayers_allied(pplayer, unit_owner(punit))) {
    return FALSE;
  }

  /* Units in cities may be hidden. */
  pcity = tile_city(ptile);
  if (pcity && !can_player_see_units_in_city(pplayer, pcity)) {
    return FALSE;
  }

  /* Allied or non-hiding units are always seen. */
  if (pplayers_allied(unit_owner(punit), pplayer)
      || !is_hiding_unit(punit)) {
    return TRUE;
  }

  /* Hiding units are only seen by the V_INVIS fog layer. */
  return fc_funcs->player_tile_vision_get(ptile, pplayer, V_INVIS);

  return FALSE;
}


/****************************************************************************
  Checks if a unit can be seen by pplayer at its current location.

  See can_player_see_unit_at.
****************************************************************************/
bool can_player_see_unit(const struct player *pplayer,
			 const struct unit *punit)
{
  return can_player_see_unit_at(pplayer, punit, unit_tile(punit),
                                unit_transported(punit));
}

/****************************************************************************
  Return TRUE iff the player can see units in the city.  Either they
  can see all units or none.

  If the player can see units in the city, then the server sends the
  unit info for units in the city to the client.  The client uses the
  tile's unitlist to determine whether to show the city occupied flag.  Of
  course the units will be visible to the player as well, if he clicks on
  them.

  If the player can't see units in the city, then the server doesn't send
  the unit info for these units.  The client therefore uses the "occupied"
  flag sent in the short city packet to determine whether to show the city
  occupied flag.

  Note that can_player_see_city_internals => can_player_see_units_in_city.
  Otherwise the player would not know anything about the city's units at
  all, since the full city packet has no "occupied" flag.

  Returns TRUE if given a NULL player.  This is used by the client when in
  observer mode.
****************************************************************************/
bool can_player_see_units_in_city(const struct player *pplayer,
				  const struct city *pcity)
{
  return (!pplayer
	  || can_player_see_city_internals(pplayer, pcity)
	  || pplayers_allied(pplayer, city_owner(pcity)));
}

/****************************************************************************
  Return TRUE iff the player can see the city's internals.  This means the
  full city packet is sent to the client, who should then be able to popup
  a dialog for it.

  Returns TRUE if given a NULL player.  This is used by the client when in
  observer mode.
****************************************************************************/
bool can_player_see_city_internals(const struct player *pplayer,
				   const struct city *pcity)
{
  return (!pplayer || pplayer == city_owner(pcity));
}

/**************************************************************************
  Returns TRUE iff pow_player can see externally visible features of
  target_city.

  A city's external features are visible to its owner, to players that
  currently sees the tile it is located at and to players that has it as
  a trade partner.
**************************************************************************/
bool player_can_see_city_externals(const struct player *pow_player,
                                   const struct city *target_city) {
  fc_assert_ret_val(target_city, FALSE);
  fc_assert_ret_val(pow_player, FALSE);

  if (can_player_see_city_internals(pow_player, target_city)) {
    /* City internals includes city externals. */
    return TRUE;
  }

  if (tile_is_seen(city_tile(target_city), pow_player)) {
    /* The tile is being observed. */
    return TRUE;
  }

  trade_routes_iterate(target_city, trade_city) {
    if (city_owner(trade_city) == pow_player) {
      /* Revealed because of the trade route. */
      return TRUE;
    }
  } trade_routes_iterate_end;

  return FALSE;
}

/***************************************************************
 If the specified player owns the city with the specified id,
 return pointer to the city struct.  Else return NULL.
 Now always uses fast idex_lookup_city.

 pplayer may be NULL in which case all cities registered to
 hash are considered - even those not currently owned by any
 player. Callers expect this behavior.
***************************************************************/
struct city *player_city_by_number(const struct player *pplayer, int city_id)
{
  /* We call idex directly. Should use game_city_by_number() instead? */
  struct city *pcity = idex_lookup_city(city_id);

  if (!pcity) {
    return NULL;
  }

  if (!pplayer || (city_owner(pcity) == pplayer)) {
    /* Correct owner */
    return pcity;
  }

  return NULL;
}

/***************************************************************
 If the specified player owns the unit with the specified id,
 return pointer to the unit struct.  Else return NULL.
 Uses fast idex_lookup_city.

 pplayer may be NULL in which case all units registered to
 hash are considered - even those not currently owned by any
 player. Callers expect this behavior.
***************************************************************/
struct unit *player_unit_by_number(const struct player *pplayer, int unit_id)
{
  /* We call idex directly. Should use game_unit_by_number() instead? */
  struct unit *punit = idex_lookup_unit(unit_id);

  if (!punit) {
    return NULL;
  }

  if (!pplayer || (unit_owner(punit) == pplayer)) {
    /* Correct owner */
    return punit;
  }

  return NULL;
}

/*************************************************************************
  Return true iff x,y is inside any of the player's city map.
**************************************************************************/
bool player_in_city_map(const struct player *pplayer,
                        const struct tile *ptile)
{
  city_tile_iterate(CITY_MAP_MAX_RADIUS_SQ, ptile, ptile1) {
    struct city *pcity = tile_city(ptile1);

    if (pcity
        && (pplayer == NULL || city_owner(pcity) == pplayer)
        && city_map_radius_sq_get(pcity) >= sq_map_distance(ptile,
                                                            ptile1)) {
      return TRUE;
    }
  } city_tile_iterate_end;

  return FALSE;
}

/**************************************************************************
 Returns the number of techs the player has researched which has this
 flag. Needs to be optimized later (e.g. int tech_flags[TF_COUNT] in
 struct player)
**************************************************************************/
int num_known_tech_with_flag(const struct player *pplayer,
                             enum tech_flag_id flag)
{
  return research_get(pplayer)->num_known_tech_with_flag[flag];
}

/**************************************************************************
  Return the expected net income of the player this turn.  This includes
  tax revenue and upkeep, but not one-time purchases or found gold.

  This function depends on pcity->prod[O_GOLD] being set for all cities, so
  make sure the player's cities have been refreshed.
**************************************************************************/
int player_get_expected_income(const struct player *pplayer)
{
  int income = 0;

  /* City income/expenses. */
  city_list_iterate(pplayer->cities, pcity) {
    /* Gold suplus accounts for imcome plus building and unit upkeep. */
    income += pcity->surplus[O_GOLD];

    /* Gold upkeep for buildings and units is defined by the setting
     * 'game.info.gold_upkeep_style':
     * GOLD_UPKEEP_CITY: Cities pay for buildings and units (this is
     *                   included in pcity->surplus[O_GOLD]).
     * GOLD_UPKEEP_MIXED: Cities pay only for buildings; the nation pays
     *                    for units.
     * GOLD_UPKEEP_NATION: The nation pays for buildings and units. */
    switch (game.info.gold_upkeep_style) {
    case GOLD_UPKEEP_CITY:
      break;
    case GOLD_UPKEEP_NATION:
      /* Nation pays for buildings (and units). */
      income -= city_total_impr_gold_upkeep(pcity);
      fc__fallthrough; /* No break. */
    case GOLD_UPKEEP_MIXED:
      /* Nation pays for units. */
      income -= city_total_unit_gold_upkeep(pcity);
      break;
    }

    /* Capitalization income. */
    if (city_production_has_flag(pcity, IF_GOLD)) {
      income += pcity->shield_stock + pcity->surplus[O_SHIELD];
    }
  } city_list_iterate_end;

  return income;
}

/**************************************************************************
 Returns TRUE iff the player knows at least one tech which has the
 given flag.
**************************************************************************/
bool player_knows_techs_with_flag(const struct player *pplayer,
				  enum tech_flag_id flag)
{
  return num_known_tech_with_flag(pplayer, flag) > 0;
}

/**************************************************************************
  Locate the player capital city, (NULL Otherwise) 
**************************************************************************/
struct city *player_capital(const struct player *pplayer)
{
  if (!pplayer) {
    /* The client depends on this behavior in some places. */
    return NULL;
  }
  city_list_iterate(pplayer->cities, pcity) {
    if (is_capital(pcity)) {
      return pcity;
    }
  } city_list_iterate_end;
  return NULL;
}

/**************************************************************************
  Return a text describing an AI's love for you.  (Oooh, kinky!!)
**************************************************************************/
const char *love_text(const int love)
{
  if (love <= - MAX_AI_LOVE * 90 / 100) {
    /* TRANS: These words should be adjectives which can fit in the sentence
       "The x are y towards us"
       "The Babylonians are respectful towards us" */
    return Q_("?attitude:Genocidal");
  } else if (love <= - MAX_AI_LOVE * 70 / 100) {
    return Q_("?attitude:Belligerent");
  } else if (love <= - MAX_AI_LOVE * 50 / 100) {
    return Q_("?attitude:Hostile");
  } else if (love <= - MAX_AI_LOVE * 25 / 100) {
    return Q_("?attitude:Uncooperative");
  } else if (love <= - MAX_AI_LOVE * 10 / 100) {
    return Q_("?attitude:Uneasy");
  } else if (love <= MAX_AI_LOVE * 10 / 100) {
    return Q_("?attitude:Neutral");
  } else if (love <= MAX_AI_LOVE * 25 / 100) {
    return Q_("?attitude:Respectful");
  } else if (love <= MAX_AI_LOVE * 50 / 100) {
    return Q_("?attitude:Helpful");
  } else if (love <= MAX_AI_LOVE * 70 / 100) {
    return Q_("?attitude:Enthusiastic");
  } else if (love <= MAX_AI_LOVE * 90 / 100) {
    return Q_("?attitude:Admiring");
  } else {
    fc_assert(love > MAX_AI_LOVE * 90 / 100);
    return Q_("?attitude:Worshipful");
  }
}

/***************************************************************
  Returns true iff players can attack each other.
***************************************************************/
bool pplayers_at_war(const struct player *pplayer,
                     const struct player *pplayer2)
{
  enum diplstate_type ds;

  if (pplayer == pplayer2) {
    return FALSE;
  }

  ds = player_diplstate_get(pplayer, pplayer2)->type;

  return ds == DS_WAR || ds == DS_NO_CONTACT;
}

/***************************************************************
  Returns true iff players are allied.
***************************************************************/
bool pplayers_allied(const struct player *pplayer,
                     const struct player *pplayer2)
{
  enum diplstate_type ds;

  if (!pplayer || !pplayer2) {
    return FALSE;
  }

  if (pplayer == pplayer2) {
    return TRUE;
  }

  ds = player_diplstate_get(pplayer, pplayer2)->type;

  return (ds == DS_ALLIANCE || ds == DS_TEAM);
}

/***************************************************************
  Returns true iff players are allied or at peace.
***************************************************************/
bool pplayers_in_peace(const struct player *pplayer,
                       const struct player *pplayer2)
{
  enum diplstate_type ds = player_diplstate_get(pplayer, pplayer2)->type;

  if (pplayer == pplayer2) {
    return TRUE;
  }

  return (ds == DS_PEACE || ds == DS_ALLIANCE
          || ds == DS_ARMISTICE || ds == DS_TEAM);
}

/****************************************************************************
  Returns TRUE if players can't enter each others' territory.
****************************************************************************/
bool players_non_invade(const struct player *pplayer1,
                        const struct player *pplayer2)
{
  if (pplayer1 == pplayer2 || !pplayer1 || !pplayer2) {
    return FALSE;
  }

  /* Movement during armistice is allowed so that player can withdraw
     units deeper inside opponent territory. */

  return player_diplstate_get(pplayer1, pplayer2)->type == DS_PEACE;
}

/***************************************************************
  Returns true iff players have peace, cease-fire, or
  armistice.
***************************************************************/
bool pplayers_non_attack(const struct player *pplayer,
                         const struct player *pplayer2)
{
  enum diplstate_type ds;

  if (pplayer == pplayer2) {
    return FALSE;
  }

  ds = player_diplstate_get(pplayer, pplayer2)->type;

  return (ds == DS_PEACE || ds == DS_CEASEFIRE || ds == DS_ARMISTICE);
}

/**************************************************************************
  Return TRUE if players are in the same team
**************************************************************************/
bool players_on_same_team(const struct player *pplayer1,
                          const struct player *pplayer2)
{
  return pplayer1->team == pplayer2->team;
}

/**************************************************************************
  Return TRUE iff the player me gives shared vision to player them.
**************************************************************************/
bool gives_shared_vision(const struct player *me, const struct player *them)
{
  return BV_ISSET(me->gives_shared_vision, player_index(them));
}

/**************************************************************************
  Return TRUE iff the two diplstates are equal.
**************************************************************************/
bool are_diplstates_equal(const struct player_diplstate *pds1,
                          const struct player_diplstate *pds2)
{
  return (pds1->type == pds2->type && pds1->turns_left == pds2->turns_left
          && pds1->has_reason_to_cancel == pds2->has_reason_to_cancel
          && pds1->contact_turns_left == pds2->contact_turns_left);
}

/**************************************************************************
  Return TRUE iff player1 has the diplomatic relation to player2
**************************************************************************/
bool is_diplrel_between(const struct player *player1,
                        const struct player *player2,
                        int diplrel)
{
  fc_assert(player1 != NULL);
  fc_assert(player2 != NULL);

  /* No relationship to it self. */
  if (player1 == player2 && diplrel != DRO_FOREIGN) {
    return FALSE;
  }

  if (diplrel < DS_LAST) {
    return player_diplstate_get(player1, player2)->type == diplrel;
  }

  switch (diplrel) {
  case DRO_GIVES_SHARED_VISION:
    return gives_shared_vision(player1, player2);
  case DRO_RECEIVES_SHARED_VISION:
    return gives_shared_vision(player2, player1);
  case DRO_HOSTS_EMBASSY:
    return player_has_embassy(player2, player1);
  case DRO_HAS_EMBASSY:
    return player_has_embassy(player1, player2);
  case DRO_HOSTS_REAL_EMBASSY:
    return player_has_real_embassy(player2, player1);
  case DRO_HAS_REAL_EMBASSY:
    return player_has_real_embassy(player1, player2);
  case DRO_HAS_CASUS_BELLI:
    return 0 < player_diplstate_get(player1, player2)->has_reason_to_cancel;
  case DRO_PROVIDED_CASUS_BELLI:
    return 0 < player_diplstate_get(player2, player1)->has_reason_to_cancel;
  case DRO_FOREIGN:
    return player1 != player2;
  }

  fc_assert_msg(FALSE, "diplrel_between(): invalid diplrel number %d.",
                diplrel);

  return FALSE;
}

/**************************************************************************
  Return TRUE iff pplayer has the diplomatic relation to any living player
**************************************************************************/
bool is_diplrel_to_other(const struct player *pplayer, int diplrel)
{
  fc_assert(pplayer != NULL);

  players_iterate_alive(oplayer) {
    if (oplayer == pplayer) {
      continue;
    }
    if (is_diplrel_between(pplayer, oplayer, diplrel)) {
      return TRUE;
    }
  } players_iterate_alive_end;
  return FALSE;
}

/**************************************************************************
  Return the diplomatic relation that has the given (untranslated) rule
 name.
**************************************************************************/
int diplrel_by_rule_name(const char *value)
{
  /* Look for asymmetric diplomatic relations */
  int diplrel = diplrel_other_by_name(value, fc_strcasecmp);

  if (diplrel != diplrel_other_invalid()) {
    return diplrel;
  }

  /* Look for symmetric diplomatic relations */
  diplrel = diplstate_type_by_name(value, fc_strcasecmp);

  /*
   * Make sure DS_LAST isn't returned as DS_LAST is the first diplrel_other.
   *
   * Can't happend now. This is in case that changes in the future. */
  fc_assert_ret_val(diplrel != DS_LAST, diplrel_other_invalid());

  /*
   * Make sure that diplrel_other_invalid() is returned.
   *
   * Can't happen now. At the moment dpilrel_asym_invalid() is the same as
   * diplstate_type_invalid(). This is in case that changes in the future.
   */
  if (diplrel != diplstate_type_invalid()) {
    return diplrel;
  }

  return diplrel_other_invalid();
}

/**************************************************************************
  Return the (untranslated) rule name of the given diplomatic relation.
**************************************************************************/
const char *diplrel_rule_name(int value)
{
  if (value < DS_LAST) {
    return diplstate_type_name(value);
  } else {
    return diplrel_other_name(value);
  }
}

/**************************************************************************
  Return the translated name of the given diplomatic relation.
**************************************************************************/
const char *diplrel_name_translation(int value)
{
  if (value < DS_LAST) {
    return diplstate_type_translated_name(value);
  } else {
    return _(diplrel_other_name(value));
  }
}

/* The number of mutually exclusive requirement sets that
 * diplrel_mess_gen() creates for the DiplRel requirement type. */
#define DIPLREL_MESS_SIZE (3 + (DRO_LAST * (5 + 4 + 3 + 2 + 1)))

/**************************************************************************
  Generate and return an array of mutually exclusive requirement sets for
  the DiplRel requirement type. The array has DIPLREL_MESS_SIZE sets.

  A mutually exclusive set is a set of requirements were the presence of
  one requirement proves the absence of every other requirement. In other
  words: at most one of the requirements in the set can be present.
**************************************************************************/
static bv_diplrel_all_reqs *diplrel_mess_gen(void)
{
  /* The ranges supported by the DiplRel requiremnt type. */
  const enum req_range legal_ranges[] = {
    REQ_RANGE_LOCAL,
    REQ_RANGE_PLAYER,
    REQ_RANGE_ALLIANCE,
    REQ_RANGE_TEAM,
    REQ_RANGE_WORLD
  };

  /* Iterators. */
  int rel;
  int i;
  int j;

  /* Storage for the mutually exclusive requirement sets. */
  bv_diplrel_all_reqs *mess = fc_malloc(DIPLREL_MESS_SIZE
                                        * sizeof(bv_diplrel_all_reqs));

  /* Position in mess. */
  int mess_pos = 0;

  /* The first mutually exclusive set is about local diplstate. */
  BV_CLR_ALL(mess[mess_pos]);

  /* It is not possible to have more than one diplstate to a nation. */
  BV_SET(mess[mess_pos],
         requirement_diplrel_ereq(DS_ARMISTICE, REQ_RANGE_LOCAL, TRUE));
  BV_SET(mess[mess_pos],
         requirement_diplrel_ereq(DS_WAR, REQ_RANGE_LOCAL, TRUE));
  BV_SET(mess[mess_pos],
         requirement_diplrel_ereq(DS_CEASEFIRE, REQ_RANGE_LOCAL, TRUE));
  BV_SET(mess[mess_pos],
         requirement_diplrel_ereq(DS_PEACE, REQ_RANGE_LOCAL, TRUE));
  BV_SET(mess[mess_pos],
         requirement_diplrel_ereq(DS_ALLIANCE, REQ_RANGE_LOCAL, TRUE));
  BV_SET(mess[mess_pos],
         requirement_diplrel_ereq(DS_NO_CONTACT, REQ_RANGE_LOCAL, TRUE));
  BV_SET(mess[mess_pos],
         requirement_diplrel_ereq(DS_TEAM, REQ_RANGE_LOCAL, TRUE));

  /* It is not possible to have a diplstate to your self. */
  BV_SET(mess[mess_pos],
         requirement_diplrel_ereq(DRO_FOREIGN, REQ_RANGE_LOCAL, FALSE));

  mess_pos++;

  /* Having a real embassy excludes not having an embassy. */
  BV_CLR_ALL(mess[mess_pos]);

  BV_SET(mess[mess_pos],
         requirement_diplrel_ereq(DRO_HAS_REAL_EMBASSY, REQ_RANGE_LOCAL,
                                  TRUE));
  BV_SET(mess[mess_pos],
         requirement_diplrel_ereq(DRO_HAS_EMBASSY, REQ_RANGE_LOCAL,
                                  FALSE));

  mess_pos++;

  /* Hosting a real embassy excludes not hosting an embassy. */
  BV_CLR_ALL(mess[mess_pos]);

  BV_SET(mess[mess_pos],
         requirement_diplrel_ereq(DRO_HOSTS_REAL_EMBASSY, REQ_RANGE_LOCAL,
                                  TRUE));
  BV_SET(mess[mess_pos],
         requirement_diplrel_ereq(DRO_HOSTS_EMBASSY, REQ_RANGE_LOCAL,
                                  FALSE));

  mess_pos++;

  /* Loop over diplstate_type and diplrel_other. */
  for (rel = 0; rel < DRO_LAST; rel++) {
    /* The presence of a DiplRel at a more local range proves that it can't
     * be absent in a more global range. (The alliance range includes the
     * Team range) */
    for (i = 0; i < 5; i++) {
      for (j = i; j < 5; j++) {
        BV_CLR_ALL(mess[mess_pos]);

        BV_SET(mess[mess_pos],
               requirement_diplrel_ereq(rel, legal_ranges[i], TRUE));
        BV_SET(mess[mess_pos],
               requirement_diplrel_ereq(rel, legal_ranges[j], FALSE));

        mess_pos++;
      }
    }
  }

  /* No uninitialized element exists. */
  fc_assert(mess_pos == DIPLREL_MESS_SIZE);

  return mess;
}

/* An array of mutually exclusive requirement sets for the DiplRel
 * requirement type. Is initialized the first time diplrel_mess_get() is
 * called. */
static bv_diplrel_all_reqs *diplrel_mess = NULL;

/**************************************************************************
  Get the mutually exclusive requirement sets for DiplRel.
**************************************************************************/
static bv_diplrel_all_reqs *diplrel_mess_get(void)
{
  if (diplrel_mess == NULL) {
    /* This is the first call. Initialize diplrel_mess. */
    diplrel_mess = diplrel_mess_gen();
  }

  return diplrel_mess;
}

/**************************************************************************
  Free diplrel_mess
**************************************************************************/
void diplrel_mess_close(void)
{
  if (diplrel_mess != NULL) {
    free(diplrel_mess);
    diplrel_mess = NULL;
  }
}

/**************************************************************************
  Get the DiplRel requirements that are known to contradict the specified
  DiplRel requirement.

  The known contratictions have their position in the enumeration of all
  possible DiplRel requirements set in the returned bitvector.
**************************************************************************/
bv_diplrel_all_reqs diplrel_req_contradicts(const struct requirement *req)
{
  int diplrel_req_num;
  bv_diplrel_all_reqs *mess;
  bv_diplrel_all_reqs known;
  int set;

  /* Nothing is known to contradict the requirement yet. */
  BV_CLR_ALL(known);

  if (req->source.kind != VUT_DIPLREL) {
    /* No known contradiction of a requirement of any other kind. */
    fc_assert(req->source.kind == VUT_DIPLREL);

    return known;
  }

  /* Convert the requirement to its position in the enumeration of all
   * DiplRel requirements. */
  diplrel_req_num = requirement_diplrel_ereq(req->source.value.diplrel,
                                             req->range, req->present);

  /* Get the mutually exclusive requirement sets for DiplRel. */
  mess = diplrel_mess_get();

  /* Add all known contradictions. */
  for (set = 0; set < DIPLREL_MESS_SIZE; set++) {
    if (BV_ISSET(mess[set], diplrel_req_num)) {
      /* The requirement req is mentioned in the set. It is therefore known
       * that all other requirements in the set contradicts it. They should
       * therefore be added to the known contradictions. */
      BV_SET_ALL_FROM(known, mess[set]);
    }
  }

  /* The requirement isn't self contradicting. It was set by the mutually
   * exclusive requirement sets that mentioned it. Remove it. */
  BV_CLR(known, diplrel_req_num);

  return known;
}

/***************************************************************************
  Return the number of pplayer2's visible units in pplayer's territory,
  from the point of view of pplayer.  Units that cannot be seen by pplayer
  will not be found (this function doesn't cheat).
***************************************************************************/
int player_in_territory(const struct player *pplayer,
			const struct player *pplayer2)
{
  int in_territory = 0;

  /* This algorithm should work at server or client.  It only returns the
   * number of visible units (a unit can potentially hide inside the
   * transport of a different player).
   *
   * Note this may be quite slow.  An even slower alternative is to iterate
   * over the entire map, checking all units inside the player's territory
   * to see if they're owned by the enemy. */
  unit_list_iterate(pplayer2->units, punit) {
    /* Get the owner of the tile/territory. */
    struct player *owner = tile_owner(unit_tile(punit));

    if (owner == pplayer && can_player_see_unit(pplayer, punit)) {
      /* Found one! */
      in_territory += 1;
    }
  } unit_list_iterate_end;

  return in_territory;
}

/****************************************************************************
  Returns whether this is a valid username.  This is used by the server to
  validate usernames and should be used by the client to avoid invalid
  ones.
****************************************************************************/
bool is_valid_username(const char *name)
{
  return (strlen(name) > 0
          && !fc_isdigit(name[0])
          && is_ascii_name(name)
          && fc_strcasecmp(name, ANON_USER_NAME) != 0);
}

/***************************************************************
  Return is AI can be set to given level
***************************************************************/
bool is_settable_ai_level(enum ai_level level)
{
  if (level == AI_LEVEL_AWAY) {
    /* Cannot set away level for AI */
    return FALSE;
  }

  return TRUE;
}

/***************************************************************
  Return number of AI levels in game
***************************************************************/
int number_of_ai_levels(void)
{
  return AI_LEVEL_COUNT - 1; /* AI_LEVEL_AWAY is not real AI */
}

/**************************************************************************
  Return pointer to ai data of given player and ai type.
**************************************************************************/
void *player_ai_data(const struct player *pplayer, const struct ai_type *ai)
{
  return pplayer->server.ais[ai_type_number(ai)];
}

/**************************************************************************
  Attach ai data to player
**************************************************************************/
void player_set_ai_data(struct player *pplayer, const struct ai_type *ai,
                        void *data)
{
  pplayer->server.ais[ai_type_number(ai)] = data;
}

/**************************************************************************
  Return the multiplier value currently in effect for pplayer (in display
  units).
**************************************************************************/
int player_multiplier_value(const struct player *pplayer,
                            const struct multiplier *pmul)
{
  return pplayer->multipliers[multiplier_index(pmul)];
}

/**************************************************************************
  Return the multiplier value currently in effect for pplayer, scaled
  from display units to the units used in the effect system (if different).
  Result is multiplied by 100 (caller should divide down).
**************************************************************************/
int player_multiplier_effect_value(const struct player *pplayer,
                                   const struct multiplier *pmul)
{
  return (player_multiplier_value(pplayer, pmul) + pmul->offset)
    * pmul->factor;
}

/**************************************************************************
  Return the player's target value for a multiplier (which may be
  different from the value currently in force; it will take effect
  next turn). Result is in display units.
**************************************************************************/
int player_multiplier_target_value(const struct player *pplayer,
                                   const struct multiplier *pmul)
{
  return pplayer->multipliers_target[multiplier_index(pmul)];
}