summaryrefslogtreecommitdiffstats
path: root/apps/plugins/superdom.c
blob: 3e1e23785a5cd8175694917dc39decd3ef161573 (plain)
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
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (C) 2006 Will Robertson
 *
 * 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
 * of the License, or (at your option) any later version.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/
#include "plugin.h"
#include "lib/playback_control.h"
#include "lib/display_text.h"
#include "pluginbitmaps/superdom_boarditems.h"
PLUGIN_HEADER

extern const fb_data superdom_boarditems[];
char buf[255];

#define COLOUR_DARK 0
#define COLOUR_LIGHT 1

#define MARGIN 5

#if (LCD_DEPTH == 16)
#define MY_BITMAP_PART   rb->lcd_bitmap_transparent_part
#else
#define MY_BITMAP_PART   rb->lcd_mono_bitmap_part
#endif

#if LCD_WIDTH > LCD_HEIGHT
#define BOX_WIDTH ((LCD_WIDTH-(MARGIN*2))/10)
#define BOX_HEIGHT ((BOX_WIDTH*2)/3)

#else
#define BOX_HEIGHT ((LCD_HEIGHT-(MARGIN*2)-15)/10)
#define BOX_WIDTH ((BOX_HEIGHT*2)/3)

#endif

/* NUM_BOX HEIGHT and WIDTH are used for the number pad in the game.  The height
 *  calculation includes spacing for the text placed above and below the number
 *  pad (it divides by 6 instead of just 4).  The width calculation gives extra
 *  spacing on the sides of the pad too (divides by 5 instead of 3).
 */
#define NUM_BOX_HEIGHT  (LCD_HEIGHT/6)
#define NUM_BOX_WIDTH   (LCD_WIDTH/5)

#define NUM_MARGIN_X    (LCD_WIDTH-3*NUM_BOX_WIDTH)/2
#define NUM_MARGIN_Y    (LCD_HEIGHT-4*NUM_BOX_HEIGHT)/2

/* These parameters define the piece image dimensions, Stride is the total width
 *  of the bitmap.
 */
#define STRIDE          BMPWIDTH_superdom_boarditems
#define ICON_HEIGHT     (BMPHEIGHT_superdom_boarditems/6)
#define ICON_WIDTH      (BMPWIDTH_superdom_boarditems/2)

#if (CONFIG_KEYPAD == IPOD_4G_PAD) || (CONFIG_KEYPAD == IPOD_3G_PAD) || \
    (CONFIG_KEYPAD == IPOD_1G2G_PAD)
#define SUPERDOM_OK BUTTON_SELECT
#define SUPERDOM_CANCEL BUTTON_MENU
#define SUPERDOM_LEFT BUTTON_LEFT
#define SUPERDOM_RIGHT BUTTON_RIGHT
#define IPOD_STYLE

#elif CONFIG_KEYPAD == IRIVER_H300_PAD || CONFIG_KEYPAD == IRIVER_H100_PAD
#define SUPERDOM_OK BUTTON_SELECT
#define SUPERDOM_LEFT BUTTON_LEFT
#define SUPERDOM_RIGHT BUTTON_RIGHT
#define SUPERDOM_UP BUTTON_UP
#define SUPERDOM_DOWN BUTTON_DOWN
#define SUPERDOM_CANCEL BUTTON_OFF

#elif CONFIG_KEYPAD == IAUDIO_X5M5_PAD
#define SUPERDOM_OK BUTTON_SELECT
#define SUPERDOM_LEFT BUTTON_LEFT
#define SUPERDOM_RIGHT BUTTON_RIGHT
#define SUPERDOM_UP BUTTON_UP
#define SUPERDOM_DOWN BUTTON_DOWN
#define SUPERDOM_CANCEL BUTTON_REC

#elif CONFIG_KEYPAD == IRIVER_H10_PAD
#define SUPERDOM_OK BUTTON_RIGHT
#define SUPERDOM_UP BUTTON_SCROLL_UP
#define SUPERDOM_DOWN BUTTON_SCROLL_DOWN
#define SUPERDOM_CANCEL BUTTON_LEFT

#elif CONFIG_KEYPAD == GIGABEAT_PAD
#define SUPERDOM_OK BUTTON_SELECT
#define SUPERDOM_UP BUTTON_UP
#define SUPERDOM_DOWN BUTTON_DOWN
#define SUPERDOM_LEFT BUTTON_LEFT
#define SUPERDOM_RIGHT BUTTON_RIGHT
#define SUPERDOM_CANCEL BUTTON_POWER

#elif CONFIG_KEYPAD == SANSA_E200_PAD
#define SUPERDOM_OK BUTTON_SELECT
#define SUPERDOM_UP BUTTON_SCROLL_BACK
#define SUPERDOM_DOWN BUTTON_SCROLL_FWD
#define SUPERDOM_LEFT BUTTON_LEFT
#define SUPERDOM_RIGHT BUTTON_RIGHT
#define SUPERDOM_CANCEL BUTTON_POWER

#elif CONFIG_KEYPAD == SANSA_FUZE_PAD
#define SUPERDOM_OK BUTTON_SELECT
#define SUPERDOM_UP BUTTON_SCROLL_BACK
#define SUPERDOM_DOWN BUTTON_SCROLL_FWD
#define SUPERDOM_LEFT BUTTON_LEFT
#define SUPERDOM_RIGHT BUTTON_RIGHT
#define SUPERDOM_CANCEL (BUTTON_HOME|BUTTON_REPEAT)

#elif CONFIG_KEYPAD == GIGABEAT_S_PAD
#define SUPERDOM_OK BUTTON_SELECT
#define SUPERDOM_UP BUTTON_UP
#define SUPERDOM_DOWN BUTTON_DOWN
#define SUPERDOM_LEFT BUTTON_LEFT
#define SUPERDOM_RIGHT BUTTON_RIGHT
#define SUPERDOM_CANCEL BUTTON_BACK

#elif CONFIG_KEYPAD == COWOND2_PAD
#define SUPERDOM_CANCEL BUTTON_POWER

#elif CONFIG_KEYPAD == CREATIVEZVM_PAD
#define SUPERDOM_OK BUTTON_SELECT
#define SUPERDOM_UP BUTTON_UP
#define SUPERDOM_DOWN BUTTON_DOWN
#define SUPERDOM_LEFT BUTTON_LEFT
#define SUPERDOM_RIGHT BUTTON_RIGHT
#define SUPERDOM_CANCEL BUTTON_BACK

#elif (CONFIG_KEYPAD == ONDAVX747_PAD) || (CONFIG_KEYPAD == MROBE500_PAD)
#define SUPERDOM_CANCEL BUTTON_POWER

#endif

#ifdef HAVE_TOUCHSCREEN
#ifndef SUPERDOM_OK
#define SUPERDOM_OK     BUTTON_CENTER
#endif
#ifndef SUPERDOM_UP
#define SUPERDOM_UP     BUTTON_TOPMIDDLE
#endif
#ifndef SUPERDOM_LEFT
#define SUPERDOM_LEFT   BUTTON_MIDLEFT
#endif
#ifndef SUPERDOM_RIGHT
#define SUPERDOM_RIGHT  BUTTON_MIDRIGHT
#endif
#ifndef SUPERDOM_DOWN
#define SUPERDOM_DOWN   BUTTON_BOTTOMMIDDLE
#endif
#ifndef SUPERDOM_CANCEL
#define SUPERDOM_CANCEL BUTTON_TOPLEFT
#endif
#endif

#define SUPERDOM_QUIT 23

void gen_interest(void);
int production_menu(void);
void init_resources(void);
int select_square(void);
void update_score(void);
void gen_resources(void);
void draw_cursor(void);
int calc_strength(int colour, int x, int y);
void draw_board(void);

struct tile{
    signed int colour; /* -1 = Unset */
    bool tank;
    bool plane;
    bool nuke;
    bool ind;
    bool farm;
    int men;
};

struct resources {
    int cash;
    int food;
    int farms;
    int inds;
    int men;
    int tanks;
    int planes;
    int nukes;
    int bank;
    int moves;
};

struct settings {
    int compstartfarms;
    int compstartinds;
    int humanstartfarms;
    int humanstartinds;
    int startcash;
    int startfood;
    int movesperturn;
} superdom_settings;

struct resources humanres;
struct resources compres;
enum { GS_PROD, GS_MOVE, GS_WAR } gamestate;

struct cursor{
    int x;
    int y;
} cursor;

struct tile board[12][12];

void init_board(void) {
    int i,j;
    rb->srand(*rb->current_tick);
    for(i=0;i<12;i++) {  /* Hopefully about 50% each colour */
        for(j=0;j<12;j++) {
            if((i<1)||(j<1)||(i>10)||(j>10))
                board[i][j].colour = -1;   /* Unset */
            else
                board[i][j].colour = rb->rand()%2;
            board[i][j].tank = false;
            board[i][j].plane = false;
            board[i][j].nuke = false;
            board[i][j].ind = false;
            board[i][j].farm = false;
            board[i][j].men = 0;
        }
    }

    while(compres.farms < superdom_settings.compstartfarms) {
        i = rb->rand()%10 + 1;
        j = rb->rand()%10 + 1;
        if((board[i][j].colour == COLOUR_DARK) && (board[i][j].farm == false)) {
            board[i][j].farm = true;
            compres.farms++;
        }
    }
    while(compres.inds < superdom_settings.compstartinds) {
        i = rb->rand()%10 + 1;
        j = rb->rand()%10 + 1;
        if((board[i][j].colour == COLOUR_DARK) && (board[i][j].ind == false)) {
            board[i][j].ind = true;
            compres.inds++;
        }
    }
    while(humanres.farms<superdom_settings.humanstartfarms) {
        i = rb->rand()%10 + 1;
        j = rb->rand()%10 + 1;
        if((board[i][j].colour == COLOUR_LIGHT)&&(board[i][j].farm == false)) {
            board[i][j].farm = true;
            humanres.farms++;
        }
    }
    while(humanres.inds<superdom_settings.humanstartfarms) {
        i = rb->rand()%10 + 1;
        j = rb->rand()%10 + 1;
        if((board[i][j].colour == COLOUR_LIGHT) && (board[i][j].ind == false)) {
            board[i][j].ind = true;
            humanres.inds++;
        }
    }
}

void draw_board(void) {
    int i,j;
    rb->lcd_clear_display();
    for(i=1;i<11;i++) {
        for(j=1;j<11;j++) {
            if(board[i][j].colour == COLOUR_DARK) {
                rb->lcd_set_foreground(LCD_DARKGRAY);
            } else {
                rb->lcd_set_foreground(LCD_LIGHTGRAY);
            }
            rb->lcd_fillrect(MARGIN+(BOX_WIDTH*(i-1)), 
                            MARGIN+(BOX_HEIGHT*(j-1)), BOX_WIDTH, 
                            BOX_HEIGHT);
#if LCD_DEPTH != 16
            rb->lcd_set_drawmode(DRMODE_BG | DRMODE_INVERSEVID); 
#endif
            if(board[i][j].ind) {
                MY_BITMAP_PART(superdom_boarditems,
                                board[i][j].colour?ICON_WIDTH:0, 0, STRIDE, 
#if LCD_WIDTH > LCD_HEIGHT
                                MARGIN+(BOX_WIDTH*(i-1))+1, 
                                MARGIN+(BOX_HEIGHT*(j-1))+ICON_HEIGHT+1, 
#else
                                MARGIN+(BOX_WIDTH*(i-1))+1+ICON_WIDTH,
                                MARGIN+(BOX_HEIGHT*(j-1))+1,
#endif
                                ICON_WIDTH, ICON_HEIGHT);
            }
            if(board[i][j].farm) {
                MY_BITMAP_PART(superdom_boarditems,
                                board[i][j].colour?ICON_WIDTH:0, ICON_HEIGHT, 
                                STRIDE, MARGIN+(BOX_WIDTH*(i-1))+1, 
                                MARGIN+(BOX_HEIGHT*(j-1))+1, 
                                ICON_WIDTH, ICON_HEIGHT);
            }
            if(board[i][j].tank) {
                MY_BITMAP_PART(superdom_boarditems,
                                board[i][j].colour?ICON_WIDTH:0, ICON_HEIGHT*2,
                                STRIDE, MARGIN+(BOX_WIDTH*(i-1))+ICON_WIDTH+1, 
                                MARGIN+(BOX_HEIGHT*(j-1))+ICON_HEIGHT+1, 
                                ICON_WIDTH, ICON_HEIGHT);
            }
            if(board[i][j].men) {
                MY_BITMAP_PART(superdom_boarditems,
                                board[i][j].colour?ICON_WIDTH:0, ICON_HEIGHT*3,
#if LCD_WIDTH > LCD_HEIGHT
                                STRIDE, MARGIN+(BOX_WIDTH*(i-1))+ICON_WIDTH+1,
                                MARGIN+(BOX_HEIGHT*(j-1))+1, 
#else
                                STRIDE, MARGIN+(BOX_WIDTH*(i-1))+1,
                                MARGIN+(BOX_HEIGHT*(j-1))+1+ICON_HEIGHT,
#endif
                                ICON_WIDTH, ICON_HEIGHT);
            }
            if(board[i][j].plane) {
                MY_BITMAP_PART(superdom_boarditems,
                                board[i][j].colour?ICON_WIDTH:0, ICON_HEIGHT*4,
#if LCD_WIDTH > LCD_HEIGHT
                                STRIDE,MARGIN+(BOX_WIDTH*(i-1))+ICON_WIDTH*2+1,
                                MARGIN+(BOX_HEIGHT*(j-1))+ICON_HEIGHT+1,
#else
                                STRIDE,MARGIN+(BOX_WIDTH*(i-1))+ICON_WIDTH+1,
                                MARGIN+(BOX_HEIGHT*(j-1))+ICON_HEIGHT*2+1,
#endif
                                ICON_WIDTH, ICON_HEIGHT);
            }
            if(board[i][j].nuke) {
                MY_BITMAP_PART(superdom_boarditems,
                                board[i][j].colour?ICON_WIDTH:0, ICON_HEIGHT*5,
#if LCD_WIDTH > LCD_HEIGHT
                                STRIDE,MARGIN+(BOX_WIDTH*(i-1))+ICON_WIDTH*2+1,
                                MARGIN+(BOX_HEIGHT*(j-1))+1, 
#else
                                STRIDE,MARGIN+(BOX_WIDTH*(i-1))+1,
                                MARGIN+(BOX_HEIGHT*(j-1))+ICON_HEIGHT*2+1,
#endif
                                ICON_WIDTH, ICON_HEIGHT);
            }
#if LCD_DEPTH != 16
            rb->lcd_set_drawmode(DRMODE_SOLID); 
#endif
        }
    }
    rb->lcd_set_foreground(LCD_BLACK);
    for(i=0;i<=10;i++) { /* Draw Horizontal lines */
        rb->lcd_hline(MARGIN, MARGIN+(BOX_WIDTH*10), MARGIN+(BOX_HEIGHT*i));
    }
    for(i=0;i<=10;i++) { /* Draw Vertical lines */
        rb->lcd_vline(MARGIN+(BOX_WIDTH*i), MARGIN, MARGIN+(BOX_HEIGHT*10));
    }
    rb->lcd_update();
}

int calc_strength(int colour, int x, int y) {
    int a, b, score=0;
    for (a = -1; a < 2; a++) {
        for (b = -1; b < 2; b++) {
            if ((b == 0 || a == 0) &&
                (board[x + a][y + b].colour == colour)) {
                score += 10;
                if(board[x + a][y + b].tank || board[x + a][y + b].farm)
                    score += 30;
                if(board[x + a][y + b].plane || board[x + a][y + b].ind)
                    score += 40;
                if(board[x + a][y + b].nuke)
                    score += 20;
                if(board[x + a][y + b].men)
                    score += (board[x + a][y + b].men*133/1000);
            }
        }
    }
    return score;
}

void gen_interest(void) {
    /* Interest should be around 10% */
    rb->srand(*rb->current_tick);
    int interest = 7+rb->rand()%6;
    humanres.bank = humanres.bank+(interest*humanres.bank/100);
    compres.bank = compres.bank+(interest*compres.bank/100);
}

void draw_cursor(void) {
    rb->lcd_set_drawmode(DRMODE_COMPLEMENT);
    rb->lcd_fillrect(MARGIN+((cursor.x-1)*BOX_WIDTH), 
                  MARGIN+((cursor.y-1)*BOX_HEIGHT), BOX_WIDTH+1, BOX_HEIGHT+1);
    rb->lcd_set_drawmode(DRMODE_SOLID);
    rb->lcd_update();
}

void gen_resources(void) {
    int inccash = 0;
    int incfood = 0;
    int ratecash = 0;
    int ratefood = 0;
    int i;
    gen_interest();
    rb->srand(*rb->current_tick);
    /* Generate Human's resources */
        for(i=0;i<humanres.inds;i++) {
            inccash += (300+rb->rand()%200);
        }
        for(i=0;i<humanres.farms;i++) {
            incfood += (200+rb->rand()%200);
        }
        if(humanres.inds)
            ratecash = inccash/humanres.inds;
        if(humanres.farms)
            ratefood = incfood/humanres.farms;
        if(ratecash > 450) {
            if(ratefood > 350) {
                rb->splash(HZ*2, "Patriotism sweeps the land, all production" 
                                " is up this year!");
            } else {
                rb->splash(HZ*2, "Factories working at maximum efficiency," 
                                " cash production up this year!");
            }
        } else if(ratecash > 350) {
            if(ratefood > 350) {
                rb->splash(HZ*2, "Record crop harvest this year!");
            } else if(ratefood > 250) {
                rb->splash(HZ*2, "Production continues as normal");
            } else {
                rb->splash(HZ*2, "Spoilage of crops leads to reduced farm" 
                                " output this  year");
            }
        } else {
            if(ratefood > 350) {
                rb->splash(HZ*2, "Record crop harvest this year!");
            } else if(ratefood > 250) {
                rb->splash(HZ*2, "Factory unions introduced. Industrial" 
                                " production is down this year.");
            } else {
                rb->splash(HZ*2, "Internet created. All production is down" 
                                " due to time wasted.");
            }
        }
        humanres.cash += inccash;
        humanres.food += incfood;

    /* Generate Computer's resources */
        inccash = 0;
        incfood = 0;
        for(i=0;i<compres.inds;i++) {
            inccash += (300+rb->rand()%200);
        }
        for(i=0;i<compres.farms;i++) {
            incfood += (200+rb->rand()%200);
        }
        compres.cash += inccash;
        compres.food += incfood;
}

void update_score(void) {
    int strength;
    rb->lcd_setfont(FONT_SYSFIXED);
    rb->lcd_set_drawmode(DRMODE_BG|DRMODE_INVERSEVID);
    rb->lcd_fillrect(5,LCD_HEIGHT-20,105,20);
    rb->lcd_set_drawmode(DRMODE_SOLID);
    strength = calc_strength(COLOUR_LIGHT, cursor.x, cursor.y);
    rb->snprintf(buf, sizeof(buf), "Your power: %d.%d", 
                    strength/10, strength%10);
    rb->lcd_putsxy(5,LCD_HEIGHT-20, buf);
    strength = calc_strength(COLOUR_DARK, cursor.x, cursor.y);
    rb->snprintf(buf, sizeof(buf), "Comp power: %d.%d", 
                    strength/10, strength%10);
    rb->lcd_putsxy(5,LCD_HEIGHT-10, buf);
    rb->lcd_setfont(FONT_UI);
}

int settings_menu_function(void) {
    int selection = 0;

    MENUITEM_STRINGLIST(settings_menu,"Super Domination Settings",NULL,
                    "Computer starting farms","Computer starting factories",
                    "Human starting farms","Human starting factories",
                    "Starting cash","Starting food","Moves per turn");

    while(1) {
        selection=rb->do_menu(&settings_menu,&selection, NULL, false);
        switch(selection) {
        case 0:
            rb->set_int("Computer starting farms", "", UNIT_INT, 
                            &superdom_settings.compstartfarms, NULL, 
                            1, 0, 5, NULL);
            break;
        case 1:
            rb->set_int("Computer starting factories", "", UNIT_INT, 
                            &superdom_settings.compstartinds, NULL, 
                            1, 0, 5, NULL);
            break;
        case 2:
            rb->set_int("Human starting farms", "", UNIT_INT, 
                            &superdom_settings.humanstartfarms, NULL, 
                            1, 0, 5, NULL);
            break;
        case 3:
            rb->set_int("Human starting factories", "", UNIT_INT,
                    &superdom_settings.humanstartinds, NULL,
                    1, 0, 5, NULL);
            break;
        case 4:
            rb->set_int("Starting cash", "", UNIT_INT, 
                            &superdom_settings.startcash, NULL, 
                            250, 0, 5000, NULL);
            break;
        case 5:
            rb->set_int("Starting food", "", UNIT_INT, 
                            &superdom_settings.startfood, NULL, 
                            250, 0, 5000, NULL);
            break;
        case 6:
            rb->set_int("Moves per turn", "", UNIT_INT, 
                            &superdom_settings.movesperturn, NULL,
                            1, 1, 5, NULL);
            break;
        case MENU_ATTACHED_USB:
            return PLUGIN_USB_CONNECTED;
            break;
        case GO_TO_PREVIOUS:
            return 0;
            break;
        }
    }
    return 0;
}

static int do_help(void) {
    int button;
#define WORDS (sizeof help_text / sizeof (char*))
    static char* help_text[] = {
        "Super", "domination", "is", "a", "turn", "based", "strategy", "game,",
        "where", "the", "aim", "is", "to", "overpower", "the", "computer",
        "player", "by", "taking", "their", "territory.", "",
        "Each", "year", "you", "are", "allocated", "an", "amount", "of", "cash",
        "and", "food,", "depending", "on", "how", "many", "farms", "and",
        "factories", "you", "control.", "",
        "Use", "this", "cash", "and", "food", "to", "buy", "and", "feed", "your",
        "army.", "Each", "tile", "has", "a", "strength,", "calculated", "by",
        "the", "ownership", "of", "adjacent", "tiles,", "and", "the", "type",
        "and", "number", "of", "troops", "on", "them.",
    };

    if (display_text(WORDS, help_text, NULL, NULL))
        return PLUGIN_USB_CONNECTED;
    do {
        button = rb->button_get(true);
        if ( rb->default_event_handler( button ) == SYS_USB_CONNECTED )
            return PLUGIN_USB_CONNECTED;
    } while( ( button == BUTTON_NONE )
            || ( button & (BUTTON_REL|BUTTON_REPEAT) ) );

    return PLUGIN_OK;
}

int menu(void) {
    int selection = 0;
     
    MENUITEM_STRINGLIST(main_menu,"Super Domination Menu",NULL,
                    "Play Super Domination","Settings","Help","Quit");

    while(1) {
        selection=rb->do_menu(&main_menu,&selection, NULL, false);
        switch(selection) {
            case 0:
                return 0; /* start playing */
                break;
            case 1:
                if(settings_menu_function()==PLUGIN_USB_CONNECTED)
                    return PLUGIN_USB_CONNECTED;
                break;
            case 2:
                if(do_help()==PLUGIN_USB_CONNECTED)
                    return PLUGIN_USB_CONNECTED;
                break;
            default:
                return 2; /* quit program */
                break;
        }
    }

    return 3;
}

int save_game(void) {
    int fd;
    char savepath[MAX_PATH];

    rb->snprintf(savepath, sizeof(savepath), "/Savegame.ssg");
    if(rb->kbd_input(savepath, MAX_PATH)) {
        DEBUGF("Keyboard input failed\n");
        return -1;
    }

    fd = rb->open(savepath, O_WRONLY|O_CREAT);
    DEBUGF("savepath: %s\n", savepath);
    if(fd < 0) {
        DEBUGF("Couldn't create/open file\n");
        return -1;
    }
    
    rb->write(fd, "SSGv3", 5);
    rb->write(fd, &gamestate, sizeof(gamestate));
    rb->write(fd, &humanres.cash, sizeof(humanres.cash));
    rb->write(fd, &humanres.food, sizeof(humanres.food));
    rb->write(fd, &humanres.bank, sizeof(humanres.bank));
    rb->write(fd, &humanres.planes, sizeof(humanres.planes));
    rb->write(fd, &humanres.tanks, sizeof(humanres.tanks));
    rb->write(fd, &humanres.men, sizeof(humanres.men));
    rb->write(fd, &humanres.nukes, sizeof(humanres.nukes));
    rb->write(fd, &humanres.inds, sizeof(humanres.inds));
    rb->write(fd, &humanres.farms, sizeof(humanres.farms));
    rb->write(fd, &humanres.moves, sizeof(humanres.moves));
    rb->write(fd, &compres.cash, sizeof(compres.cash));
    rb->write(fd, &compres.food, sizeof(compres.food));
    rb->write(fd, &compres.bank, sizeof(compres.bank));
    rb->write(fd, &compres.planes, sizeof(compres.planes));
    rb->write(fd, &compres.tanks, sizeof(compres.tanks));
    rb->write(fd, &compres.men, sizeof(compres.men));
    rb->write(fd, &compres.nukes, sizeof(compres.nukes));
    rb->write(fd, &compres.inds, sizeof(compres.inds));
    rb->write(fd, &compres.farms, sizeof(compres.farms));
    rb->write(fd, &compres.moves, sizeof(compres.moves));
    rb->write(fd, board, sizeof(board));
    rb->write(fd, &superdom_settings.compstartfarms, sizeof(int));
    rb->write(fd, &superdom_settings.compstartinds, sizeof(int));
    rb->write(fd, &superdom_settings.humanstartfarms, sizeof(int));
    rb->write(fd, &superdom_settings.humanstartfarms, sizeof(int));
    rb->write(fd, &superdom_settings.startcash, sizeof(int));
    rb->write(fd, &superdom_settings.startfood, sizeof(int));
    rb->write(fd, &superdom_settings.movesperturn, sizeof(int));
    rb->close(fd);
    return 0;
}

int ingame_menu(void) {
    int selection = 0;
     
    MENUITEM_STRINGLIST(ingame_menu,"Super Domination Menu",NULL,
                    "Return to game","Save Game","Playback Control", "Quit");

    selection=rb->do_menu(&ingame_menu,&selection, NULL, false);
    switch(selection) {
        case 0:
            return 0;
            break;
        case 1:
            if(!save_game())
                rb->splash(HZ, "Game saved");
            else
                rb->splash(HZ, "Error in save");
            break;
        case 2:
            playback_control(NULL);
            break;
        case 3:
            return SUPERDOM_QUIT;
            break;
        case MENU_ATTACHED_USB:
            return PLUGIN_USB_CONNECTED;
            break;
        case GO_TO_PREVIOUS:
            return 0;
            break;
    }
    return 0;
}

int get_number(char* param, int* value) {
    //int numbers[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int numbers[3][3];
    int i,j,x=0,y=0;
    int height, width;
    int button = 0;
    numbers[0][0] = 1;
    numbers[0][1] = 2;
    numbers[0][2] = 3;
    numbers[1][0] = 4;
    numbers[1][1] = 5;
    numbers[1][2] = 6;
    numbers[2][0] = 7;
    numbers[2][1] = 8;
    numbers[2][2] = 9;
    rb->lcd_clear_display();
    /* Draw a 3x4 grid */
    for(i=0;i<=3;i++) {  /* Vertical lines */
        rb->lcd_vline(NUM_MARGIN_X+(NUM_BOX_WIDTH*i), NUM_MARGIN_Y,
                      NUM_MARGIN_Y+(4*NUM_BOX_HEIGHT));
    }
    for(i=0;i<=4;i++) {  /* Horizontal lines */
        rb->lcd_hline(NUM_MARGIN_X, NUM_MARGIN_X+(3*NUM_BOX_WIDTH),
                      NUM_MARGIN_Y+(NUM_BOX_HEIGHT*i));
    }
    for(i=0;i<3;i++) {
        for(j=0;j<3;j++) {
            rb->snprintf(buf, sizeof(buf), "%d", numbers[i][j]);
            rb->lcd_putsxy(NUM_MARGIN_X+(j*NUM_BOX_WIDTH)+10, 
                            NUM_MARGIN_Y+(i*NUM_BOX_HEIGHT)+8, buf);
        }
    }
    rb->lcd_putsxy(NUM_MARGIN_X+5, NUM_MARGIN_Y+(3*NUM_BOX_HEIGHT)+8, "CLR");
    rb->lcd_putsxy(NUM_MARGIN_X+NUM_BOX_WIDTH+10, 
                    NUM_MARGIN_Y+(3*NUM_BOX_HEIGHT)+8, "0");
    rb->lcd_putsxy(NUM_MARGIN_X+2*NUM_BOX_WIDTH+8, 
                    NUM_MARGIN_Y+(3*NUM_BOX_HEIGHT)+8, "OK");
    rb->snprintf(buf,sizeof(buf), "%d", *value);
    rb->lcd_putsxy(NUM_MARGIN_X+10, NUM_MARGIN_Y+4*NUM_BOX_HEIGHT+10, buf);
    rb->lcd_getstringsize(param, &width, &height);
    rb->lcd_putsxy((LCD_WIDTH-width)/2, (NUM_MARGIN_Y-height)/2, param);
    rb->lcd_set_drawmode(DRMODE_COMPLEMENT);
    rb->lcd_fillrect(NUM_MARGIN_X+(NUM_BOX_WIDTH*x), 
                    NUM_MARGIN_Y+(NUM_BOX_HEIGHT*y), NUM_BOX_WIDTH+1, 
                    NUM_BOX_HEIGHT+1);
    rb->lcd_set_drawmode(DRMODE_SOLID);
    rb->lcd_update();
    while(1) {
        button = rb->button_get(true);
        switch(button) {
            case SUPERDOM_OK:
                if(y!=3) {
                    *value *= 10;
                    *value += numbers[y][x];
                } else if(x==0) {
                    *value /= 10;
                } else if(x==1) {
                    *value *= 10;
                } else if(x==2) {
                    return 0;
                }
                rb->lcd_set_drawmode(DRMODE_BG|DRMODE_INVERSEVID);
                rb->lcd_fillrect(0, NUM_MARGIN_Y+4*NUM_BOX_HEIGHT+10,
                                LCD_WIDTH, 30);
                rb->lcd_set_drawmode(DRMODE_SOLID);
                rb->snprintf(buf,sizeof(buf), "%d", *value);
                rb->lcd_putsxy(NUM_MARGIN_X+10, 
                                NUM_MARGIN_Y+4*NUM_BOX_HEIGHT+10, buf);
                break;
            case SUPERDOM_CANCEL:
                *value = 0;
                rb->splash(HZ, "Cancelled");
                return 2;
                break;
#if CONFIG_KEYPAD != IRIVER_H10_PAD
            case SUPERDOM_LEFT:
                rb->lcd_set_drawmode(DRMODE_COMPLEMENT);
                rb->lcd_fillrect(NUM_MARGIN_X+(NUM_BOX_WIDTH*x), 
                                NUM_MARGIN_Y+(NUM_BOX_HEIGHT*y), 
                                NUM_BOX_WIDTH+1, NUM_BOX_HEIGHT+1);
                rb->lcd_set_drawmode(DRMODE_SOLID);
                if(x==0) {
#ifdef IPOD_STYLE
                    if(y>0)
                        y--;
                    else
                        y=3;
#endif
                    x=2;
                } else {
                    x--;
                }
                rb->lcd_set_drawmode(DRMODE_COMPLEMENT);
                rb->lcd_fillrect(NUM_MARGIN_X+(NUM_BOX_WIDTH*x), 
                                NUM_MARGIN_Y+(NUM_BOX_HEIGHT*y), 
                                NUM_BOX_WIDTH+1, NUM_BOX_HEIGHT+1);
                rb->lcd_set_drawmode(DRMODE_SOLID);
                break;
            case SUPERDOM_RIGHT:
                rb->lcd_set_drawmode(DRMODE_COMPLEMENT);
                rb->lcd_fillrect(NUM_MARGIN_X+(NUM_BOX_WIDTH*x), 
                                NUM_MARGIN_Y+(NUM_BOX_HEIGHT*y), 
                                NUM_BOX_WIDTH+1, NUM_BOX_HEIGHT+1);
                rb->lcd_set_drawmode(DRMODE_SOLID);
                if(x==2) {
#ifdef IPOD_STYLE
                    if(y==3)
                        y=0;
                    else
                        y++;
#endif
                    x=0;
                } else {
                    x++;
                }
                rb->lcd_set_drawmode(DRMODE_COMPLEMENT);
                rb->lcd_fillrect(NUM_MARGIN_X+(NUM_BOX_WIDTH*x), 
                                NUM_MARGIN_Y+(NUM_BOX_HEIGHT*y), 
                                NUM_BOX_WIDTH+1, NUM_BOX_HEIGHT+1);
                rb->lcd_set_drawmode(DRMODE_SOLID);
                break;
#endif
#ifndef IPOD_STYLE
            case SUPERDOM_UP:
                rb->lcd_set_drawmode(DRMODE_COMPLEMENT);
                rb->lcd_fillrect(NUM_MARGIN_X+(NUM_BOX_WIDTH*x), 
                                NUM_MARGIN_Y+(NUM_BOX_HEIGHT*y), 
                                NUM_BOX_WIDTH+1, NUM_BOX_HEIGHT+1);
                rb->lcd_set_drawmode(DRMODE_SOLID);
                if(y==0) {
#if CONFIG_KEYPAD == IRIVER_H10_PAD
                    if(x > 0)
                        x--;
                    else
                        x=2;
#endif
                    y=3;
                } else {
                    y--;
                }
                rb->lcd_set_drawmode(DRMODE_COMPLEMENT);
                rb->lcd_fillrect(NUM_MARGIN_X+(NUM_BOX_WIDTH*x), 
                                NUM_MARGIN_Y+(NUM_BOX_HEIGHT*y), 
                                NUM_BOX_WIDTH+1, NUM_BOX_HEIGHT+1);
                rb->lcd_set_drawmode(DRMODE_SOLID);
                break;
            case SUPERDOM_DOWN:
                rb->lcd_set_drawmode(DRMODE_COMPLEMENT);
                rb->lcd_fillrect(NUM_MARGIN_X+(NUM_BOX_WIDTH*x), 
                                NUM_MARGIN_Y+(NUM_BOX_HEIGHT*y), 
                                NUM_BOX_WIDTH+1, NUM_BOX_HEIGHT+1);
                rb->lcd_set_drawmode(DRMODE_SOLID);
                if(y==3) {
#if CONFIG_KEYPAD == IRIVER_H10_PAD
                    if(x < 2)
                        x++;
                    else
                        x=0;
#endif
                    y=0;
                } else {
                    y++;
                }
                rb->lcd_set_drawmode(DRMODE_COMPLEMENT);
                rb->lcd_fillrect(NUM_MARGIN_X+(NUM_BOX_WIDTH*x), 
                                NUM_MARGIN_Y+(NUM_BOX_HEIGHT*y), 
                                NUM_BOX_WIDTH+1, NUM_BOX_HEIGHT+1);
                rb->lcd_set_drawmode(DRMODE_SOLID);
                break;
#endif
            default:
                if (rb->default_event_handler(button) == SYS_USB_CONNECTED)
                {
                    return PLUGIN_USB_CONNECTED;
                }
                break;
        }
        rb->lcd_update();
    }
    return 0;
}

bool tile_has_item(int type, int x, int y) {
    switch(type) {
        case 0:
            return (board[x][y].men > 0);
            break;
        case 1:
            return board[x][y].tank;
            break;
        case 2:
            return board[x][y].plane;
            break;
        case 3:
            return board[x][y].farm;
            break;
        case 4:
            return board[x][y].ind;
            break;
        case 5:
            return board[x][y].nuke;
            break;
    }
    return false;
}

int buy_resources(int colour, int type, int x, int y, int nummen) {
    const char *itemnames[][6] = {
        {
            "them",
            "the tank",
            "the plane",
            "the farm",
            "the industrial plant",
            "the nuke",
        }, {
            "place men",
            "place a tank",
            "place a plane",
            "build a farm",
            "build an industrial plant",
            "place a nuke",
        }, {
            NULL,
            "a tank",
            "a plane",
            "a farm",
            "an industrial plant",
            "a nuke",
        },
    };

    bool human = (colour == COLOUR_LIGHT);
    int price = 0;
    struct resources *res;

    if(human) {
        res = &humanres;
    } else {
        res = &compres;
    }
    switch(type) {
        case 0: /* men */
            price = 1*nummen;
            break;
        case 1: /* tank */
            price = 300;
            break;
        case 2: /* plane */
            price = 600;
            break;
        case 3: /* Farm */
            price = 1150;
            break;
        case 4: /* Factory */
            price = 1300;
            break;
        case 5: /* nuke */
            price = 2000;
            break;
    }
    if(res->cash < price) {
        if(human)
            rb->splash(HZ, "Not enough money!");
        return 2;
    }
    if(human) {
        rb->splashf(HZ, "Where do you want to place %s?", itemnames[0][type]);
        switch(select_square()) {
            case 2:
                return 2;
                break;
            case PLUGIN_USB_CONNECTED:
                return PLUGIN_USB_CONNECTED;
                break;
        }
        x = cursor.x;
        y = cursor.y;
    }
    if(board[x][y].colour != colour) {
        if(human)
            rb->splashf(HZ, "Can't %s on enemy territory", itemnames[1][type]);
        return 2;
    }
    if(type != 0 && tile_has_item(type, x, y)) {
        if(human)
            rb->splashf(HZ, "There is already %s there", itemnames[2][type]);
        return 2;
    }
    switch(type) {
        case 0:
            board[x][y].men += nummen;
            res->men += nummen;
            break;
        case 1:
            board[x][y].tank = true;
            res->tanks++;
            break;
        case 2:
            board[x][y].plane = true;
            res->planes++;
            break;
        case 3:
            board[x][y].farm = true;
            res->farms++;
            break;
        case 4:
            board[x][y].ind = true;
            res->inds++;
            break;
        case 5:
            board[x][y].nuke = true;
            res->nukes++;
            break;
    }
    res->cash -= price;

    draw_board();
    rb->sleep(HZ);

    return 0;
}

int buy_resources_menu(void) {
    int selection,nummen;

    MENUITEM_STRINGLIST(res_menu, "Buy Resources", NULL, "Buy men ($1)",
                    "Buy tank ($300)", "Buy plane ($600)", "Buy Farm ($1150)",
                    "Buy Factory ($1300)", "Buy Nuke ($2000)",
                    "Finish buying");

    while(1) {
        selection=rb->do_menu(&res_menu,&selection, NULL, false);
        switch(selection) {
            case 0:
                nummen = 0;
                if(get_number("How many men would you like?", &nummen)
                                == PLUGIN_USB_CONNECTED)
                    return PLUGIN_USB_CONNECTED;
                if(!nummen)
                    break;
                /* fall through */
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                if(buy_resources(COLOUR_LIGHT, selection, 0, 0, nummen)
                    == PLUGIN_USB_CONNECTED)
                    return PLUGIN_USB_CONNECTED;
                break;
            case 6:
                return 0;
                break;
            case MENU_ATTACHED_USB:
                return PLUGIN_USB_CONNECTED;
                break;
            case GO_TO_PREVIOUS:
                return 0;
                break;
        }
    }
    return 0;
}

int move_unit(int colour, int type, int fromx, int fromy,
                int tox, int toy, int nummen) {
    const char *itemnames[][3] = {
        {
            "troops",
            "the tank",
            "the plane",
        }, {
            "any troops",
            "a tank",
            "a plane",
        }, {
            "the troops",
            "the tank",
            "the plane",
        }
    };
    bool human = (colour == COLOUR_LIGHT);

    if(human) {
        rb->splashf(HZ, "Select where you want to move %s from",
                        itemnames[0][type]);
        switch(select_square()) {
            case 2:
                return 2;
                break;
            case PLUGIN_USB_CONNECTED:
                return PLUGIN_USB_CONNECTED;
                break;
        }
        fromx = cursor.x;
        fromy = cursor.y;
    }
    if(board[fromx][fromy].colour != colour) {
        if(human)
            rb->splash(HZ, "That isn't your territory");
        return 2;
    }
    if(!tile_has_item(type, fromx, fromy)) {
        if(human)
            rb->splashf(HZ, "You don't have %s there", itemnames[1][type]);
        return 2;
    }
    if(type == 0) {
        if(human) {
            nummen = board[fromx][fromy].men;
            switch(get_number("How many men do you want to move?", &nummen)) {
                case 2:
                    return 2;
                    break;
                case PLUGIN_USB_CONNECTED:
                    return PLUGIN_USB_CONNECTED;
                    break;
            }
        }
        if(nummen > board[fromx][fromy].men) {
            if(human)
                rb->splash(HZ, "You don't have that many troops.");
            return 2;
        }
    }
    if(human) {
        rb->splashf(HZ, "Select where you want to move %s to",
                        itemnames[2][type]);
        switch(select_square()) {
            case 2:
                return 2;
                break;
            case PLUGIN_USB_CONNECTED:
                return PLUGIN_USB_CONNECTED;
                break;
        }
        tox = cursor.x;
        toy = cursor.y;
    }
    if((tox == fromx && toy == fromy) ||
       board[tox][toy].colour != colour ||
       (type != 2 && (abs(tox - fromx) > 1 || abs(toy - fromy) > 1))) {
        if(human)
            rb->splash(HZ, "Invalid move");
        return 2;
    }
    if(type != 0 && tile_has_item(type, tox, toy)) {
        if(human)
            rb->splashf(HZ, "There is already %s there", itemnames[1][type]);
        return 2;
    }
    switch(type) {
        case 0:
            board[fromx][fromy].men -= nummen;
            board[tox][toy].men += nummen;
            break;
        case 1:
            board[fromx][fromy].tank = false;
            board[tox][toy].tank = true;
            break;
        case 2:
            board[fromx][fromy].plane = false;
            board[tox][toy].plane = true;
            break;
    }
    return 0;
}

int move_unit_menu(void) {
    int selection;

    MENUITEM_STRINGLIST(move_unit_menu, "Move unit", NULL, "Move men", 
                    "Move tank", "Move plane");
    selection=rb->do_menu(&move_unit_menu,&selection, NULL, false);
    switch(selection) {
        case 0:
        case 1:
        case 2:
            switch(move_unit(COLOUR_LIGHT, selection, 0, 0, 0, 0, 0)) {
                case 0:
                    humanres.moves--;
                    break;
                case PLUGIN_USB_CONNECTED:
                    return PLUGIN_USB_CONNECTED;
                    break;
            }
            break;
        case MENU_ATTACHED_USB:
            return PLUGIN_USB_CONNECTED;
    }
    return 0;
}

int launch_nuke(int colour, int nukex, int nukey, int targetx, int targety) {
    bool human = (colour == COLOUR_LIGHT);
    struct resources *res;

    if(board[nukex][nukey].colour != colour) {
        if(human)
            rb->splash(HZ, "That isn't your territory");
        return 2;
    }
    if(! board[nukex][nukey].nuke) {
        if(human)
            rb->splashf(HZ, "You don't have %s there", "a nuke");
        return 2;
    }
    if(human) {
        rb->splash(HZ, "Select place to target with nuke");
        switch(select_square()) {
            case 2:
                return 2;
                break;
            case PLUGIN_USB_CONNECTED:
                return PLUGIN_USB_CONNECTED;
                break;
        }
        targetx = cursor.x;
        targety = cursor.y;
    }
    if(human) {
        humanres.nukes--;
    } else {
        compres.nukes--;
    }
    board[nukex][nukey].nuke = false;

    if(board[targetx][targety].colour == COLOUR_LIGHT) {
        res = &humanres;
    } else {
        res = &compres;
    }
    res->men -= board[targetx][targety].men;
    res->tanks -= board[targetx][targety].tank;
    res->planes -= board[targetx][targety].plane;
    res->nukes -= board[targetx][targety].nuke;
    res->farms -= board[targetx][targety].farm;
    res->inds -= board[targetx][targety].ind;
    board[targetx][targety].men = 0;
    board[targetx][targety].tank = false;
    board[targetx][targety].plane = false;
    board[targetx][targety].ind = false;
    board[targetx][targety].nuke = false;
    board[targetx][targety].farm = false;
    /* TODO: Fallout carried by wind */

    return 0;
}

int movement_menu(void) {
    int selection, tempmenu;

    MENUITEM_STRINGLIST(move_menu, "Movement", NULL, "Move unit", 
                    "Buy additional moves ($100)", "Launch nuclear missile", 
                    "Check map", "Finish moving", "Game menu");

    while(1) {
        selection=rb->do_menu(&move_menu,&selection, NULL, false);
        switch(selection) {
            case 0:
                if(humanres.moves) {
                    if(move_unit_menu()==PLUGIN_USB_CONNECTED)
                        return PLUGIN_USB_CONNECTED;
                } else {
                    rb->splash(HZ, "You have no more moves left." 
                                   " You can buy more for $100 each.");
                }
                break;
            case 1:
                if(humanres.cash > 100) {
                    humanres.moves++;
                    humanres.cash -= 100;
                    rb->snprintf(buf, sizeof(buf), "You now have %d moves", 
                                    humanres.moves);
                    rb->splash(HZ, buf);
                }
                break;
            case 2:
                if(humanres.nukes==0) {
                    rb->splash(HZ, "You do not have any nukes to launch");
                } else {
                    rb->splash(HZ, "Select place to launch nuke from");
                    switch(select_square()) {
                        case 0:
                            if(launch_nuke(COLOUR_LIGHT, cursor.x, cursor.y,
                                0, 0) == PLUGIN_USB_CONNECTED)
                                return PLUGIN_USB_CONNECTED;
                            break;
                        case PLUGIN_USB_CONNECTED:
                            return PLUGIN_USB_CONNECTED;
                            break;
                    }
                }
                break;
            case 3:
                if(select_square() == PLUGIN_USB_CONNECTED)
                    return PLUGIN_USB_CONNECTED;
                break;
            case 4:
                return 0;
                break;
            case 5:
                tempmenu = ingame_menu();
                switch(tempmenu) {
                    case PLUGIN_USB_CONNECTED:
                        return PLUGIN_USB_CONNECTED;
                        break;
                    case SUPERDOM_QUIT:
                        return SUPERDOM_QUIT;
                        break;
                }
                break;
            case MENU_ATTACHED_USB:
                return PLUGIN_USB_CONNECTED;
                break;
        }
    }
    return 0;
}

int show_inventory(void) {
    char men[20], tanks[20], planes[20], inds[20], farms[20], nukes[20], 
         cash[20], food[20], bank[20];
    rb->snprintf(men, sizeof(men), "Men: %d", humanres.men);
    rb->snprintf(tanks, sizeof(tanks), "Tanks: %d", humanres.tanks);
    rb->snprintf(planes, sizeof(planes), "Planes: %d", humanres.planes);
    rb->snprintf(inds, sizeof(inds), "Factories: %d", humanres.inds);
    rb->snprintf(farms, sizeof(farms), "Farms: %d", humanres.farms);
    rb->snprintf(nukes, sizeof(nukes), "Nukes: %d", humanres.nukes);
    rb->snprintf(cash, sizeof(cash), "Cash: %d", humanres.cash);
    rb->snprintf(food, sizeof(food), "Food: %d", humanres.food);
    rb->snprintf(bank, sizeof(bank), "Bank: %d", humanres.bank);
    rb->lcd_clear_display();
    rb->lcd_puts(1, 0, "Inventory");
    rb->lcd_puts(2, 1, men);
    rb->lcd_puts(2, 2, tanks);
    rb->lcd_puts(2, 3, planes);
    rb->lcd_puts(2, 4, inds);
    rb->lcd_puts(2, 5, farms);
    rb->lcd_puts(2, 6, nukes);
    rb->lcd_puts(2, 7, cash);
    rb->lcd_puts(2, 8, food);
    rb->lcd_puts(2, 9, bank);
    rb->lcd_update();
    if(rb->default_event_handler(rb->button_get(true)) == SYS_USB_CONNECTED) {
        return PLUGIN_USB_CONNECTED;
    } else {
        return 0;
    }
}

int production_menu(void) {
    int selection, tempbank, tempmenu;

    MENUITEM_STRINGLIST(prod_menu, "Production", NULL, "Buy resources", 
                    "Show inventory", "Check map", "Invest money", 
                    "Withdraw money", "Finish turn", "Game menu");

    while(1) {
        selection=rb->do_menu(&prod_menu,&selection, NULL, false);
        switch(selection) {
            case 0:
                if(buy_resources_menu() == PLUGIN_USB_CONNECTED)
                    return PLUGIN_USB_CONNECTED;
                break;
            case 1:
                if(show_inventory() == PLUGIN_USB_CONNECTED)
                    return PLUGIN_USB_CONNECTED;
                break;
            case 2:
                if(select_square() == PLUGIN_USB_CONNECTED)
                    return PLUGIN_USB_CONNECTED;
                break;
            case 3:
                tempbank = humanres.cash;
                if(get_number("How much do you want to invest?", &tempbank)
                                == PLUGIN_USB_CONNECTED)
                    return PLUGIN_USB_CONNECTED;
                if(tempbank>humanres.cash) {
                    rb->splash(HZ, "You don't have that much cash to invest");
                } else {
                    humanres.cash -= tempbank;
                    humanres.bank += tempbank;
                }
                break;
            case 4:
                tempbank = 0;
                if(get_number("How much do you want to withdraw?", &tempbank)
                                == PLUGIN_USB_CONNECTED)
                    return PLUGIN_USB_CONNECTED;
                if(tempbank>humanres.bank) {
                    rb->splash(HZ, "You don't have that much cash to withdraw");
                } else {
                    humanres.cash += tempbank;
                    humanres.bank -= tempbank;
                }
                break;
            case 5:
                return 0;
                break;
            case 6:
                tempmenu = ingame_menu();
                switch(tempmenu) {
                    case PLUGIN_USB_CONNECTED:
                        return PLUGIN_USB_CONNECTED;
                        break;
                    case SUPERDOM_QUIT:
                        return SUPERDOM_QUIT;
                        break;
                }
                break;
            case MENU_ATTACHED_USB:
                return PLUGIN_USB_CONNECTED;
                break;
        }
    }
    return 0;
}

void init_resources(void) {
    humanres.cash = superdom_settings.startcash;
    humanres.food = superdom_settings.startfood;
    humanres.tanks = 0;
    humanres.planes = 0;
    humanres.nukes = 0;
    humanres.inds = 0;
    humanres.farms = 0;
    humanres.men = 0;
    humanres.bank = 0;
    humanres.moves = 0;
    compres.cash = superdom_settings.startcash;
    compres.food = superdom_settings.startfood;
    compres.tanks = 0;
    compres.planes = 0;
    compres.nukes = 0;
    compres.inds = 0;
    compres.farms = 0;
    compres.men = 0;
    compres.bank = 0;
    compres.moves = 0;
}

int select_square(void) {
    int button = 0;
    draw_board();
    draw_cursor();
    update_score();
#if LCD_WIDTH >= 220
    rb->lcd_setfont(FONT_SYSFIXED);
    rb->snprintf(buf, sizeof(buf), "Cash: %d", humanres.cash);
    rb->lcd_putsxy(125, LCD_HEIGHT-20, buf);
    rb->snprintf(buf, sizeof(buf), "Food: %d", humanres.food);
    rb->lcd_putsxy(125, LCD_HEIGHT-10, buf);
    rb->lcd_setfont(FONT_UI);
#endif
    rb->lcd_update();
    while(1) {
        button = rb->button_get(true);
        switch(button) {
            case SUPERDOM_CANCEL:
                rb->splash(HZ, "Cancelled");
                return 2;
                break;
            case SUPERDOM_OK:
                return 0;
                break;
#if CONFIG_KEYPAD != IRIVER_H10_PAD
            case SUPERDOM_LEFT:
            case (SUPERDOM_LEFT|BUTTON_REPEAT):
                draw_cursor(); /* Deselect the current tile */
                if(cursor.x>1) {
                    cursor.x--;
                } else {
#ifdef IPOD_STYLE
                    if(cursor.y>1)
                        cursor.y--;
                    else
                        cursor.y = 10;
#endif
                    cursor.x = 10;
                }
                update_score();
                draw_cursor();
                break;
            case SUPERDOM_RIGHT:
            case (SUPERDOM_RIGHT|BUTTON_REPEAT):
                draw_cursor(); /* Deselect the current tile */
                if(cursor.x<10) {
                    cursor.x++;
                } else {
#ifdef IPOD_STYLE
                    if(cursor.y<10)
                        cursor.y++;
                    else
                        cursor.y = 1;
#endif
                    cursor.x = 1;
                }
                update_score();
                draw_cursor();
                break;
#endif
#ifndef IPOD_STYLE
            case SUPERDOM_UP:
            case (SUPERDOM_UP|BUTTON_REPEAT):
                draw_cursor(); /* Deselect the current tile */
                if(cursor.y>1) {
                    cursor.y--;
                } else {
#if CONFIG_KEYPAD == IRIVER_H10_PAD
                    if(cursor.x > 1)
                        cursor.x--;
                    else
                        cursor.x = 10;
#endif
                    cursor.y = 10;
                }
                update_score();
                draw_cursor();
                break;
            case SUPERDOM_DOWN:
            case (SUPERDOM_DOWN|BUTTON_REPEAT):
                draw_cursor(); /* Deselect the current tile */
                if(cursor.y<10) {
                    cursor.y++;
                } else {
#if CONFIG_KEYPAD == IRIVER_H10_PAD
                    if(cursor.x < 10)
                        cursor.x++;
                    else
                        cursor.x = 1;
#endif
                    cursor.y = 1;
                }
                update_score();
                draw_cursor();
                break;
#endif
            default:
                if (rb->default_event_handler(button) == SYS_USB_CONNECTED)
                {
                    return PLUGIN_USB_CONNECTED;
                }
        }
    }
}

int killmen(int colour) {
    bool human = (colour == COLOUR_LIGHT);
    int menkilled,i,j;
    int percent;
    if(human) {
        percent = (humanres.food*1000)/humanres.men;
        humanres.food = 0;
    } else {
        percent = (compres.food*1000)/compres.men;
        compres.food = 0;
    }
    menkilled = 0;
    for(i=1;i<11;i++) {
        for(j=1;j<11;j++) {
            if(board[i][j].colour == colour) {
                int nummen = ((board[i][j].men * percent)/1000);
                menkilled += board[i][j].men - nummen;
                board[i][j].men = nummen;
            }
        }
    }

    if(human)
        humanres.men -= menkilled;
    else
        compres.men -= menkilled;
    return menkilled;
}

/* return -1 if error, 1 if attack is succeeded, 0 otherwise */
int attack_territory(int colour, int x, int y) {
    bool human = (colour == COLOUR_LIGHT);
    int str_diff;

    if(board[x][y].colour == colour) {
        if(human)
            rb->splash(HZ, "You can't attack your own territory");
        return -1;
    }
    str_diff = calc_strength(COLOUR_DARK, x, y) -
               calc_strength(COLOUR_LIGHT, x, y);
    if(human) {
        str_diff = -str_diff;
    }
    rb->srand(*rb->current_tick);
    if(str_diff > 0 || (str_diff == 0 && rb->rand()%2)) {
        struct resources *offres, *defres;
        if(human) {
            offres = &humanres;
            defres = &compres;
        } else {
            offres = &compres;
            defres = &humanres;
        }
        defres->men -= board[x][y].men;
        defres->tanks -= board[x][y].tank;
        defres->planes -= board[x][y].plane;
        defres->nukes -= board[x][y].nuke;
        defres->farms -= board[x][y].farm;
        defres->inds -= board[x][y].ind;
        offres->farms += board[x][y].farm;
        offres->inds += board[x][y].ind;
        board[x][y].colour = colour;
        board[x][y].men = 0;
        board[x][y].tank = false;
        board[x][y].plane = false;
        board[x][y].nuke = false;
        draw_board();
        if(human)
            rb->sleep(HZ*2);
        else
            rb->sleep(HZ);
        return 1;
    } else {
        if(human)
            rb->splash(HZ, "Your troops were unable to overcome"
                           " the enemy troops");
        else
            rb->splash(HZ*2, "The computer attempted to "
                            "attack, but the invasion was"
                            " pushed back");
        return 0;
    }
    return 0;
}

int war_menu(void) {
    int selection, tempmenu;

    MENUITEM_STRINGLIST(wartime_menu, "War!", NULL, 
                    "Select territory to attack", "Finish turn", "Game menu");

    while(humanres.moves) {
        selection=rb->do_menu(&wartime_menu,&selection, NULL, false);
        switch(selection) {
            case 0:
                switch(select_square()) {
                    case 0:
                        if(attack_territory(COLOUR_LIGHT, cursor.x, cursor.y)
                            >= 0)
                            humanres.moves--;
                        break;
                    case PLUGIN_USB_CONNECTED:
                        return PLUGIN_USB_CONNECTED;
                        break;
                }
                break;
            case 1:
                return 0;
                break;
            case 2:
                tempmenu = ingame_menu();
                switch(tempmenu) {
                    case PLUGIN_USB_CONNECTED:
                        return PLUGIN_USB_CONNECTED;
                        break;
                    case SUPERDOM_QUIT:
                        return SUPERDOM_QUIT;
                        break;
                }
                break;
        }
    }
    return 0;
}

struct threat {
    int x;
    int y;
    int str_diff;
};

bool place_adjacent(bool tank, int x, int y) {
    int type = (tank? 1: 2);
    if(!buy_resources(COLOUR_DARK, type, x, y, 0)) {
        return true;
    }
    if(!buy_resources(COLOUR_DARK, type, x-1, y, 0)) {
        return true;
    }
    if(!buy_resources(COLOUR_DARK, type, x+1, y, 0)) {
        return true;
    }
    if(!buy_resources(COLOUR_DARK, type, x, y-1, 0)) {
        return true;
    }
    if(!buy_resources(COLOUR_DARK, type, x, y+1, 0)) {
        return true;
    }
    return false;
}

bool has_adjacent(int x, int y) {
    if((board[x][y].colour == COLOUR_LIGHT) && 
       ((board[x-1][y].colour == COLOUR_DARK) ||
       (board[x+1][y].colour == COLOUR_DARK) ||
       (board[x][y+1].colour == COLOUR_DARK) ||
       (board[x][y-1].colour == COLOUR_DARK)))
        return 1;
    else
        return 0;
}

void find_adjacent(int x, int y, int* adj_x, int* adj_y) {
    /* Finds adjacent squares, returning squares without tanks on them
     * in preference to those with them */
    if(board[x-1][y].colour == COLOUR_DARK) {
        *adj_x = x-1;
        *adj_y = y;
        return;
    }
    if(board[x+1][y].colour == COLOUR_DARK) {
        *adj_x = x+1;
        *adj_y = y;
        return;
    }
    if(board[x][y-1].colour == COLOUR_DARK) {
        *adj_x = x;
        *adj_y = y-1;
        return;
    }
    if(board[x][y+1].colour == COLOUR_DARK) {
        *adj_x = x;
        *adj_y = y+1;
        return;
    }
}

void computer_allocate(void) {
    /* Firstly, decide whether to go offensive or defensive.
     * This is primarily decided by the human player posing a threat to either
     * the computer's farms or factories */
    int i, j, k;
    bool offensive = true;
    struct threat threats[4];
    int numthreats = 0;
    int total_str_diff = 0;
    int numterritory = 0;
    int str_diff;
    int men_needed;
    struct threat targets[2];
    int numtargets;
    struct cursor adj;

    compres.cash += compres.bank;
    compres.bank = 0;
    for(i=1;i<11;i++) {
        for(j=1;j<11;j++) {
            if(board[i][j].colour == COLOUR_DARK) {
                numterritory++;
                str_diff = calc_strength(COLOUR_LIGHT,i,j) -
                           calc_strength(COLOUR_DARK,i,j);
                if(str_diff > 0 && (board[i][j].ind || board[i][j].farm)) {
                    if(numthreats < 3) {
                        offensive = false;
                        threats[numthreats].x = i;
                        threats[numthreats].y = j;
                        threats[numthreats].str_diff = str_diff;
                        numthreats++;
                    }
                }
            }
            rb->yield();
        }
    }
    if(offensive) {
        /* The AI is going to go straight for the throat here and attack
         * the player's farms and factories. The amount of cash
         * the AI has to spend will determine how many targets there are */
        if(compres.cash > 1200) {
            /* 1200 is a figure I pulled out of nowhere. Adjust as needed */
            numtargets = 2;
        } else {
            numtargets = 1;
        }
        /* Work out which target(s) to attack. They must have adjacent squares
         * owned by the computer. If none are found just place troops in
         * random places around the map until we run out of money */
        k = 0;
        for(i=1;i<11;i++) {
            for(j=1;j<11;j++) {
                if(has_adjacent(i,j) &&
                   (board[i][j].ind || board[i][j].farm)) {
                    if(k<numtargets) {
                        targets[k].x = i;
                        targets[k].y = j;
                        targets[k].str_diff =
                                calc_strength(COLOUR_LIGHT, i, j) -
                                calc_strength(COLOUR_DARK, i, j);
                        k++;
                    }
                }
                rb->yield();
            }
        }
        if(k == 0) {
            /* No targets found! Randomly pick squares and if they're owned 
             * by the computer then stick a tank on it. */
                rb->srand(*rb->current_tick);
                while(compres.cash >= 300 && compres.tanks < numterritory) {
                    i = rb->rand()%10 + 1;
                    j = rb->rand()%10 + 1;
                    if(board[i][j].colour == COLOUR_DARK) {
                        buy_resources(COLOUR_DARK, 1, i, j, 0);
                    }
                    rb->yield();
                }
        } else {
            for(i=0;i<k;i++) {
                str_diff = targets[i].str_diff;
                while(str_diff + 20 > 0 && compres.cash > 0) {
                    /* While we still need them keep placing men */
                    if(!place_adjacent(true, targets[i].x, targets[i].y)) {
                        find_adjacent(targets[i].x, targets[i].y,
                            &adj.x, &adj.y);
                        men_needed = (str_diff + 20)*1000/133;
                        if(compres.cash < men_needed) {
                            men_needed = compres.cash;
                        }
                        buy_resources(COLOUR_DARK, 0, adj.x, adj.y,
                                            men_needed);
                        break;
                    }
                    str_diff = calc_strength(COLOUR_LIGHT,
                                      targets[i].x, targets[i].y) -
                               calc_strength(COLOUR_DARK,
                                      targets[i].x, targets[i].y);
                }
            }
        }
    } else {
        /* Work out what to place on each square to defend it.
         * Tanks are preferential because they do not require food,
         * but if the budget is tight then we fall back onto troops.
         * Conversely if cash is not an issue and there are already tanks in
         * place planes will be deployed. We would like a margin of at least
         * 20 points to be safe. */

        for(i=0;i<numthreats;i++) {
            total_str_diff += threats[i].str_diff;
        }
        if((total_str_diff+20)*10 > compres.cash) {
            /* Not enough cash to accomodate all threats using tanks alone -
             * use men as a backup */
            for(i=0;i<numthreats;i++) {
                men_needed = ((threats[i].str_diff + 20)*1000)/133;
                if(compres.cash < men_needed) {
                    men_needed = compres.cash;
                }
                buy_resources(COLOUR_DARK, 0, threats[i].x, threats[i].y,
                                    men_needed);
            }
        } else {
            /* Tanks it is */
            /* Enough money to pay their way by planes? */
            bool tank = ((total_str_diff+20)*15 >= compres.cash);
            for(i=0;i<numthreats;i++) {
                str_diff = threats[i].str_diff;
                while(str_diff + 20 > 0) {
                    if(!place_adjacent(tank, threats[i].x, threats[i].y)) {
                        /* No room for any more planes or tanks, revert to
                         * men */
                        find_adjacent(threats[i].x, threats[i].y,
                            &adj.x, &adj.y);
                        men_needed = (str_diff + 20)*1000/133;
                        if(compres.cash < men_needed) {
                            men_needed = compres.cash;
                        }
                        buy_resources(COLOUR_DARK, 0, threats[i].x,
                                        threats[i].y, men_needed);
                        break;
                    }
                    str_diff = calc_strength(COLOUR_LIGHT,
                                      threats[i].x, threats[i].y) -
                               calc_strength(COLOUR_DARK,
                                      threats[i].x, threats[i].y);
                }
            }
        }
    }
    compres.bank += compres.cash;
    compres.cash = 0;
}

int find_adj_target(int x, int y, struct cursor* adj) {
    /* Find a square next to a computer's farm or factory owned by the player
     * that is vulnerable. Return 1 on success, 0 otherwise */
    if(board[x+1][y].colour == COLOUR_LIGHT && 
         calc_strength(COLOUR_LIGHT,x+1,y)<=calc_strength(COLOUR_DARK,x+1,y)) {
        adj->x = x+1;
        adj->y = y;
        return 1;
    }
    if(board[x-1][y].colour == COLOUR_LIGHT && 
         calc_strength(COLOUR_LIGHT,x-1,y)<=calc_strength(COLOUR_DARK,x-1,y)) {
        adj->x = x-1;
        adj->y = y;
        return 1;
    }
    if(board[x][y+1].colour == COLOUR_LIGHT && 
         calc_strength(COLOUR_LIGHT,x,y+1)<=calc_strength(COLOUR_DARK,x,y+1)) {
        adj->x = x;
        adj->y = y+1;
        return 1;
    }
    if(board[x][y-1].colour == COLOUR_LIGHT && 
         calc_strength(COLOUR_LIGHT,x,y-1)<=calc_strength(COLOUR_DARK,x,y-1)) {
        adj->x = x;
        adj->y = y-1;
        return 1;
    }
    return 0;
}

void computer_war(void) {
    /* Work out where to attack - prioritise the defence of buildings */
    int i, j;
    bool found_target = true;
    struct cursor adj;
    
    while(found_target) {
        found_target = false;
        for(i=1;i<11;i++) {
            for(j=1;j<11;j++) {
                if((board[i][j].colour == COLOUR_DARK) &&
                   (board[i][j].farm || board[i][j].ind) &&
                   find_adj_target(i, j, &adj)) {
                    found_target = true;
                    if(attack_territory(COLOUR_DARK, adj.x, adj.y) >= 0) {
                        compres.moves--;
                        if(!compres.moves)
                            return;
                    }
                }
                rb->yield();
            }
        }
    }
    /* Defence stage done, move on to OFFENCE */
    found_target = true;
    while(found_target) {
        found_target = false;
        for(i=1;i<11;i++) {
            for(j=1;j<11;j++) {
                if(board[i][j].colour == COLOUR_LIGHT &&
                        (board[i][j].ind || board[i][j].farm) &&
                        (calc_strength(COLOUR_DARK, i, j) >=
                         calc_strength(COLOUR_LIGHT, i, j))) {
                    found_target = true;
                    if(attack_territory(COLOUR_DARK, i, j) >= 0) {
                        compres.moves--;
                        if(!compres.moves)
                            return;
                    }
                }
                rb->yield();
            }
        }
    }
    /* Spend leftover moves wherever attacking randomly */
    found_target = true;
    while(found_target) {
        found_target = false;
        for(i=1;i<11;i++) {
            for(j=1;j<11;j++) {
                if(board[i][j].colour == COLOUR_LIGHT && 
                  (calc_strength(COLOUR_DARK, i, j)  >= 
                   calc_strength(COLOUR_LIGHT, i, j))) {
                    found_target = true;
                    if(attack_territory(COLOUR_DARK, i, j) >= 0) {
                        compres.moves--;
                        if(!compres.moves)
                            return;
                    }
                }
                rb->yield();
            }
        }
    }
}

static int load_game(const char* file) {
    int fd;

    fd = rb->open(file, O_RDONLY);
    if(fd == 0) {
        DEBUGF("Couldn't open savegame\n");
        return -1;
    }
    rb->read(fd, buf, 5);
    if(rb->strcmp(buf, "SSGv3")) {
        rb->splash(HZ, "Invalid/incompatible savegame");
        return -1;
    }
    rb->read(fd, &gamestate, sizeof(gamestate));
    rb->read(fd, &humanres.cash, sizeof(humanres.cash));
    rb->read(fd, &humanres.food, sizeof(humanres.food));
    rb->read(fd, &humanres.bank, sizeof(humanres.bank));
    rb->read(fd, &humanres.planes, sizeof(humanres.planes));
    rb->read(fd, &humanres.tanks, sizeof(humanres.tanks));
    rb->read(fd, &humanres.men, sizeof(humanres.men));
    rb->read(fd, &humanres.nukes, sizeof(humanres.nukes));
    rb->read(fd, &humanres.inds, sizeof(humanres.inds));
    rb->read(fd, &humanres.farms, sizeof(humanres.farms));
    rb->read(fd, &humanres.moves, sizeof(humanres.moves));
    rb->read(fd, &compres.cash, sizeof(humanres.cash));
    rb->read(fd, &compres.food, sizeof(humanres.food));
    rb->read(fd, &compres.bank, sizeof(humanres.bank));
    rb->read(fd, &compres.planes, sizeof(humanres.planes));
    rb->read(fd, &compres.tanks, sizeof(humanres.tanks));
    rb->read(fd, &compres.men, sizeof(humanres.men));
    rb->read(fd, &compres.nukes, sizeof(humanres.nukes));
    rb->read(fd, &compres.inds, sizeof(humanres.inds));
    rb->read(fd, &compres.farms, sizeof(humanres.farms));
    rb->read(fd, &compres.moves, sizeof(humanres.moves));
    rb->read(fd, board, sizeof(board));
    rb->read(fd, &superdom_settings.compstartfarms, sizeof(int));
    rb->read(fd, &superdom_settings.compstartinds, sizeof(int));
    rb->read(fd, &superdom_settings.humanstartfarms, sizeof(int));
    rb->read(fd, &superdom_settings.humanstartfarms, sizeof(int));
    rb->read(fd, &superdom_settings.startcash, sizeof(int));
    rb->read(fd, &superdom_settings.startfood, sizeof(int));
    rb->read(fd, &superdom_settings.movesperturn, sizeof(int));
    rb->close(fd);
    return 0;
}

void default_settings(void) {
    superdom_settings.compstartfarms = 1;
    superdom_settings.compstartinds = 1;
    superdom_settings.humanstartfarms = 2;
    superdom_settings.humanstartinds = 2;
    superdom_settings.startcash = 0;
    superdom_settings.startfood = 0;
    superdom_settings.movesperturn = 2;
}

int average_strength(int colour) {
    /* This function calculates the average strength of the given player,
     * used to determine when the computer wins or loses. */
    int i,j;
    int totalpower = 0;
    for(i=1;i<11;i++) {
        for(j=1;j<11;j++) {
            if(board[i][j].colour != -1) {
                totalpower += calc_strength(colour, i, j);
            }
        }
    }
    return totalpower/100;
}

enum plugin_status plugin_start(const void* parameter)
{
#if LCD_DEPTH > 1
    rb->lcd_set_backdrop(NULL);
    rb->lcd_set_foreground(LCD_BLACK);
    rb->lcd_set_background(LCD_WHITE);
#endif

    cursor.x = 1;
    cursor.y = 1;
    default_settings();
    if(parameter) {
        if(load_game(parameter) != 0) {
            DEBUGF("Loading failed, generating new game\n");
        } else {
            switch(gamestate) {
                case GS_PROD:
                    goto startprod;
                    break;
                case GS_MOVE:
                    goto startmove;
                    break;
                case GS_WAR:
                    goto startwar;
                    break;
                default:
                    goto startyear;
                    break;
            }
        }
    }

    bool play = false;
    while(!play) {
        switch(menu()) {
            case 0:
                play = true;
                break;
            case 2:
                return PLUGIN_OK;
                break;
            case PLUGIN_USB_CONNECTED:
                return PLUGIN_USB_CONNECTED;
                break;
        }
    }
    init_resources();
    init_board();
    gen_resources();
startyear:
    while(1) {
        int avg_str_diff = (average_strength(COLOUR_LIGHT) -
                            average_strength(COLOUR_DARK));
        if(avg_str_diff > 15) {
            rb->splash(HZ*4, "The computer has surrendered. You win.");
            return PLUGIN_OK;
        }
        if(-avg_str_diff > 15) {
            rb->splash(HZ*4, "Your army have suffered terrible morale from"
                             " the bleak prospects of winning. You lose.");
            return PLUGIN_OK;
        }

        /* production */
startprod:
        gamestate = GS_PROD;
        switch(production_menu()) {
            case PLUGIN_USB_CONNECTED:
                return PLUGIN_USB_CONNECTED;
                break;
            case SUPERDOM_QUIT:
                return PLUGIN_OK;
                break;
        }
        computer_allocate();

        /* movement */
        humanres.moves = superdom_settings.movesperturn;
startmove:
        gamestate = GS_MOVE;
        switch(movement_menu()) {
            case PLUGIN_USB_CONNECTED:
                return PLUGIN_USB_CONNECTED;
                break;
            case SUPERDOM_QUIT:
                return PLUGIN_OK;
                break;
        }
        /* feed men */
        if(humanres.men) {
            if(humanres.food > humanres.men) {
                rb->snprintf(buf, sizeof(buf), "Your men ate %d units of food",
                                humanres.men);
                humanres.food -= humanres.men;
            } else {
                rb->snprintf(buf, sizeof(buf), "There was not enough food"
                   " to feed all your men, %d men have died of starvation",
                                killmen(COLOUR_LIGHT));
            }
            rb->splash(HZ*2, buf);
        }
        if(compres.men) {
            if(compres.food > compres.men) {
                compres.food -= compres.men;
            } else {
                rb->snprintf(buf, sizeof(buf), "The computer does not have"
                 " enough food to feed its men. %d have died of starvation",
                                killmen(COLOUR_DARK));
                rb->splash(HZ, buf);
            }
        }
        /* war */
        humanres.moves = superdom_settings.movesperturn;
startwar:
        gamestate = GS_WAR;
        switch(war_menu()) {
            case PLUGIN_USB_CONNECTED:
                return PLUGIN_USB_CONNECTED;
                break;
            case SUPERDOM_QUIT:
                return PLUGIN_OK;
                break;
        }
        compres.moves = superdom_settings.movesperturn;
        computer_war();
        gen_resources();
    }
    return PLUGIN_OK;
}