mille / mille.py

   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
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
#!/usr/bin/env python3
#
# Copyright 2012 Larry Hastings
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
# distribution.
#
#
# todo:
#
#
# write test for
#	* p1 draw/play Go
#	* p2 draw/play Accident
#	* p1 draw/play ExtraTank
#	* p2 draw/play OutOfGas
#	* p1 coup fourres with ExtraTank
#	* p1 should not be running! battle top is Accident!
#
# statistics to track:
#	* each card
#		* played
#		* discarded
#		* still in hand at end of game
#   * all scorable things (delayed, all four, extension)
#		* make object that represents a scorable thing,
#		  then use Counter to count them just like cards
#		* these objects then add themselves to your score!
#		  self-assembly!
#	* # of perfect games
#
# norman:
#	* if he can't play any of his cards but safeties,
#	  then at the end of the game he sees you discard,
#	  he'll play all his safeties.
#   * when deciding to continue,
#		* if by not continuing we will win the entire game, DON'T CONTINUE
#	    * if by not continuing they will win the entire game, CONTINUE
#		* consider how many safeties we/they have, Right Of Way counts 2x (3x?)
#		* consider the delta in miles
#
# smart computer player
#	* calculates odds on whether a card is still in the draw pile / in opponent's hand
#		* if both hazards have been seen, discard the remedy
#		* if both hazards have been seen, play the safety immediately
#			* even do that for Right-Of-Way (even though unlikely)
#		* discard hazards in order of how likely the opponent has the remedy / safety
#	* decides whether to continue based on how much mileage they have / is left
#
# store recordings, allow replaying the recordings for debugging
#
# write tests for scoring
#

from collections import Counter, namedtuple
import getpass
import itertools
import os
import pickle
import random
import sys
import time
import traceback
import unittest


savegame_revision = 1

series = None
game = None
hand = None

class IllegalMove(Exception):
	def __init__(self, card, reason=None):
		if isinstance(card, str):
			s = card
		elif card:
			s = "Can't play " + str(card) + reason
		else:
			s = None
		super().__init__(s)


sort_order = 0



class Card:
	__atoms = {}

	def __new__(cls):
		if cls not in cls.__atoms:
			o = object.__new__(cls)
			cls.__atoms[cls] = o
		return cls.__atoms[cls]

	def __init__(self):
		# detect that we're being re-initialized and skip it
		if hasattr(self, "sort_order"):
			return

		global sort_order
		sort_order += 1
		self.sort_order = sort_order

		self._str = self.__class__.__name__
		self.abbreviation = self._str[0:9]

	def __repr__(self):
		return "<" + self.__class__.__name__ + ">"

	def __str__(self):
		return self._str

	def __lt__(self, other):
		return self.sort_order < other.sort_order

	def __hash__(self):
		return self.sort_order

	def illegal(self, message):
		raise IllegalMove(self, message)

	def must_draw_first(self, player):
		if not hand.draw_pile:
			return
		if len(player.hand.hand) < 7:
			self.illegal(" yet, must draw first")

	def not_on_other(self, player, playee):
		if playee not in (player, series.discard):
			self.illegal(" on other players")

	def not_on_self(self, player, playee):
		if playee == player:
			self.illegal(" on yourself")

	def on_discard(self, playee):
		return playee == series.discard

	def not_on_discard(self, playee):
		if self.on_discard(playee):
			raise IllegalMove("Can't discard " + str(self))

	def playee_is_protected(self, playee):
		if ((not self.on_discard(playee))
			and (self.safety in playee.hand.safeties)):
			self.illegal(", player is protected by " + str(self.safety))

	def playee_is_not_rolling(self, player, playee):
		if (not self.on_discard(playee)) and (not playee.hand.rolling()):
			self.illegal(", " + playee.name + " is not rolling")

	def played(self, player, playee):
		self.pile(playee).append(self)


mileages = set()
hazards = set()
remedies = set()
safeties = set()

class Mileage(Card):
	def __init__(self):
		super().__init__()
		self.abbreviation = self._str = str(self.distance)
		global mileages
		mileages.add(self)

	def pile(self, playee):
		return playee.hand.mileage_pile

	def is_legal(self, player, playee, silent=False):
		self.must_draw_first(player)
		self.not_on_other(player, playee)
		self.playee_is_not_rolling(player, playee)

		if self.on_discard(playee):
			return

		mileage = playee.hand.mileage()
		limit = 1000 if hand.extended else 700
		if ((mileage < limit) and ((mileage + self.distance) > limit)):
			self.illegal(", it would take you over " + str(limit))

class Mileage25(Mileage):
	distance = 25

class Mileage50(Mileage):
	distance = 50

class HighMileage(Mileage):
	def is_legal(self, player, playee, silent=False):
		super().is_legal(player, playee, silent)
		if self.on_discard(playee):
			return
		if not playee.hand.autobahn():
			self.illegal(", speed limit in effect")

class Mileage75(HighMileage):
	distance = 75

class Mileage100(HighMileage):
	distance = 100

class Mileage200(HighMileage):
	distance = 200

	def is_legal(self, player, playee, silent=False):
		super().is_legal(player, playee, silent)
		if self.on_discard(playee):
			return
		if playee.hand.two_hundreds() == 2:
			self.illegal(", you can only play two per hand")


class Safety(Card):
	def __init__(self):
		super().__init__()
		self.categories = self.__class__.__bases__[1:]
		global safeties
		safeties.add(self)

	def pile(self, playee):
		return playee.hand.safeties

	def is_coup_fouree(self, playee):
		if not hand.plays:
			return False
		last_play = hand.plays[-1]
		last_card = last_play.card
		last_playee = last_play.playee
		return (isinstance(last_card, Hazard)
			and (last_card.safety is self)
			and (last_playee is playee)
			and (len(playee.hand.hand) == 6)
			)

	def is_legal(self, player, playee, silent=False):
		self.not_on_discard(playee)
		self.not_on_other(player, playee)

		if not self.is_coup_fouree(playee):
			self.must_draw_first(player)

	def played(self, player, playee):
		if self.is_coup_fouree(playee):
			last_card = hand.plays[-1].card
			pile = last_card.pile(playee)
			assert pile and pile[-1] == last_card
			del pile[-1]
			series.discard.pile.append(last_card)
			playee.hand.coups_fourres.append(self)
		super().played(player, playee)

class RightOfWay(Safety):
	abbreviation_6 = "ROfWay"
class PunctureProof(Safety):
	abbreviation_6 = "PProof"
class ExtraTank(Safety):
	abbreviation_6 = "ExTank"
class DrivingAce(Safety):
	abbreviation_6 = "DriAce"


class Hazard(Card):
	def __init__(self):
		super().__init__()
		self.safety = self.safety_class()
		global hazards
		hazards.add(self)

	def pile(self, playee):
		return playee.hand.battle_pile

	def is_legal_base(self, player, playee):
		self.must_draw_first(player)
		self.not_on_self(player, playee)

		if self.on_discard(playee):
			return
		if self.safety in playee.hand.safeties:
			self.illegal(", playee is protected by " + str(self.safety))

	def is_legal(self, player, playee, silent=False):
		self.is_legal_base(player, playee)
		if self.on_discard(playee):
			return

		top = playee.hand.normalized_battle_top()
		if top is None:
			self.illegal(", playee has not started rolling")
		elif (isinstance(top, Remedy)
			and (top is not roll)
			):
			self.illegal(", can't play a hazard on a remedy (" + str(top) + ") (unless they've played the safety)")
		elif isinstance(top, Hazard) and not silent:
			player.double_check(self, top)



class Stop(Hazard):
	safety_class = RightOfWay

class FlatTire(Hazard):
	safety_class = PunctureProof
	
class OutOfGas(Hazard):
	safety_class = ExtraTank
	
class Accident(Hazard):
	safety_class = DrivingAce


class SpeedLimit(Hazard):
	safety_class = RightOfWay

	def pile(self, playee):
		return playee.hand.speed_pile

	def is_legal(self, player, playee, silent=False):
		self.is_legal_base(player, playee)

		if self.on_discard(playee):
			return

		top = playee.hand.normalized_speed_top()
		if isinstance(top, SpeedLimit) and not silent:
			player.double_check(self, top)


class Remedy(Card):
	def __init__(self):
		super().__init__()
		self.safety = self.safety_class()
		self.hazard = self.hazard_class()
		global remedies
		remedies.add(self)

	def pile(self, playee):
		return playee.hand.battle_pile

	def is_legal(self, player, playee, silent=False):
		self.must_draw_first(player)
		self.not_on_other(player, playee)
		self.playee_is_protected(playee)

		if self.on_discard(playee):
			return

		pile = self.pile(playee)
		on_hazard = pile
		if on_hazard:
			top = pile[-1]
			on_hazard = top == self.hazard
		if not on_hazard:
			raise IllegalMove(self, ", can only play on top of " + str(self.hazard))

class SpareTire(Remedy):
	safety_class = PunctureProof
	hazard_class = FlatTire

class Gasoline(Remedy):
	safety_class = ExtraTank
	hazard_class = OutOfGas
	
class Repair(Remedy):
	safety_class = DrivingAce
	hazard_class = Accident
	

class Roll(Remedy):
	safety_class = RightOfWay
	hazard_class = Stop

	def is_legal(self, player, playee, silent=False):
		self.must_draw_first(player)
		self.not_on_other(player, playee)

		if self.on_discard(playee):
			return

		if right_of_way in playee.hand.safeties:
			raise IllegalMove(self, ", player already has right-of-way")
		pile = self.pile(playee)
		if not pile:
			return
		top = pile[-1]
		if not ((top is stop)
			or (isinstance(top, Remedy) and (top is not roll))
			or (isinstance(top, Hazard) and top.safety in playee.hand.safeties)):
			raise IllegalMove(self, ", can only play on top of remedy or Stop (or after safety for top hazard)")

class EndOfLimit(Remedy):
	safety_class = RightOfWay
	hazard_class = SpeedLimit

	def pile(self, playee):
		return playee.hand.speed_pile


 
right_of_way   = RightOfWay()
puncture_proof = PunctureProof()
extra_tank     = ExtraTank()
driving_ace    = DrivingAce()

speed_limit    = SpeedLimit()
stop           = Stop()
flat_tire      = FlatTire()
out_of_gas     = OutOfGas()
accident       = Accident()

end_of_limit   = EndOfLimit()
roll           = Roll()
spare_tire     = SpareTire()
gasoline       = Gasoline()
repair         = Repair()

# now wire up the backwards edges of the safety -> hazard -> remedy DAG

stop.remedy        = roll
speed_limit.remedy = end_of_limit
flat_tire.remedy   = spare_tire
out_of_gas.remedy  = gasoline
accident.remedy    = repair

driving_ace.hazard    = accident
driving_ace.remedy    = repair
extra_tank.hazard     = out_of_gas
extra_tank.remedy     = gasoline
puncture_proof.hazard = flat_tire
puncture_proof.remedy = spare_tire
right_of_way.hazard   = speed_limit # used by Moriarty
right_of_way.remedy   = end_of_limit # used by Moriarty

mileage_200    = Mileage200()
mileage_100    = Mileage100()
mileage_75     = Mileage75()
mileage_50     = Mileage50()
mileage_25     = Mileage25()


deck = []
def add(card, count=1):
	deck.extend([card] * count)

add(mileage_200,  4)
add(mileage_100, 12)
add(mileage_75,  10)
add(mileage_50,  10)
add(mileage_25,  10)

for hazard, remedy, safety in (
	(out_of_gas, gasoline,   extra_tank),
	(accident,   repair,     driving_ace),
	(flat_tire,  spare_tire, puncture_proof),
	):
	add(hazard, 3)
	add(remedy, 6)
	add(safety)

add(speed_limit,  4)
add(end_of_limit, 6)

add(stop,  5)
add(roll, 14)
add(right_of_way)

del add


card_to_int = {
	mileage_200: 200,
	mileage_100: 100,
	mileage_75:   75,
	mileage_50:   50,
	mileage_25:   25,
}

card_to_string = {
	mileage_25  : "mileage_25",
	mileage_50  : "mileage_50",
	mileage_75  : "mileage_75",
	mileage_100 : "mileage_100",
	mileage_200 : "mileage_200",

	accident : "accident",
	repair : "repair",
	driving_ace : "driving_ace",

	flat_tire : "flat_tire",
	spare_tire : "spare_tire",
	puncture_proof : "puncture_proof",

	out_of_gas : "out_of_gas",
	gasoline : "gasoline",
	extra_tank : "extra_tank",

	stop : "stop",
	roll : "roll",
	right_of_way : "right_of_way",

	speed_limit : "speed_limit",
	end_of_limit : "end_of_limit",
}

# to_card maps either a string or an int into the matching card
to_card = {}
for d in (card_to_string, card_to_int):
	to_card.update({value: card for (card, value) in d.items()})
	to_card.update({ card: card for card in d})


# now let card_to_string and card_to_int also return the string/int
# if passed in
card_to_string.update({value: value for value in card_to_string.values()})
card_to_int.update(   {value: value for value in card_to_int.values()})



cardinal = "zero one two three four five".split().__getitem__

class Score:

	mileage = 0
	safeties = 0
	coups_fourres = 0

	trip_complete = False
	delayed_action = False
	safe_trip = False
	shutout = False

	def __init__(self, player, as_if_won=False):
		self.mileage = player.hand.mileage()

		self.safeties = len(player.hand.safeties)
		self.coups_fourres = len(player.hand.coups_fourres)

		if (
			  as_if_won
			  or (self.mileage == (1000 if hand.extended else 700))
			):
			self.trip_complete = True
			self.extension = self.mileage == 1000
			self.delayed_action = not len(hand.draw_pile)
			self.safe_trip = not player.hand.two_hundreds()
			self.shutout = not player.others[0].hand.mileage()

	def __repr__(self):
		return " ".join((str(x) for x in (
			"<Score",
			self.mileage,
			"safeties",
			self.safeties, self.coups_fourres,
			"complete",
			"NY"[self.trip_complete],
			"da", "NY"[self.delayed_action],
			"st", "NY"[self.safe_trip],
			"so", "NY"[self.shutout],
			))) + ">"

	def render(self):
		array = []
		def add(points, *a):
			nonlocal array
			if not points:
				return
			s = ' '.join(str(x) for x in a)
			array.append((points, s.rjust(19) + ' ... ' + str(points).rjust(4)))

		add(self.mileage, self.mileage, "miles")

		safeties = self.safeties 
		add(safeties * 100, cardinal(safeties), "safet" + ("y" if safeties == 1 else "ies"))
		if safeties == 4:
			add(300, "all four safeties")
		coups = self.coups_fourres
		add(coups * 300, cardinal(coups), "coup{s} fourré{s}".format(s="" if coups == 1 else "s"))

		if self.trip_complete:
			add(400, "trip complete")
			if self.mileage == 1000:
				add(200, "extension")
			if self.delayed_action:
				add(300, "delayed action")
			if self.safe_trip:
				add(300, "safe trip (no 200s)")
			if self.shutout:
				add(500, "shut-out")

		return array

	@property
	def total(self):
		return sum((x[0] for x in self.render()))

	def __str__(self):
		return "\n".join((x[1] for x in self.render()))

	@property
	def statistics(self):
		return {
			"mileage": self.mileage,
			"0 safeties": self.safeties == 0,
			"1 safeties": self.safeties == 1,
			"2 safeties": self.safeties == 2,
			"3 safeties": self.safeties == 3,
			"4 safeties": self.safeties == 4,
			"0 coups fourrés": self.coups_fourres == 0,
			"1 coups fourrés": self.coups_fourres == 1,
			"2 coups fourrés": self.coups_fourres == 2,
			"3 coups fourrés": self.coups_fourres == 3,
			"4 coups fourrés": self.coups_fourres == 4,
			"trips_completed": self.trip_complete,
			"extensions": self.trip_complete and (self.mileage == 1000),
			"delayed_actions": self.delayed_action,
			"safe_trips": self.safe_trip,
			"shutouts": self.shutout,
			"perfect_games": self.total == 4600,
		}
		return { k: int(v) for k, v in d.items() }


class Play:

	def __init__(self, card, player, playee):
		self.card = card
		self.player = player
		self.playee = playee


class CardCounter(Counter):
	def add(self, cards):
		if isinstance(cards, Card):
			cards = [cards]
		for card in cards:
			self[card] += 1



class PlayerData:
	def __init__(self, player):
		self.player = player
		self.score = 0
		self.drawn = CardCounter()
		self.played = CardCounter()
		self.discarded = CardCounter()
		self.unplayed = CardCounter()

	def game_start(self):
		pass

	def score_game(self, winner):
		pass

	def game_end_ui(self, winner):
		pass

	def game_end(self):
		pass

	def hand_start(self):
		pass

	def score_hand(self, winner):
		pass

	def hand_end_ui(self, winner):
		pass

	def hand_end(self):
		pass

	def update_statistics(self, src):
		for attr in "discarded drawn played unplayed".split():
			s = getattr(src, attr)
			d = getattr(self, attr)
			d.update(s)


class SeriesPlayerData(PlayerData):
	"""
	The data for a player in a Series.
	"""

	def __init__(self, player):
		super().__init__(player)
		self.games_won = 0
		self.hands_won = 0
		self.shutouts = 0
		self.highest_score = 0

	def score_game(self, winner):
		if winner == self.player:
			self.games_won += 1
		g = self.player.game
		score = g.score
		self.score += score
		self.highest_score = max(self.highest_score, score)

	def score_hand(self, winner):
		if winner == self.player:
			self.hands_won += 1
			if not winner.others[0].hand.mileage():
				self.shutouts += 1
		self.update_statistics(self.player.hand)
		



class GamePlayerData(PlayerData):

	def score_hand(self, winner):
		h = self.player.hand
		self.score += h.score.total
		self.update_statistics(h)


class HandPlayerData(PlayerData):

	def __init__(self, player):
		super().__init__(player)

		self.score = None
		self.hand = []
		self.mileage_pile = []
		self.battle_pile = []
		self.speed_pile = []
		self.safeties = []
		self.coups_fourres = []

	def score_hand(self, winner):
		self.score = Score(self.player)
		self.unplayed.add(self.hand)

	def sort(self):
		self.hand.sort(reverse=True)

	def draw(self, card=None):
		assert len(self.hand) <= 7
		if not hand.draw_pile:
			return None

		if card is None:
			card = hand.draw_pile.pop()
		else:
			card = to_card[card]
			hand.draw_pile.remove(card)
		self.hand.append(card)
		self.drawn.add(card)
		return card

	def discard(self, card):
		self.play(card, series.discard)

	def is_legal(self, card, playee=None, silent=False):
		playee = playee or self.player
		to_card[card].is_legal(self.player, playee, silent)

	def play(self, card, playee=None):
		card = to_card[card]
		playee = playee or self.player
		self.is_legal(card, playee)
		playee.played(card, self)
		self.hand.remove(card)
		if playee is series.discard:
			self.discarded.add(card)
		else:
			self.played.add(card)

	# only used for testing
	def draw_and_play(self, card, playee = None):
		self.play(self.draw(card), playee)

	def draw_and_discard(self, card):
		self.discard(self.draw(card))

	def normalized_battle_top(self):
		"""
		Returns effective top of battle pile once safeties are taken into effect.
		 * if, all things considered, we're rolling, return roll.
		 * if top is a hazard but we've played the safety (non-coup fourre),
		   and we don't have Right-Of-Way,
		   then return the safety's corresponding remedy.
		"""
		row = roll if right_of_way in self.safeties else None
		if not self.battle_pile:
			return row

		top = self.battle_pile[-1]
		if top is roll:
			return top
		if isinstance(top, Remedy):
			return row or top
		assert isinstance(top, Hazard)
		safety = top.safety
		if safety in self.safeties:
			return row or top.remedy
		return top

	def rolling(self):
		return self.normalized_battle_top() == roll

	def normalized_speed_top(self):
		"""
		Same idea as normalized_battle_top but for the speed pile.
		"""
		row = right_of_way in self.safeties
		if (not self.speed_pile) or row:
			return end_of_limit
		return self.speed_pile[-1]

	def autobahn(self):
		row = right_of_way in self.safeties
		if (not self.speed_pile) or row:
			return True
		return self.speed_pile[-1] == end_of_limit

	def mileage(self):
		return sum((card.distance for card in self.mileage_pile))

	def two_hundreds(self):
		return len([card for card in self.mileage_pile if card.distance == 200])

	def won(self):
		mileage = self.mileage()
		return ((mileage == 1000)
			or ((mileage == 700) and (not hand.extended)))



class Player:

	"""
	Abstract base class for players.
	"""

	name = None

	def __init__(self, name=None):
		self.name = name or self.__class__.name
		self.series = SeriesPlayerData(self)
		self.game = None
		self.hand = None

	def __repr__(self):
		return "".join(("<", self.__class__.__name__ ," ", str(self.name), ">"))

	@property
	def others(self):
		l = list(series.players)
		l.remove(self)
		return l

	def turn(self):
		pass

	# self is the playee
	def played(self, card, player):
		card = to_card[card]
		card.played(player, self)
		hand.plays.append(Play(card, player, self))

	def double_check(self, card, top):
		pass

	#
	# for prefix in ("game", "hand") :
	#   prefix + "_start" is called when {prefix} starts
	#   "score_" + prefix is called to calculate the score at the end of {prefix}
	#	prefix + "_end_ui" is called to present the calculated scores to the user
	#   prefix + "_end" is called for final cleanup of {prefix}

	def game_start(self):
		self.game = GamePlayerData(self)

	def score_game(self, winner):
		pass

	def game_end_ui(self, winner):
		pass

	def game_end(self):
		self.game = None

	def hand_start(self):
		self.hand = HandPlayerData(self)

	def score_hand(self, winner):
		pass

	def hand_end_ui(self, winner):
		pass

	def hand_end(self):
		self.hand = None



class DiscardPile(Player):

	name = "discard pile"

	def __init__(self):
		super().__init__()
		self.series = None

	def game_start(self):
		pass

	hand_start = hand_end = game_end = game_start

	def hand_start(self):
		self.pile = []

	def hand_end(self):
		self.pile = None

	def played(self, card, player):
		card = to_card[card]
		self.pile.append(card)
		hand.plays.append(Play(card, player, self))

	def other(self):
		raise RuntimeError("DiscardPile isn't a normal player")

	def turn(self):
		raise RuntimeError("DiscardPile doesn't take a turn")




class DumbComputerPlayer(Player):

	"""
	Rosey is the dumbest player who could play a legal game.

	On every turn she shuffles her cards.
	Shen then tries each in order.
	If she finds a card that is legally playable, she plays it--
		unless it's redundant (plays hazards only when stopped, plays
		speed limit only if you don't already have one)
	If she finds no legally playable cards, she discards a card at random.
	(She will never discard a safety, because safeties are always legally playable.)
	She extends if half the cards remain in the draw pile.

	(Rosey is named for the Jetsons' housemaid.)
	"""

	name = "Rosey"

	def double_check(self, card, top):
		raise IllegalMove("du-uh, nevermind")

	def turn(self):
		self.hand.draw()
		cards = list(self.hand.hand)
		random.shuffle(cards)
		for card in cards:
			try:
				self.hand.play(card, playee)
				print("    du-uh, played", card, "on", "herself" if playee == self else "you")
				if self.hand.won() and self.hand.mileage() == 700:
					extending = len(hand.draw_pile) > (len(hand.original_deck) // 2)
					if extending:
						print()
						print("    ------------------------")
						print("    du-uh, extending to 1000")
						print("    ------------------------")
						print()
						hand.extended = True
					else:
						print("    du-uh, not extending")
				break
			except IllegalMove:
				continue
		else:
			card = cards[0]
			self.hand.discard(card)
			print("du-uh, discarded", card)


class AverageComputerPlayer(Player):
	"""
	"Norman" is a reasonably sophisticated player.

	* doesn't count cards
	* understands coup fouree
	* when playing, prefers in order of preference:
		* winning
		* damage
		* remedies
		* mileage
   	* when discarding, prefers:
	    * 200s if already played 2
		* hazards for safeties opponent already played
		* remedies for safeties already played
		* remedies for safeties not yet played
		* remedies for which you have 2 or more
		* mileage (lowest to highest)
		* remedies of which you have only one
		* hazards of which you have 2
		* hazards of which you have 1
   	* don't play speed limit / safeties until discarding
		random(5%, 10%) (% of remaining cards in draw pile)
	    cards in a row
   	* smart about playing mileage >= 550

   	(Norman is named for the head android from "I, Mudd".)
	"""

	name = "Norman"

	def print(self, *a):
		print("    hmm,", *a)

	def debug(self, *a):
		print("        //", *a)


	def hand_start(self):
		super().hand_start()
		self.hand.safety_countdown = 0
		self.hand.play_safety = False
		self.hand.discardables = set()

	def check_for_coup_fouree(self, debug):
		if not hand.plays:
			return False

		play = hand.plays[-1]
		if not ((play.playee == self)
			and isinstance(play.card, Hazard)):
			return False

		safety = play.card.safety
		if safety in self.hand.hand:
			self.print("coup fourré!")
			self.play(safety)
			self.hand.draw()
			return True
		return False

	def card_to_get_moving(self):
		if self.hand.rolling():
			return None

		if not self.hand.battle_pile:
			return roll

		top = self.hand.battle_pile[-1]
		if isinstance(top, Hazard):
			safety = top.safety
			if safety in self.hand.safeties:
				return roll
			return top.remedy

		assert isinstance(top, Remedy)
		return roll

	def _decide_to_extend(self):
		# shutout?  hot damn!
		# don't chance the extend, take the points!
		other = self.others[0]
		if not other.hand.mileage():
			return True

		other_safeties = other.hand.safeties
		extend_if = (
			# we have half or more of the cards remining in the draw pile
			(len(hand.draw_pile) > (len(hand.original_deck) // 2))
			# and they don't have right_of_way
			and (right_of_way not in other_safeties)
			# or 2 or more safeties
			and (len(other_safeties) <= 2)
			)
		return extend_if

	def decide_to_extend(self):
		if self.hand.won() and self.hand.mileage() == 700:
			if self._decide_to_extend():
				print()
				print("    ----------------------")
				print("    hmm, extending to 1000")
				print("    ----------------------")
				print()
				hand.extended = True
				return True
			else:
				print("    hmm, not extending")
		return False


	def smart_mileage_play(self, cards):
		if not cards:
			return None

		mileage = self.hand.mileage()
		limit = 1000 if hand.extended else 700

		# if we're not near winning, play biggest card.
		if mileage < (limit - 150):
			return cards[-1]

		# if we have a mileage ending in 25 or 75,
		# try to get to a 50 or 100
		def can_play(card):
			return (card in cards) and ((mileage + card.distance) < limit)

		if mileage % 10:
			# ends in 25 or 75
			if can_play(mileage_75):
				return mileage_75
			if mileage_25 in cards:
				return mileage_25
			# not safe to play anything
			return None
		
		# if we can play a 50 or a 100, do it
		if can_play(mileage_100):
			return mileage_100
		if can_play(mileage_50):
			return mileage_50
		
		# if we have two cards ending in a 5, play the higher one
		if can_play(mileage_75) and (len([x for x in cards if x == mileage_75]) >= 2):
			return mileage_75
		if can_play(mileage_75) and (mileage_25 in cards):
			return mileage_75
		if (len([x for x in cards if x == mileage_25]) >= 2):
			return mileage_25
		
		return None

	def double_check(self, card, top):
		raise RuntimeError("hmm, Norman should never do this")

	def play(self, card, playee=None):
		addendum = ""
		if playee == series.discard:
			verb = "discarding"
		else:
			verb = "playing"
			if playee == self.others[0]:
				addendum = "on you"
		print("    hmm,", verb, card, addendum)
		self.hand.play(card, playee)
		self.decide_to_extend()

	def discard(self, card):
		self.play(card, series.discard)

	def turn(self):
		debug = self.debug

		self.check_for_coup_fouree(debug)
		drew = self.hand.draw()
		debug("drew", drew)

		safety_countdown = self.hand.safety_countdown
		self.hand.safety_countdown = 0
		play_safety = self.hand.play_safety
		self.hand.play_safety = False

		preferred_hazards = []
		hazards = []
		stops = []
		limits = []
		remedies = []
		rolls = []
		end_of_limits = []
		mileage = []
		safeties = []
		preferred_discards = []
		discards = []
		tertiary_discards = []

		def randomly_play_one(cards, debug_step, playee=None):
			if not cards:
				return False
			debug(debug_step)
			random.shuffle(cards)
			self.play(cards[0], playee)
			return True

		def randomly_discard_one(cards, debug_step):
			if not cards:
				return False
			debug(debug_step)
			random.shuffle(cards)
			self.discard(cards[0])
			return True

		def randomly_discard_one_if_duplicates(cards, debug_step):
			if not cards:
				return False
			random.shuffle(cards)
			for card, count in Counter(cards).items():
				if count >= 2:
					debug(debug_step)
					self.discard(card)
					return True
			return False

		other = self.others[0]

		all_my_safeties = set(self.hand.safeties) | set((x for x in self.hand.hand if isinstance(x, Safety)))

		limit = 1000 if hand.extended else 700
		mileage_so_far = self.hand.mileage()
		maxed_out_200s = self.hand.two_hundreds() == 2
		debug("cards", " ".join([card.abbreviation for card in self.hand.hand]))
		debug("limit", limit, "mileage", mileage, "maxed_out_200s", maxed_out_200s)
		for card in self.hand.hand:
			if card in self.hand.discardables:
				debug(card, "-> preferred_discards (in discardables)")
				preferred_discards.append(card)
			elif isinstance(card, Hazard):
				if card.safety in other.hand.safeties:
					debug(card, "-> preferred_discards")
					preferred_discards.append(card)
				elif card == speed_limit:
					debug(card, "-> limits")
					limits.append(card)
				elif card == stop:
					debug(card, "-> stops")
					stops.append(card)
				elif card.safety in all_my_safeties:
					debug(card, "-> preferred_hazards")
					preferred_hazards.append(card)
				else:
					debug(card, "-> hazards")
					hazards.append(card)
			elif isinstance(card, Remedy):
				if card.safety in self.hand.safeties:
					debug(card, "-> preferred_discards")
					preferred_discards.append(card)
				elif card == roll:
					# never discard rolls out-of-hand
					# if we haven't played ROW yet
					debug(card, "-> rolls")
					rolls.append(card)
				elif card == end_of_limit:
					# never discard end-of-limit out-of-hand
					# if we haven't played ROW yet
					debug(card, "-> end_of_limits")
					end_of_limits.append(card)
				elif card.safety in all_my_safeties:
					debug(card, "-> discards")
					discards.append(card)
				else:
					debug(card, "-> remedies")
					remedies.append(card)
			elif isinstance(card, Mileage):
				if (card.distance == 200) and maxed_out_200s:
					debug(card, "-> preferred_discards")
					preferred_discards.append(card)
				elif (mileage_so_far + card.distance) > limit:
					debug(card, "-> tertiary_discards")
					tertiary_discards.append(card)
				else:
					debug(card, "-> mileage")
					mileage.append(card)
			elif isinstance(card, Safety):
				debug(card, "-> safeties")
				safeties.append(card)

		self.hand.discardables.update(preferred_discards)

		mileage.sort(key=lambda x: x.distance)
		safeties.sort()

		##################################################
		##################################################
		##
		## priority 0: if we're one card away from winning,
		## we probably want to win right now.
		##

		they_can_win = other.hand.rolling()
		if they_can_win:
			other_mileage = other.hand.mileage()
			if other_mileage >= 700:
				other_mileage -= 300
			possibles = {25, 50}
			if other.hand.autobahn():
				possibles.add(75)
				possibles.add(100)
				if other.hand.two_hundreds() < 2:
					possibles.add(200)
			they_can_win = (700 - other_mileage) in possibles

		# are we moving?
		safeties_needed_to_win = set()
		card_to_win = None
		we_can_win = self.hand.rolling()
		debug("P0.a", we_can_win)

		if not we_can_win:
			# can we get moving?
			needed = self.card_to_get_moving()
			assert needed
			we_can_win = ((needed.safety in all_my_safeties)
				and (right_of_way in all_my_safeties))
			if we_can_win:
				safeties_needed_to_win.add(needed.safety)
				if right_of_way not in self.hand.safeties:
					safeties_needed_to_win.add(right_of_way)
			debug("P0.b", we_can_win, safeties_needed_to_win)

		if we_can_win:
			# do we have the mileage card we'd need to play?
			limit = 1000 if hand.extended else 700
			card_to_win = to_card.get(limit - mileage_so_far)
			we_can_win = card_to_win in mileage
			debug("P0.c", card_to_win, we_can_win)

		if we_can_win:
			# will a speed limit prevent us from playing it?
			we_can_win = (
				(card_to_win.distance <= 50)
				or self.hand.autobahn()
				)
			if not we_can_win and (right_of_way in self.hand.hand):
				we_can_win = True
				safeties_needed_to_win.add(right_of_way)

			debug("P0.d", we_can_win, safeties_needed_to_win)

		extending = False
		if we_can_win:
			# would we want to extend?  and, if so, would we have
			# to play safeties in order to win?
			extending = (not hand.extended) and self._decide_to_extend()
			if (extending and safeties_needed_to_win):
				# if so, hold off on winning unless the
				# other player is in striking distance of winning.
				we_can_win = they_can_win
			debug("P0.e", we_can_win)

		if we_can_win:
			# we can win, and we've decided we want to.
			# first, play all the safeties we're going to.
			# * if we're ending the game, play all safeties,
			#   including ones we draw while playing safeties!
			# * if we're extending, only play the safeties
			#   necessary for us to play the mileage and win.
			safeties_to_play = safeties_needed_to_win if extending else safeties
			while safeties_to_play:
				next = set()
				for safety in safeties_to_play:
					debug("P0.f")
					self.play(safety)
					drew = self.hand.draw()
					debug("drew", drew)
					if extending and isinstance(drew, Safety):
						next.add(drew)
				safeties_to_play = next
			debug("P0.g")
			was_unextended = not hand.extended
			self.play(card_to_win)
			assert self.hand.won() or (was_unextended and hand.extended)
			return

		################################################################
		################################################################
		##
		## priority 1: if other is rolling, stop them or slow them down;
		## otherwise, if they're within striking distance of the limit,
		## play all our safeties, both to ensure we get their points,
		## and to get more cards so we can try to stop them.
		##

		if other.hand.rolling():
			for cards in (preferred_hazards, hazards, stops):
				if cards:
					randomly_play_one(cards, "P1.a", other)
					return
		
			if other.hand.autobahn() and limits:
				debug("P1.b")
				self.play(speed_limit, other)
				return

			other_mileage = other.hand.mileage()
			if other_mileage >= 700:
				other_mileage -= 300
			possibles = {25, 50}
			if other.hand.autobahn():
				possibles.add(75)
				possibles.add(100)
				if other.hand.two_hundreds() < 2:
					possibles.add(200)
			if ((700 - other_mileage) in possibles) and safeties:
				debug("P1.c")
				self.play(safeties[0])
				return self.turn()

		##################################################
		##################################################
		##
		## priority 2: if we are not rolling, get rolling.
		##

		if not self.hand.rolling():
			needed = self.card_to_get_moving()
			assert needed
			debug("P2:", needed)
			if needed == roll:
				if rolls:
					debug("P2.a")
					self.play(roll)
					return
			elif needed in remedies:
				debug("P2.b")
				self.play(needed)
				return
			elif (needed.safety in safeties) and rolls:
				# go ahead and forego the coup fourre
				# if we can get moving immediately.
				debug("P2.c")
				self.play(needed.safety)
				return self.turn()

		##########################################################
		##########################################################
		##
		## priority 3: if we are rolling, and we have 0 miles,
		## play any viable mileage card so as to prevent shut-out.
		##

		if self.hand.rolling() and not self.hand.mileage() and mileage:
			if self.hand.autobahn():
				debug("P3.a")
				self.play(mileage[-1])
				return
			if mileage_50 in mileage:
				debug("P3.b")
				self.play(mileage_50)
				return
			if mileage[0] == mileage_25:
				debug("P3.c")
				self.play(mileage_25)
				return
		
		##################################
		##################################
		##
		## priority 4: remove speed limits
		##

		if not self.hand.autobahn() and end_of_limits:
			debug("P4")
			self.play(end_of_limit)
			return
		
		###########################
		###########################
		##
		## priority 5: play mileage
		##

		if mileage and self.hand.rolling():
			play_from = mileage
			if not self.hand.autobahn():
				low_mileage = [x for x in mileage if x.distance <= 50]
				play_from = low_mileage
			card = self.smart_mileage_play(play_from)
			if card:
				debug("P5")
				self.play(card)
				return

		##############################################
		##############################################
		##
		## priority 6: if we've discarded for too long
		## and we have a speed limit or safety,
		## play the speed limit or safety
		##
		## (and if it's a safety, recurse)
		##

		debug("P6:", play_safety, safety_countdown)
		if play_safety:
			if limits and other.hand.autobahn():
				debug("P6.a")
				self.play(speed_limit, other)
				return
			if safeties:
				# prefer to play any other safety to Right Of Way
				row = right_of_way in safeties
				if row:
					safeties.remove(right_of_way)
				if safeties:
					randomly_play_one(safeties, "P6.b")
					return self.turn()
				if row:
					debug("P6.c")
					self.play(right_of_way)
					return self.turn()
			self.hand.play_safety = True
		elif safety_countdown:
			safety_countdown -= 1
			if not safety_countdown:
				self.hand.play_safety = True
			else:
				self.hand.safety_countdown = safety_countdown
		else:
			cards_remaining = len(hand.draw_pile)
			self.hand.safety_countdown = random.randint(int(cards_remaining * 0.05), int(cards_remaining * 0.1))

		###################################################
		###################################################
		##
		## priority 7: discard a card we know we don't want
		## P7.a, P7.b, P7.c
		##

		discard_preferences = (preferred_discards, discards, tertiary_discards)
		for i, cards in enumerate(discard_preferences):
			if cards:
				randomly_discard_one(cards, "P7." + "abc"[i])
				return

		###################################################
		###################################################
		##
		## priority 8: discard a card we might someday want
		##

		remedy_preferences = (end_of_limits, remedies, rolls)
		hazard_preferences = (hazards, stops, limits, preferred_hazards)

		# remedies for which we have two or more
		for cards in remedy_preferences:
			if randomly_discard_one_if_duplicates(cards, "P8.a"):
				return

		# mileage
		if mileage:
			# if we're one card away from winning,
			# don't discard it here
			if card_to_win in mileage:
				debug("P8.b.1")
				mileage.remove(card_to_win)
			if mileage:
				debug("P8.b.2")
				self.discard(mileage[0])
				return

		# remedies of which you have only one
		if remedies:
			randomly_discard_one(remedies, "P8.c")
			return
		
		# hazards
		for cards in hazard_preferences:
			if randomly_discard_one_if_duplicates(cards, "P8.d"):
				return
		for cards in hazard_preferences:
			if cards:
				randomly_discard_one(cards, "P8.e")
				return

		# I give up!

		# if all we have left is safeties, play them all.
		# (don't compare them directly, the ordering may
		# be different.)
		if len(safeties) == len(self.hand.hand):
			# note: if all we we have is safeties,
			# then we have 4 or fewer cards in our hand,
			# which means the draw pile is empty,
			# which means I don't bother drawing.
			assert not hand.draw_pile
			for card in safeties:
				debug("P9.a")
				self.play(card)
				return

		# discard *something* none-safety-ish.
		non_safeties = [card for card in self.hand.hand if not isinstance(card, Safety)]
		if non_safeties:
			randomly_discard_one(non_safeties, "P9.b")
		
		debug("no possible plays.")




class Scenario:

	mileage_25  = 1
	mileage_50  = 1
	mileage_75  = 1
	mileage_100 = 1
	mileage_200 = 1
	mileage_repetition_multiplier = 0.5

	accident = flat_tire = out_of_gas = 1
	hazard_repetition_multiplier = 0.5

	speed_limit = 1
	speed_limit_repetition_multiplier = 0.5

	repair = spare_tire = gasoline = 1
	remedy_repetition_multiplier = 0.5

	end_of_limit = 1
	end_of_limit_repetition_multiplier = 0.5

	stop = 1
	stop_repetition_multiplier = 0.5

	roll = 1
	roll_repetition_multiplier = 0.5

	driving_ace = 1
	puncture_proof = 1
	extra_tank = 1
	right_of_way = 1
	safety_repetition_multiplier = 1

	repetition_multiplier = 0.5

	def weight(self, card):
		return getattr(self, card_to_string[card])

	card_repetition_multiplier_map = {
		mileage_25  : "mileage_repetition_multiplier",
		mileage_50  : "mileage_repetition_multiplier",
		mileage_75  : "mileage_repetition_multiplier",
		mileage_100 : "mileage_repetition_multiplier",
		mileage_200 : "mileage_repetition_multiplier",

		accident   : "hazard_repetition_multiplier",
		flat_tire  : "hazard_repetition_multiplier",
		out_of_gas : "hazard_repetition_multiplier",

		speed_limit : "speed_limit_repetition_multiplier",

		repair     : "remedy_repetition_multiplier",
		spare_tire : "remedy_repetition_multiplier",
		gasoline   : "remedy_repetition_multiplier",

		end_of_limit : "end_of_limit_repetition_multiplier",

		stop : "stop_repetition_multiplier",

		roll : "roll_repetition_multiplier",

		driving_ace    : "safety_repetition_multiplier",
		puncture_proof : "safety_repetition_multiplier",
		extra_tank     : "safety_repetition_multiplier",
		right_of_way   : "safety_repetition_multiplier",
		
	}

	def card_repetition_multiplier(self, card):
		return getattr(self, self.card_repetition_multiplier_map[card])

	def drew(card):
		pass

	def played(card):
		pass

	def discarded(card):
		pass



class SmartComputerPlayer(AverageComputerPlayer):
	"""
	Moriarty is as smart as I can make him.
	His main achievement over Norman is that he counts cards
	and calculates odds.

	(Moriarty is named for the machine intelligence that escaped
	from the holodeck on the NCC 1701-D.)
	"""

	name = "Moriarty"

	def __init__(self):
		super().__init__()

	def odds_that_opponent_has_card(self, card, on_next_turn=True):
		# If there are D cards in the draw pile,
		# and the opponent has C cards in their hand (normally 5),
		# and there are N of this particular card yet unplayed,
		# then the odds that the opponent has at least one of that card are
		#   1 - (D-N/D)*(D-(N+1)/D-1)*...*(D-(N+C)/D-C)
		# (thanks to Dan Peek, Steve Hastings, and Ben Mathews!)

		self.update_seen()

		remaining = hand.total_cards[card] - hand.seen_cards[card]
		if not remaining:
			return 0

		hand_size = len(self.others[0].hand.hand) + bool(hand.draw_pile and on_next_turn)
		all_cards = len(hand.draw_pile) + hand_size + 1  # the + 1 fixes off-by-ones for range

		# special case: if we only care about one card, the math is easy.
		if remaining == 1:
			return hand_size / all_cards

		any_other_card = all_cards - remaining

		numerators = range(any_other_card - hand_size, any_other_card)
		denominators = range(all_cards - hand_size, all_cards)

		if remaining < hand_size:
			# the ranges overlap!
			# that means they must have numbers in common.
			# remove these common factors to make the operands smaller.
			numerators = set(numerators)
			denominators = set(denominators)
			common = numerators & denominators
			assert common
			numerators -= common
			denominators -= common

		numerator = functools.reduce(operator.mul, numerators)
		denominator = functools.reduce(operator.mul, denominators)

		# remove irrelevant powers of two.
		# this losslessly shrinks the numerator and denominator,
		# and with the sorts of numbers we work with in mille
		# they'll now always fit in a 32-bit int--the idea is
		# this'll be kinder to the conversion to double
		mask = 3
		shift = 2
		while mask:
			orred = numerator | denominator
			if orred & mask:
				mask >>= 1
				shift -= 1
				continue
			numerator >>= shift
			denominator >>= shift

		return 1.0 - (numerator / denominator)

	tracked_hazards = (accident, flat_tire, out_of_gas, speed_limit)

	def hand_start(self):
		super().hand_start()
		self.scanned = 0

		# maximum # of that card we should hold in our hand
		cards_total = hand.cards_total
		self.maximums = Counter(hand.original_deck)
		self.maximums[roll] = cards_total[stop]
		for hazard in self.tracked_hazards:
			hazard_count = cards_total[hazard]
			self.maximums[hazard.safety] = hazard_count
			self.maximums[hazard.remedy] = hazard_count
			if hazard is not speed_limit:
				self.maximums[roll] += hazard_count
		self.maximums[right_of_way] = cards_total[speed_limit] + cards_total[stop]

	def update_scan(self):
		hand.update_scan()
		other = self.others[0]
		discard = series.discard
		for play in hand.plays[self.scanned:]:
			if play.player is self:
				continue
			card = play.card
			playee = play.playee
			if playee is discard:
				self.discards.add(card)
				if card in self.tracked_hazards:
					self.maximums[card.remedy] -= 1
					self.maximums[card.safety] -= 1
					if card is not speed_limit:
						self.maximums[roll] -= 1
				elif card is stop:
					self.maximums[roll] -= 1
		self.scanned = len(hand.plays)


	def manage_25_and_75(self, weights):
		if self.mileage() % 50 == 25:
			weights[mileage_25] *= 1.5
			weights[mileage_75] *= 1.5
		else:
			weights[mileage_25] *= 0.75
			weights[mileage_75] *= 0.5

	def preserve_safe_trip(self, weights):
		if not self.hand.two_hundreds():
			weights[mileage_200] *= 0.75


	def draw(self):
		self.update_scan()
		card = super().draw()
		if card is right_of_way:
			# TODO fix here
			pass
		elif isinstance(card, Safety):
			decrement = 2
			if self.hand.battle_pile and self.hand.battle_pile[-1] == card.hazard:
				decrement = 1
			self.maximums[card.remedy] -= decrement

			outstanding_hazards = hand.total_cards[card.hazard] - hand.seen_cards[card.hazard]
			self.maximums[roll] -= outstanding_hazards
			if card is right_of_way:
				outstanding_stops = hand.total_cards[stop] - hand.seen_cards[stop]
		elif card is stop:
			self.maximums[roll] -= 1
			self.maximums[right_of_way] -= 1
		elif card is speed_limit:
			self.maximums[end_of_limit] -= 1
			self.maximums[right_of_way] -= 1
		elif isinstance(card, Hazard):
			self.maximums[card.remedy] -= 1
			self.maximums[card.safety] -= 1
			self.maximums[roll] -= 1
		return self.play_obsolete_safeties(card)

	def double_check(self, card, top):
		raise RuntimeError("ah!  Moriarty has made an error.")

	def turn(self):
		self.update_scan()

		seen = hand.cards_seen
		total = hand.cards_total

		# discard remedies and play safeties
		# for hazards that have all been played
		needed = self.card_to_get_moving()
		assert needed not in self.hand.discardables

		def remedy_unneeded(remedy):
			if remedy not in self.hand.discardables:
				self.debug("[:] ah!  we no longer have a use for", remedy)
				self.hand.discardables.add(remedy)

		def coup_fouree_impossible_for(safety):
			self.obsolete_safeties.add(safety)
			if safety in self.hand.hand:
				self.play_obsolete_safeties(safety)

		def hazards_all_played(remedy):
			remedy_unneeded(remedy)
			coup_fouree_impossible_for(remedy.safety)

		for hazard in (accident, flat_tire, out_of_gas):
			remedy = hazard.remedy
			safety = hazard.safety

			in_hand = len([card for card in self.hand.hand if card == hazard])
			if (
				(remedy is not needed)
				and ((seen[hazard] + in_hand) == total[hazard])
				):
				hazards_all_played(remedy)

			if (safety in self.hand.hand) or (safety in self.hand.safeties):
				remedy_unneeded(remedy)

		# if you're waiting on a remedy,
		# but all of that remedy have been seen,
		# and you have the relevant safety in hand,
		# no point in holding on to that safety
		if ((needed in (repair, spare_tire, gasoline))
			and (seen[needed] == total[needed])):
			debug("[:] we need", needed, "but they're all gone.")
			coup_fouree_impossible_for(needed.safety)

		super().turn()


savepath = os.path.expanduser("~/.mille/savegame")

def save():
	directory = os.path.dirname(savepath)
	if not os.path.isdir(directory):
		os.makedirs(directory)
	with open(savepath, "wb") as f:
		print()
		print("Saving game.")
		pickle.dump({
			"savegame_revision": savegame_revision,
			"random.state": random.getstate(),
			"series": series,
			"game": game,
			"hand": hand,
			}, f)

def load():
	try:
		with open(savepath, "rb") as f:
			print()
			print("Loading game.")
			d = pickle.load(f)

			global series
			global game
			global hand

			assert d["savegame_revision"] == savegame_revision
			random.setstate(d["random.state"])
			series = d["series"]
			game = d["game"]
			hand = d["hand"]
	except EOFError:
		pass




class Series:
	"""
	A series of games.
	"""

	def __init__(self):
		self.players = []
		self.discard = DiscardPile()

		self.games_played = 0
		self.hands_played = 0
		self.winner = None

	def add(self, player):
		self.players.append(player)

	def start(self):
		global game
		assert self.players
		if not game:
			game = Game()

	def play(self):
		global game
		try:
			while True:
				self.start()
				game.play()
				game = None
		except KeyboardInterrupt as e:
			save()
		except BaseException as e:
			save()
			raise e

	@property
	def player_objects(self):
		for p in self.players:
			yield p
		yield self.discard

	def delegate(self, method_name, *a):
		def call_method_on_member(player, member_name, method_name, a):
			member = getattr(player, member_name, None)
			if member:
				method = getattr(member, method_name, None)
				if method:
					method(*a)

		# order is important:
		# * data flows from hand to game to series
		for player in self.player_objects:
			for member_name in "hand game series".split():
				call_method_on_member(player, member_name, method_name, a)
			getattr(player, method_name)(*a)

	def game_start(self):
		self.delegate('game_start')

	def score_game(self, winner):
		self.delegate('score_game', winner)

	def game_end_ui(self, winner):
		self.delegate('game_end_ui', winner)

	def game_end(self):
		self.delegate('game_end')

	def hand_start(self):
		self.delegate('hand_start')

	def score_hand(self, winner):
		self.delegate('score_hand', winner)

	def hand_end_ui(self, winner):
		self.delegate('hand_end_ui', winner)

	def hand_end(self):
		self.delegate('hand_end')


class Game:
	def __init__(self):
		self.round = 0
		self.winner = None
		series.games_played += 1
		series.game_start()

	def start(self):
		global hand
		if not hand:
			hand = Hand()

	def play(self):
		global hand

		while True:
			if self.winner:
				series.game_end_ui(self.winner)
				series.game_end()
				hand = None
				return self.winner

			self.start()
			hand.play()

			winner = None
			if any((p for p in series.players if p.game.score >= 5000)):
				p1, p2 = series.players
				if p1.game.score > p2.game.score:
					winner = p1
				if p1.game.score < p2.game.score:
					winner = p2
				# else--a tie game!  you must play another hand!

			if winner:
				self.winner = winner
				series.score_game(winner)
			else:
				hand = None


class Hand:

	over = False

	def __init__(self):

		self.winner = None
		self.extended = False
		self.over = False

		game.round += 1
		series.hands_played += 1

		self.draw_pile = list(deck)

		assert len(series.players) in {2, 3, 4, 6}
		if len(series.players) < 4:
			# remove one of each hazard
			hazards = set()
			new_draw_pile = []
			for card in self.draw_pile:
				if isinstance(card, Hazard):
					if card not in hazards:
						hazards.add(card)
						continue
				new_draw_pile.append(card)
			self.draw_pile = new_draw_pile

		self.original_deck = list(self.draw_pile)

		random.shuffle(self.draw_pile)

		self.plays = []
		self.plays_scanned = 0
		self.cards_seen = Counter()
		self.cards_total = Counter(self.original_deck)

		series.hand_start()

		for player in series.players:
			player.hand.hand = self.draw_pile[0:6]
			del self.draw_pile[0:6]
			player.hand.sort()

		# alternate who starts first
		self.current_player = series.players[game.round % len(series.players)]

	def update_seen(self):
		for play in self.plays[self.plays_scanned:]:
			self.cards_seen[play.card] += 1
		self.plays_scanned = len(self.plays)

	def play(self):
		allow_seven = True
		def check_cards(player, allow_seven=False):
			n = len(player.hand.hand)
			if allow_seven:
				assert n <= 7
			elif self.draw_pile:
				assert n == 6
			else:
				assert n <= 6

		players = itertools.cycle(series.players)
		assert self.current_player in series.players
		while True:
			p = next(players)
			if p == self.current_player:
				break

		print("Game #{game}, Hand #{hand}, it's {player}'s turn.".format(
			game=str(series.games_played + 1),
			hand=str(game.round + 1),
			player=self.current_player.name,
			))

		while True:
			if self.over:
				series.hand_end_ui(self.winner)
				series.hand_end()
				return self.winner

			if not self.draw_pile:
				# are there any plausible remaining moves?
				playable = None
				for player in series.players:
					if playable:
						break
					other = player.others[0]
					for card in player.hand.hand:
						playee = other if isinstance(card, Hazard) else player
						try:
							player.hand.is_legal(card, playee, silent=True)
							playable = card
							break
						except IllegalMove:
							pass
				if not playable:
					self.over = True
					series.score_hand(self.winner)
					continue

			player = self.current_player

			if player.hand.hand:
				check_cards(player, allow_seven)
				print()
				print("[" + player.name + "]")
				plays = len(self.plays)
				cards = len(self.draw_pile)
				while player.hand.hand:
					player.turn()
					if isinstance(self.plays[-1].card, Safety):
						continue
					break

				# sanity checks:
				# until we've run out of cards, on every turn
				#	* the player should draw and play at least one card
				#	* there should be a record of each play
				#   * the last card played should not be a safety
				#	* all other cards played should be safeties
				cards_drawn = cards - len(self.draw_pile)
				plays_taken = len(self.plays) - plays
				if self.draw_pile and not allow_seven:
					assert cards_drawn
					assert cards_drawn == plays_taken
					for play in self.plays[-plays_taken:-1]:
						assert isinstance(play.card, Safety)
					assert not isinstance(self.plays[-1].card, Safety)

				if player.hand.won():
					self.winner = player
					self.over = True
					series.score_hand(self.winner)
					continue
				check_cards(player)

			# go to next player
			self.current_player = next(players)
			allow_seven = False


	ScoresResult = namedtuple("ScoresResult", "winner lost_by_points")
	def print_scores(self, as_if_won=False):
		scores = {}
		all_comments = []
		all_totals = []
		winner = None
		divider = "--------------------------------"
		for p in series.players:
			score = Score(p, as_if_won)
			comments = score.render()
			score = score.total
			comments = ["    " + x[1] for x in comments]
			comments.insert(0, divider)
			comments.insert(0, p.name)
			totals = [divider]
			totals.append("             hand total ... " + str(score).rjust(4))
			scores[p] = score
			totals.append("             game total ... " + str(p.game.score).rjust(4))
			all_comments.append(comments)
			all_totals.append(totals)
			if p.hand.won():
				assert winner is None
				winner = p

		print()
		for strings in (all_comments, all_totals):
			for s1, s2 in itertools.zip_longest(*strings):
				s1 = s1 or ""
				s2 = s2 or ""
				print(s1.ljust(40), s2)

		print()
		lost_by_points = scores[winner] < scores[winner.others[0]] if winner else False
		return self.ScoresResult(winner, lost_by_points)

class TestBase(unittest.TestCase):

	def setUp(self):
		global series
		series = Series()
		series.add(Player())
		series.add(Player())

		self.p1, self.p2 = series.players
		self.p1.name = "p1"
		self.p2.name = "p2"

		def p1_illegal(card, playee=None):
			self.assertRaises(IllegalMove, self.p1.hand.play, card, playee)
		self.p1.illegal = p1_illegal
		def p2_illegal(card, playee=None):
			self.assertRaises(IllegalMove, self.p2.hand.play, card, playee)
		self.p2.illegal = p2_illegal

		series.start()

		# put cards back
		hand.draw_pile = list(hand.original_deck)
		for player in series.players:
			player.hand.hand = []
			for method in "discard draw draw_and_play draw_and_discard mileage play rolling".split():
				setattr(player, method, getattr(player.hand, method))

	def tearDown(self):
		global series
		global game
		global hand

		series = game = hand = None

	def draw_hand(self, player, *cards):
		assert len(cards) in {6, 7}
		player.hand.hand = []
		for card in cards:
			card = to_card[card]
			hand.draw_pile.remove(card)
			player.hand.hand.append(card)

	def illegal(self, player, card, playee=None):
		self.assertRaises(IllegalMove, player.play, card, playee)

class TestObjects(TestBase):

	def test_singletons(self):
		row1 = RightOfWay()
		row2 = RightOfWay()
		self.assertTrue(row1 is row2)


class TestRoll(TestBase):

	def setUp(self):
		super().setUp()
		self.draw_hand(self.p1, 50, 75, 100, roll, roll, roll)
		self.draw_hand(self.p2, 50, 75, 100, roll, roll, roll)
		self.assertFalse(self.p1.hand.rolling())
		self.assertFalse(self.p2.hand.rolling())

	def test_can_only_play_hazard_on_other(self):
		self.p1.draw(25)
		self.p1.illegal(accident)
		self.p1.play(roll)
		self.p1.illegal(accident)

		self.p2.draw(accident)
		self.p2.play(accident, self.p1)

	def test_can_only_play_remedy_on_self(self):
		self.p1.draw(repair)
		self.p1.play(roll)

		self.p2.draw(accident)
		self.p2.illegal(repair, self.p1)
		self.p2.play(accident, self.p1)

		self.p1.discard(self.p1.draw(100))

		self.p2.draw(repair)
		self.p2.illegal(repair, self.p1)
		self.p2.discard(repair)

		self.p1.draw_and_play(repair)

	def test_can_only_play_safety_on_self(self):
		self.p1.draw(right_of_way)
		self.p1.illegal(right_of_way, self.p2)
		self.p1.play(right_of_way)

	def cannot_discard_safety(self, safety):
		self.p1.draw(safety)
		self.assertRaises(IllegalMove, self.p1.discard, safety)

	def test_cannot_discard_right_of_way(self):
		self.cannot_discard_safety(right_of_way)

	def test_cannot_discard_puncture_proof(self):
		self.cannot_discard_safety(puncture_proof)

	def test_cannot_discard_driving_ace(self):
		self.cannot_discard_safety(driving_ace)

	def test_cannot_discard_extra_tank(self):
		self.cannot_discard_safety(extra_tank)

	def test_can_roll(self):
		self.p1.draw_and_play(roll)

	def test_cant_play_mileage_when_not_rolling(self):
		self.p1.draw(50)
		self.p1.illegal(50)
		self.p1.play(roll)

		self.p2.draw_and_play(stop, self.p1)

		self.p1.draw(50)
		self.p1.illegal(50)

	def test_can_play_mileage_when_rolling(self):
		self.p1.draw_and_play(roll)

		for mileage in mileages:
			self.p2.draw_and_discard(mileage)
			self.p1.draw_and_play(mileage)

	def test_cant_play_roll_when_rolling(self):
		self.p1.draw_and_play(roll)
		self.p2.draw_and_play(roll)
		self.assertRaises(IllegalMove, self.p1.draw_and_play, roll)

	def test_cant_play_stop_until_rolling(self):
		self.p1.draw(stop)
		self.p1.illegal(stop, self.p2)

	def test_cant_play_accident_until_rolling(self):
		self.p1.draw(accident)
		self.p1.illegal(accident, self.p2)

	def test_cant_play_flat_tire_until_rolling(self):
		self.p1.draw(flat_tire)
		self.p1.illegal(flat_tire, self.p2)

	def test_cant_play_out_of_gas_until_rolling(self):
		self.p1.draw(out_of_gas)
		self.p1.illegal(out_of_gas, self.p2)

	def test_can_play_speed_limit_when_not_rolling(self):
		self.p1.draw_and_play(speed_limit, self.p2)

	def test_can_play_speed_limit_when_rolling(self):
		self.p1.draw_and_play(roll)
		self.p2.draw_and_play(speed_limit, self.p1)

	def test_can_play_speed_limit_on_speed_limit(self):
		# this is legal!
		self.p1.draw_and_play(speed_limit, self.p2)
		self.p2.draw_and_discard(roll)
		self.p1.draw_and_play(speed_limit, self.p2)

	def test_speed_limit_only_allows_playing_25_and_50(self):
		self.p1.draw_and_play(roll)
		self.p2.draw_and_play(speed_limit, self.p1)
		for mileage in mileages:
			self.p1.draw(mileage)
			if mileage.distance <= 50:
				self.p1.play(mileage)
			else:
				self.p1.illegal(mileage)
				self.p1.discard(mileage)
			self.p2.draw_and_discard(mileage)

	def can_only_play_correct_remedy_on_hazard(self, hazard, remedy):
		def fail_on_except(*working):
			for remedy in (repair, spare_tire, gasoline):
				method = "play" if remedy in working else "illegal"
				getattr(self.p1, method)(remedy)

		self.p1.draw(remedy)
		fail_on_except()
		self.p1.play(roll)
		fail_on_except()

		self.p2.draw_and_play(hazard, self.p1)
		self.p1.draw(remedy)
		fail_on_except(remedy)
	
	def test_can_only_play_repair_on_accident(self):
		self.can_only_play_correct_remedy_on_hazard(accident, repair)

	def test_can_only_play_spare_tire_on_flat_tire(self):
		self.can_only_play_correct_remedy_on_hazard(flat_tire, spare_tire)

	def test_can_only_play_gasoline_on_out_of_gas(self):
		self.can_only_play_correct_remedy_on_hazard(out_of_gas, gasoline)

	def coup_fourre(self, hazard):
		safety = hazard.safety
		self.p1.draw(safety)
		self.p1.play(roll)

		self.p2.draw_and_play(hazard, self.p1)

		self.p1.play(safety)
		self.assertEqual(len(series.discard.pile), 1)
		self.assertEqual(series.discard.pile[0], hazard)
		self.assertIn(safety, self.p1.hand.safeties)
		self.assertIn(safety, self.p1.hand.coups_fourres)

	def test_coup_fourre_accident(self):
		self.coup_fourre(accident)

	def test_coup_fourre_flat_tire(self):
		self.coup_fourre(flat_tire)

	def test_coup_fourre_out_of_gas(self):
		self.coup_fourre(out_of_gas)

	def test_coup_fourre_stop(self):
		self.coup_fourre(stop)

	def test_coup_fourre_speed_limit(self):
		self.coup_fourre(speed_limit)

	def roll_after_playing_safety_for_hazard(self, hazard):
		safety = hazard.safety

		self.p1.draw(safety)
		self.p1.play(roll)

		self.p2.draw_and_play(hazard, self.p1)

		self.p1.draw(roll)
		self.p1.play(safety)
		self.p1.draw_and_play(roll)

		self.assertTrue(self.p1.hand.rolling())
		self.assertFalse(self.p1.hand.coups_fourres)

	def test_roll_after_playing_safety_for_accident(self):
		self.roll_after_playing_safety_for_hazard(accident)

	def test_roll_after_playing_safety_for_flat_tire(self):
		self.roll_after_playing_safety_for_hazard(flat_tire)

	def test_roll_after_playing_safety_for_out_of_gas(self):
		self.roll_after_playing_safety_for_hazard(out_of_gas)

	def test_right_of_way_starts_rolling_and_removes_speed_limit(self):
		self.p1.draw(25)
		self.p1.play(roll)

		self.p2.draw_and_play(stop, self.p1)

		self.p1.draw_and_discard(25)

		self.p2.draw_and_play(speed_limit, self.p1)

		self.p1.draw_and_play(right_of_way)

		self.assertTrue(self.p1.hand.rolling())
		self.assertTrue(self.p1.hand.autobahn())

	def right_of_way_starts_rolling_after_hazard(self, hazard):
		self.p1.draw(25)
		self.p1.play(roll)

		self.p2.draw_and_play(hazard, self.p1)

		self.p1.draw_and_play(hazard.remedy)

		self.p2.draw_and_play(speed_limit, self.p1)

		self.p1.draw_and_play(right_of_way)
		self.assertTrue(self.p1.hand.rolling())

	def test_right_of_way_starts_rolling_after_accident(self):
		self.right_of_way_starts_rolling_after_hazard(accident)

	def test_right_of_way_starts_rolling_after_flat_tire(self):
		self.right_of_way_starts_rolling_after_hazard(flat_tire)

	def test_right_of_way_starts_rolling_after_out_of_gas(self):
		self.right_of_way_starts_rolling_after_hazard(out_of_gas)

	def can_play_hazard_on_hazard(self, hazard1, hazard2):
		self.p1.draw_and_play(roll)
		self.p2.draw_and_play(hazard1, self.p1)
		self.p1.draw_and_discard(25)
		self.p2.draw_and_play(hazard2, self.p1)

	def test_can_play_accident_then_accident(self):
		self.can_play_hazard_on_hazard(accident, accident)

	def test_can_play_accident_then_flat_tire(self):
		self.can_play_hazard_on_hazard(accident, flat_tire)

	def test_can_play_accident_then_out_of_gas(self):
		self.can_play_hazard_on_hazard(accident, out_of_gas)

	def test_can_play_accident_then_stop(self):
		self.can_play_hazard_on_hazard(accident, stop)

	def test_can_play_flat_tire_then_accident(self):
		self.can_play_hazard_on_hazard(flat_tire, accident)

	def test_can_play_flat_tire_then_flat_tire(self):
		self.can_play_hazard_on_hazard(flat_tire, flat_tire)

	def test_can_play_flat_tire_then_out_of_gas(self):
		self.can_play_hazard_on_hazard(flat_tire, out_of_gas)

	def test_can_play_flat_tire_then_stop(self):
		self.can_play_hazard_on_hazard(flat_tire, stop)

	def test_can_play_out_of_gas_then_accident(self):
		self.can_play_hazard_on_hazard(out_of_gas, accident)

	def test_can_play_out_of_gas_then_flat_tire(self):
		self.can_play_hazard_on_hazard(out_of_gas, flat_tire)

	def test_can_play_out_of_gas_then_out_of_gas(self):
		self.can_play_hazard_on_hazard(out_of_gas, out_of_gas)

	def test_can_play_out_of_gas_then_stop(self):
		self.can_play_hazard_on_hazard(out_of_gas, stop)

	def test_can_play_stop_then_accident(self):
		self.can_play_hazard_on_hazard(stop, accident)

	def test_can_play_stop_then_flat_tire(self):
		self.can_play_hazard_on_hazard(stop, flat_tire)

	def test_can_play_stop_then_out_of_gas(self):
		self.can_play_hazard_on_hazard(stop, out_of_gas)

	def test_can_play_stop_then_stop(self):
		self.can_play_hazard_on_hazard(stop, stop)

	def can_play_hazard_on_hazard_when_other_player_uses_safety_and_has_right_of_way(self, hazard1, hazard2):
		self.p1.draw_and_play(right_of_way)
		self.p1.draw_and_play(100)

		self.p2.draw_and_play(hazard1, self.p1)

		self.p1.draw_and_play(hazard1.remedy)
		self.assertTrue(self.p1.hand.rolling())

		self.p2.draw_and_play(hazard2, self.p1)
		self.assertFalse(self.p1.hand.rolling())

	def test_can_play_accident_when_other_player_uses_safety_and_has_right_of_way(self):
		self.can_play_hazard_on_hazard_when_other_player_uses_safety_and_has_right_of_way(out_of_gas, accident)

	def test_can_play_flat_tire_when_other_player_uses_safety_and_has_right_of_way(self):
		self.can_play_hazard_on_hazard_when_other_player_uses_safety_and_has_right_of_way(accident, flat_tire)

	def test_can_play_out_of_gas_when_other_player_uses_safety_and_has_right_of_way(self):
		self.can_play_hazard_on_hazard_when_other_player_uses_safety_and_has_right_of_way(accident, out_of_gas)


import sys, tty, termios

def getch(prompt, valid=None):
	sys.stdout.flush()
	fd = sys.stdin.fileno()
	while True:
		if prompt:
			print(prompt, end="")
			sys.stdout.flush()
		try:
			old_settings = termios.tcgetattr(fd)
			tty.setraw(sys.stdin.fileno())
			c = sys.stdin.read(1)
			sys.stdout.flush()
		finally:
			termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
		if ord(c) == 3:
			raise KeyboardInterrupt()
		print(c if c.isprintable() else "")
		sys.stdout.flush()
		if valid and (c not in valid):
			# print("Invalid keypress! valid chars:", repr(valid))
			# sys.stdout.flush()
			continue
		break
	sys.stdout.flush()
	return c


def pile_repr(pile):
	s = str(pile[-1])[:10] if pile else ''
	return s.rjust(10)

def safeties_repr(player, highlights=()):
	array = []
	for card in sorted(player.hand.safeties, reverse=True):
		s = card.abbreviation_6
		if card in player.hand.coups_fourres:
			s = s.upper()
		if card in highlights:
			s = ">" + s + "<"
		array.append(s)
	return ' '.join(array)

def help():
	print("""
Keys you can press at any time:

      c - show all cards visible so far this hand (played or discarded)
      s - show current scores
      S - show current scores as if each player had won the current hand
      t - redraw the table (discard, piles, etc)
      ? - display this help

 Ctrl-C - exit, automatically saving state

Other random hints:
  * At the "discard which card?" prompt, press any invalid key to return
    to the main play prompt.
  * The number of dots next to a player's mileage indicates how many 200s
    they've played.
_______________________________________
""")

def print_scores(as_if_won=False):
	if not hand:
		print("No current hand being played.")
		return

	hand.print_scores(as_if_won)

def played_so_far():
	global series

	if not hand:
		print("No current hand being played.")
		return

	hand.update_seen()

	print()

	width = 3
	first_line = True
	for line in (
		(mileage_25, mileage_50, mileage_75, mileage_100, mileage_200),
		(accident, repair, driving_ace),
		(flat_tire, spare_tire, puncture_proof),
		(out_of_gas, gasoline, extra_tank),
		(stop, roll, right_of_way),
		(speed_limit, end_of_limit),
		):
		result = []
		for card in line:
			count = hand.cards_seen[card]
			total = hand.cards_total[card]
			s = card.abbreviation.rjust(width) + " " + str(count).rjust(2)
			if not isinstance(card, Safety):
				s += "/" + str(total).ljust(2)
			result.append(s)
		s = " :: ".join(result)
		if first_line:
			print("-" * len(s))
		print(s)
		if first_line:
			first_line = False
			print("-" * len(s))
			width = 10
	print()


class StdioPlayer(Player):
	
	name = getpass.getuser()

	def hand_start(self):
		super().hand_start()

		self.hand.last_drawn = None
		self.hand.state = None

	def getch(self, prompt, keys=None):
		if keys:
			keys += "c?sSt"
		global getch
		while True:
			c = getch(prompt, keys)
			if c == 'c':
				played_so_far()
				continue
			if c == '?':
				help()
				continue
			if c == 's':
				print_scores()
				continue
			if c == 'S':
				print_scores(True)
				continue
			if c == 't':
				self.print_table()
				continue
			return c

	def space_to_continue(self, prompt=""):
		if prompt:
			prompt += "\n"
		prompt += "Press [space] to continue > "
		self.getch(prompt, " ")

	def print_table(self):
		if not hand:
			print("No hand currently being played.")
			return

		other = self.others[0]

		if hand.plays and hand.plays[-1].playee is series.discard:
			discard_before = ">"
			discard_after = "<"
		else:
			discard_before = discard_after = "|"
		print("draw pile", str(len(hand.draw_pile)).rjust(3) + "/" + str(len(hand.original_deck)), "       discard " + discard_before + pile_repr(series.discard.pile) + discard_after)
		print("         total|hand    miles|battlepile|speed pile|safeties")
		def stats(player):
			before_miles = " "
			before_battle = between_piles = after_speed = "|"
			highlights = set()
			if hand.plays:
				play = hand.plays[-1]
				last_player = play.player
				card = play.card
				if play.playee == player:
					if isinstance(play.card, Mileage):
						before_miles = ">"
						before_battle = "<"
					elif play.card in {speed_limit, end_of_limit}:
						between_piles = ">"
						after_speed = "<"
					elif isinstance(play.card, (Hazard, Remedy)):
						before_battle = ">"
						between_piles = "<"
				for play in reversed(hand.plays):
					if play.player != last_player:
						break
					if isinstance(play.card, Safety):
						highlights.add(play.card)

			strings = [player.name.ljust(8)[:8]]
			add = strings.append

			score = Score(player).total

			add(" ")
			add(str(score + player.game.score).rjust(5))

			add("|")
			add(str(score).rjust(4))

			add("   ")
			add(before_miles)
			add(str(player.hand.mileage()).rjust(4))

			add(" .:"[player.hand.two_hundreds()])

			add(before_battle)
			add(pile_repr(player.hand.battle_pile))

			add(between_piles)
			add(pile_repr(player.hand.speed_pile))

			add(after_speed)
			add(safeties_repr(player, highlights))

			print("".join(strings))

		stats(other)
		stats(self)

		highlight = self.hand.last_drawn

		highlight_line = []
		line1 = []
		line2 = []

		before = " "
		after = ""

		card_highlight = ":"

		for i, card in enumerate(self.hand.hand, 1):

			if card == highlight:
				before = after = card_highlight
				highlight_line.append(card_highlight * 10)
				highlight = None
			else:
				highlight_line.append(before)
				highlight_line.append(" " * 9)

			field1 = ("[" + str(i) + "]").rjust(9)
			field2 = (card.abbreviation).rjust(9)

			line1.append(before)
			line1.append(field1)
			line2.append(before)
			line2.append(field2)

			before = after or " "
			after = ""

		if before:
			line1.append(before)
			line2.append(before)

		print()
		print(" ", ''.join(highlight_line))
		print(" ", ''.join(line1))
		print(" ", ''.join(line2))
		print(" ", ''.join(highlight_line))

	def hand_end_ui(self, winner):
		hand.print_scores()
		text = []
		add = text.append
		if winner:
			add(winner.name + " wins the hand!")
			loser = winner.others[0]
			lost_by_points = Score(winner).total < Score(loser).total
			if lost_by_points:
				add("(Which is weird, because " + loser.name + " got more points.)")
			if not loser.hand.mileage():
				add("And it's a shutout, #{} for {}!".format(winner.series.shutouts, winner.name))
		else:
			add("Nobody won the hand.")

		text = "\n".join(text)
		if game.winner:
			print(text)
		else:
			self.space_to_continue(text)

	def game_end_ui(self, winner):
		text = []
		add = text.append
		if not winner:
			add("Game is a tie!  Golly, that's unusual!")
		else:
			screed = """
Gentlemen!  You've both worked very hard.  And in a way you're both winners.
But--in another, more accurate way--{winner.name} is the winner.
			""".format(winner=winner)
			add(screed)
		for player in series.players:
			add("{} lifetime games won: {} total score: {}".format(player.name, player.series.games_won, player.series.score))
		
		self.space_to_continue("\n".join(text))

	def double_check(self, card, top):
		c = self.getch("You're playing a {} on a {}.\nAre you sure that's what you want?  [yn] >".format(str(card), str(top)), "yn")
		if c == 'n':
			raise IllegalMove(None)

	def turn(self):
		other = self.others[0]

		while True:

			if self.hand.state == "prompt for extend":
				c = self.getch("    You reached 700!  Extend? > ", "yn")
				hand.extended = c == "y"
				self.hand.state = None
				return

			redraw = True
			while self.hand.hand:
				if redraw:
					self.print_table()
					redraw = False

				c = None
				valid_cards = "1234567"[:len(self.hand.hand)]
				valid = valid_cards
				prompt = "    play [" + valid + "]"

				if hand.draw_pile and (len(self.hand.hand) < 7):
					prompt += " or [d]raw? > "
					valid += "d"
				else:
					prompt += " or [.]discard? > "
					valid += "."
				c = self.getch(prompt, valid)

				if c == 'd':
					self.hand.last_drawn = card = self.hand.draw()
					self.hand.sort()
					print()
					print("    drew", card)
					print()
					redraw = True
					continue
				if c == '.':
					c2 = self.getch("    Discard which card? [" + valid_cards + "] > ")
					if c2 not in valid_cards:
						continue
					i = int(c2) - 1
				else:
					assert '1' <= c <= str(len(self.hand.hand))
					i = int(c) - 1

				card = self.hand.hand[i]
				player = self
				if c == '.':
					playee = series.discard
				elif isinstance(card, Hazard):
					playee = other
				else:
					playee = self

				# print("    Playing", card, "on", playee.name)
				try:
					player.hand.play(card, playee)
					self.hand.last_drawn = None
				except IllegalMove as response:
					c = None
					if response.__context__:
						message = str(response)
						bangs = "!" * len(message)
						print()
						print("   ", bangs)
						print("   ", message)
						print("   ", bangs)
					print()
					continue
				break

			if (self.hand.mileage() == 700) and not hand.extended:
				self.hand.state = "prompt for extend"
				continue
			return

if __name__ == "__main__":

	if len(sys.argv) > 1:
		if sys.argv[1] == "test":
			del sys.argv[1]
			sys.exit(unittest.main())
		if sys.argv[1] == "battle":
			del sys.argv[1]
			players = []
			for arg in sys.argv[1:3]:
				players.append(DumbComputerPlayer
					if arg == "dumb"
					else AverageComputerPlayer)
			series = Series()
			players += [AverageComputerPlayer] * (2 - len(players))
			for p in players:
				series.add(p())
	else:
		if os.path.isfile(savepath):
			load()
		if not series:
			print("Couldn't load savegame.  Starting new game.")
			help()
			series = Series()
			series.add(StdioPlayer())
			series.add(AverageComputerPlayer())

	series.play()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.