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
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
34821
34822
34823
34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853
34854
34855
34856
34857
34858
34859
34860
34861
34862
34863
34864
34865
34866
34867
34868
34869
34870
34871
34872
34873
34874
34875
34876
34877
34878
34879
34880
34881
34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903
34904
34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981
34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
35012
35013
35014
35015
35016
35017
35018
35019
35020
35021
35022
35023
35024
35025
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
35047
35048
35049
35050
35051
35052
35053
35054
35055
35056
35057
35058
35059
35060
35061
35062
35063
35064
35065
35066
35067
35068
35069
35070
35071
35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
35133
35134
35135
35136
35137
35138
35139
35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168
35169
35170
35171
35172
35173
35174
35175
35176
35177
35178
35179
35180
35181
35182
35183
35184
35185
35186
35187
35188
35189
35190
35191
35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202
35203
35204
35205
35206
35207
35208
35209
35210
35211
35212
35213
35214
35215
35216
35217
35218
35219
35220
35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
35259
35260
35261
35262
35263
35264
35265
35266
35267
35268
35269
35270
35271
35272
35273
35274
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292
35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350
35351
35352
35353
35354
35355
35356
35357
35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382
35383
35384
35385
35386
35387
35388
35389
35390
35391
35392
35393
35394
35395
35396
35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410
35411
35412
35413
35414
35415
35416
35417
35418
35419
35420
35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445
35446
35447
35448
35449
35450
35451
35452
35453
35454
35455
35456
35457
35458
35459
35460
35461
35462
35463
35464
35465
35466
35467
35468
35469
35470
35471
35472
35473
35474
35475
35476
35477
35478
35479
35480
35481
35482
35483
35484
35485
35486
35487
35488
35489
35490
35491
35492
35493
35494
35495
35496
35497
35498
35499
35500
35501
35502
35503
35504
35505
35506
35507
35508
35509
35510
35511
35512
35513
35514
35515
35516
35517
35518
35519
35520
35521
35522
35523
35524
35525
35526
35527
35528
35529
35530
35531
35532
35533
35534
35535
35536
35537
35538
35539
35540
35541
35542
35543
35544
35545
35546
35547
35548
35549
35550
35551
35552
35553
35554
35555
35556
35557
35558
35559
35560
35561
35562
35563
35564
35565
35566
35567
35568
35569
35570
35571
35572
35573
35574
35575
35576
35577
35578
35579
35580
35581
35582
35583
35584
35585
35586
35587
35588
35589
35590
35591
35592
35593
35594
35595
35596
35597
35598
35599
35600
35601
35602
35603
35604
35605
35606
35607
35608
35609
35610
35611
35612
35613
35614
35615
35616
35617
35618
35619
35620
35621
35622
35623
35624
35625
35626
35627
35628
35629
35630
35631
35632
35633
35634
35635
35636
35637
35638
35639
35640
35641
35642
35643
35644
35645
35646
35647
35648
35649
35650
35651
35652
35653
35654
35655
35656
35657
35658
35659
35660
35661
35662
35663
35664
35665
35666
35667
35668
35669
35670
35671
35672
35673
35674
35675
35676
35677
35678
35679
35680
35681
35682
35683
35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
35700
35701
35702
35703
35704
35705
35706
35707
35708
35709
35710
35711
35712
35713
35714
35715
35716
35717
35718
35719
35720
35721
35722
35723
35724
35725
35726
35727
35728
35729
35730
35731
35732
35733
35734
35735
35736
35737
35738
35739
35740
35741
35742
35743
35744
35745
35746
35747
35748
35749
35750
35751
35752
35753
35754
35755
35756
35757
35758
35759
35760
35761
35762
35763
35764
35765
35766
35767
35768
35769
35770
35771
35772
35773
35774
35775
35776
35777
35778
35779
35780
35781
35782
35783
35784
35785
35786
35787
35788
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838
35839
35840
35841
35842
35843
35844
35845
35846
35847
35848
35849
35850
35851
35852
35853
35854
35855
35856
35857
35858
35859
35860
35861
35862
35863
35864
35865
35866
35867
35868
35869
35870
35871
35872
35873
35874
35875
35876
35877
35878
35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891
35892
35893
35894
35895
35896
35897
35898
35899
35900
35901
35902
35903
35904
35905
35906
35907
35908
35909
35910
35911
35912
35913
35914
35915
35916
35917
35918
35919
35920
35921
35922
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932
35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944
35945
35946
35947
35948
35949
35950
35951
35952
35953
35954
35955
35956
35957
35958
35959
35960
35961
35962
35963
35964
35965
35966
35967
35968
35969
35970
35971
35972
35973
35974
35975
35976
35977
35978
35979
35980
35981
35982
35983
35984
35985
35986
35987
35988
35989
35990
35991
35992
35993
35994
35995
35996
35997
35998
35999
36000
36001
36002
36003
36004
36005
36006
36007
36008
36009
36010
36011
36012
36013
36014
36015
36016
36017
36018
36019
36020
36021
36022
36023
36024
36025
36026
36027
36028
36029
36030
36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059
36060
36061
36062
36063
36064
36065
36066
36067
36068
36069
36070
36071
36072
36073
36074
36075
36076
36077
36078
36079
36080
36081
36082
36083
36084
36085
36086
36087
36088
36089
36090
36091
36092
36093
36094
36095
36096
36097
36098
36099
36100
36101
36102
36103
36104
36105
36106
36107
36108
36109
36110
36111
36112
36113
36114
36115
36116
36117
36118
36119
36120
36121
36122
36123
36124
36125
36126
36127
36128
36129
36130
36131
36132
36133
36134
36135
36136
36137
36138
36139
36140
36141
36142
36143
36144
36145
36146
36147
36148
36149
36150
36151
36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162
36163
36164
36165
36166
36167
36168
36169
36170
36171
36172
36173
36174
36175
36176
36177
36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
36188
36189
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228
36229
36230
36231
36232
36233
36234
36235
36236
36237
36238
36239
36240
36241
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
36257
36258
36259
36260
36261
36262
36263
36264
36265
36266
36267
36268
36269
36270
36271
36272
36273
36274
36275
36276
36277
36278
36279
36280
36281
36282
36283
36284
36285
36286
36287
36288
36289
36290
36291
36292
36293
36294
36295
36296
36297
36298
36299
36300
36301
36302
36303
36304
36305
36306
36307
36308
36309
36310
36311
36312
36313
36314
36315
36316
36317
36318
36319
36320
36321
36322
36323
36324
36325
36326
36327
36328
36329
36330
36331
36332
36333
36334
36335
36336
36337
36338
36339
36340
36341
36342
36343
36344
36345
36346
36347
36348
36349
36350
36351
36352
36353
36354
36355
36356
36357
36358
36359
36360
36361
36362
36363
36364
36365
36366
36367
36368
36369
36370
36371
36372
36373
36374
36375
36376
36377
36378
36379
36380
36381
36382
36383
36384
36385
36386
36387
36388
36389
36390
36391
36392
36393
36394
36395
36396
36397
36398
36399
36400
36401
36402
36403
36404
36405
36406
36407
36408
36409
36410
36411
36412
36413
36414
36415
36416
36417
36418
36419
36420
36421
36422
36423
36424
36425
36426
36427
36428
36429
36430
36431
36432
36433
36434
36435
36436
36437
36438
36439
36440
36441
36442
36443
36444
36445
36446
36447
36448
36449
36450
36451
36452
36453
36454
36455
36456
36457
36458
36459
36460
36461
36462
36463
36464
36465
36466
36467
36468
36469
36470
36471
36472
36473
36474
36475
36476
36477
36478
36479
36480
36481
36482
36483
36484
36485
36486
36487
36488
36489
36490
36491
36492
36493
36494
36495
36496
36497
36498
36499
36500
36501
36502
36503
36504
36505
36506
36507
36508
36509
36510
36511
36512
36513
36514
36515
36516
36517
36518
36519
36520
36521
36522
36523
36524
36525
36526
36527
36528
36529
36530
36531
36532
36533
36534
36535
36536
36537
36538
36539
36540
36541
36542
36543
36544
36545
36546
36547
36548
36549
36550
36551
36552
36553
36554
36555
36556
36557
36558
36559
36560
36561
36562
36563
36564
36565
36566
36567
36568
36569
36570
36571
36572
36573
36574
36575
36576
36577
36578
36579
36580
36581
36582
36583
36584
36585
36586
36587
36588
36589
36590
36591
36592
36593
36594
36595
36596
36597
36598
36599
36600
36601
36602
36603
36604
36605
36606
36607
36608
36609
36610
36611
36612
36613
36614
36615
36616
36617
36618
36619
36620
36621
36622
36623
36624
36625
36626
36627
36628
36629
36630
36631
36632
36633
36634
36635
36636
36637
36638
36639
36640
36641
36642
36643
36644
36645
36646
36647
36648
36649
36650
36651
36652
36653
36654
36655
36656
36657
36658
36659
36660
36661
36662
36663
36664
36665
36666
36667
36668
36669
36670
36671
36672
36673
36674
36675
36676
36677
36678
36679
36680
36681
36682
36683
36684
36685
36686
36687
36688
36689
36690
36691
36692
36693
36694
36695
36696
36697
36698
36699
36700
36701
36702
36703
36704
36705
36706
36707
36708
36709
36710
36711
36712
36713
36714
36715
36716
36717
36718
36719
36720
36721
36722
36723
36724
36725
36726
36727
36728
36729
36730
36731
36732
36733
36734
36735
36736
36737
36738
36739
36740
36741
36742
36743
36744
36745
36746
36747
36748
36749
36750
36751
36752
36753
36754
36755
36756
36757
36758
36759
36760
36761
36762
36763
36764
36765
36766
36767
36768
36769
36770
36771
36772
36773
36774
36775
36776
36777
36778
36779
36780
36781
36782
36783
36784
36785
36786
36787
36788
36789
36790
36791
36792
36793
36794
36795
36796
36797
36798
36799
36800
36801
36802
36803
36804
36805
36806
36807
36808
36809
36810
36811
36812
36813
36814
36815
36816
36817
36818
36819
36820
36821
36822
36823
36824
36825
36826
36827
36828
36829
36830
36831
36832
36833
36834
36835
36836
36837
36838
36839
36840
36841
36842
36843
36844
36845
36846
36847
36848
36849
36850
36851
36852
36853
36854
36855
36856
36857
36858
36859
36860
36861
36862
36863
36864
36865
36866
36867
36868
36869
36870
36871
36872
36873
36874
36875
36876
36877
36878
36879
36880
36881
36882
36883
36884
36885
36886
36887
36888
36889
36890
36891
36892
36893
36894
36895
36896
36897
36898
36899
36900
36901
36902
36903
36904
36905
36906
36907
36908
36909
36910
36911
36912
36913
36914
36915
36916
36917
36918
36919
36920
36921
36922
36923
36924
36925
36926
36927
36928
36929
36930
36931
36932
36933
36934
36935
36936
36937
36938
36939
36940
36941
36942
36943
36944
36945
36946
36947
36948
36949
36950
36951
36952
36953
36954
36955
36956
36957
36958
36959
36960
36961
36962
36963
36964
36965
36966
36967
36968
36969
36970
36971
36972
36973
36974
36975
36976
36977
36978
36979
36980
36981
36982
36983
36984
36985
36986
36987
36988
36989
36990
36991
36992
36993
36994
36995
36996
36997
36998
36999
37000
37001
37002
37003
37004
37005
37006
37007
37008
37009
37010
37011
37012
37013
37014
37015
37016
37017
37018
37019
37020
37021
37022
37023
37024
37025
37026
37027
37028
37029
37030
37031
37032
37033
37034
37035
37036
37037
37038
37039
37040
37041
37042
37043
37044
37045
37046
37047
37048
37049
37050
37051
37052
37053
37054
37055
37056
37057
37058
37059
37060
37061
37062
37063
37064
37065
37066
37067
37068
37069
37070
37071
37072
37073
37074
37075
37076
37077
37078
37079
37080
37081
37082
37083
37084
37085
37086
37087
37088
37089
37090
37091
37092
37093
37094
37095
37096
37097
37098
37099
37100
37101
37102
37103
37104
37105
37106
37107
37108
37109
37110
37111
37112
37113
37114
37115
37116
37117
37118
37119
37120
37121
37122
37123
37124
37125
37126
37127
37128
37129
37130
37131
37132
37133
37134
37135
37136
37137
37138
37139
37140
37141
37142
37143
37144
37145
37146
37147
37148
37149
37150
37151
37152
37153
37154
37155
37156
37157
37158
37159
37160
37161
37162
37163
37164
37165
37166
37167
37168
37169
37170
37171
37172
37173
37174
37175
37176
37177
37178
37179
37180
37181
37182
37183
37184
37185
37186
37187
37188
37189
37190
37191
37192
37193
37194
37195
37196
37197
37198
37199
37200
37201
37202
37203
37204
37205
37206
37207
37208
37209
37210
37211
37212
37213
37214
37215
37216
37217
37218
37219
37220
37221
37222
37223
37224
37225
37226
37227
37228
37229
37230
37231
37232
37233
37234
37235
37236
37237
37238
37239
37240
37241
37242
37243
37244
37245
37246
37247
37248
37249
37250
37251
37252
37253
37254
37255
37256
37257
37258
37259
37260
37261
37262
37263
37264
37265
37266
37267
37268
37269
37270
37271
37272
37273
37274
37275
37276
37277
37278
37279
37280
37281
37282
37283
37284
37285
37286
37287
37288
37289
37290
37291
37292
37293
37294
37295
37296
37297
37298
37299
37300
37301
37302
37303
37304
37305
37306
37307
37308
37309
37310
37311
37312
37313
37314
37315
37316
37317
37318
37319
37320
37321
37322
37323
37324
37325
37326
37327
37328
37329
37330
37331
37332
37333
37334
37335
37336
37337
37338
37339
37340
37341
37342
37343
37344
37345
37346
37347
37348
37349
37350
37351
37352
37353
37354
37355
37356
37357
37358
37359
37360
37361
37362
37363
37364
37365
37366
37367
37368
37369
37370
37371
37372
37373
37374
37375
37376
37377
37378
37379
37380
37381
37382
37383
37384
37385
37386
37387
37388
37389
37390
37391
37392
37393
37394
37395
37396
37397
37398
37399
37400
37401
37402
37403
37404
37405
37406
37407
37408
37409
37410
37411
37412
37413
37414
37415
37416
37417
37418
37419
37420
37421
37422
37423
37424
37425
37426
37427
37428
37429
37430
37431
37432
37433
37434
37435
37436
37437
37438
37439
37440
37441
37442
37443
37444
37445
37446
37447
37448
37449
37450
37451
37452
37453
37454
37455
37456
37457
37458
37459
37460
37461
37462
37463
37464
37465
37466
37467
37468
37469
37470
37471
37472
37473
37474
37475
37476
37477
37478
37479
37480
37481
37482
37483
37484
37485
37486
37487
37488
37489
37490
37491
37492
37493
37494
37495
37496
37497
37498
37499
37500
37501
37502
37503
37504
37505
37506
37507
37508
37509
37510
37511
37512
37513
37514
37515
37516
37517
37518
37519
37520
37521
37522
37523
37524
37525
37526
37527
37528
37529
37530
37531
37532
37533
37534
37535
37536
37537
37538
37539
37540
37541
37542
37543
37544
37545
37546
37547
37548
37549
37550
37551
37552
37553
37554
37555
37556
37557
37558
37559
37560
37561
37562
37563
37564
37565
37566
37567
37568
37569
37570
37571
37572
37573
37574
37575
37576
37577
37578
37579
37580
37581
37582
37583
37584
37585
37586
37587
37588
37589
37590
37591
37592
37593
37594
37595
37596
37597
37598
37599
37600
37601
37602
37603
37604
37605
37606
37607
37608
37609
37610
37611
37612
37613
37614
37615
37616
37617
37618
37619
37620
37621
37622
37623
37624
37625
37626
37627
37628
37629
37630
37631
37632
37633
37634
37635
37636
37637
37638
37639
37640
37641
37642
37643
37644
37645
37646
37647
37648
37649
37650
37651
37652
37653
37654
37655
37656
37657
37658
37659
37660
37661
37662
37663
37664
37665
37666
37667
37668
37669
37670
37671
37672
37673
37674
37675
37676
37677
37678
37679
37680
37681
37682
37683
37684
37685
37686
37687
37688
37689
37690
37691
37692
37693
37694
37695
37696
37697
37698
37699
37700
37701
37702
37703
37704
37705
37706
37707
37708
37709
37710
37711
37712
37713
37714
37715
37716
37717
37718
37719
37720
37721
37722
37723
37724
37725
37726
37727
37728
37729
37730
37731
37732
37733
37734
37735
37736
37737
37738
37739
37740
37741
37742
37743
37744
37745
37746
37747
37748
37749
37750
37751
37752
37753
37754
37755
37756
37757
37758
37759
37760
37761
37762
37763
37764
37765
37766
37767
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
37782
37783
37784
37785
37786
37787
37788
37789
37790
37791
37792
37793
37794
37795
37796
37797
37798
37799
37800
37801
37802
37803
37804
37805
37806
37807
37808
37809
37810
37811
37812
37813
37814
37815
37816
37817
37818
37819
37820
37821
37822
37823
37824
37825
37826
37827
37828
37829
37830
37831
37832
37833
37834
37835
37836
37837
37838
37839
37840
37841
37842
37843
37844
37845
37846
37847
37848
37849
37850
37851
37852
37853
37854
37855
37856
37857
37858
37859
37860
37861
37862
37863
37864
37865
37866
37867
37868
37869
37870
37871
37872
37873
37874
37875
37876
37877
37878
37879
37880
37881
37882
37883
37884
37885
37886
37887
37888
37889
37890
37891
37892
37893
37894
37895
37896
37897
37898
37899
37900
37901
37902
37903
37904
37905
37906
37907
37908
37909
37910
37911
37912
37913
37914
37915
37916
37917
37918
37919
37920
37921
37922
37923
37924
37925
37926
37927
37928
37929
37930
37931
37932
37933
37934
37935
37936
37937
37938
37939
37940
37941
37942
37943
37944
37945
37946
37947
37948
37949
37950
37951
37952
37953
37954
37955
37956
37957
37958
37959
37960
37961
37962
37963
37964
37965
37966
37967
37968
37969
37970
37971
37972
37973
37974
37975
37976
37977
37978
37979
37980
37981
37982
37983
37984
37985
37986
37987
37988
37989
37990
37991
37992
37993
37994
37995
37996
37997
37998
37999
38000
38001
38002
38003
38004
38005
38006
38007
38008
38009
38010
38011
38012
38013
38014
38015
38016
38017
38018
38019
38020
38021
38022
38023
38024
38025
38026
38027
38028
38029
38030
38031
38032
38033
38034
38035
38036
38037
38038
38039
38040
38041
38042
38043
38044
38045
38046
38047
38048
38049
38050
38051
38052
38053
38054
38055
38056
38057
38058
38059
38060
38061
38062
38063
38064
38065
38066
38067
38068
38069
38070
38071
38072
38073
38074
38075
38076
38077
38078
38079
38080
38081
38082
38083
38084
38085
38086
38087
38088
38089
38090
38091
38092
38093
38094
38095
38096
38097
38098
38099
38100
38101
38102
38103
38104
38105
38106
38107
38108
38109
38110
38111
38112
38113
38114
38115
38116
38117
38118
38119
38120
38121
38122
38123
38124
38125
38126
38127
38128
38129
38130
38131
38132
38133
38134
38135
38136
38137
38138
38139
38140
38141
38142
38143
38144
38145
38146
38147
38148
38149
38150
38151
38152
38153
38154
38155
38156
38157
38158
38159
38160
38161
38162
38163
38164
38165
38166
38167
38168
38169
38170
38171
38172
38173
38174
38175
38176
38177
38178
38179
38180
38181
38182
38183
38184
38185
38186
38187
38188
38189
38190
38191
38192
38193
38194
38195
38196
38197
38198
38199
38200
38201
38202
38203
38204
38205
38206
38207
38208
38209
38210
38211
38212
38213
38214
38215
38216
38217
38218
38219
38220
38221
38222
38223
38224
38225
38226
38227
38228
38229
38230
38231
38232
38233
38234
38235
38236
38237
38238
38239
38240
38241
38242
38243
38244
38245
38246
38247
38248
38249
38250
38251
38252
38253
38254
38255
38256
38257
38258
38259
38260
38261
38262
38263
38264
38265
38266
38267
38268
38269
38270
38271
38272
38273
38274
38275
38276
38277
38278
38279
38280
38281
38282
38283
38284
38285
38286
38287
38288
38289
38290
38291
38292
38293
38294
38295
38296
38297
38298
38299
38300
38301
38302
38303
38304
38305
38306
38307
38308
38309
38310
38311
38312
38313
38314
38315
38316
38317
38318
38319
38320
38321
38322
38323
38324
38325
38326
38327
38328
38329
38330
38331
38332
38333
38334
38335
38336
38337
38338
38339
38340
38341
38342
38343
38344
38345
38346
38347
38348
38349
38350
38351
38352
38353
38354
38355
38356
38357
38358
38359
38360
38361
38362
38363
38364
38365
38366
38367
38368
38369
38370
38371
38372
38373
38374
38375
38376
38377
38378
38379
38380
38381
38382
38383
38384
38385
38386
38387
38388
38389
38390
38391
38392
38393
38394
38395
38396
38397
38398
38399
38400
38401
38402
38403
38404
38405
38406
38407
38408
38409
38410
38411
38412
38413
38414
38415
38416
38417
38418
38419
38420
38421
38422
38423
38424
38425
38426
38427
38428
38429
38430
38431
38432
38433
38434
38435
38436
38437
38438
38439
38440
38441
38442
38443
38444
38445
38446
38447
38448
38449
38450
38451
38452
38453
38454
38455
38456
38457
38458
38459
38460
38461
38462
38463
38464
38465
38466
38467
38468
38469
38470
38471
38472
38473
38474
38475
38476
38477
38478
38479
38480
38481
38482
38483
38484
38485
38486
38487
38488
38489
38490
38491
38492
38493
38494
38495
38496
38497
38498
38499
38500
38501
38502
38503
38504
38505
38506
38507
38508
38509
38510
38511
38512
38513
38514
38515
38516
38517
38518
38519
38520
38521
38522
38523
38524
38525
38526
38527
38528
38529
38530
38531
38532
38533
38534
38535
38536
38537
38538
38539
38540
38541
38542
38543
38544
38545
38546
38547
38548
38549
38550
38551
38552
38553
38554
38555
38556
38557
38558
38559
38560
38561
38562
38563
38564
38565
38566
38567
38568
38569
38570
38571
38572
38573
38574
38575
38576
38577
38578
38579
38580
38581
38582
38583
38584
38585
38586
38587
38588
38589
38590
38591
38592
38593
38594
38595
38596
38597
38598
38599
38600
38601
38602
38603
38604
38605
38606
38607
38608
38609
38610
38611
38612
38613
38614
38615
38616
38617
38618
38619
38620
38621
38622
38623
38624
38625
38626
38627
38628
38629
38630
38631
38632
38633
38634
38635
38636
38637
38638
38639
38640
38641
38642
38643
38644
38645
38646
38647
38648
38649
38650
38651
38652
38653
38654
38655
38656
38657
38658
38659
38660
38661
38662
38663
38664
38665
38666
38667
38668
38669
38670
38671
38672
38673
38674
38675
38676
38677
38678
38679
38680
38681
38682
38683
38684
38685
38686
38687
38688
38689
38690
38691
38692
38693
38694
38695
38696
38697
38698
38699
38700
38701
38702
38703
38704
38705
38706
38707
38708
38709
38710
38711
38712
38713
38714
38715
38716
38717
38718
38719
38720
38721
38722
38723
38724
38725
38726
38727
38728
38729
38730
38731
38732
38733
38734
38735
38736
38737
38738
38739
38740
38741
38742
38743
38744
38745
38746
38747
38748
38749
38750
38751
38752
38753
38754
38755
38756
38757
38758
38759
38760
38761
38762
38763
38764
38765
38766
38767
38768
38769
38770
38771
38772
38773
38774
38775
38776
38777
38778
38779
38780
38781
38782
38783
38784
38785
38786
38787
38788
38789
38790
38791
38792
38793
38794
38795
38796
38797
38798
38799
38800
38801
38802
38803
38804
38805
38806
38807
38808
38809
38810
38811
38812
38813
38814
38815
38816
38817
38818
38819
38820
38821
38822
38823
38824
38825
38826
38827
38828
38829
38830
38831
38832
38833
38834
38835
38836
38837
38838
38839
38840
38841
38842
38843
38844
38845
38846
38847
38848
38849
38850
38851
38852
38853
38854
38855
38856
38857
38858
38859
38860
38861
38862
38863
38864
38865
38866
38867
38868
38869
38870
38871
38872
38873
38874
38875
38876
38877
38878
38879
38880
38881
38882
38883
38884
38885
38886
38887
38888
38889
38890
38891
38892
38893
38894
38895
38896
38897
38898
38899
38900
38901
38902
38903
38904
38905
38906
38907
38908
38909
38910
38911
38912
38913
38914
38915
38916
38917
38918
38919
38920
38921
38922
38923
38924
38925
38926
38927
38928
38929
38930
38931
38932
38933
38934
38935
38936
38937
38938
38939
38940
38941
38942
38943
38944
38945
38946
38947
38948
38949
38950
38951
38952
38953
38954
38955
38956
38957
38958
38959
38960
38961
38962
38963
38964
38965
38966
38967
38968
38969
38970
38971
38972
38973
38974
38975
38976
38977
38978
38979
38980
38981
38982
38983
38984
38985
38986
38987
38988
38989
38990
38991
38992
38993
38994
38995
38996
38997
38998
38999
39000
39001
39002
39003
39004
39005
39006
39007
39008
39009
39010
39011
39012
39013
39014
39015
39016
39017
39018
39019
39020
39021
39022
39023
39024
39025
39026
39027
39028
39029
39030
39031
39032
39033
39034
39035
39036
39037
39038
39039
39040
39041
39042
39043
39044
39045
39046
39047
39048
39049
39050
39051
39052
39053
39054
39055
39056
39057
39058
39059
39060
39061
39062
39063
39064
39065
39066
39067
39068
39069
39070
39071
39072
39073
39074
39075
39076
39077
39078
39079
39080
39081
39082
39083
39084
39085
39086
39087
39088
39089
39090
39091
39092
39093
39094
39095
39096
39097
39098
39099
39100
39101
39102
39103
39104
39105
39106
39107
39108
39109
39110
39111
39112
39113
39114
39115
39116
39117
39118
39119
39120
39121
39122
39123
39124
39125
39126
39127
39128
39129
39130
39131
39132
39133
39134
39135
39136
39137
39138
39139
39140
39141
39142
39143
39144
39145
39146
39147
39148
39149
39150
39151
39152
39153
39154
39155
39156
39157
39158
39159
39160
39161
39162
39163
39164
39165
39166
39167
39168
39169
39170
39171
39172
39173
39174
39175
39176
39177
39178
39179
39180
39181
39182
39183
39184
39185
39186
39187
39188
39189
39190
39191
39192
39193
39194
39195
39196
39197
39198
39199
39200
39201
39202
39203
39204
39205
39206
39207
39208
39209
39210
39211
39212
39213
39214
39215
39216
39217
39218
39219
39220
39221
39222
39223
39224
39225
39226
39227
39228
39229
39230
39231
39232
39233
39234
39235
39236
39237
39238
39239
39240
39241
39242
39243
39244
39245
39246
39247
39248
39249
39250
39251
39252
39253
39254
39255
39256
39257
39258
39259
39260
39261
39262
39263
39264
39265
39266
39267
39268
39269
39270
39271
39272
39273
39274
39275
39276
39277
39278
39279
39280
39281
39282
39283
39284
39285
39286
39287
39288
39289
39290
39291
39292
39293
39294
39295
39296
39297
39298
39299
39300
39301
39302
39303
39304
39305
39306
39307
39308
39309
39310
39311
39312
39313
39314
39315
39316
39317
39318
39319
39320
39321
39322
39323
39324
39325
39326
39327
39328
39329
39330
39331
39332
39333
39334
39335
39336
39337
39338
39339
39340
39341
39342
39343
39344
39345
39346
39347
39348
39349
39350
39351
39352
39353
39354
39355
39356
39357
39358
39359
39360
39361
39362
39363
39364
39365
39366
39367
39368
39369
39370
39371
39372
39373
39374
39375
39376
39377
39378
39379
39380
39381
39382
39383
39384
39385
39386
39387
39388
39389
39390
39391
39392
39393
39394
39395
39396
39397
39398
39399
39400
39401
39402
39403
39404
39405
39406
39407
39408
39409
39410
39411
39412
39413
39414
39415
39416
39417
39418
39419
39420
39421
39422
39423
39424
39425
39426
39427
39428
39429
39430
39431
39432
39433
39434
39435
39436
39437
39438
39439
39440
39441
39442
39443
39444
39445
39446
39447
39448
39449
39450
39451
39452
39453
39454
39455
39456
39457
39458
39459
39460
39461
39462
39463
39464
39465
39466
39467
39468
39469
39470
39471
39472
39473
39474
39475
39476
39477
39478
39479
39480
39481
39482
39483
39484
39485
39486
39487
39488
39489
39490
39491
39492
39493
39494
39495
39496
39497
39498
39499
39500
39501
39502
39503
39504
39505
39506
39507
39508
39509
39510
39511
39512
39513
39514
39515
39516
39517
39518
39519
39520
39521
39522
39523
39524
39525
39526
39527
39528
39529
39530
39531
39532
39533
39534
39535
39536
39537
39538
39539
39540
39541
39542
39543
39544
39545
39546
39547
39548
39549
39550
39551
39552
39553
39554
39555
39556
39557
39558
39559
39560
39561
39562
39563
39564
39565
39566
39567
39568
39569
39570
39571
39572
39573
39574
39575
39576
39577
39578
39579
39580
39581
39582
39583
39584
39585
39586
39587
39588
39589
39590
39591
39592
39593
39594
39595
39596
39597
39598
39599
39600
39601
39602
39603
39604
39605
39606
39607
39608
39609
39610
39611
39612
39613
39614
39615
39616
39617
39618
39619
39620
39621
39622
39623
39624
39625
39626
39627
39628
39629
39630
39631
39632
39633
39634
39635
39636
39637
39638
39639
39640
39641
39642
39643
39644
39645
39646
39647
39648
39649
39650
39651
39652
39653
39654
39655
39656
39657
39658
39659
39660
39661
39662
39663
39664
39665
39666
39667
39668
39669
39670
39671
39672
39673
39674
39675
39676
39677
39678
39679
39680
39681
39682
39683
39684
39685
39686
39687
39688
39689
39690
39691
39692
39693
39694
39695
39696
39697
39698
39699
39700
39701
39702
39703
39704
39705
39706
39707
39708
39709
39710
39711
39712
39713
39714
39715
39716
39717
39718
39719
39720
39721
39722
39723
39724
39725
39726
39727
39728
39729
39730
39731
39732
39733
39734
39735
39736
39737
39738
39739
39740
39741
39742
39743
39744
39745
39746
39747
39748
39749
39750
39751
39752
39753
39754
39755
39756
39757
39758
39759
39760
39761
39762
39763
39764
39765
39766
39767
39768
39769
39770
39771
39772
39773
39774
39775
39776
39777
39778
39779
39780
39781
39782
39783
39784
39785
39786
39787
39788
39789
39790
39791
39792
39793
39794
39795
39796
39797
39798
39799
39800
39801
39802
39803
39804
39805
39806
39807
39808
39809
39810
39811
39812
39813
39814
39815
39816
39817
39818
39819
39820
39821
39822
39823
39824
39825
39826
39827
39828
39829
39830
39831
39832
39833
39834
39835
39836
39837
39838
39839
39840
39841
39842
39843
39844
39845
39846
39847
39848
39849
39850
39851
39852
39853
39854
39855
39856
39857
39858
39859
39860
39861
39862
39863
39864
39865
39866
39867
39868
39869
39870
39871
39872
39873
39874
39875
39876
39877
39878
39879
39880
39881
39882
39883
39884
39885
39886
39887
39888
39889
39890
39891
39892
39893
39894
39895
39896
39897
39898
39899
39900
39901
39902
39903
39904
39905
39906
39907
39908
39909
39910
39911
39912
39913
39914
39915
39916
39917
39918
39919
39920
39921
39922
39923
39924
39925
39926
39927
39928
39929
39930
39931
39932
39933
39934
39935
39936
39937
39938
39939
39940
39941
39942
39943
39944
39945
39946
39947
39948
39949
39950
39951
39952
39953
39954
39955
39956
39957
39958
39959
39960
39961
39962
39963
39964
39965
39966
39967
39968
39969
39970
39971
39972
39973
39974
39975
39976
39977
39978
39979
39980
39981
39982
39983
39984
39985
39986
39987
39988
39989
39990
39991
39992
39993
39994
39995
39996
39997
39998
39999
40000
40001
40002
40003
40004
40005
40006
40007
40008
40009
40010
40011
40012
40013
40014
40015
40016
40017
40018
40019
40020
40021
40022
40023
40024
40025
40026
40027
40028
40029
40030
40031
40032
40033
40034
40035
40036
40037
40038
40039
40040
40041
40042
40043
40044
40045
40046
40047
40048
40049
40050
40051
40052
40053
40054
40055
40056
40057
40058
40059
40060
40061
40062
40063
40064
40065
40066
40067
40068
40069
40070
40071
40072
40073
40074
40075
40076
40077
40078
40079
40080
40081
40082
40083
40084
40085
40086
40087
40088
40089
40090
40091
40092
40093
40094
40095
40096
40097
40098
40099
40100
40101
40102
40103
40104
40105
40106
40107
40108
40109
40110
40111
40112
40113
40114
40115
40116
40117
40118
40119
40120
40121
40122
40123
40124
40125
40126
40127
40128
40129
40130
40131
40132
40133
40134
40135
40136
40137
40138
40139
40140
40141
40142
40143
40144
40145
40146
40147
40148
40149
40150
40151
40152
40153
40154
40155
40156
40157
40158
40159
40160
40161
40162
40163
40164
40165
40166
40167
40168
40169
40170
40171
40172
40173
40174
40175
40176
40177
40178
40179
40180
40181
40182
40183
40184
40185
40186
40187
40188
40189
40190
40191
40192
40193
40194
40195
40196
40197
40198
40199
40200
40201
40202
40203
40204
40205
40206
40207
40208
40209
40210
40211
40212
40213
40214
40215
40216
40217
40218
40219
40220
40221
40222
40223
40224
40225
40226
40227
40228
40229
40230
40231
40232
40233
40234
40235
40236
40237
40238
40239
40240
40241
40242
40243
40244
40245
40246
40247
40248
40249
40250
40251
40252
40253
40254
40255
40256
40257
40258
40259
40260
40261
40262
40263
40264
40265
40266
40267
40268
40269
40270
40271
40272
40273
40274
40275
40276
40277
40278
40279
40280
40281
40282
40283
40284
40285
40286
40287
40288
40289
40290
40291
40292
40293
40294
40295
40296
40297
40298
40299
40300
40301
40302
40303
40304
40305
40306
40307
40308
40309
40310
40311
40312
40313
40314
40315
40316
40317
40318
40319
40320
40321
40322
40323
40324
40325
40326
40327
40328
40329
40330
40331
40332
40333
40334
40335
40336
40337
40338
40339
40340
40341
40342
40343
40344
40345
40346
40347
40348
40349
40350
40351
40352
40353
40354
40355
40356
40357
40358
40359
40360
40361
40362
40363
40364
40365
40366
40367
40368
40369
40370
40371
40372
40373
40374
40375
40376
40377
40378
40379
40380
40381
40382
40383
40384
40385
40386
40387
40388
40389
40390
40391
40392
40393
40394
40395
40396
40397
40398
40399
40400
40401
40402
40403
40404
40405
40406
40407
40408
40409
40410
40411
40412
40413
40414
40415
40416
40417
40418
40419
40420
40421
40422
40423
40424
40425
40426
40427
40428
40429
40430
40431
40432
40433
40434
40435
40436
40437
40438
40439
40440
40441
40442
40443
40444
40445
40446
40447
40448
40449
40450
40451
40452
40453
40454
40455
40456
40457
40458
40459
40460
40461
40462
40463
40464
40465
40466
40467
40468
40469
40470
40471
40472
40473
40474
40475
40476
40477
40478
40479
40480
40481
40482
40483
40484
40485
40486
40487
40488
40489
40490
40491
40492
40493
40494
40495
40496
40497
40498
40499
40500
40501
40502
40503
40504
40505
40506
40507
40508
40509
40510
40511
40512
40513
40514
40515
40516
40517
40518
40519
40520
40521
40522
40523
40524
40525
40526
40527
40528
40529
40530
40531
40532
40533
40534
40535
40536
40537
40538
40539
40540
40541
40542
40543
40544
40545
40546
40547
40548
40549
40550
40551
40552
40553
40554
40555
40556
40557
40558
40559
40560
40561
40562
40563
40564
40565
40566
40567
40568
40569
40570
40571
40572
40573
40574
40575
40576
40577
40578
40579
40580
40581
40582
40583
40584
40585
40586
40587
40588
40589
40590
40591
40592
40593
40594
40595
40596
40597
40598
40599
40600
40601
40602
40603
40604
40605
40606
40607
40608
40609
40610
40611
40612
40613
40614
40615
40616
40617
40618
40619
40620
40621
40622
40623
40624
40625
40626
40627
40628
40629
40630
40631
40632
40633
40634
40635
40636
40637
40638
40639
40640
40641
40642
40643
40644
40645
40646
40647
40648
40649
40650
40651
40652
40653
40654
40655
40656
40657
40658
40659
40660
40661
40662
40663
40664
40665
40666
40667
40668
40669
40670
40671
40672
40673
40674
40675
40676
40677
40678
40679
40680
40681
40682
40683
40684
40685
40686
40687
40688
40689
40690
40691
40692
40693
40694
40695
40696
40697
40698
40699
40700
40701
40702
40703
40704
40705
40706
40707
40708
40709
40710
40711
40712
40713
40714
40715
40716
40717
40718
40719
40720
40721
40722
40723
40724
40725
40726
40727
40728
40729
40730
40731
40732
40733
40734
40735
40736
40737
40738
40739
40740
40741
40742
40743
40744
40745
40746
40747
40748
40749
40750
40751
40752
40753
40754
40755
40756
40757
40758
40759
40760
40761
40762
40763
40764
40765
40766
40767
40768
40769
40770
40771
40772
40773
40774
40775
40776
40777
40778
40779
40780
40781
40782
40783
40784
40785
40786
40787
40788
40789
40790
40791
40792
40793
40794
40795
40796
40797
40798
40799
40800
40801
40802
40803
40804
40805
40806
40807
40808
40809
40810
40811
40812
40813
40814
40815
40816
40817
40818
40819
40820
40821
40822
40823
40824
40825
40826
40827
40828
40829
40830
40831
40832
40833
40834
40835
40836
40837
40838
40839
40840
40841
40842
40843
40844
40845
40846
40847
40848
40849
40850
40851
40852
40853
40854
40855
40856
40857
40858
40859
40860
40861
40862
40863
40864
40865
40866
40867
40868
40869
40870
40871
40872
40873
40874
40875
40876
40877
40878
40879
40880
40881
40882
40883
40884
40885
40886
40887
40888
40889
40890
40891
40892
40893
40894
40895
40896
40897
40898
40899
40900
40901
40902
40903
40904
40905
40906
40907
40908
40909
40910
40911
40912
40913
40914
40915
40916
40917
40918
40919
40920
40921
40922
40923
40924
40925
40926
40927
40928
40929
40930
40931
40932
40933
40934
40935
40936
40937
40938
40939
40940
40941
40942
40943
40944
40945
40946
40947
40948
40949
40950
40951
40952
40953
40954
40955
40956
40957
40958
40959
40960
40961
40962
40963
40964
40965
40966
40967
40968
40969
40970
40971
40972
40973
40974
40975
40976
40977
40978
40979
40980
40981
40982
40983
40984
40985
40986
40987
40988
40989
40990
40991
40992
40993
40994
40995
40996
40997
40998
40999
41000
41001
41002
41003
41004
41005
41006
41007
41008
41009
41010
41011
41012
41013
41014
41015
41016
41017
41018
41019
41020
41021
41022
41023
41024
41025
41026
41027
41028
41029
41030
41031
41032
41033
41034
41035
41036
41037
41038
41039
41040
41041
41042
41043
41044
41045
41046
41047
41048
41049
41050
41051
41052
41053
41054
41055
41056
41057
41058
41059
41060
41061
41062
41063
41064
41065
41066
41067
41068
41069
41070
41071
41072
41073
41074
41075
41076
41077
41078
41079
41080
41081
41082
41083
41084
41085
41086
41087
41088
41089
41090
41091
41092
41093
41094
41095
41096
41097
41098
41099
41100
41101
41102
41103
41104
41105
41106
41107
41108
41109
41110
41111
41112
41113
41114
41115
41116
41117
41118
41119
41120
41121
41122
41123
41124
41125
41126
41127
41128
41129
41130
41131
41132
41133
41134
41135
41136
41137
41138
41139
41140
41141
41142
41143
41144
41145
41146
41147
41148
41149
41150
41151
41152
41153
41154
41155
41156
41157
41158
41159
41160
41161
41162
41163
41164
41165
41166
41167
41168
41169
41170
41171
41172
41173
41174
41175
41176
41177
41178
41179
41180
41181
41182
41183
41184
41185
41186
41187
41188
41189
41190
41191
41192
41193
41194
41195
41196
41197
41198
41199
41200
41201
41202
41203
41204
41205
41206
41207
41208
41209
41210
41211
41212
41213
41214
41215
41216
41217
41218
41219
41220
41221
41222
41223
41224
41225
41226
41227
41228
41229
41230
41231
41232
41233
41234
41235
41236
41237
41238
41239
41240
41241
41242
41243
41244
41245
41246
41247
41248
41249
41250
41251
41252
41253
41254
41255
41256
41257
41258
41259
41260
41261
41262
41263
41264
41265
41266
41267
41268
41269
41270
41271
41272
41273
41274
41275
41276
41277
41278
41279
41280
41281
41282
41283
41284
41285
41286
41287
41288
41289
41290
41291
41292
41293
41294
41295
41296
41297
41298
41299
41300
41301
41302
41303
41304
41305
41306
41307
41308
41309
41310
41311
41312
41313
41314
41315
41316
41317
41318
41319
41320
41321
41322
41323
41324
41325
41326
41327
41328
41329
41330
41331
41332
41333
41334
41335
41336
41337
41338
41339
41340
41341
41342
41343
41344
41345
41346
41347
41348
41349
41350
41351
41352
41353
41354
41355
41356
41357
41358
41359
41360
41361
41362
41363
41364
41365
41366
41367
41368
41369
41370
41371
41372
41373
41374
41375
41376
41377
41378
41379
41380
41381
41382
41383
41384
41385
41386
41387
41388
41389
41390
41391
41392
41393
41394
41395
41396
41397
41398
41399
41400
41401
41402
41403
41404
41405
41406
41407
41408
41409
41410
41411
41412
41413
41414
41415
41416
41417
41418
41419
41420
41421
41422
41423
41424
41425
41426
41427
41428
41429
41430
41431
41432
41433
41434
41435
41436
41437
41438
41439
41440
41441
41442
41443
41444
41445
41446
41447
41448
41449
41450
41451
41452
41453
41454
41455
41456
41457
41458
41459
41460
41461
41462
41463
41464
41465
41466
41467
41468
41469
41470
41471
41472
41473
41474
41475
41476
41477
41478
41479
41480
41481
41482
41483
41484
41485
41486
41487
41488
41489
41490
41491
41492
41493
41494
41495
41496
41497
41498
41499
41500
41501
41502
41503
41504
41505
41506
41507
41508
41509
41510
41511
41512
41513
41514
41515
41516
41517
41518
41519
41520
41521
41522
41523
41524
41525
41526
41527
41528
41529
41530
41531
41532
41533
41534
41535
41536
41537
41538
41539
41540
41541
41542
41543
41544
41545
41546
41547
41548
41549
41550
41551
41552
41553
41554
41555
41556
41557
41558
41559
41560
41561
41562
41563
41564
41565
41566
41567
41568
41569
41570
41571
41572
41573
41574
41575
41576
41577
41578
41579
41580
41581
41582
41583
41584
41585
41586
41587
41588
41589
41590
41591
41592
41593
41594
41595
41596
41597
41598
41599
41600
41601
41602
41603
41604
41605
41606
41607
41608
41609
41610
41611
41612
41613
41614
41615
41616
41617
41618
41619
41620
41621
41622
41623
41624
41625
41626
41627
41628
41629
41630
41631
41632
41633
41634
41635
41636
41637
41638
41639
41640
41641
41642
41643
41644
41645
41646
41647
41648
41649
41650
41651
41652
41653
41654
41655
41656
41657
41658
41659
41660
41661
41662
41663
41664
41665
41666
41667
41668
41669
41670
41671
41672
41673
41674
41675
41676
41677
41678
41679
41680
41681
41682
41683
41684
41685
41686
41687
41688
41689
41690
41691
41692
41693
41694
41695
41696
41697
41698
41699
41700
41701
41702
41703
41704
41705
41706
41707
41708
41709
41710
41711
41712
41713
41714
41715
41716
41717
41718
41719
41720
41721
41722
41723
41724
41725
41726
41727
41728
41729
41730
41731
41732
41733
41734
41735
41736
41737
41738
41739
41740
41741
41742
41743
41744
41745
41746
41747
41748
41749
41750
41751
41752
41753
41754
41755
41756
41757
41758
41759
41760
41761
41762
41763
41764
41765
41766
41767
41768
41769
41770
41771
41772
41773
41774
41775
41776
41777
41778
41779
41780
41781
41782
41783
41784
41785
41786
41787
41788
41789
41790
41791
41792
41793
41794
41795
41796
41797
41798
41799
41800
41801
41802
41803
41804
41805
41806
41807
41808
41809
41810
41811
41812
41813
41814
41815
41816
41817
41818
41819
41820
41821
41822
41823
41824
41825
41826
41827
41828
41829
41830
41831
41832
41833
41834
41835
41836
41837
41838
41839
41840
41841
41842
41843
41844
41845
41846
41847
41848
41849
41850
41851
41852
41853
41854
41855
41856
41857
41858
41859
41860
41861
41862
41863
41864
41865
41866
41867
41868
41869
41870
41871
41872
41873
41874
41875
41876
41877
41878
41879
41880
41881
41882
41883
41884
41885
41886
41887
41888
41889
41890
41891
41892
41893
41894
41895
41896
41897
41898
41899
41900
41901
41902
41903
41904
41905
41906
41907
41908
41909
41910
41911
41912
41913
41914
41915
41916
41917
41918
41919
41920
41921
41922
41923
41924
41925
41926
41927
41928
41929
41930
41931
41932
41933
41934
41935
41936
41937
41938
41939
41940
41941
41942
41943
41944
41945
41946
41947
41948
41949
41950
41951
41952
41953
41954
41955
41956
41957
41958
41959
41960
41961
41962
41963
41964
41965
41966
41967
41968
41969
41970
41971
41972
41973
41974
41975
41976
41977
41978
41979
41980
41981
41982
41983
41984
41985
41986
41987
41988
41989
41990
41991
41992
41993
41994
41995
41996
41997
41998
41999
42000
42001
42002
42003
42004
42005
42006
42007
42008
42009
42010
42011
42012
42013
42014
42015
42016
42017
42018
42019
42020
42021
42022
42023
42024
42025
42026
42027
42028
42029
42030
42031
42032
42033
42034
42035
42036
42037
42038
42039
42040
42041
42042
42043
42044
42045
42046
42047
42048
42049
42050
42051
42052
42053
42054
42055
42056
42057
42058
42059
42060
42061
42062
42063
42064
42065
42066
42067
42068
42069
42070
42071
42072
42073
42074
42075
42076
42077
42078
42079
42080
42081
42082
42083
42084
42085
42086
42087
42088
42089
42090
42091
42092
42093
42094
42095
42096
42097
42098
42099
42100
42101
42102
42103
42104
42105
42106
42107
42108
42109
42110
42111
42112
42113
42114
42115
42116
42117
42118
42119
42120
42121
42122
42123
42124
42125
42126
42127
42128
42129
42130
42131
42132
42133
42134
42135
42136
42137
42138
42139
42140
42141
42142
42143
42144
42145
42146
42147
42148
42149
42150
42151
42152
42153
42154
42155
42156
42157
42158
42159
42160
42161
42162
42163
42164
42165
42166
42167
42168
42169
42170
42171
42172
42173
42174
42175
42176
42177
42178
42179
42180
42181
42182
42183
42184
42185
42186
42187
42188
42189
42190
42191
42192
42193
42194
42195
42196
42197
42198
42199
42200
42201
42202
42203
42204
42205
42206
42207
42208
42209
42210
42211
42212
42213
42214
42215
42216
42217
42218
42219
42220
42221
42222
42223
42224
42225
42226
42227
42228
42229
42230
42231
42232
42233
42234
42235
42236
42237
42238
42239
42240
42241
42242
42243
42244
42245
42246
42247
42248
42249
42250
42251
42252
42253
42254
42255
42256
42257
42258
42259
42260
42261
42262
42263
42264
42265
42266
42267
42268
42269
42270
42271
42272
42273
42274
42275
42276
42277
42278
42279
42280
42281
42282
42283
42284
42285
42286
42287
42288
42289
42290
42291
42292
42293
42294
42295
42296
42297
42298
42299
42300
42301
42302
42303
42304
42305
42306
42307
42308
42309
42310
42311
42312
42313
42314
42315
42316
42317
42318
42319
42320
42321
42322
42323
42324
42325
42326
42327
42328
42329
42330
42331
42332
42333
42334
42335
42336
42337
42338
42339
42340
42341
42342
42343
42344
42345
42346
42347
42348
42349
42350
42351
42352
42353
42354
42355
42356
42357
42358
42359
42360
42361
42362
42363
42364
42365
42366
42367
42368
42369
42370
42371
42372
42373
42374
42375
42376
42377
42378
42379
42380
42381
42382
42383
42384
42385
42386
42387
42388
42389
42390
42391
42392
42393
42394
42395
42396
42397
42398
42399
42400
42401
42402
42403
42404
42405
42406
42407
42408
42409
42410
42411
42412
42413
42414
42415
42416
42417
42418
42419
42420
42421
42422
42423
42424
42425
42426
42427
42428
42429
42430
42431
42432
42433
42434
42435
42436
42437
42438
42439
42440
42441
42442
42443
42444
42445
42446
42447
42448
42449
42450
42451
42452
42453
42454
42455
42456
42457
42458
42459
42460
42461
42462
42463
42464
42465
42466
42467
42468
42469
42470
42471
42472
42473
42474
42475
42476
42477
42478
42479
42480
42481
42482
42483
42484
42485
42486
42487
42488
42489
42490
42491
42492
42493
42494
42495
42496
42497
42498
42499
42500
42501
42502
42503
42504
42505
42506
42507
42508
42509
42510
42511
42512
42513
42514
42515
42516
42517
42518
42519
42520
42521
42522
42523
42524
42525
42526
42527
42528
42529
42530
42531
42532
42533
42534
42535
42536
42537
42538
42539
42540
42541
42542
42543
42544
42545
42546
42547
42548
42549
42550
42551
42552
42553
42554
42555
42556
42557
42558
42559
42560
42561
42562
42563
42564
42565
42566
42567
42568
42569
42570
42571
42572
42573
42574
42575
42576
42577
42578
42579
42580
42581
42582
42583
42584
42585
42586
42587
42588
42589
42590
42591
42592
42593
42594
42595
42596
42597
42598
42599
42600
42601
42602
42603
42604
42605
42606
42607
42608
42609
42610
42611
42612
42613
42614
42615
42616
42617
42618
42619
42620
42621
42622
42623
42624
42625
42626
42627
42628
42629
42630
42631
42632
42633
42634
42635
42636
42637
42638
42639
42640
42641
42642
42643
42644
42645
42646
42647
42648
42649
42650
42651
42652
42653
42654
42655
42656
42657
42658
42659
42660
42661
42662
42663
42664
42665
42666
42667
42668
42669
42670
42671
42672
42673
42674
42675
42676
42677
42678
42679
42680
42681
42682
42683
42684
42685
42686
42687
42688
42689
42690
42691
42692
42693
42694
42695
42696
42697
42698
42699
42700
42701
42702
42703
42704
42705
42706
42707
42708
42709
42710
42711
42712
42713
42714
42715
42716
42717
42718
42719
42720
42721
42722
42723
42724
42725
42726
42727
42728
42729
42730
42731
42732
42733
42734
42735
42736
42737
42738
42739
42740
42741
42742
42743
42744
42745
42746
42747
42748
42749
42750
42751
42752
42753
42754
42755
42756
42757
42758
42759
42760
42761
42762
42763
42764
42765
42766
42767
42768
42769
42770
42771
42772
42773
42774
42775
42776
42777
42778
42779
42780
42781
42782
42783
42784
42785
42786
42787
42788
42789
42790
42791
42792
42793
42794
42795
42796
42797
42798
42799
42800
42801
42802
42803
42804
42805
42806
42807
42808
42809
42810
42811
42812
42813
42814
42815
42816
42817
42818
42819
42820
42821
42822
42823
42824
42825
42826
42827
42828
42829
42830
42831
42832
42833
42834
42835
42836
42837
42838
42839
42840
42841
42842
42843
42844
42845
42846
42847
42848
42849
42850
42851
42852
42853
42854
42855
42856
42857
42858
42859
42860
42861
42862
42863
42864
42865
42866
42867
42868
42869
42870
42871
42872
42873
42874
42875
42876
42877
42878
42879
42880
42881
42882
42883
42884
42885
42886
42887
42888
42889
42890
42891
42892
42893
42894
42895
42896
42897
42898
42899
42900
42901
42902
42903
42904
42905
42906
42907
42908
42909
42910
42911
42912
42913
42914
42915
42916
42917
42918
42919
42920
42921
42922
42923
42924
42925
42926
42927
42928
42929
42930
42931
42932
42933
42934
42935
42936
42937
42938
42939
42940
42941
42942
42943
42944
42945
42946
42947
42948
42949
42950
42951
42952
42953
42954
42955
42956
42957
42958
42959
42960
42961
42962
42963
42964
42965
42966
42967
42968
42969
42970
42971
42972
42973
42974
42975
42976
42977
42978
42979
42980
42981
42982
42983
42984
42985
42986
42987
42988
42989
42990
42991
42992
42993
42994
42995
42996
42997
42998
42999
43000
43001
43002
43003
43004
43005
43006
43007
43008
43009
43010
43011
43012
43013
43014
43015
43016
43017
43018
43019
43020
43021
43022
43023
43024
43025
43026
43027
43028
43029
43030
43031
43032
43033
43034
43035
43036
43037
43038
43039
43040
43041
43042
43043
43044
43045
43046
43047
43048
43049
43050
43051
43052
43053
43054
43055
43056
43057
43058
43059
43060
43061
43062
43063
43064
43065
43066
43067
43068
43069
43070
43071
43072
43073
43074
43075
43076
43077
43078
43079
43080
43081
43082
43083
43084
43085
43086
43087
43088
43089
43090
43091
43092
43093
43094
43095
43096
43097
43098
43099
43100
43101
43102
43103
43104
43105
43106
43107
43108
43109
43110
43111
43112
43113
43114
43115
43116
43117
43118
43119
43120
43121
43122
43123
43124
43125
43126
43127
43128
43129
43130
43131
43132
43133
43134
43135
43136
43137
43138
43139
43140
43141
43142
43143
43144
43145
43146
43147
43148
43149
43150
43151
43152
43153
43154
43155
43156
43157
43158
43159
43160
43161
43162
43163
43164
43165
43166
43167
43168
43169
43170
43171
43172
43173
43174
43175
43176
43177
43178
43179
43180
43181
43182
43183
43184
43185
43186
43187
43188
43189
43190
43191
43192
43193
43194
43195
43196
43197
43198
43199
43200
43201
43202
43203
43204
43205
43206
43207
43208
43209
43210
43211
43212
43213
43214
43215
43216
43217
43218
43219
43220
43221
43222
43223
43224
43225
43226
43227
43228
43229
43230
43231
43232
43233
43234
43235
43236
43237
43238
43239
43240
43241
43242
43243
43244
43245
43246
43247
43248
43249
43250
43251
43252
43253
43254
43255
43256
43257
43258
43259
43260
43261
43262
43263
43264
43265
43266
43267
43268
43269
43270
43271
43272
43273
43274
43275
43276
43277
43278
43279
43280
43281
43282
43283
43284
43285
43286
43287
43288
43289
43290
43291
43292
43293
43294
43295
43296
43297
43298
43299
43300
43301
43302
43303
43304
43305
43306
43307
43308
43309
43310
43311
43312
43313
43314
43315
43316
43317
43318
43319
43320
43321
43322
43323
43324
43325
43326
43327
43328
43329
43330
43331
43332
43333
43334
43335
43336
43337
43338
43339
43340
43341
43342
43343
43344
43345
43346
43347
43348
43349
43350
43351
43352
43353
43354
43355
43356
43357
43358
43359
43360
43361
43362
43363
43364
43365
43366
43367
43368
43369
43370
43371
43372
43373
43374
43375
43376
43377
43378
43379
43380
43381
43382
43383
43384
43385
43386
43387
43388
43389
43390
43391
43392
43393
43394
43395
43396
43397
43398
43399
43400
43401
43402
43403
43404
43405
43406
43407
43408
43409
43410
43411
43412
43413
43414
43415
43416
43417
43418
43419
43420
43421
43422
43423
43424
43425
43426
43427
43428
43429
43430
43431
43432
43433
43434
43435
43436
43437
43438
43439
43440
43441
43442
43443
43444
43445
43446
43447
43448
43449
43450
43451
43452
43453
43454
43455
43456
43457
43458
43459
43460
43461
43462
43463
43464
43465
43466
43467
43468
43469
43470
43471
43472
43473
43474
43475
43476
43477
43478
43479
43480
43481
43482
43483
43484
43485
43486
43487
43488
43489
43490
43491
43492
43493
43494
43495
43496
43497
43498
43499
43500
43501
43502
43503
43504
43505
43506
43507
43508
43509
43510
43511
43512
43513
43514
43515
43516
43517
43518
43519
43520
43521
43522
43523
43524
43525
43526
43527
43528
43529
43530
43531
43532
43533
43534
43535
43536
43537
43538
43539
43540
43541
43542
43543
43544
43545
43546
43547
43548
43549
43550
43551
43552
43553
43554
43555
43556
43557
43558
43559
43560
43561
43562
43563
43564
43565
43566
43567
43568
43569
43570
43571
43572
43573
43574
43575
43576
43577
43578
43579
43580
43581
43582
43583
43584
43585
43586
43587
43588
43589
43590
43591
43592
43593
43594
43595
43596
43597
43598
43599
43600
43601
43602
43603
43604
43605
43606
43607
43608
43609
43610
43611
43612
43613
43614
43615
43616
43617
43618
43619
43620
43621
43622
43623
43624
43625
43626
43627
43628
43629
43630
43631
43632
43633
43634
43635
43636
43637
43638
43639
43640
43641
43642
43643
43644
43645
43646
43647
43648
43649
43650
43651
43652
43653
43654
43655
43656
43657
43658
43659
43660
43661
43662
43663
43664
43665
43666
43667
43668
43669
43670
43671
43672
43673
43674
43675
43676
43677
43678
43679
43680
43681
43682
43683
43684
43685
43686
43687
43688
43689
43690
43691
43692
43693
43694
43695
43696
43697
43698
43699
43700
43701
43702
43703
43704
43705
43706
43707
43708
43709
43710
43711
43712
43713
43714
43715
43716
43717
43718
43719
43720
43721
43722
43723
43724
43725
43726
43727
43728
43729
43730
43731
43732
43733
43734
43735
43736
43737
43738
43739
43740
43741
43742
43743
43744
43745
43746
43747
43748
43749
43750
43751
43752
43753
43754
43755
43756
43757
43758
43759
43760
43761
43762
43763
43764
43765
43766
43767
43768
43769
43770
43771
43772
43773
43774
43775
43776
43777
43778
43779
43780
43781
43782
43783
43784
43785
43786
43787
43788
43789
43790
43791
43792
43793
43794
43795
43796
43797
43798
43799
43800
43801
43802
43803
43804
43805
43806
43807
43808
43809
43810
43811
43812
43813
43814
43815
43816
43817
43818
43819
43820
43821
43822
43823
43824
43825
43826
43827
43828
43829
43830
43831
43832
43833
43834
43835
43836
43837
43838
43839
43840
43841
43842
43843
43844
43845
43846
43847
43848
43849
43850
43851
43852
43853
43854
43855
43856
43857
43858
43859
43860
43861
43862
43863
43864
43865
43866
43867
43868
43869
43870
43871
43872
43873
43874
43875
43876
43877
43878
43879
43880
43881
43882
43883
43884
43885
43886
43887
43888
43889
43890
43891
43892
43893
43894
43895
43896
43897
43898
43899
43900
43901
43902
43903
43904
43905
43906
43907
43908
43909
43910
43911
43912
43913
43914
43915
43916
43917
43918
43919
43920
43921
43922
43923
43924
43925
43926
43927
43928
43929
43930
43931
43932
43933
43934
43935
43936
43937
43938
43939
43940
43941
43942
43943
43944
43945
43946
43947
43948
43949
43950
43951
43952
43953
43954
43955
43956
43957
43958
43959
43960
43961
43962
43963
43964
43965
43966
43967
43968
43969
43970
43971
43972
43973
43974
43975
43976
43977
43978
43979
43980
43981
43982
43983
43984
43985
43986
43987
43988
43989
43990
43991
43992
43993
43994
43995
43996
43997
43998
43999
44000
44001
44002
44003
44004
44005
44006
44007
44008
44009
44010
44011
44012
44013
44014
44015
44016
44017
44018
44019
44020
44021
44022
44023
44024
44025
44026
44027
44028
44029
44030
44031
44032
44033
44034
44035
44036
44037
44038
44039
44040
44041
44042
44043
44044
44045
44046
44047
44048
44049
44050
44051
44052
44053
44054
44055
44056
44057
44058
44059
44060
44061
44062
44063
44064
44065
44066
44067
44068
44069
44070
44071
44072
44073
44074
44075
44076
44077
44078
44079
44080
44081
44082
44083
44084
44085
44086
44087
44088
44089
44090
44091
44092
44093
44094
44095
44096
44097
44098
44099
44100
44101
44102
44103
44104
44105
44106
44107
44108
44109
44110
44111
44112
44113
44114
44115
44116
44117
44118
44119
44120
44121
44122
44123
44124
44125
44126
44127
44128
44129
44130
44131
44132
44133
44134
44135
44136
44137
44138
44139
44140
44141
44142
44143
44144
44145
44146
44147
44148
44149
44150
44151
44152
44153
44154
44155
44156
44157
44158
44159
44160
44161
44162
44163
44164
44165
44166
44167
44168
44169
44170
44171
44172
44173
44174
44175
44176
44177
44178
44179
44180
44181
44182
44183
44184
44185
44186
44187
44188
44189
44190
44191
44192
44193
44194
44195
44196
44197
44198
44199
44200
44201
44202
44203
44204
44205
44206
44207
44208
44209
44210
44211
44212
44213
44214
44215
44216
44217
44218
44219
44220
44221
44222
44223
44224
44225
44226
44227
44228
44229
44230
44231
44232
44233
44234
44235
44236
44237
44238
44239
44240
44241
44242
44243
44244
44245
44246
44247
44248
44249
44250
44251
44252
44253
44254
44255
44256
44257
44258
44259
44260
44261
44262
44263
44264
44265
44266
44267
44268
44269
44270
44271
44272
44273
44274
44275
44276
44277
44278
44279
44280
44281
44282
44283
44284
44285
44286
44287
44288
44289
44290
44291
44292
44293
44294
44295
44296
44297
44298
44299
44300
44301
44302
44303
44304
44305
44306
44307
44308
44309
44310
44311
44312
44313
44314
44315
44316
44317
44318
44319
44320
44321
44322
44323
44324
44325
44326
44327
44328
44329
44330
44331
44332
44333
44334
44335
44336
44337
44338
44339
44340
44341
44342
44343
44344
44345
44346
44347
44348
44349
44350
44351
44352
44353
44354
44355
44356
44357
44358
44359
44360
44361
44362
44363
44364
44365
44366
44367
44368
44369
44370
44371
44372
44373
44374
44375
44376
44377
44378
44379
44380
44381
44382
44383
44384
44385
44386
44387
44388
44389
44390
44391
44392
44393
44394
44395
44396
44397
44398
44399
44400
44401
44402
44403
44404
44405
44406
44407
44408
44409
44410
44411
44412
44413
44414
44415
44416
44417
44418
44419
44420
44421
44422
44423
44424
44425
44426
44427
44428
44429
44430
44431
44432
44433
44434
44435
44436
44437
44438
44439
44440
44441
44442
44443
44444
44445
44446
44447
44448
44449
44450
44451
44452
44453
44454
44455
44456
44457
44458
44459
44460
44461
44462
44463
44464
44465
44466
44467
44468
44469
44470
44471
44472
44473
44474
44475
44476
44477
44478
44479
44480
44481
44482
44483
44484
44485
44486
44487
44488
44489
44490
44491
44492
44493
44494
44495
44496
44497
44498
44499
44500
44501
44502
44503
44504
44505
44506
44507
44508
44509
44510
44511
44512
44513
44514
44515
44516
44517
44518
44519
44520
44521
44522
44523
44524
44525
44526
44527
44528
44529
44530
44531
44532
44533
44534
44535
44536
44537
44538
44539
44540
44541
44542
44543
44544
44545
44546
44547
44548
44549
44550
44551
44552
44553
44554
44555
44556
44557
44558
44559
44560
44561
44562
44563
44564
44565
44566
44567
44568
44569
44570
44571
44572
44573
44574
44575
44576
44577
44578
44579
44580
44581
44582
44583
44584
44585
44586
44587
44588
44589
44590
44591
44592
44593
44594
44595
44596
44597
44598
44599
44600
44601
44602
44603
44604
44605
44606
44607
44608
44609
44610
44611
44612
44613
44614
44615
44616
44617
44618
44619
44620
44621
44622
44623
44624
44625
44626
44627
44628
44629
44630
44631
44632
44633
44634
44635
44636
44637
44638
44639
44640
44641
44642
44643
44644
44645
44646
44647
44648
44649
44650
44651
44652
44653
44654
44655
44656
44657
44658
44659
44660
44661
44662
44663
44664
44665
44666
44667
44668
44669
44670
44671
44672
44673
44674
44675
44676
44677
44678
44679
44680
44681
44682
44683
44684
44685
44686
44687
44688
44689
44690
44691
44692
44693
44694
44695
44696
44697
44698
44699
44700
44701
44702
44703
44704
44705
44706
44707
44708
44709
44710
44711
44712
44713
44714
44715
44716
44717
44718
44719
44720
44721
44722
44723
44724
44725
44726
44727
44728
44729
44730
44731
44732
44733
44734
44735
44736
44737
44738
44739
44740
44741
44742
44743
44744
44745
44746
44747
44748
44749
44750
44751
44752
44753
44754
44755
44756
44757
44758
44759
44760
44761
44762
44763
44764
44765
44766
44767
44768
44769
44770
44771
44772
44773
44774
44775
44776
44777
44778
44779
44780
44781
44782
44783
44784
44785
44786
44787
44788
44789
44790
44791
44792
44793
44794
44795
44796
44797
44798
44799
44800
44801
44802
44803
44804
44805
44806
44807
44808
44809
44810
44811
44812
44813
44814
44815
44816
44817
44818
44819
44820
44821
44822
44823
44824
44825
44826
44827
44828
44829
44830
44831
44832
44833
44834
44835
44836
44837
44838
44839
44840
44841
44842
44843
44844
44845
44846
44847
44848
44849
44850
44851
44852
44853
44854
44855
44856
44857
44858
44859
44860
44861
44862
44863
44864
44865
44866
44867
44868
44869
44870
44871
44872
44873
44874
44875
44876
44877
44878
44879
44880
44881
44882
44883
44884
44885
44886
44887
44888
44889
44890
44891
44892
44893
44894
44895
44896
44897
44898
44899
44900
44901
44902
44903
44904
44905
44906
44907
44908
44909
44910
44911
44912
44913
44914
44915
44916
44917
44918
44919
44920
44921
44922
44923
44924
44925
44926
44927
44928
44929
44930
44931
44932
44933
44934
44935
44936
44937
44938
44939
44940
44941
44942
44943
44944
44945
44946
44947
44948
44949
44950
44951
44952
44953
44954
44955
44956
44957
44958
44959
44960
44961
44962
44963
44964
44965
44966
44967
44968
44969
44970
44971
44972
44973
44974
44975
44976
44977
44978
44979
44980
44981
44982
44983
44984
44985
44986
44987
44988
44989
44990
44991
44992
44993
44994
44995
44996
44997
44998
44999
45000
45001
45002
45003
45004
45005
45006
45007
45008
45009
45010
45011
45012
45013
45014
45015
45016
45017
45018
45019
45020
45021
45022
45023
45024
45025
45026
45027
45028
45029
45030
45031
45032
45033
45034
45035
45036
45037
45038
45039
45040
45041
45042
45043
45044
45045
45046
45047
45048
45049
45050
45051
45052
45053
45054
45055
45056
45057
45058
45059
45060
45061
45062
45063
45064
45065
45066
45067
45068
45069
45070
45071
45072
45073
45074
45075
45076
45077
45078
45079
45080
45081
45082
45083
45084
45085
45086
45087
45088
45089
45090
45091
45092
45093
45094
45095
45096
45097
45098
45099
45100
45101
45102
45103
45104
45105
45106
45107
45108
45109
45110
45111
45112
45113
45114
45115
45116
45117
45118
45119
45120
45121
45122
45123
45124
45125
45126
45127
45128
45129
45130
45131
45132
45133
45134
45135
45136
45137
45138
45139
45140
45141
45142
45143
45144
45145
45146
45147
45148
45149
45150
45151
45152
45153
45154
45155
45156
45157
45158
45159
45160
45161
45162
45163
45164
45165
45166
45167
45168
45169
45170
45171
45172
45173
45174
45175
45176
45177
45178
45179
45180
45181
45182
45183
45184
45185
45186
45187
45188
45189
45190
45191
45192
45193
45194
45195
45196
45197
45198
45199
45200
45201
45202
45203
45204
45205
45206
45207
45208
45209
45210
45211
45212
45213
45214
45215
45216
45217
45218
45219
45220
45221
45222
45223
45224
45225
45226
45227
45228
45229
45230
45231
45232
45233
45234
45235
45236
45237
45238
45239
45240
45241
45242
45243
45244
45245
45246
45247
45248
45249
45250
45251
45252
45253
45254
45255
45256
45257
45258
45259
45260
45261
45262
45263
45264
45265
45266
45267
45268
45269
45270
45271
45272
45273
45274
45275
45276
45277
45278
45279
45280
45281
45282
45283
45284
45285
45286
45287
45288
45289
45290
45291
45292
45293
45294
45295
45296
45297
45298
45299
45300
45301
45302
45303
45304
45305
45306
45307
45308
45309
45310
45311
45312
45313
45314
45315
45316
45317
45318
45319
45320
45321
45322
45323
45324
45325
45326
45327
45328
45329
45330
45331
45332
45333
45334
45335
45336
45337
45338
45339
45340
45341
45342
45343
45344
45345
45346
45347
45348
45349
45350
45351
45352
45353
45354
45355
45356
45357
45358
45359
45360
45361
45362
45363
45364
45365
45366
45367
45368
45369
45370
45371
45372
45373
45374
45375
45376
45377
45378
45379
45380
45381
45382
45383
45384
45385
45386
45387
45388
45389
45390
45391
45392
45393
45394
45395
45396
45397
45398
45399
45400
45401
45402
45403
45404
45405
45406
45407
45408
45409
45410
45411
45412
45413
45414
45415
45416
45417
45418
45419
45420
45421
45422
45423
45424
45425
45426
45427
45428
45429
45430
45431
45432
45433
45434
45435
45436
45437
45438
45439
45440
45441
45442
45443
45444
45445
45446
45447
45448
45449
45450
45451
45452
45453
45454
45455
45456
45457
45458
45459
45460
45461
45462
45463
45464
45465
45466
45467
45468
45469
45470
45471
45472
45473
45474
45475
45476
45477
45478
45479
45480
45481
45482
45483
45484
45485
45486
45487
45488
45489
45490
45491
45492
45493
45494
45495
45496
45497
45498
45499
45500
45501
45502
45503
45504
45505
45506
45507
45508
45509
45510
45511
45512
45513
45514
45515
45516
45517
45518
45519
45520
45521
45522
45523
45524
45525
45526
45527
45528
45529
45530
45531
45532
45533
45534
45535
45536
45537
45538
45539
45540
45541
45542
45543
45544
45545
45546
45547
45548
45549
45550
45551
45552
45553
45554
45555
45556
45557
45558
45559
45560
45561
45562
45563
45564
45565
45566
45567
45568
45569
45570
45571
45572
45573
45574
45575
45576
45577
45578
45579
45580
45581
45582
45583
45584
45585
45586
45587
45588
45589
45590
45591
45592
45593
45594
45595
45596
45597
45598
45599
45600
45601
45602
45603
45604
45605
45606
45607
45608
45609
45610
45611
45612
45613
45614
45615
45616
45617
45618
45619
45620
45621
45622
45623
45624
45625
45626
45627
45628
45629
45630
45631
45632
45633
45634
45635
45636
45637
45638
45639
45640
45641
45642
45643
45644
45645
45646
45647
45648
45649
45650
45651
45652
45653
45654
45655
45656
45657
45658
45659
45660
45661
45662
45663
45664
45665
45666
45667
45668
45669
45670
45671
45672
45673
45674
45675
45676
45677
45678
45679
45680
45681
45682
45683
45684
45685
45686
45687
45688
45689
45690
45691
45692
45693
45694
45695
45696
45697
45698
45699
45700
45701
45702
45703
45704
45705
45706
45707
45708
45709
45710
|
<html lang="en">
<head>
<meta charset="utf-8">
<title>DragonRuby Game Toolkit Documentation</title>
<link href="docs.css?ver=1628311142" rel="stylesheet" type="text/css" media="all">
</head>
<body>
<div id='toc'>
<h1>Table Of Contents</h1>
<ul>
<li><a class='header-1' href='#--dragonruby-game-toolkit-live-docs'>DragonRuby Game Toolkit Live Docs</a></li>
<li><a class='header-1' href='#--hello-world'>Hello World</a></li>
<li><a class='header-1' href='#--join-the-discord-and-subscribe-to-the-news-letter'>Join the Discord and Subscribe to the News Letter</a></li>
<li><a class='header-1' href='#--intro-videos'>Intro Videos</a></li>
<ul><li><a class='header-2' href='#---quick-api-tour'>Quick Api Tour</a></li></ul><ul><li><a class='header-2' href='#---if-you-are-completely-new-to-ruby-and-programming'>If You Are Completely New to Ruby and Programming</a></li></ul><ul><li><a class='header-2' href='#---if-you-have-game-dev-experience'>If You Have Game Dev Experience</a></li></ul><li><a class='header-1' href='#--getting-started-tutorial'>Getting Started Tutorial</a></li>
<ul><li><a class='header-2' href='#---introduction'>Introduction</a></li></ul><ul><li><a class='header-2' href='#---prerequisites'>Prerequisites</a></li></ul><ul><li><a class='header-2' href='#---the-game-loop'>The Game Loop</a></li></ul><ul><li><a class='header-2' href='#---breakdown-of-the--tick--method'>Breakdown Of The <code>tick</code> Method</a></li></ul><ul><li><a class='header-2' href='#---rendering-a-sprite'>Rendering A Sprite</a></li></ul><ul><li><a class='header-2' href='#---coordinate-system-and-virtual-canvas'>Coordinate System and Virtual Canvas</a></li></ul><ul><li><a class='header-2' href='#---game-state'>Game State</a></li></ul><ul><li><a class='header-2' href='#---there-is-no-delta-time'>There Is No Delta Time</a></li></ul><ul><li><a class='header-2' href='#---handling-user-input'>Handling User Input</a></li></ul><ul><li><a class='header-2' href='#---coding-on-a-raspberry-pi'>Coding On A Raspberry Pi</a></li></ul><ul><li><a class='header-2' href='#---conclusion'>Conclusion</a></li></ul><li><a class='header-1' href='#--deploying-to-itch-io'>Deploying To Itch.io</a></li>
<ul><li><a class='header-2' href='#---creating-your-game-landing-page'>Creating Your Game Landing Page</a></li></ul><ul><li><a class='header-2' href='#---update-your-game's-metadata'>Update Your Game's Metadata</a></li></ul><ul><li><a class='header-2' href='#---building-your-game-for-distribution'>Building Your Game For Distribution</a></li></ul><li><a class='header-1' href='#--deploying-to-mobile-devices'>Deploying To Mobile Devices</a></li>
<li><a class='header-1' href='#--dragonruby's-philosophy'>DragonRuby's Philosophy</a></li>
<ul><li><a class='header-2' href='#---challenge-the-status-quo'>Challenge The Status Quo</a></li></ul><ul><li><a class='header-2' href='#---continuity-of-design'>Continuity of Design</a></li></ul><ul><li><a class='header-2' href='#---release-early-and-often'>Release Early and Often</a></li></ul><ul><li><a class='header-2' href='#---sustainable-and-ethical-monetization'>Sustainable And Ethical Monetization</a></li></ul><ul><li><a class='header-2' href='#---sustainable-and-ethical-open-source'>Sustainable And Ethical Open Source</a></li></ul><ul><li><a class='header-2' href='#---people-over-entities'>People Over Entities</a></li></ul><ul><li><a class='header-2' href='#---building-a-game-should-be-fun-and-bring-happiness'>Building A Game Should Be Fun And Bring Happiness</a></li></ul><ul><li><a class='header-2' href='#---real-world-application-drives-features'>Real World Application Drives Features</a></li></ul><li><a class='header-1' href='#--frequently-asked-questions--comments--and-concerns'>Frequently Asked Questions, Comments, and Concerns</a></li>
<ul><li><a class='header-2' href='#---frequently-asked-questions'>Frequently Asked Questions</a></li></ul><ul><ul><li><a class='header-3' href='#----what-is-dragonruby-llp-'>What is DragonRuby LLP?</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----what-is-dragonruby-'>What is DragonRuby?</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----how-is-dragonruby-different-than-mri-'>How is DragonRuby different than MRI?</a></li></ul></ul><ul><li><a class='header-2' href='#---frequent-comments-about-ruby-as-a-language-choice'>Frequent Comments About Ruby as a Language Choice</a></li></ul><ul><ul><li><a class='header-3' href='#----but-ruby-is-dead-'>But Ruby is dead.</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----but-ruby-is-slow-'>But Ruby is slow.</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----dynamic-languages-are-slow-'>Dynamic languages are slow.</a></li></ul></ul><ul><li><a class='header-2' href='#---frequent-concerns'>Frequent Concerns</a></li></ul><ul><ul><li><a class='header-3' href='#----dragonruby-is-not-open-source--that's-not-right-'>DragonRuby is not open source. That's not right.</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----dragonruby-is-for-pay--you-should-offer-a-free-version-'>DragonRuby is for pay. You should offer a free version.</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----but-still--you-should-offer-a-free-version--so-i-can-try-it-out-and-see-if-i-like-it-'>But still, you should offer a free version. So I can try it out and see if I like it.</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----i-still-think-you-should-do-a-free-version--think-of-all-people-who-would-give-it-a-shot-'>I still think you should do a free version. Think of all people who would give it a shot.</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----what-if-i-build-something-with-dragonruby--but-dragonruby-llp-becomes-insolvent-'>What if I build something with DragonRuby, but DragonRuby LLP becomes insolvent.</a></li></ul></ul><li><a class='header-1' href='#--recipies-'>RECIPIES:</a></li>
<ul><li><a class='header-2' href='#---how-to-determine-what-frame-you-are-on'>How To Determine What Frame You Are On</a></li></ul><ul><li><a class='header-2' href='#---how-to-get-current-framerate'>How To Get Current Framerate</a></li></ul><ul><li><a class='header-2' href='#---how-to-render-a-sprite-using-an-array'>How To Render A Sprite Using An Array</a></li></ul><ul><li><a class='header-2' href='#---more-sprite-properties-as-an-array'>More Sprite Properties As An Array</a></li></ul><ul><li><a class='header-2' href='#---different-sprite-representations'>Different Sprite Representations</a></li></ul><ul><li><a class='header-2' href='#---how-to-render-a-label'>How To Render A Label</a></li></ul><ul><li><a class='header-2' href='#---a-colored-label'>A Colored Label</a></li></ul><ul><li><a class='header-2' href='#---extended-label-properties'>Extended Label Properties</a></li></ul><ul><li><a class='header-2' href='#---rendering-a-label-as-a--hash-'>Rendering A Label As A <code>Hash</code></a></li></ul><ul><li><a class='header-2' href='#---getting-the-size-of-a-piece-of-text'>Getting The Size Of A Piece Of Text</a></li></ul><ul><li><a class='header-2' href='#---rendering-labels-with-new-line-characters-and-wrapping'>Rendering Labels With New Line Characters And Wrapping</a></li></ul><ul><li><a class='header-2' href='#---how-to-play-a-sound'>How To Play A Sound</a></li></ul><ul><li><a class='header-2' href='#---using--args-state--to-store-your-game-state'>Using <code>args.state</code> To Store Your Game State</a></li></ul><ul><li><a class='header-2' href='#---troubleshoot-performance'>Troubleshoot Performance</a></li></ul><li><a class='header-1' href='#--docs---gtk--runtime-'>DOCS: <code>GTK::Runtime</code></a></li>
<li><a class='header-1' href='#--summary---def-tick-args;-end;-'>SUMMARY: <code>def tick args; end;</code></a></li>
<ul><li><a class='header-2' href='#----args-state-'><code>args.state</code></a></li></ul><ul><ul><li><a class='header-3' href='#--------entity_id-'><code>.*.entity_id</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#--------entity_type-'><code>.*.entity_type</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#--------created_at-'><code>.*.created_at</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#--------created_at_elapsed-'><code>.*.created_at_elapsed</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#--------global_created_at-'><code>.*.global_created_at</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#--------global_created_at_elapsed-'><code>.*.global_created_at_elapsed</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#--------as_hash-'><code>.*.as_hash</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------new_entity-'><code>.new_entity</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------new_entity_strict-'><code>.new_entity_strict</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------tick_count-'><code>.tick_count</code></a></li></ul></ul><ul><li><a class='header-2' href='#----args-inputs-'><code>args.inputs</code></a></li></ul><ul><ul><li><a class='header-3' href='#------up-'><code>.up</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------down-'><code>.down</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------left-'><code>.left</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------right-'><code>.right</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------left_right-'><code>.left_right</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------up_down-'><code>.up_down</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------text--or---history-'><code>.text</code> OR <code>.history</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------mouse-'><code>.mouse</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------controller_one-----controller_two-'><code>.controller_one</code>, <code>.controller_two</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------keyboard-'><code>.keyboard</code></a></li></ul></ul><ul><li><a class='header-2' href='#----args-outputs-'><code>args.outputs</code></a></li></ul><ul><ul><li><a class='header-3' href='#------background_color-'><code>.background_color</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------sounds-'><code>.sounds</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------solids-'><code>.solids</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------static_solids-'><code>.static_solids</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------sprites-----static_sprites-'><code>.sprites</code>, <code>.static_sprites</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------primitives-----static_primitives-'><code>.primitives</code>, <code>.static_primitives</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------labels-----static_labels-'><code>.labels</code>, <code>.static_labels</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------lines-----static_lines-'><code>.lines</code>, <code>.static_lines</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------borders-----static_borders-'><code>.borders</code>, <code>.static_borders</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------debug-----static_debug-'><code>.debug</code>, <code>.static_debug</code></a></li></ul></ul><ul><li><a class='header-2' href='#----args-geometry-'><code>args.geometry</code></a></li></ul><ul><ul><li><a class='header-3' href='#------inside_rect--rect_1--rect_2-'><code>.inside_rect? rect_1, rect_2</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------intersect_rect--rect_2--rect_2-'><code>.intersect_rect? rect_2, rect_2</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------scale_rect-rect--x_percentage--y_percentage-'><code>.scale_rect rect, x_percentage, y_percentage</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------angle_to-start_point--end_point-'><code>.angle_to start_point, end_point</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------angle_from-start_point--end_point-'><code>.angle_from start_point, end_point</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------point_inside_circle--point--circle_center_point--radius-'><code>.point_inside_circle? point, circle_center_point, radius</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------center_inside_rect-rect--other_rect-'><code>.center_inside_rect rect, other_rect</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------center_inside_rect_x-rect--other_rect-'><code>.center_inside_rect_x rect, other_rect</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------center_inside_rect_y-rect--other_rect-'><code>.center_inside_rect_y rect, other_rect</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------anchor_rect-rect--anchor_x--anchor_y-'><code>.anchor_rect rect, anchor_x, anchor_y</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------shift_line-line--x--y-'><code>.shift_line line, x, y</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------line_y_intercept-line-'><code>.line_y_intercept line</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------angle_between_lines-line_one--line_two--replace_infinity--'><code>.angle_between_lines line_one, line_two, replace_infinity:</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------line_slope-line--replace_infinity--'><code>.line_slope line, replace_infinity:</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------line_rise_run-'><code>.line_rise_run</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------ray_test-point--line-'><code>.ray_test point, line</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------line_rect-line-'><code>.line_rect line</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------line_intersect-line_one--line_two-'><code>.line_intersect line_one, line_two</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------distance-point_one--point_two-'><code>.distance point_one, point_two</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------cubic_bezier-t--a--b--c--d-'><code>.cubic_bezier t, a, b, c, d</code></a></li></ul></ul><ul><li><a class='header-2' href='#----args-easing-'><code>args.easing</code></a></li></ul><ul><ul><li><a class='header-3' href='#------ease-start_tick--current_tick--duration--easing_functions-'><code>.ease start_tick, current_tick, duration, easing_functions</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------ease_spline-start_tick--current_tick--duration--spline-'><code>.ease_spline start_tick, current_tick, duration, spline</code></a></li></ul></ul><ul><li><a class='header-2' href='#----args-string-'><code>args.string</code></a></li></ul><ul><ul><li><a class='header-3' href='#------wrapped_lines-string--max_character_length-'><code>.wrapped_lines string, max_character_length</code></a></li></ul></ul><ul><li><a class='header-2' href='#----args-grid-'><code>args.grid</code></a></li></ul><ul><ul><li><a class='header-3' href='#------name-'><code>.name</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------bottom-'><code>.bottom</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------top-'><code>.top</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------left-'><code>.left</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------right-'><code>.right</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------rect-'><code>.rect</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------origin_bottom_left!-'><code>.origin_bottom_left!</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------origin_center!-'><code>.origin_center!</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------w-'><code>.w</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------h-'><code>.h</code></a></li></ul></ul><ul><li><a class='header-2' href='#----args-gtk-'><code>args.gtk</code></a></li></ul><ul><ul><li><a class='header-3' href='#------argv-'><code>.argv</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------platform-'><code>.platform</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------request_quit-'><code>.request_quit</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------write_file-path--contents-'><code>.write_file path, contents</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------write_file_root-'><code>.write_file_root</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------append_file-path--contents-'><code>.append_file path, contents</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------append_file_root-path--contents-'><code>.append_file_root path, contents</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------read_file-path-'><code>.read_file path</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------parse_xml-string--parse_xml_file-path-'><code>.parse_xml string, parse_xml_file path</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------parse_json-string--parse_json_file-path-'><code>.parse_json string, parse_json_file path</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------http_get-url--extra_headers-=-{}-'><code>.http_get url, extra_headers = {}</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------http_post-url--form_fields-=-{}--extra_headers-=-{}-'><code>.http_post url, form_fields = {}, extra_headers = {}</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------reset-'><code>.reset</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------stop_music-'><code>.stop_music</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------calcstringbox-str--size_enum--font-'><code>.calcstringbox str, size_enum, font</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------slowmo!-factor-'><code>.slowmo! factor</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------notify!-string-'><code>.notify! string</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------system-'><code>.system</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------exec-'><code>.exec</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------save_state-'><code>.save_state</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------load_state-'><code>.load_state</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------serialize_state-file--state-'><code>.serialize_state file, state</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------deserialize_state-file-'><code>.deserialize_state file</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------reset_sprite-path-'><code>.reset_sprite path</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------show_cursor-'><code>.show_cursor</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------hide_cursor-'><code>.hide_cursor</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------cursor_shown--'><code>.cursor_shown?</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------set_window_fullscreen-enabled-'><code>.set_window_fullscreen enabled</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------openurl-url-'><code>.openurl url</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------get_base_dir-'><code>.get_base_dir</code></a></li></ul></ul><ul><ul><li><a class='header-3' href='#------get_game_dir-'><code>.get_game_dir</code></a></li></ul></ul><li><a class='header-1' href='#--docs---gtk--runtime#reset-'>DOCS: <code>GTK::Runtime#reset</code></a></li>
<li><a class='header-1' href='#--docs---gtk--runtime#calcstringbox-'>DOCS: <code>GTK::Runtime#calcstringbox</code></a></li>
<li><a class='header-1' href='#--docs---gtk--runtime#write_file-'>DOCS: <code>GTK::Runtime#write_file</code></a></li>
<li><a class='header-1' href='#--docs---array-'>DOCS: <code>Array</code></a></li>
<li><a class='header-1' href='#--docs---array#map-'>DOCS: <code>Array#map</code></a></li>
<li><a class='header-1' href='#--docs---array#each-'>DOCS: <code>Array#each</code></a></li>
<li><a class='header-1' href='#--docs---array#reject_nil-'>DOCS: <code>Array#reject_nil</code></a></li>
<li><a class='header-1' href='#--docs---array#reject_false-'>DOCS: <code>Array#reject_false</code></a></li>
<li><a class='header-1' href='#--docs---array#product-'>DOCS: <code>Array#product</code></a></li>
<li><a class='header-1' href='#--docs---array#map_2d-'>DOCS: <code>Array#map_2d</code></a></li>
<li><a class='header-1' href='#--docs---array#include_any--'>DOCS: <code>Array#include_any?</code></a></li>
<li><a class='header-1' href='#--docs---array#any_intersect_rect--'>DOCS: <code>Array#any_intersect_rect?</code></a></li>
<li><a class='header-1' href='#--docs---gtk--args#audio-'>DOCS: <code>GTK::Args#audio</code></a></li>
<ul><li><a class='header-2' href='#---audio-synthesis-(pro-only)'>Audio synthesis (Pro only)</a></li></ul><ul><ul><li><a class='header-3' href='#----sound-source'>Sound source</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----example-'>Example:</a></li></ul></ul><li><a class='header-1' href='#--docs---gtk--outputs-'>DOCS: <code>GTK::Outputs</code></a></li>
<li><a class='header-1' href='#--docs---gtk--outputs#solids-'>DOCS: <code>GTK::Outputs#solids</code></a></li>
<ul><li><a class='header-2' href='#---rendering-a-solid-using-an-array'>Rendering a solid using an Array</a></li></ul><ul><li><a class='header-2' href='#---rendering-a-solid-using-an-array-with-colors-and-alpha'>Rendering a solid using an Array with colors and alpha</a></li></ul><ul><li><a class='header-2' href='#---rendering-a-solid-using-a-hash'>Rendering a solid using a Hash</a></li></ul><ul><li><a class='header-2' href='#---rendering-a-solid-using-a-class'>Rendering a solid using a Class</a></li></ul><li><a class='header-1' href='#--docs---gtk--outputs#borders-'>DOCS: <code>GTK::Outputs#borders</code></a></li>
<li><a class='header-1' href='#--docs---gtk--outputs#sprites-'>DOCS: <code>GTK::Outputs#sprites</code></a></li>
<ul><li><a class='header-2' href='#---rendering-a-sprite-using-an-array'>Rendering a sprite using an Array</a></li></ul><ul><li><a class='header-2' href='#---rendering-a-sprite-using-an-array-with-colors-and-alpha'>Rendering a sprite using an Array with colors and alpha</a></li></ul><ul><li><a class='header-2' href='#---rendering-a-sprite-using-a-hash'>Rendering a sprite using a Hash</a></li></ul><ul><li><a class='header-2' href='#---rendering-a-solid-using-a-class'>Rendering a solid using a Class</a></li></ul><li><a class='header-1' href='#--docs---gtk--outputs#screenshots-'>DOCS: <code>GTK::Outputs#screenshots</code></a></li>
<ul><li><a class='header-2' href='#---chroma-key-(making-a-color-transparent)'>Chroma key (Making a color transparent)</a></li></ul><li><a class='header-1' href='#--docs---gtk--mouse-'>DOCS: <code>GTK::Mouse</code></a></li>
<li><a class='header-1' href='#--docs---gtk--mousepoint-'>DOCS: <code>GTK::MousePoint</code></a></li>
<li><a class='header-1' href='#--docs---gtk--openentity-'>DOCS: <code>GTK::OpenEntity</code></a></li>
<li><a class='header-1' href='#--docs---gtk--openentity#as_hash-'>DOCS: <code>GTK::OpenEntity#as_hash</code></a></li>
<li><a class='header-1' href='#--docs---numeric#frame_index-'>DOCS: <code>Numeric#frame_index</code></a></li>
<li><a class='header-1' href='#--docs---numeric#elapsed_time-'>DOCS: <code>Numeric#elapsed_time</code></a></li>
<li><a class='header-1' href='#--docs---numeric#elapsed--'>DOCS: <code>Numeric#elapsed?</code></a></li>
<li><a class='header-1' href='#--docs---numeric#created--'>DOCS: <code>Numeric#created?</code></a></li>
<li><a class='header-1' href='#--docs---kernel-'>DOCS: <code>Kernel</code></a></li>
<li><a class='header-1' href='#--docs---kernel--tick_count-'>DOCS: <code>Kernel::tick_count</code></a></li>
<li><a class='header-1' href='#--docs---kernel--global_tick_count-'>DOCS: <code>Kernel::global_tick_count</code></a></li>
<li><a class='header-1' href='#--docs---geometry-'>DOCS: <code>Geometry</code></a></li>
<li><a class='header-1' href='#--docs---gtk--geometry#scale_rect-'>DOCS: <code>GTK::Geometry#scale_rect</code></a></li>
<li><a class='header-1' href='#--source-code'>Source Code</a></li>
<ul><li><a class='header-2' href='#---samples'>Samples</a></li></ul><ul><ul><li><a class='header-3' href='#----learn-ruby-optional---beginner-ruby-primer---automation-rb'>Learn Ruby Optional - Beginner Ruby Primer - automation.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----learn-ruby-optional---beginner-ruby-primer---main-rb'>Learn Ruby Optional - Beginner Ruby Primer - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----learn-ruby-optional---intermediate-ruby-primer---printing-txt'>Learn Ruby Optional - Intermediate Ruby Primer - printing.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----learn-ruby-optional---intermediate-ruby-primer---strings-txt'>Learn Ruby Optional - Intermediate Ruby Primer - strings.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----learn-ruby-optional---intermediate-ruby-primer---numbers-txt'>Learn Ruby Optional - Intermediate Ruby Primer - numbers.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----learn-ruby-optional---intermediate-ruby-primer---booleans-txt'>Learn Ruby Optional - Intermediate Ruby Primer - booleans.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----learn-ruby-optional---intermediate-ruby-primer---conditionals-txt'>Learn Ruby Optional - Intermediate Ruby Primer - conditionals.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----learn-ruby-optional---intermediate-ruby-primer---looping-txt'>Learn Ruby Optional - Intermediate Ruby Primer - looping.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----learn-ruby-optional---intermediate-ruby-primer---functions-txt'>Learn Ruby Optional - Intermediate Ruby Primer - functions.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----learn-ruby-optional---intermediate-ruby-primer---arrays-txt'>Learn Ruby Optional - Intermediate Ruby Primer - arrays.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----learn-ruby-optional---intermediate-ruby-primer---main-rb'>Learn Ruby Optional - Intermediate Ruby Primer - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rendering-basics---labels---main-rb'>Rendering Basics - Labels - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rendering-basics---lines---main-rb'>Rendering Basics - Lines - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rendering-basics---solids-borders---main-rb'>Rendering Basics - Solids Borders - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rendering-basics---sprites---main-rb'>Rendering Basics - Sprites - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rendering-basics---sounds---main-rb'>Rendering Basics - Sounds - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----input-basics---keyboard---main-rb'>Input Basics - Keyboard - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----input-basics---moving-a-sprite---main-rb'>Input Basics - Moving A Sprite - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----input-basics---mouse---main-rb'>Input Basics - Mouse - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----input-basics---mouse-point-to-rect---main-rb'>Input Basics - Mouse Point To Rect - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----input-basics---mouse-rect-to-rect---main-rb'>Input Basics - Mouse Rect To Rect - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----input-basics---controller---main-rb'>Input Basics - Controller - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----input-basics---touch---main-rb'>Input Basics - Touch - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rendering-sprites---animation-using-separate-pngs---main-rb'>Rendering Sprites - Animation Using Separate Pngs - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rendering-sprites---animation-using-sprite-sheet---main-rb'>Rendering Sprites - Animation Using Sprite Sheet - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rendering-sprites---animation-states---main-rb'>Rendering Sprites - Animation States - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rendering-sprites---color-and-rotation---main-rb'>Rendering Sprites - Color And Rotation - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---simple---main-rb'>Physics And Collisions - Simple - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---moving-objects---main-rb'>Physics And Collisions - Moving Objects - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---entities---main-rb'>Physics And Collisions - Entities - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---box-collision---main-rb'>Physics And Collisions - Box Collision - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---box-collision-2---main-rb'>Physics And Collisions - Box Collision 2 - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---box-collision-3---main-rb'>Physics And Collisions - Box Collision 3 - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---jump-physics---main-rb'>Physics And Collisions - Jump Physics - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---bouncing-on-collision---ball-rb'>Physics And Collisions - Bouncing On Collision - ball.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---bouncing-on-collision---block-rb'>Physics And Collisions - Bouncing On Collision - block.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---bouncing-on-collision---cannon-rb'>Physics And Collisions - Bouncing On Collision - cannon.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---bouncing-on-collision---main-rb'>Physics And Collisions - Bouncing On Collision - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---bouncing-on-collision---peg-rb'>Physics And Collisions - Bouncing On Collision - peg.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---bouncing-on-collision---vector2d-rb'>Physics And Collisions - Bouncing On Collision - vector2d.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---arbitrary-collision---ball-rb'>Physics And Collisions - Arbitrary Collision - ball.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---arbitrary-collision---blocks-rb'>Physics And Collisions - Arbitrary Collision - blocks.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---arbitrary-collision---linear_collider-rb'>Physics And Collisions - Arbitrary Collision - linear_collider.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---arbitrary-collision---main-rb'>Physics And Collisions - Arbitrary Collision - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---arbitrary-collision---paddle-rb'>Physics And Collisions - Arbitrary Collision - paddle.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---arbitrary-collision---rectangle-rb'>Physics And Collisions - Arbitrary Collision - rectangle.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---arbitrary-collision---square_collider-rb'>Physics And Collisions - Arbitrary Collision - square_collider.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---arbitrary-collision---vector2d-rb'>Physics And Collisions - Arbitrary Collision - vector2d.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---collision-with-object-removal---ball-rb'>Physics And Collisions - Collision With Object Removal - ball.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---collision-with-object-removal---linear_collider-rb'>Physics And Collisions - Collision With Object Removal - linear_collider.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---collision-with-object-removal---main-rb'>Physics And Collisions - Collision With Object Removal - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---collision-with-object-removal---paddle-rb'>Physics And Collisions - Collision With Object Removal - paddle.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---collision-with-object-removal---tests-rb'>Physics And Collisions - Collision With Object Removal - tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----physics-and-collisions---collision-with-object-removal---vector2d-rb'>Physics And Collisions - Collision With Object Removal - vector2d.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----mouse---mouse-click---main-rb'>Mouse - Mouse Click - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----mouse---mouse-move---main-rb'>Mouse - Mouse Move - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----mouse---mouse-move-paint-app---main-rb'>Mouse - Mouse Move Paint App - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----mouse---coordinate-systems---main-rb'>Mouse - Coordinate Systems - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----save-load---save-load-game---main-rb'>Save Load - Save Load Game - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-audio---audio-mixer---main-rb'>Advanced Audio - Audio Mixer - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-audio---audio-mixer---server_ip_address-txt'>Advanced Audio - Audio Mixer - server_ip_address.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-audio---audio-mixer---metadata---ios_metadata-txt'>Advanced Audio - Audio Mixer - Metadata - ios_metadata.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-audio---sound-synthesis---main-rb'>Advanced Audio - Sound Synthesis - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-rendering---simple-render-targets---main-rb'>Advanced Rendering - Simple Render Targets - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-rendering---render-targets-with-tile-manipulation---main-rb'>Advanced Rendering - Render Targets With Tile Manipulation - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-rendering---render-target-viewports---main-rb'>Advanced Rendering - Render Target Viewports - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-rendering---render-primitive-hierarchies---main-rb'>Advanced Rendering - Render Primitive Hierarchies - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-rendering---render-primitives-as-hash---main-rb'>Advanced Rendering - Render Primitives As Hash - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-rendering---pixel-arrays---main-rb'>Advanced Rendering - Pixel Arrays - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-rendering---simple-camera---main-rb'>Advanced Rendering - Simple Camera - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-rendering---splitscreen-camera---main-rb'>Advanced Rendering - Splitscreen Camera - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-rendering---z-targeting-camera---main-rb'>Advanced Rendering - Z Targeting Camera - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-rendering---blend-modes---main-rb'>Advanced Rendering - Blend Modes - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----tweening-lerping-easing-functions---easing-functions---main-rb'>Tweening Lerping Easing Functions - Easing Functions - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----tweening-lerping-easing-functions---cubic-bezier---main-rb'>Tweening Lerping Easing Functions - Cubic Bezier - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----tweening-lerping-easing-functions---easing-using-spline---main-rb'>Tweening Lerping Easing Functions - Easing Using Spline - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----tweening-lerping-easing-functions---parametric-enemy-movement---main-rb'>Tweening Lerping Easing Functions - Parametric Enemy Movement - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----performance---sprites-as-hash---main-rb'>Performance - Sprites As Hash - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----performance---sprites-as-entities---main-rb'>Performance - Sprites As Entities - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----performance---sprites-as-strict-entities---main-rb'>Performance - Sprites As Strict Entities - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----performance---sprites-as-classes---main-rb'>Performance - Sprites As Classes - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----performance---static-sprites-as-classes---main-rb'>Performance - Static Sprites As Classes - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----performance---static-sprites-as-classes-with-custom-drawing---main-rb'>Performance - Static Sprites As Classes With Custom Drawing - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----performance---collision-limits---main-rb'>Performance - Collision Limits - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---trace-debugging---main-rb'>Advanced Debugging - Trace Debugging - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---trace-debugging-classes---main-rb'>Advanced Debugging - Trace Debugging Classes - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---benchmark_api_tests-rb'>Advanced Debugging - Unit Tests - benchmark_api_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---exception_raising_tests-rb'>Advanced Debugging - Unit Tests - exception_raising_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---fn_tests-rb'>Advanced Debugging - Unit Tests - fn_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---gen_docs-rb'>Advanced Debugging - Unit Tests - gen_docs.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---geometry_tests-rb'>Advanced Debugging - Unit Tests - geometry_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---http_tests-rb'>Advanced Debugging - Unit Tests - http_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---nil_coercion_tests-rb'>Advanced Debugging - Unit Tests - nil_coercion_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---object_to_primitive_tests-rb'>Advanced Debugging - Unit Tests - object_to_primitive_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---parsing_tests-rb'>Advanced Debugging - Unit Tests - parsing_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---pretty_format_tests-rb'>Advanced Debugging - Unit Tests - pretty_format_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---require_tests-rb'>Advanced Debugging - Unit Tests - require_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---serialize_deserialize_tests-rb'>Advanced Debugging - Unit Tests - serialize_deserialize_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---state_serialization_experimental_tests-rb'>Advanced Debugging - Unit Tests - state_serialization_experimental_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----advanced-debugging---unit-tests---suggest_autocompletion_tests-rb'>Advanced Debugging - Unit Tests - suggest_autocompletion_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----http---retrieve-images---main-rb'>Http - Retrieve Images - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----http---web-server---main-rb'>Http - Web Server - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----c-extensions---basics---main-rb'>C Extensions - Basics - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----c-extensions---intermediate---main-rb'>C Extensions - Intermediate - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----c-extensions---native-pixel-arrays---main-rb'>C Extensions - Native Pixel Arrays - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----path-finding-algorithms---breadth-first-search---main-rb'>Path Finding Algorithms - Breadth First Search - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----path-finding-algorithms---detailed-breadth-first-search---main-rb'>Path Finding Algorithms - Detailed Breadth First Search - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----path-finding-algorithms---breadcrumbs---main-rb'>Path Finding Algorithms - Breadcrumbs - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----path-finding-algorithms---early-exit---main-rb'>Path Finding Algorithms - Early Exit - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----path-finding-algorithms---dijkstra---main-rb'>Path Finding Algorithms - Dijkstra - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----path-finding-algorithms---heuristic---main-rb'>Path Finding Algorithms - Heuristic - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----path-finding-algorithms---heuristic-with-walls---main-rb'>Path Finding Algorithms - Heuristic With Walls - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----path-finding-algorithms---a-star---main-rb'>Path Finding Algorithms - A Star - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----path-finding-algorithms---tower-defense---main-rb'>Path Finding Algorithms - Tower Defense - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----3d---3d-cube---main-rb'>3d - 3d Cube - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----3d---wireframe---main-rb'>3d - Wireframe - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----3d---wireframe---data---what-is-this-txt'>3d - Wireframe - Data - what-is-this.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----arcade---bullet-hell---main-rb'>Arcade - Bullet Hell - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----arcade---dueling-starships---main-rb'>Arcade - Dueling Starships - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----arcade/flappy-dragon/credits-txt'>arcade/flappy dragon/credits.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----arcade/flappy-dragon/main-rb'>arcade/flappy dragon/main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----arcade---pong---main-rb'>Arcade - Pong - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----arcade---snakemoji---main-rb'>Arcade - Snakemoji - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----arcade---solar-system---main-rb'>Arcade - Solar System - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----arcade---sound-golf---main-rb'>Arcade - Sound Golf - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----arcade---twinstick---main-rb'>Arcade - Twinstick - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----crafting---craft-game-starting-point---main-rb'>Crafting - Craft Game Starting Point - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----crafting---farming-game-starting-point---main-rb'>Crafting - Farming Game Starting Point - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----crafting---farming-game-starting-point---repl-rb'>Crafting - Farming Game Starting Point - repl.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----crafting---farming-game-starting-point---tests-rb'>Crafting - Farming Game Starting Point - tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----dev-tools---add-buttons-to-console---main-rb'>Dev Tools - Add Buttons To Console - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----dev-tools---animation-creator-starting-point---main-rb'>Dev Tools - Animation Creator Starting Point - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----dev-tools---tile-editor-starting-point---main-rb'>Dev Tools - Tile Editor Starting Point - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----dungeon-crawl---classics-jam---main-rb'>Dungeon Crawl - Classics Jam - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----fighting---special-move-inputs---main-rb'>Fighting - Special Move Inputs - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----lowrez---nokia-3310---main-rb'>Lowrez - Nokia 3310 - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----lowrez---nokia-3310---nokia-rb'>Lowrez - Nokia 3310 - nokia.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----lowrez---resolution-64x64---lowrez-rb'>Lowrez - Resolution 64x64 - lowrez.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----lowrez---resolution-64x64---main-rb'>Lowrez - Resolution 64x64 - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----platformer---clepto-frog---main-rb'>Platformer - Clepto Frog - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----platformer---clepto-frog---map-rb'>Platformer - Clepto Frog - map.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----platformer---gorillas-basic---credits-txt'>Platformer - Gorillas Basic - credits.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----platformer---gorillas-basic---main-rb'>Platformer - Gorillas Basic - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----platformer---gorillas-basic---tests-rb'>Platformer - Gorillas Basic - tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----platformer---gorillas-basic---tests---building_generation_tests-rb'>Platformer - Gorillas Basic - Tests - building_generation_tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----platformer---the-little-probe---main-rb'>Platformer - The Little Probe - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----platformer---the-little-probe---data---level-txt'>Platformer - The Little Probe - Data - level.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----platformer---the-little-probe---data---level_lava-txt'>Platformer - The Little Probe - Data - level_lava.txt</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---choose-your-own-adventure---decision-rb'>Rpg Narrative - Choose Your Own Adventure - decision.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---choose-your-own-adventure---main-rb'>Rpg Narrative - Choose Your Own Adventure - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---lowrez_simulator-rb'>Rpg Narrative - Return Of Serenity - lowrez_simulator.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---main-rb'>Rpg Narrative - Return Of Serenity - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---require-rb'>Rpg Narrative - Return Of Serenity - require.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---storyline-rb'>Rpg Narrative - Return Of Serenity - storyline.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---storyline_anka-rb'>Rpg Narrative - Return Of Serenity - storyline_anka.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---storyline_blinking_light-rb'>Rpg Narrative - Return Of Serenity - storyline_blinking_light.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---storyline_day_one-rb'>Rpg Narrative - Return Of Serenity - storyline_day_one.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---storyline_final_decision-rb'>Rpg Narrative - Return Of Serenity - storyline_final_decision.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---storyline_final_message-rb'>Rpg Narrative - Return Of Serenity - storyline_final_message.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---storyline_serenity_alive-rb'>Rpg Narrative - Return Of Serenity - storyline_serenity_alive.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---storyline_serenity_bio-rb'>Rpg Narrative - Return Of Serenity - storyline_serenity_bio.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---storyline_serenity_introduction-rb'>Rpg Narrative - Return Of Serenity - storyline_serenity_introduction.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-narrative---return-of-serenity---storyline_speed_of_light-rb'>Rpg Narrative - Return Of Serenity - storyline_speed_of_light.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-roguelike---roguelike-starting-point---constants-rb'>Rpg Roguelike - Roguelike Starting Point - constants.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-roguelike---roguelike-starting-point---legend-rb'>Rpg Roguelike - Roguelike Starting Point - legend.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-roguelike---roguelike-starting-point---main-rb'>Rpg Roguelike - Roguelike Starting Point - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-roguelike---roguelike-starting-point---sprite_lookup-rb'>Rpg Roguelike - Roguelike Starting Point - sprite_lookup.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-roguelike---roguelike-line-of-sight---main-rb'>Rpg Roguelike - Roguelike Line Of Sight - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-tactical---hexagonal-grid---main-rb'>Rpg Tactical - Hexagonal Grid - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-tactical---isometric-grid---main-rb'>Rpg Tactical - Isometric Grid - main.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----rpg-topdown---topdown-starting-point---main-rb'>Rpg Topdown - Topdown Starting Point - main.rb</a></li></ul></ul><ul><li><a class='header-2' href='#---oss'>OSS</a></li></ul><ul><ul><li><a class='header-3' href='#----args-rb'>args.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----assert-rb'>assert.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----attr_gtk-rb'>attr_gtk.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----attr_sprite-rb'>attr_sprite.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----console-rb'>console.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----console_color-rb'>console_color.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----console_font_style-rb'>console_font_style.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----console_menu-rb'>console_menu.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----console_prompt-rb'>console_prompt.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----controller-rb'>controller.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----controller/config-rb'>controller/config.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----controller/keys-rb'>controller/keys.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----directional_input_helper_methods-rb'>directional_input_helper_methods.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----easing-rb'>easing.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----entity-rb'>entity.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----geometry-rb'>geometry.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----grid-rb'>grid.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----inputs-rb'>inputs.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----ios_wizard-rb'>ios_wizard.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----itch_wizard-rb'>itch_wizard.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----layout-rb'>layout.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----log-rb'>log.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----metadata-rb'>metadata.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----numeric-rb'>numeric.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----remote_hotload_client-rb'>remote_hotload_client.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----runtime/autocomplete-rb'>runtime/autocomplete.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----runtime/benchmark-rb'>runtime/benchmark.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----runtime/draw-rb'>runtime/draw.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----runtime/framerate-rb'>runtime/framerate.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----runtime/framerate_diagnostics-rb'>runtime/framerate_diagnostics.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----runtime/hotload-rb'>runtime/hotload.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----string-rb'>string.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----tests-rb'>tests.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----trace-rb'>trace.rb</a></li></ul></ul><ul><ul><li><a class='header-3' href='#----wizards-rb'>wizards.rb</a></li></ul></ul></ul> </div>
<div id='content'>
<h1 id='--dragonruby-game-toolkit-live-docs'>DragonRuby Game Toolkit Live Docs</h1>
<p>
The information contained here is all available via the DragonRuby Console. You can Open the DragonRuby Console by pressing [`] [~] [²] [^] [º] or [§] within your game.
</p>
<p>
To search docs you can type <code>docs_search "SEARCH TERM"</code> or if you want to get fancy you can provide a <code>lambda</code> to filter documentation:
</p>
<pre><code class="language-ruby">docs_search { |entry| (entry.include? "Array") && (!entry.include? "Enumerable") }
</code></pre>
<h1 id='--hello-world'>Hello World</h1>
<p>
Welcome to DragonRuby Game Toolkit. Take the steps below to get started.
</p>
<h1 id='--join-the-discord-and-subscribe-to-the-news-letter'>Join the Discord and Subscribe to the News Letter</h1>
<p>
Our Discord channel is <a href='http://discord.dragonruby.org'>http://discord.dragonruby.org</a>.
</p>
<p>
The News Letter will keep you in the loop with regards to current DragonRuby Events: <a href='http://dragonrubydispatch.com'>http://dragonrubydispatch.com</a>.
</p>
<p>
Those who use DragonRuby are called Dragon Riders. This identity is incredibly important to us. When someone asks you:
</p>
<blockquote>
<p>
What game engine do you use?
</p>
</blockquote>
<p>
Reply with:
</p>
<blockquote>
<p>
I am a Dragon Rider.
</p>
</blockquote>
<h1 id='--intro-videos'>Intro Videos</h1>
<p>
Here are some videos to help you get the lay of the land.
</p>
<h2 id='---quick-api-tour'>Quick Api Tour</h2>
<ol>
<li> Beginner Introduction to DragonRuby Game Toolkit: <a href='https://youtu.be/ixw7TJhU08E'>https://youtu.be/ixw7TJhU08E</a></li>
</ol>
<h2 id='---if-you-are-completely-new-to-ruby-and-programming'>If You Are Completely New to Ruby and Programming</h2>
<ol>
<li> Intermediate Introduction to Ruby Syntax: <a href='https://youtu.be/HG-XRZ5Ppgc'>https://youtu.be/HG-XRZ5Ppgc</a></li>
<li> Intermediate Introduction to Arrays in Ruby: <a href='https://youtu.be/N72sEYFRqfo'>https://youtu.be/N72sEYFRqfo</a></li>
<li> You may also want to try this free course provided at <a href='http://dragonruby.school'>http://dragonruby.school</a>.</li>
</ol>
<h2 id='---if-you-have-game-dev-experience'>If You Have Game Dev Experience</h2>
<ol>
<li> Building Tetris - Part 1: <a href='https://youtu.be/xZMwRSbC4rY'>https://youtu.be/xZMwRSbC4rY</a></li>
<li> Building Tetris - Part 2: <a href='https://youtu.be/C3LLzDUDgz4'>https://youtu.be/C3LLzDUDgz4</a></li>
<li> Low Res Game Jam Tutorial: <a href='https://youtu.be/pCI90ukKCME'>https://youtu.be/pCI90ukKCME</a></li>
</ol>
<h1 id='--getting-started-tutorial'>Getting Started Tutorial</h1>
<p>
This is a tutorial written by Ryan C Gordon (a Juggernaut in the industry who has contracted to Valve, Epic, Activision, and EA... check out his Wikipedia page: <a href='https://en.wikipedia.org/wiki/Ryan_C._Gordon'>https://en.wikipedia.org/wiki/Ryan_C._Gordon</a>).
</p>
<h2 id='---introduction'>Introduction</h2>
<p>
Welcome!
</p>
<p>
Here's just a little push to get you started if you're new to programming or game development.
</p>
<p>
If you want to write a game, it's no different than writing any other program for any other framework: there are a few simple rules that might be new to you, but more or less programming is programming no matter what you are building.
</p>
<p>
Did you not know that? Did you think you couldn't write a game because you're a "web guy" or you're writing Java at a desk job? Stop letting people tell you that you can't, because you already have everything you need.
</p>
<p>
Here, we're going to be programming in a language called "Ruby." In the interest of full disclosure, I (Ryan Gordon) wrote the C parts of this toolkit and Ruby looks a little strange to me (Amir Rajan wrote the Ruby parts, discounting the parts I mangled), but I'm going to walk you through the basics because we're all learning together, and if you mostly think of yourself as someone that writes C (or C++, C#, Objective-C), PHP, or Java, then you're only a step behind me right now.
</p>
<h2 id='---prerequisites'>Prerequisites</h2>
<p>
Here's the most important thing you should know: Ruby lets you do some complicated things really easily, and you can learn that stuff later. I'm going to show you one or two cool tricks, but that's all.
</p>
<p>
Do you know what an if statement is? A for-loop? An array? That's all you'll need to start.
</p>
<h2 id='---the-game-loop'>The Game Loop</h2>
<p>
Ok, here are few rules with regards to game development with GTK:
</p>
<ul>
<li>Your game is all going to happen under one function ...</li>
<li>that runs 60 times a second ...</li>
<li>and has to tell the computer what to draw each time.</li>
</ul>
<p>
That's an entire video game in one run-on sentence.
</p>
<p>
Here's that function. You're going to want to put this in mygame/app/main.rb, because that's where we'll look for it by default. Load it up in your favorite text editor.
</p>
<pre><code class="language-ruby">def tick args
args.outputs.labels << [580, 400, 'Hello World!']
end
</code></pre>
<p>
Now run <code>dragonruby</code> ...did you get a window with "Hello World!" written in it? Good, you're officially a game developer!
</p>
<h2 id='---breakdown-of-the--tick--method'>Breakdown Of The <code>tick</code> Method</h2>
<p>
<code>mygame/app/main.rb</code>, is where the Ruby source code is located. This looks a little strange, so I'll break it down line by line. In Ruby, a '#' character starts a single-line comment, so I'll talk about this inline.
</p>
<pre><code class="language-ruby"># This "def"ines a function, named "tick," which takes a single argument
# named "args". DragonRuby looks for this function and calls it every
# frame, 60 times a second. "args" is a magic structure with lots of
# information in it. You can set variables in there for your own game state,
# and every frame it will updated if keys are pressed, joysticks moved,
# mice clicked, etc.
def tick args
# One of the things in "args" is the "outputs" object that your game uses
# to draw things. Afraid of rendering APIs? No problem. In DragonRuby,
# you use arrays to draw things and we figure out the details.
# If you want to draw text on the screen, you give it an array (the thing
# in the [ brackets ]), with an X and Y coordinate and the text to draw.
# The "<<" thing says "append this array onto the list of them at
# args.outputs.labels)
args.outputs.labels << [580, 400, 'Hello World!']
end
</code></pre>
<p>
Once your <code>tick</code> function finishes, we look at all the arrays you made and figure out how to draw it. You don't need to know about graphics APIs. You're just setting up some arrays! DragonRuby clears out these arrays every frame, so you just need to add what you need _right now_ each time.
</p>
<h2 id='---rendering-a-sprite'>Rendering A Sprite</h2>
<p>
Now let's spice this up a little.
</p>
<p>
We're going to add some graphics. Each 2D image in DragonRuby is called a "sprite," and to use them, you just make sure they exist in a reasonable file format (png, jpg, gif, bmp, etc) and specify them by filename. The first time you use one, DragonRuby will load it and keep it in video memory for fast access in the future. If you use a filename that doesn't exist, you get a fun checkerboard pattern!
</p>
<p>
There's a "dragonruby.png" file included, just to get you started. Let's have it draw every frame with our text:
</p>
<pre><code class="language-ruby">def tick args
args.outputs.labels << [580, 400, 'Hello World!']
args.outputs.sprites << [576, 100, 128, 101, 'dragonruby.png']
end
</code></pre>
<p>
(Pro Tip: you don't have to restart DragonRuby to test your changes; when you save main.rb, DragonRuby will notice and reload your program.)
</p>
<p>
That <code>.sprites</code> line says "add a sprite to the list of sprites we're drawing, and draw it at position (576, 100) at a size of 128x101 pixels". You can find the image to draw at dragonruby.png.
</p>
<h2 id='---coordinate-system-and-virtual-canvas'>Coordinate System and Virtual Canvas</h2>
<p>
Quick note about coordinates: (0, 0) is the bottom left corner of the screen, and positive numbers go up and to the right. This is more "geometrically correct," even if it's not how you remember doing 2D graphics, but we chose this for a simpler reason: when you're making Super Mario Brothers and you want Mario to jump, you should be able to add to Mario's y position as he goes up and subtract as he falls. It makes things easier to understand.
</p>
<p>
Also: your game screen is _always_ 1280x720 pixels. If you resize the window, we will scale and letterbox everything appropriately, so you never have to worry about different resolutions.
</p>
<p>
Ok, now we have an image on the screen, let's animate it:
</p>
<pre><code class="language-ruby">def tick args
args.state.rotation ||= 0
args.outputs.labels << [580, 400, 'Hello World!' ]
args.outputs.sprites << [576, 100, 128, 101, 'dragonruby.png', args.state.rotation]
args.state.rotation -= 1
end
</code></pre>
<p>
Now you can see that this function is getting called a lot!
</p>
<h2 id='---game-state'>Game State</h2>
<p>
Here's a fun Ruby thing: <code>args.state.rotation ||= 0</code> is shorthand for "if args.state.rotation isn't initialized, set it to zero." It's a nice way to embed your initialization code right next to where you need the variable.
</p>
<p>
<code>args.state</code> is a place you can hang your own data. It's an open data structure that allows you to define properties that are arbitrarily nested. You don't need to define any kind of class.
</p>
<p>
In this case, the current rotation of our sprite, which is happily spinning at 60 frames per second. If you don't specify rotation (or alpha, or color modulation, or a source rectangle, etc), DragonRuby picks a reasonable default, and the array is ordered by the most likely things you need to tell us: position, size, name.
</p>
<h2 id='---there-is-no-delta-time'>There Is No Delta Time</h2>
<p>
One thing we decided to do in DragonRuby is not make you worry about delta time: your function runs at 60 frames per second (about 16 milliseconds) and that's that. Having to worry about framerate is something massive triple-AAA games do, but for fun little 2D games? You'd have to work really hard to not hit 60fps. All your drawing is happening on a GPU designed to run Fortnite quickly; it can definitely handle this.
</p>
<p>
Since we didn't make you worry about delta time, you can just move the rotation by 1 every time and it works without you having to keep track of time and math. Want it to move faster? Subtract 2.
</p>
<h2 id='---handling-user-input'>Handling User Input</h2>
<p>
Now, let's move that image around.
</p>
<pre><code class="language-ruby">def tick args
args.state.rotation ||= 0
args.state.x ||= 576
args.state.y ||= 100
if args.inputs.mouse.click
args.state.x = args.inputs.mouse.click.point.x - 64
args.state.y = args.inputs.mouse.click.point.y - 50
end
args.outputs.labels << [580, 400, 'Hello World!']
args.outputs.sprites << [args.state.x,
args.state.y,
128,
101,
'dragonruby.png',
args.state.rotation]
args.state.rotation -= 1
end
</code></pre>
<p>
Everywhere you click your mouse, the image moves there. We set a default location for it with <code>args.state.x ||= 576</code>, and then we change those variables when we see the mouse button in action. You can get at the keyboard and game controllers in similar ways.
</p>
<h2 id='---coding-on-a-raspberry-pi'>Coding On A Raspberry Pi</h2>
<p>
We have only tested DragonRuby on a Raspberry Pi 3, Models B and B+, but we believe it _should_ work on any model with comparable specs.
</p>
<p>
If you're running DragonRuby Game Toolkit on a Raspberry Pi, or trying to run a game made with the Toolkit on a Raspberry Pi, and it's really really slow-- like one frame every few seconds--then there's likely a simple fix.
</p>
<p>
You're probably running a desktop environment: menus, apps, web browsers, etc. This is okay! Launch the terminal app and type:
</p>
<pre><code class="language-ruby">do raspi-config
</code></pre>
<p>
It'll ask you for your password (if you don't know, try "raspberry"), and then give you a menu of options. Find your way to "Advanced Options", then "GL Driver", and change this to "GL (Full KMS)" ... not "fake KMS," which is also listed there. Save and reboot. In theory, this should fix the problem.
</p>
<p>
If you're _still_ having problems and have a Raspberry Pi 2 or better, go back to raspi-config and head over to "Advanced Options", "Memory split," and give the GPU 256 megabytes. You might be able to avoid this for simple games, as this takes RAM away from the system and reserves it for graphics. You can also try 128 megabytes as a gentler option.
</p>
<p>
Note that you can also run DragonRuby without X11 at all: if you run it from a virtual terminal it will render fullscreen and won't need the "Full KMS" option. This might be attractive if you want to use it as a game console sort of thing, or develop over ssh, or launch it from RetroPie, etc.
</p>
<h2 id='---conclusion'>Conclusion</h2>
<p>
There is a lot more you can do with DragonRuby, but now you've already got just about everything you need to make a simple game. After all, even the most fancy games are just creating objects and moving them around. Experiment a little. Add a few more things and have them interact in small ways. Want something to go away? Just don't add it to <code>args.output</code> anymore.
</p>
<h1 id='--deploying-to-itch-io'>Deploying To Itch.io</h1>
<p>
Once you've built your game, you're all set to deploy! Good luck in your game dev journey and if you get stuck, come to the Discord channel!
</p>
<h2 id='---creating-your-game-landing-page'>Creating Your Game Landing Page</h2>
<p>
Log into Itch.io and go to <a href='https://itch.io/game/new'>https://itch.io/game/new</a>.
</p>
<ul>
<li>Title: Give your game a Title. This value represents your `gametitle`.</li>
<li>Project URL: Set your project url. This value represents your `gameid`.</li>
<li>Classification: Keep this as Game.</li>
<li>Kind of Project: Select HTML from the drop down list. Don't worry,
the HTML project type _also supports binary downloads_.</li>
<li>Uploads: Skip this section for now.</li>
</ul>
<p>
You can fill out all the other options later.
</p>
<h2 id='---update-your-game's-metadata'>Update Your Game's Metadata</h2>
<p>
Point your text editor at mygame/metadata/game_metadata.txt and make it look like this:
</p>
<p>
NOTE: Remove the <code>#</code> at the beginning of each line.
</p>
<pre><code class="language-ruby">devid=bob
devtitle=Bob The Game Developer
gameid=mygame
gametitle=My Game
version=0.1
</code></pre>
<p>
The <code>devid</code> property is the username you use to log into Itch.io. The <code>devtitle</code> is your name or company name (it can contain spaces). The <code>gameid</code> is the Project URL value. The <code>gametitle</code> is the name of your game (it can contain spaces). The <code>version</code> can be any <code>major.minor</code> number format.
</p>
<h2 id='---building-your-game-for-distribution'>Building Your Game For Distribution</h2>
<p>
Open up the terminal and run this from the command line:
</p>
<pre><code class="language-ruby">./dragonruby-publish --only-package mygame
</code></pre>
<p>
(if you're on Windows, don't put the "./" on the front. That's a Mac and Linux thing.)
</p>
<p>
A directory called <code>./build</code> will be created that contains your binaries. You can upload this to Itch.io manually.
</p>
<p>
For the HTML version of your game after you upload it. Check the checkbox labeled "This file will be played in the browser".
</p>
<p>
For subsequent updates you can use an automated deployment to Itch.io:
</p>
<pre><code class="language-ruby">./dragonruby-publish mygame
</code></pre>
<p>
DragonRuby will package _and publish_ your game to itch.io! Tell your friends to go to your game's very own webpage and buy it!
</p>
<p>
If you make changes to your game, just re-run dragonruby-publish and it'll update the downloads for you.
</p>
<h1 id='--deploying-to-mobile-devices'>Deploying To Mobile Devices</h1>
<p>
If you have a Pro subscription, you also have the capability to deploy to mobile devices.
</p>
<p>
To deploy to iOS, you need to have a Mac running MacOS Catalina, an iOS device, and an active/paid Developer Account with Apple. From the Console type: <code>$wizards.ios.start</code> and you will be guided through the deployment process.
</p>
<p>
To deploy to Android, you need to have an Android emulator/device, and an environment that is able to run Android SDK. <code>dragonruby-publish</code> will create an APK for you. From there, you can sign the APK and install it to your device. The signing and installation procedure varies from OS to OS. Here's an example of what the command might look like:
</p>
<pre><code class="language-ruby">> adb logcat -e mygame # you'll want to run this in a separate terminal
> keytool -genkey -v -keystore mygame.keystore -alias mygame -keyalg RSA -keysize 2048 -validity 10000
> apksigner sign --ks mygame.keystore mygame-android.apk
> adb install mygame-android.apk
</code></pre>
<h1 id='--dragonruby's-philosophy'>DragonRuby's Philosophy</h1>
<p>
The following tenants of DragonRuby are what set us apart from other game engines. Given that Game Toolkit is a relatively new engine, there are definitely features that are missing. So having a big check list of "all the cool things" is not this engine's forte. This is compensated with a strong commitment to the following principles.
</p>
<h2 id='---challenge-the-status-quo'>Challenge The Status Quo</h2>
<p>
Game engines of today are in a local maximum and don't take into consideration the challenges of this day and age. Unity and GameMaker specifically rot your brain. It's not sufficient to say:
</p>
<blockquote>
<p>
But that's how we've always done it.
</p>
</blockquote>
<p>
It's a hard pill to swallow, but forget blindly accepted best practices and try to figure out the underlying motivation for a specific approach to game development. Collaborate with us.
</p>
<h2 id='---continuity-of-design'>Continuity of Design</h2>
<p>
There is a programming idiom in software called "The Pit of Success". The term normalizes upfront pain as a necessity/requirement in the hopes that the investment will yield dividends "when you become successful" or "when the code becomes more complicated". This approach to development is strongly discouraged by us. It leads to over-architected and unnecessary code; creates barriers to rapid prototyping and shipping a game; and overwhelms beginners who are new to the engine or programming in general.
</p>
<p>
DragonRuby's philosophy is to provide multiple options across the "make it fast" vs "make it right" spectrum, with incremental/intuitive transitions between the options provided. A concrete example of this philosophy would be render primitives: the spectrum of options allows renderable constructs that take the form of tuples/arrays (easy to pickup, simple, and fast to code/prototype with), hashes (a little more work, but gives you the ability to add additional properties), open and strict entities (more work than hashes, but yields cleaner apis), and finally - if you really need full power/flexibility in rendering - classes (which take the most amount of code and programming knowledge to create).
</p>
<h2 id='---release-early-and-often'>Release Early and Often</h2>
<p>
The biggest mistake game devs make is spending too much time in isolation building their game. Release something, however small, and release it soon.
</p>
<p>
Stop worrying about everything being pixel perfect. Don't wait until your game is 100% complete. Build your game publicly and iterate. Post in the #show-and-tell channel in the community Discord. You'll find a lot of support and encouragement there.
</p>
<p>
Real artists ship. Remember that.
</p>
<h2 id='---sustainable-and-ethical-monetization'>Sustainable And Ethical Monetization</h2>
<p>
We all aspire to put food on the table doing what we love. Whether it is building games, writing tools to support game development, or anything in between.
</p>
<p>
Charge a fair amount of money for the things you create. It's expected and encouraged within the community. Give what you create away for free to those that can't afford it.
</p>
<p>
If you are gainfully employed, pay full price for the things you use. If you do end up getting something at a discount, pay the difference "forward" to someone else.
</p>
<h2 id='---sustainable-and-ethical-open-source'>Sustainable And Ethical Open Source</h2>
<p>
This goes hand in hand with sustainable and ethical monetization. The current state of open source is not sustainable. There is an immense amount of contributor burnout. Users of open source expect everything to be free, and few give back. This is a problem we want to fix (we're still trying to figure out the best solution).
</p>
<p>
So, don't be "that guy" in the Discord that says "DragonRuby should be free and open source!" You will be personally flogged by Amir.
</p>
<h2 id='---people-over-entities'>People Over Entities</h2>
<p>
We prioritize the endorsement of real people over faceless entities. This game engine, and other products we create, are not insignificant line items of a large company. And you aren't a generic "commodity" or "corporate resource". So be active in the community Discord and you'll reap the benefits as more devs use DragonRuby.
</p>
<h2 id='---building-a-game-should-be-fun-and-bring-happiness'>Building A Game Should Be Fun And Bring Happiness</h2>
<p>
We will prioritize the removal of pain. The aesthetics of Ruby make it such a joy to work with, and we want to capture that within the engine.
</p>
<h2 id='---real-world-application-drives-features'>Real World Application Drives Features</h2>
<p>
We are bombarded by marketing speak day in and day out. We don't do that here. There are things that are really great in the engine, and things that need a lot of work. Collaborate with us so we can help you reach your goals. Ask for features you actually need as opposed to anything speculative.
</p>
<p>
We want DragonRuby to *actually* help you build the game you want to build (as opposed to sell you something piece of demoware that doesn't work).
</p>
<h1 id='--frequently-asked-questions--comments--and-concerns'>Frequently Asked Questions, Comments, and Concerns</h1>
<p>
Here are questions, comments, and concerns that frequently come up.
</p>
<h2 id='---frequently-asked-questions'>Frequently Asked Questions</h2>
<h3 id='----what-is-dragonruby-llp-'>What is DragonRuby LLP?</h3>
<p>
DragonRuby LLP is a partnership of four devs who came together with the goal of bringing the aesthetics and joy of Ruby, everywhere possible.
</p>
<p>
Under DragonRuby LLP, we offer a number of products (with more on the way):
</p>
<ul>
<li>Game Toolkit (GTK): A 2D game engine that is compatible with modern
gaming platforms.</li>
<li>RubyMotion (RM): A compiler toolchain that allows you to build native, cross-platform mobile
apps. <a href='http://rubymotion.com'>http://rubymotion.com</a></li>
</ul>
<p>
All of the products above leverage a shared core called DragonRuby.
</p>
<p>
NOTE: From an official branding standpoint each one of the products is suffixed with "A DragonRuby LLP Product" tagline. Also, DragonRuby is _one word, title cased_.
</p>
<p>
NOTE: We leave the "A DragonRuby LLP Product" off of this one because that just sounds really weird.
</p>
<p>
NOTE: Devs who use DragonRuby are "Dragon Riders/Riders of Dragons". That's a bad ass identifier huh?
</p>
<h3 id='----what-is-dragonruby-'>What is DragonRuby?</h3>
<p>
The response to this question requires a few subparts. First we need to clarify some terms. Specifically _language specification_ vs _runtime_.
</p>
<h4>Okay... so what is the difference between a language specification and a runtime?</h4>
<p>
A runtime is an _implementation_ of a language specification. When people say "Ruby," they are usually referring to "the Ruby 3.0+ language specification implemented via the CRuby/MRI Runtime."
</p>
<p>
But, there are many Ruby Runtimes: CRuby/MRI, JRuby, Truffle, Rubinius, Artichoke, and (last but certainly not least) DragonRuby.
</p>
<h4>Okay... what language specification does DragonRuby use then?</h4>
<p>
DragonRuby's goal is to be compliant with the ISO/IEC 30170:2012 standard. It's syntax is Ruby 2.x compatible, but also contains semantic changes that help it natively interface with platform specific libraries.
</p>
<h4>So... why another runtime?</h4>
<p>
The elevator pitch is:
</p>
<p>
DragonRuby is a Multilevel Cross-platform Runtime. The "multiple levels" within the runtime allows us to target platforms no other Ruby can target: PC, Mac, Linux, Raspberry Pi, WASM, iOS, Android, Nintendo Switch, PS4, Xbox, and Stadia.
</p>
<h4>What does Multilevel Cross-platform mean?</h4>
<p>
There are complexities associated with targeting all the platforms we support. Because of this, the runtime had to be architected in such a way that new platforms could be easily added (which lead to us partitioning the runtime internally):
</p>
<ul>
<li>Level 1 we leverage a good portion of mRuby.</li>
<li>Level 2 consists of optimizations to mRuby we've made given that our
target platforms are well known.</li>
<li>Level 3 consists of portable C libraries and their Ruby
C-Extensions.</li>
</ul>
<p>
Levels 1 through 3 are fairly commonplace in many runtime implementations (with level 1 being the most portable, and level 3 being the fastest). But the DragonRuby Runtime has taken things a bit further:
</p>
<ul>
<li>Level 4 consists of shared abstractions around hardware I/O and operating
system resources. This level leverages open source and proprietary components within Simple DirectMedia Layer (a low level multimedia component library that has been in active development for 22 years and counting).</li>
<li>Level 5 is a code generation layer which creates metadata that allows
for native interoperability with host runtime libraries. It also includes OS specific message pump orchestrations.</li>
<li>Level 6 is a Ahead of Time/Just in Time Ruby compiler built with LLVM. This
compiler outputs _very_ fast platform specific bitcode, but only supports a subset of the Ruby language specification.</li>
</ul>
<p>
These levels allow us to stay up to date with open source implementations of Ruby; provide fast, native code execution on proprietary platforms; ensure good separation between these two worlds; and provides a means to add new platforms without going insane.
</p>
<h4>Cool cool. So given that I understand everything to this point, can we answer the original question? What is DragonRuby?</h4>
<p>
DragonRuby is a Ruby runtime implementation that takes all the lessons we've learned from MRI/CRuby, and merges it with the latest and greatest compiler and OSS technologies.
</p>
<h3 id='----how-is-dragonruby-different-than-mri-'>How is DragonRuby different than MRI?</h3>
<p>
DragonRuby supports a subset of MRI apis. Our target is to support all of mRuby's standard lib. There are challenges to this given the number of platforms we are trying to support (specifically console).
</p>
<h4>Does DragonRuby support Gems?</h4>
<p>
DragonRuby does not support gems because that requires the installation of MRI Ruby on the developer's machine (which is a non-starter given that we want DragonRuby to be a zero dependency runtime). While this seems easy for Mac and Linux, it is much harder on Windows and Raspberry Pi. mRuby has taken the approach of having a git repository for compatible gems and we will most likely follow suite: <a href='https://github.com/mruby/mgem-list'>https://github.com/mruby/mgem-list</a>.
</p>
<h4>Does DragonRuby have a REPL/IRB?</h4>
<p>
You can use DragonRuby's Console within the game to inspect object and execute small pieces of code. For more complex pieces of code create a file called <code>repl.rb</code> and put it in <code>mygame/app/repl.rb</code>:
</p>
<ul>
<li>Any code you write in there will be executed when you change the file. You can organize different pieces of code using the <code>repl</code> method:</li>
</ul>
<pre><code class="language-ruby">repl do
puts "hello world"
puts 1 + 1
end
</code></pre>
<ul>
<li>If you use the `repl` method, the code will be executed and the DragonRuby Console will automatically open so you can see the results (on Mac and Linux, the results will also be printed to the terminal).</li>
<li>All <code>puts</code> statements will also be saved to <code>logs/puts.txt</code>. So if you want to stay in your editor and not look at the terminal, or the DragonRuby Console, you can <code>tail</code> this file.</li>
</ul>
<p>
4. To ignore code in <code>repl.rb</code>, instead of commenting it out, prefix <code>repl</code> with the letter <code>x</code> and it'll be ignored.
</p>
<pre><code class="language-ruby">xrepl do # <------- line is prefixed with an "x"
puts "hello world"
puts 1 + 1
end
# This code will be executed when you save the file.
repl do
puts "Hello"
end
repl do
puts "This code will also be executed."
end
# use xrepl to "comment out" code
xrepl do
puts "This code will not be executed because of the x in front of repl".
end
</code></pre>
<h4>Does DragonRuby support <code>pry</code> or have any other debugging facilities?</h4>
<p>
<code>pry</code> is a gem that assumes you are using the MRI Runtime (which is incompatible with DragonRuby). Eventually DragonRuby will have a pry based experience that is compatible with a debugging infrastructure called LLDB. Take the time to read about LLDB as it shows the challenges in creating something that is compatible.
</p>
<p>
You can use DragonRuby's replay capabilities to troubleshoot:
</p>
<ol>
<li> DragonRuby is hot loaded which gives you a very fast feedback loop (if the game throws an exception, it's because of the code you just added).</li>
<li> Use <code>./dragonruby mygame --record</code> to create a game play recording that you can use to find the exception (you can replay a recording by executing <code>./dragonruby mygame --replay last_replay.txt</code> or through the DragonRuby Console using <code>$gtk.recording.start_replay "last_replay.txt"</code>.</li>
<li> DragonRuby also ships with a unit testing facility. You can invoke the following command to run a test: <code>./dragonruby . --eval some_ruby_file.rb --no-tick</code>.</li>
<li> Get into the habit of adding debugging facilities within the game itself. You can add drawing primitives to <code>args.outputs.debug</code> that will render on top of your game but will be ignored in a production release.</li>
<li> Debugging something that runs at 60fps is (imo) not that helpful. The exception you are seeing could have been because of a change that occurred many frames ago.</li>
</ol>
<h2 id='---frequent-comments-about-ruby-as-a-language-choice'>Frequent Comments About Ruby as a Language Choice</h2>
<h3 id='----but-ruby-is-dead-'>But Ruby is dead.</h3>
<p>
Let's check the official source for the answer to this question: isrubydead.com: <a href='https://isrubydead.com/'>https://isrubydead.com/</a>.
</p>
<p>
On a more serious note, Ruby's _quantity_ levels aren't what they used to be. And that's totally fine. Everyone chases the new and shiny.
</p>
<p>
What really matters is _quality/maturity_. Here is the latest (StackOverflow Survey sorted by highest paid developers)[https://insights.stackoverflow.com/survey/2019#top-paying-technologies].
</p>
<p>
Let's stop making this comment shall we?
</p>
<h3 id='----but-ruby-is-slow-'>But Ruby is slow.</h3>
<p>
That doesn't make any sense. A language specification can't be slow... it's a language spec. Sure, an _implementation/runtime_ can be slow though, but then we'd have to talk about which runtime.
</p>
<h3 id='----dynamic-languages-are-slow-'>Dynamic languages are slow.</h3>
<p>
They are certainly slower than statically compiled languages. With the processing power and compiler optimizations we have today, dynamic languages like Ruby are _fast enough_.
</p>
<p>
Unless you are writing in some form of intermediate representation by hand, your language of choice also suffers this same fallacy of slow. Like, nothing is faster than a low level assembly-like language. So unless you're writing in that, let's stop making this comment.
</p>
<p>
NOTE: If you _are_ hand writing LLVM IR, we are always open to bringing on new partners with such a skill set. Email us ^_^.
</p>
<h2 id='---frequent-concerns'>Frequent Concerns</h2>
<h3 id='----dragonruby-is-not-open-source--that's-not-right-'>DragonRuby is not open source. That's not right.</h3>
<p>
The current state of open source is unsustainable. Contributors work for free, most all open source repositories are severely under-staffed, and burnout from core members is rampant.
</p>
<p>
We believe in open source very strongly. Parts of DragonRuby are in fact, open source. Just not all of it (for legal reasons, and because the IP we've created has value). And we promise that we are looking for (or creating) ways to _sustainably_ open source everything we do.
</p>
<p>
If you have ideas on how we can do this, email us!
</p>
<p>
If the reason above isn't sufficient, then definitely use something else.
</p>
<p>
All this being said, we do have parts of the engine open sourced on GitHub: <a href='https://github.com/dragonruby/dragonruby-game-toolkit-contrib/'>https://github.com/dragonruby/dragonruby-game-toolkit-contrib/</a>
</p>
<h3 id='----dragonruby-is-for-pay--you-should-offer-a-free-version-'>DragonRuby is for pay. You should offer a free version.</h3>
<p>
If you can afford to pay for DragonRuby, you should (and will). We don't go around telling writers that they should give us their books for free, and only require payment if we read the entire thing. It's time we stop asking that of software products.
</p>
<p>
That being said, we will _never_ put someone out financially. We have income assistance for anyone that can't afford a license to any one of our products.
</p>
<p>
You qualify for a free, unrestricted license to DragonRuby products if any of the following items pertain to you:
</p>
<ul>
<li>Your income is below $2,000.00 (USD) per month.</li>
<li>You are under 18 years of age.</li>
<li>You are a student of any type: traditional public school, home
schooling, college, bootcamp, or online.</li>
<li>You are a teacher, mentor, or parent who wants to teach a kid how to code.</li>
<li>You work/worked in public service or at a charitable organization:
for example public office, army, or any 501(c)(3) organization.</li>
</ul>
<p>
Just contact Amir at [email protected] with a short explanation of your current situation and he'll set you up. No questions asked.
</p>
<h3 id='----but-still--you-should-offer-a-free-version--so-i-can-try-it-out-and-see-if-i-like-it-'>But still, you should offer a free version. So I can try it out and see if I like it.</h3>
<p>
You can try our web-based sandbox environment at <a href='http://fiddle.dragonruby.org'>http://fiddle.dragonruby.org</a>. But it won't do the runtime justice. Or just come to our Discord Channel at <a href='http://discord.dragonruby.org'>http://discord.dragonruby.org</a> and ask questions. We'd be happy to have a one on one video chat with you and show off all the cool stuff we're doing.
</p>
<p>
Seriously just buy it. Get a refund if you don't like it. We make it stupid easy to do so.
</p>
<h3 id='----i-still-think-you-should-do-a-free-version--think-of-all-people-who-would-give-it-a-shot-'>I still think you should do a free version. Think of all people who would give it a shot.</h3>
<p>
Free isn't a sustainable financial model. We don't want to spam your email. We don't want to collect usage data off of you either. We just want to provide quality toolchains to quality developers (as opposed to a large quantity of developers).
</p>
<p>
The people that pay for DragonRuby and make an effort to understand it are the ones we want to build a community around, partner with, and collaborate with. So having that small monetary wall deters entitled individuals that don't value the same things we do.
</p>
<h3 id='----what-if-i-build-something-with-dragonruby--but-dragonruby-llp-becomes-insolvent-'>What if I build something with DragonRuby, but DragonRuby LLP becomes insolvent.</h3>
<p>
That won't happen if the development world stop asking for free stuff and non-trivially compensate open source developers. Look, we want to be able to work on the stuff we love, every day of our lives. And we'll go to great lengths to make that happen.
</p>
<p>
But, in the event that sad day comes, our partnership bylaws state that _all_ DragonRuby IP that can be legally open sourced, will be released under a permissive license.
</p>
<h1 id='--recipies-'>RECIPIES:</h1>
<h2 id='---how-to-determine-what-frame-you-are-on'>How To Determine What Frame You Are On</h2>
<p>
There is a property on <code>state</code> called <code>tick_count</code> that is incremented by DragonRuby every time the <code>tick</code> method is called. The following code renders a label that displays the current <code>tick_count</code>.
</p>
<pre><code class="language-ruby">def tick args
args.outputs.labels << [10, 670, "#{args.state.tick_count}"]
end
</code></pre>
<h2 id='---how-to-get-current-framerate'>How To Get Current Framerate</h2>
<p>
Current framerate is a top level property on the Game Toolkit Runtime and is accessible via <code>args.gtk.current_framerate</code>.
</p>
<pre><code class="language-ruby">def tick args
args.outputs.labels << [10, 710, "framerate: #{args.gtk.current_framerate.round}"]
end
</code></pre>
<h2 id='---how-to-render-a-sprite-using-an-array'>How To Render A Sprite Using An Array</h2>
<p>
All file paths should use the forward slash <code>/</code> *not* backslash <code></code>. Game Toolkit includes a number of sprites in the <code>sprites</code> folder (everything about your game is located in the <code>mygame</code> directory).
</p>
<p>
The following code renders a sprite with a <code>width</code> and <code>height</code> of <code>100</code> in the center of the screen.
</p>
<p>
<code>args.outputs.sprites</code> is used to render a sprite.
</p>
<pre><code class="language-ruby">def tick args
args.outputs.sprites << [
640 - 50, # X
360 - 50, # Y
100, # W
100, # H
'sprites/square-blue.png' # PATH
]
end
</code></pre>
<h2 id='---more-sprite-properties-as-an-array'>More Sprite Properties As An Array</h2>
<p>
Here are all the properties you can set on a sprite.
</p>
<pre><code class="language-ruby">def tick args
args.outputs.sprites << [
100, # X
100, # Y
32, # W
64, # H
'sprites/square-blue.png', # PATH
0, # ANGLE
255, # ALPHA
0, # RED_SATURATION
255, # GREEN_SATURATION
0 # BLUE_SATURATION
]
end
</code></pre>
<h2 id='---different-sprite-representations'>Different Sprite Representations</h2>
<p>
Using ordinal positioning can get a little unruly given so many properties you have control over.
</p>
<p>
You can represent a sprite as a <code>Hash</code>:
</p>
<pre><code class="language-ruby">def tick args
args.outputs.sprites << {
x: 640 - 50,
y: 360 - 50,
w: 100,
h: 100,
path: 'sprites/square-blue.png',
angle: 0,
a: 255,
r: 255,
g: 255,
b: 255,
source_x: 0,
source_y: 0,
source_w: -1,
source_h: -1,
flip_vertically: false,
flip_horizontally: false,
angle_anchor_x: 0.5,
angle_anchor_y: 1.0,
blendmode_enum: 1
}
end
</code></pre>
<p>
The <code>blendmode_enum</code> value can be set to <code>0</code> (no blending), <code>1</code> (alpha blending), <code>2</code> (additive blending), <code>3</code> (modulo blending), <code>4</code> (multiply blending).
</p>
<p>
You can represent a sprite as an <code>object</code>:
</p>
<pre><code class="language-ruby"># Create type with ALL sprite properties AND primitive_marker
class Sprite
attr_accessor :x, :y, :w, :h, :path, :angle, :a, :r, :g, :b,
:source_x, :source_y, :source_w, :source_h,
:tile_x, :tile_y, :tile_w, :tile_h,
:flip_horizontally, :flip_vertically,
:angle_anchor_x, :angle_anchor_y, :blendmode_enum
def primitive_marker
:sprite
end
end
class BlueSquare < Sprite
def initialize opts
@x = opts[:x]
@y = opts[:y]
@w = opts[:w]
@h = opts[:h]
@path = 'sprites/square-blue.png'
end
end
def tick args
args.outputs.sprites << (BlueSquare.new x: 640 - 50,
y: 360 - 50,
w: 50,
h: 50)
end
</code></pre>
<h2 id='---how-to-render-a-label'>How To Render A Label</h2>
<p>
<code>args.outputs.labels</code> is used to render labels.
</p>
<p>
Labels are how you display text. This code will go directly inside of the <code>def tick args</code> method.
</p>
<p>
Here is the minimum code:
</p>
<pre><code class="language-ruby">def tick args
# X Y TEXT
args.outputs.labels << [640, 360, "I am a black label."]
end
</code></pre>
<h2 id='---a-colored-label'>A Colored Label</h2>
<pre><code class="language-ruby">def tick args
# A colored label
# X Y TEXT, RED GREEN BLUE ALPHA
args.outputs.labels << [640, 360, "I am a redish label.", 255, 128, 128, 255]
end
</code></pre>
<h2 id='---extended-label-properties'>Extended Label Properties</h2>
<pre><code class="language-ruby">def tick args
# A colored label
# X Y TEXT SIZE ALIGNMENT RED GREEN BLUE ALPHA FONT FILE
args.outputs.labels << [
640, # X
360, # Y
"Hello world", # TEXT
0, # SIZE_ENUM
1, # ALIGNMENT_ENUM
0, # RED
0, # GREEN
0, # BLUE
255, # ALPHA
"fonts/coolfont.ttf" # FONT
]
end
</code></pre>
<p>
A <code>SIZE_ENUM</code> of <code>0</code> represents "default size". A <code>negative</code> value will decrease the label size. A <code>positive</code> value will increase the label's size.
</p>
<p>
An <code>ALIGNMENT_ENUM</code> of <code>0</code> represents "left aligned". <code>1</code> represents "center aligned". <code>2</code> represents "right aligned".
</p>
<h2 id='---rendering-a-label-as-a--hash-'>Rendering A Label As A <code>Hash</code></h2>
<p>
You can add additional metadata about your game within a label, which requires you to use a `Hash` instead.
</p>
<pre><code class="language-ruby">def tick args
args.outputs.labels << {
x: 200,
y: 550,
text: "dragonruby",
size_enum: 2,
alignment_enum: 1,
r: 155,
g: 50,
b: 50,
a: 255,
font: "fonts/manaspc.ttf",
vertical_alignment_enum: 0, # 0 is bottom, 1 is middle, 2 is top
# You can add any properties you like (this will be ignored/won't cause errors)
game_data_one: "Something",
game_data_two: {
value_1: "value",
value_2: "value two",
a_number: 15
}
}
end
</code></pre>
<h2 id='---getting-the-size-of-a-piece-of-text'>Getting The Size Of A Piece Of Text</h2>
<p>
You can get the render size of any string using <code>args.gtk.calcstringbox</code>.
</p>
<pre><code class="language-ruby">def tick args
# TEXT SIZE_ENUM FONT
w, h = args.gtk.calcstringbox("some string", 0, "font.ttf")
# NOTE: The SIZE_ENUM and FONT are optional arguments.
# Render a label showing the w and h of the text:
args.outputs.labels << [
10,
710,
# This string uses Ruby's string interpolation literal: #{}
"'some string' has width: #{w}, and height: #{h}."
]
end
</code></pre>
<h2 id='---rendering-labels-with-new-line-characters-and-wrapping'>Rendering Labels With New Line Characters And Wrapping</h2>
<p>
You can use a strategy like the following to create multiple labels from a String.
</p>
<pre><code class="language-ruby">def tick args
long_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elitteger dolor velit, ultricies vitae libero vel, aliquam imperdiet enim."
max_character_length = 30
long_strings_split = args.string.wrapped_lines long_string, max_character_length
args.outputs.labels << long_strings_split.map_with_index do |s, i|
{ x: 10, y: 600 - (i * 20), text: s }
end
end
</code></pre>
<h2 id='---how-to-play-a-sound'>How To Play A Sound</h2>
<p>
Sounds that end <code>.wav</code> will play once:
</p>
<pre><code class="language-ruby">def tick args
# Play a sound every second
if (args.state.tick_count % 60) == 0
args.outputs.sounds << 'something.wav'
end
end
</code></pre>
<p>
Sounds that end <code>.ogg</code> is considered background music and will loop:
</p>
<pre><code class="language-ruby">def tick args
# Start a sound loop at the beginning of the game
if args.state.tick_count == 0
args.outputs.sounds << 'background_music.ogg'
end
end
</code></pre>
<p>
If you want to play a <code>.ogg</code> once as if it were a sound effect, you can do:
</p>
<pre><code class="language-ruby">def tick args
# Play a sound every second
if (args.state.tick_count % 60) == 0
args.gtk.queue_sound 'some-ogg.ogg'
end
end
</code></pre>
<h2 id='---using--args-state--to-store-your-game-state'>Using <code>args.state</code> To Store Your Game State</h2>
<p>
<code>args.state</code> is a open data structure that allows you to define properties that are arbitrarily nested. You don't need to define any kind of <code>class</code>.
</p>
<p>
To initialize your game state, use the <code>||=</code> operator. Any value on the right side of <code>||=</code> will only be assigned _once_.
</p>
<p>
To assign a value every frame, just use the <code>=</code> operator, but _make sure_ you've initialized a default value.
</p>
<pre><code class="language-ruby">def tick args
# initialize your game state ONCE
args.state.player.x ||= 0
args.state.player.y ||= 0
args.state.player.hp ||= 100
# increment the x position of the character by one every frame
args.state.player.x += 1
# Render a sprite with a label above the sprite
args.outputs.sprites << [
args.state.player.x,
args.state.player.y,
32, 32,
"player.png"
]
args.outputs.labels << [
args.state.player.x,
args.state.player.y - 50,
args.state.player.hp
]
end
</code></pre>
<h2 id='---troubleshoot-performance'>Troubleshoot Performance</h2>
<ol>
<li> If you're using <code>Array</code>s for your primitives (<code>args.outputs.sprites << []</code>), use <code>Hash</code> instead (<code>args.outputs.sprites << { x: ... }</code>).</li>
<li> If you're using <code>Entity</code> for your primitives (<code>args.outputs.sprites << args.state.new_entity</code>), use <code>StrictEntity</code> instead (<code>args.outputs.sprites << args.state.new_entity_strict</code>).</li>
<li> Use <code>.each</code> instead of <code>.map</code> if you don't care about the return value.</li>
<li> When concatenating primitives to outputs, do them in bulk. Instead of:</li>
</ol>
<pre><code class="language-ruby">args.state.bullets.each do |bullet|
args.outputs.sprites << bullet.sprite
end
</code></pre>
<p>
do
</p>
<pre><code class="language-ruby">args.outputs.sprites << args.state.bullets.map do |b|
b.sprite
end
</code></pre>
<p>
5. Use <code>args.outputs.static_</code> variant for things that don't change often (take a look at the Basic Gorillas sample app and Dueling Starships sample app to see how <code>static_</code> is leveraged.
</p>
<p>
6. Consider using a <code>render_target</code> if you're doing some form of a camera that moves a lot of primitives (take a look at the Render Target sample apps for more info).
</p>
<h1 id='--docs---gtk--runtime-'>DOCS: <code>GTK::Runtime</code></h1>
<p>
The GTK::Runtime class is the core of DragonRuby. It is globally accessible via <code>$gtk</code>.
</p>
<h1 id='--summary---def-tick-args;-end;-'>SUMMARY: <code>def tick args; end;</code></h1>
<p>
Most everything you will need to build your game is in the <code>args</code> parameter that is provided to your <code>tick</code> method. Follows is a high level summary of each function that is available from <code>args</code>.
</p>
<p>
All the properties below hang off of <code>args</code> and can be accessed in the <code>tick</code> method:
</p>
<pre><code class="language-ruby">def tick args
args.PROPERTY
end
</code></pre>
<h2 id='----args-state-'><code>args.state</code></h2>
<p>
Store your game state inside of this <code>state</code>. Properties with arbitrary nesting is allowed and a backing Entity will be created on your behalf.
</p>
<pre><code class="language-ruby">def tick args
args.state.player.x ||= 0
args.state.player.y ||= 0
end
</code></pre>
<h3 id='--------entity_id-'><code>.*.entity_id</code></h3>
<p>
Entities automatically receive an <code>entity_id</code> of type <code>Fixnum</code>.
</p>
<h3 id='--------entity_type-'><code>.*.entity_type</code></h3>
<p>
Entities can have an <code>entity_type</code> which is represented as a <code>Symbol</code>.
</p>
<h3 id='--------created_at-'><code>.*.created_at</code></h3>
<p>
Entities have <code>created_at</code> set to <code>args.state.tick_count</code> when they are created.
</p>
<h3 id='--------created_at_elapsed-'><code>.*.created_at_elapsed</code></h3>
<p>
Returns the elapsed number of ticks since creation.
</p>
<h3 id='--------global_created_at-'><code>.*.global_created_at</code></h3>
<p>
Entities have <code>global_created_at</code> set to <code>Kernel.global_tick_count</code> when they are created.
</p>
<h3 id='--------global_created_at_elapsed-'><code>.*.global_created_at_elapsed</code></h3>
<p>
Returns the elapsed number of global ticks since creation.
</p>
<h3 id='--------as_hash-'><code>.*.as_hash</code></h3>
<p>
Entity cast to a <code>Hash</code> so you can update values as if you were updating a <code>Hash</code>.
</p>
<h3 id='------new_entity-'><code>.new_entity</code></h3>
<p>
Creates a new Entity with a <code>type</code>, and initial properties. An option block can be passed to change the newly created entity:
</p>
<pre><code class="language-ruby">def tick args
args.state.player ||= args.state.new_entity :player, x: 0, y: 0 do |e|
e.max_hp = 100
e.hp = e.max_hp * rand
end
end
</code></pre>
<h3 id='------new_entity_strict-'><code>.new_entity_strict</code></h3>
<p>
Creates a new Strict Entity. While Entities created via <code>args.state.new_entity</code> can have new properties added later on, Entities created using <code>args.state.new_entity</code> must define all properties that are allowed during its initialization. Attempting to add new properties after initialization will result in an exception.
</p>
<h3 id='------tick_count-'><code>.tick_count</code></h3>
<p>
Returns the current tick of the game. <code>args.state.tick_count</code> is <code>0</code> when the game is first started or if the game is reset via <code>$gtk.reset</code>.
</p>
<h2 id='----args-inputs-'><code>args.inputs</code></h2>
<p>
Access using input using <code>args.inputs</code>.
</p>
<h3 id='------up-'><code>.up</code></h3>
<p>
Returns <code>true</code> if: the <code>up</code> arrow or <code>w</code> key is pressed or held on the <code>keyboard</code>; or if <code>up</code> is pressed or held on <code>controller_one</code>; or if the <code>left_analog</code> on <code>controller_one</code> is tilted upwards.
</p>
<h3 id='------down-'><code>.down</code></h3>
<p>
Returns <code>true</code> if: the <code>down</code> arrow or <code>s</code> key is pressed or held on the <code>keyboard</code>; or if <code>down</code> is pressed or held on <code>controller_one</code>; or if the <code>left_analog</code> on <code>controller_one</code> is tilted downwards.
</p>
<h3 id='------left-'><code>.left</code></h3>
<p>
Returns <code>true</code> if: the <code>left</code> arrow or <code>a</code> key is pressed or held on the <code>keyboard</code>; or if <code>left</code> is pressed or held on <code>controller_one</code>; or if the <code>left_analog</code> on <code>controller_one</code> is tilted to the left.
</p>
<h3 id='------right-'><code>.right</code></h3>
<p>
Returns <code>true</code> if: the <code>right</code> arrow or <code>d</code> key is pressed or held on the <code>keyboard</code>; or if <code>right</code> is pressed or held on <code>controller_one</code>; or if the <code>left_analog</code> on <code>controller_one</code> is tilted to the right.
</p>
<h3 id='------left_right-'><code>.left_right</code></h3>
<p>
Returns <code>-1</code> (left), <code>0</code> (neutral), or <code>+1</code> (right) depending on results of <code>args.inputs.left</code> and <code>args.inputs.right</code>.
</p>
<h3 id='------up_down-'><code>.up_down</code></h3>
<p>
Returns <code>-1</code> (down), <code>0</code> (neutral), or <code>+1</code> (up) depending on results of <code>args.inputs.down</code> and <code>args.inputs.up</code>.
</p>
<h3 id='------text--or---history-'><code>.text</code> OR <code>.history</code></h3>
<p>
Returns a string that represents the last key that was pressed on the keyboard.
</p>
<h3 id='------mouse-'><code>.mouse</code></h3>
<p>
Represents the user's
</p>
<h4><code>.x</code></h4>
<p>
Returns the current <code>x</code> location of the mouse.
</p>
<h4><code>mouse.y</code></h4>
<p>
Return.
</p>
<h4><code>.inside_rect? rect</code></h4>
<p>
Return. <code>args.inputs.mouse.inside_rect?</code> takes in any primitive that responds to <code>x, y, w, h</code>:
</p>
<h4><code>.inside_circle? center_point, radius</code></h4>
<p>
Returns <code>true</code> if the mouse is inside of a specified circle. <code>args.inputs.mouse.inside_circle?</code> takes in any primitive that responds to <code>x, y</code> (which represents the circle's center), and takes in a <code>radius</code>:
</p>
<h4><code>.moved</code></h4>
<p>
Returns <code>true</code> if the mouse has moved on the current frame.
</p>
<h4><code>.button_left</code></h4>
<p>
Returns <code>true</code> if the left mouse button is down.
</p>
<h4><code>.button_middle</code></h4>
<p>
Returns <code>true</code> if the middle mouse button is down.
</p>
<h4><code>.button_right</code></h4>
<p>
Returns <code>true</code> if the right mouse button is down.
</p>
<h4><code>.button_bits</code></h4>
<p>
Returns a bitmask for all buttons on the mouse: <code>1</code> for a button in the <code>down</code> state, <code>0</code> for a button in the <code>up</code> state.
</p>
<h4><code>mouse.wheel</code></h4>
<p>
Represents the mouse wheel. Returns <code>nil</code> if no mouse wheel actions occurred.
</p>
<p>
***** <code>.x</code>
</p>
<p>
Returns the negative or positive number if the mouse wheel has changed in the <code>x</code> axis.
</p>
<p>
***** <code>.y</code>
</p>
<p>
Returns the negative or positive number if the mouse wheel has changed in the <code>y</code> axis.
</p>
<h4><code>.click</code> OR <code>.down</code>, <code>.previous_click</code>, <code>.up</code></h4>
<p>
The properties <code>args.inputs.mouse.(click|down|previous_click|up)</code> each return <code>nil</code> if the mouse button event didn't occur. And return an Entity that has an <code>x</code>, <code>y</code> properties along with helper functions to determine collision: <code>inside_rect?</code>, <code>inside_circle</code>.
</p>
<h3 id='------controller_one-----controller_two-'><code>.controller_one</code>, <code>.controller_two</code></h3>
<p>
Represents controllers connected to the usb ports.
</p>
<h4><code>.up</code></h4>
<p>
Returns <code>true</code> if <code>up</code> is pressed or held on the directional or left analog.
</p>
<h4><code>.down</code></h4>
<p>
Returns <code>true</code> if <code>down</code> is pressed or held on the directional or left analog.
</p>
<h4><code>.left</code></h4>
<p>
Returns <code>true</code> if <code>left</code> is pressed or held on the directional or left analog.
</p>
<h4><code>.right</code></h4>
<p>
Returns <code>true</code> if <code>right</code> is pressed or held on the directional or left analog.
</p>
<h4><code>.left_right</code></h4>
<p>
Returns <code>-1</code> (left), <code>0</code> (neutral), or <code>+1</code> (right) depending on results of <code>args.inputs.controller_(one|two).left</code> and <code>args.inputs.controller_(one|two).right</code>.
</p>
<h4><code>.up_down</code></h4>
<p>
Returns <code>-1</code> (down), <code>0</code> (neutral), or <code>+1</code> (up) depending on results of <code>args.inputs.controller_(one|two).up</code> and <code>args.inputs.controller_(one|two).down</code>.
</p>
<h4><code>.(left_analog_x_raw|right_analog_x_raw)</code></h4>
<p>
Returns the raw integer value for the analog's horizontal movement (<code>-32,000 to +32,000</code>).
</p>
<h4><code>.left_analog_y_raw|right_analog_y_raw)</code></h4>
<p>
Returns the raw integer value for the analog's vertical movement (<code>-32,000 to +32,000</code>).
</p>
<h4><code>.left_analog_x_perc|right_analog_x_perc)</code></h4>
<p>
Returns a number between <code>-1</code> and <code>1</code> which represents the percentage the analog is moved horizontally as a ratio of the maximum horizontal movement.
</p>
<h4><code>.left_analog_y_perc|right_analog_y_perc)</code></h4>
<p>
Returns a number between <code>-1</code> and <code>1</code> which represents the percentage the analog is moved vertically as a ratio of the maximum vertical movement.
</p>
<h4><code>.directional_up</code></h4>
<p>
Returns <code>true</code> if <code>up</code> is pressed or held on the directional.
</p>
<h4><code>.directional_down</code></h4>
<p>
Returns <code>true</code> if <code>down</code> is pressed or held on the directional.
</p>
<h4><code>.directional_left</code></h4>
<p>
Returns <code>true</code> if <code>left</code> is pressed or held on the directional.
</p>
<h4><code>.directional_right</code></h4>
<p>
Returns <code>true</code> if <code>right</code> is pressed or held on the directional.
</p>
<h4><code>.(a|b|x|y|l1|r1|l2|r2|l3|r3|start|select)</code></h4>
<p>
Returns <code>true</code> if the specific button is pressed or held.
</p>
<h4><code>.truthy_keys</code></h4>
<p>
Returns a collection of <code>Symbol</code>s that represent all keys that are in the pressed or held state.
</p>
<h4><code>.key_down</code></h4>
<p>
Returns <code>true</code> if the specific button was pressed on this frame. <code>args.inputs.controller_(one|two).key_down.BUTTON</code> will only be true on the frame it was pressed.
</p>
<h4><code>.key_held</code></h4>
<p>
Returns <code>true</code> if the specific button is being held. <code>args.inputs.controller_(one|two).key_held.BUTTON</code> will be true for all frames after <code>key_down</code> (until released).
</p>
<h4><code>.key_up</code></h4>
<p>
Returns <code>true</code> if the specific button was released. <code>args.inputs.controller_(one|two).key_up.BUTTON</code> will be true only on the frame the button was released.
</p>
<h3 id='------keyboard-'><code>.keyboard</code></h3>
<p>
Represents the user's keyboard
</p>
<h4><code>.up</code></h4>
<p>
Returns <code>true</code> if <code>up</code> or <code>w</code> is pressed or held on the keyboard.
</p>
<h4><code>.down</code></h4>
<p>
Returns <code>true</code> if <code>down</code> or <code>s</code> is pressed or held on the keyboard.
</p>
<h4><code>.left</code></h4>
<p>
Returns <code>true</code> if <code>left</code> or <code>a</code> is pressed or held on the keyboard.
</p>
<h4><code>.right</code></h4>
<p>
Returns <code>true</code> if <code>right</code> or <code>d</code> is pressed or held on the keyboard.
</p>
<h4><code>.left_right</code></h4>
<p>
Returns <code>-1</code> (left), <code>0</code> (neutral), or <code>+1</code> (right) depending on results of <code>args.inputs.keyboard.left</code> and <code>args.inputs.keyboard.right</code>.
</p>
<h4><code>.up_down</code></h4>
<p>
Returns <code>-1</code> (left), <code>0</code> (neutral), or <code>+1</code> (right) depending on results of <code>args.inputs.keyboard.up</code> and <code>args.inputs.keyboard.up</code>.
</p>
<h4>keyboard properties</h4>
<p>
The following properties represent keys on the keyboard and are available on <code>args.inputs.keyboard.KEY</code>, <code>args.inputs.keyboard.key_down.KEY</code>, <code>args.inputs.keyboard.key_held.KEY</code>, and <code>args.inputs.keyboard.key_up.KEY</code>:
</p>
<ul>
<li><code>alt</code></li>
<li><code>meta</code></li>
<li><code>control</code></li>
<li><code>shift</code></li>
<li><code>ctrl_KEY</code> (dynamic method, eg <code>args.inputs.keyboard.ctrl_a</code>)</li>
<li><code>exclamation_point</code></li>
<li><code>zero</code></li>
<li><code>one</code></li>
<li><code>two</code></li>
<li><code>three</code></li>
<li><code>four</code></li>
<li><code>five</code></li>
<li><code>six</code></li>
<li><code>seven</code></li>
<li><code>eight</code></li>
<li><code>nine</code></li>
<li><code>backspace</code></li>
<li><code>delete</code></li>
<li><code>escape</code></li>
<li><code>enter</code></li>
<li><code>tab</code></li>
<li><code>open_round_brace</code></li>
<li><code>close_round_brace</code></li>
<li><code>open_curly_brace</code></li>
<li><code>close_curly_brace</code></li>
<li><code>open_square_brace</code></li>
<li><code>close_square_brace</code></li>
<li><code>colon</code></li>
<li><code>semicolon</code></li>
<li><code>equal_sign</code></li>
<li><code>hyphen</code></li>
<li><code>space</code></li>
<li><code>dollar_sign</code></li>
<li><code>double_quotation_mark</code></li>
<li><code>single_quotation_mark</code></li>
<li><code>backtick</code></li>
<li><code>tilde</code></li>
<li><code>period</code></li>
<li><code>comma</code></li>
<li><code>pipe</code></li>
<li><code>underscore</code></li>
<li><code>a</code></li>
<li><code>b</code></li>
<li><code>c</code></li>
<li><code>d</code></li>
<li><code>e</code></li>
<li><code>f</code></li>
<li><code>g</code></li>
<li><code>h</code></li>
<li><code>i</code></li>
<li><code>j</code></li>
<li><code>k</code></li>
<li><code>l</code></li>
<li><code>m</code></li>
<li><code>n</code></li>
<li><code>o</code></li>
<li><code>p</code></li>
<li><code>q</code></li>
<li><code>r</code></li>
<li><code>s</code></li>
<li><code>t</code></li>
<li><code>u</code></li>
<li><code>v</code></li>
<li><code>w</code></li>
<li><code>x</code></li>
<li><code>y</code></li>
<li><code>z</code></li>
<li><code>shift</code></li>
<li><code>control</code></li>
<li><code>alt</code></li>
<li><code>meta</code></li>
<li><code>left</code></li>
<li><code>right</code></li>
<li><code>up</code></li>
<li><code>down</code></li>
<li><code>pageup</code></li>
<li><code>pagedown</code></li>
<li><code>char</code></li>
<li><code>plus</code></li>
<li><code>at</code></li>
<li><code>forward_slash</code></li>
<li><code>back_slash</code></li>
<li><code>asterisk</code></li>
<li><code>less_than</code></li>
<li><code>greater_than</code></li>
<li><code>carat</code></li>
<li><code>ampersand</code></li>
<li><code>superscript_two</code></li>
<li><code>circumflex</code></li>
<li><code>question_mark</code></li>
<li><code>section_sign</code></li>
<li><code>ordinal_indicator</code></li>
<li><code>raw_key</code></li>
<li><code>raw_key</code></li>
<li><code>left_right</code></li>
<li><code>up_down</code></li>
<li><code>directional_vector</code></li>
<li><code>truthy_keys</code></li>
</ul>
<h4><code>inputs.keyboard.keys</code></h4>
<p>
Returns a <code>Hash</code> with all keys on the keyboard in their respective state. The <code>Hash</code> contains the following <code>keys</code>
</p>
<ul>
<li><code>:down</code></li>
<li><code>:held</code></li>
<li><code>:down_or_held</code></li>
<li><code>:up</code></li>
</ul>
<h2 id='----args-outputs-'><code>args.outputs</code></h2>
<p>
<code>args.outputs.PROPERTY</code> is how you render to the screen.
</p>
<h3 id='------background_color-'><code>.background_color</code></h3>
<p>
Set <code>args.outputs.background_color</code> to an <code>Array</code> with <code>RGB</code> values (eg. <code>[255, 255, 255]</code> for the color white).
</p>
<h3 id='------sounds-'><code>.sounds</code></h3>
<p>
Send a file path to this collection to play a sound. The sound file must be under the <code>mygame</code> directory. Example: <code>args.outputs.sounds << "sounds/jump.wav"</code>.
</p>
<h3 id='------solids-'><code>.solids</code></h3>
<p>
Send a Primitive to this collection to render a filled in rectangle to the screen. This collection is cleared at the end of every frame.
</p>
<h3 id='------static_solids-'><code>.static_solids</code></h3>
<p>
Send a Primitive to this collection to render a filled in rectangle to the screen. This collection is not cleared at the end of every frame. And objects can be mutated by reference.
</p>
<h3 id='------sprites-----static_sprites-'><code>.sprites</code>, <code>.static_sprites</code></h3>
<p>
Send a Primitive to this collection to render a sprite to the screen.
</p>
<h3 id='------primitives-----static_primitives-'><code>.primitives</code>, <code>.static_primitives</code></h3>
<p>
Send a Primitive of any type and it'll be rendered. The Primitive must have a <code>primitive_marker</code> that returns <code>:solid</code>, <code>:sprite</code>, <code>:label</code>, <code>:line</code>, <code>:border</code>.
</p>
<h3 id='------labels-----static_labels-'><code>.labels</code>, <code>.static_labels</code></h3>
<p>
Send a Primitive to this collection to render text to the screen.
</p>
<h3 id='------lines-----static_lines-'><code>.lines</code>, <code>.static_lines</code></h3>
<p>
Send a Primitive to this collection to render a line to the screen.
</p>
<h3 id='------borders-----static_borders-'><code>.borders</code>, <code>.static_borders</code></h3>
<p>
Send a Primitive to this collection to render an unfilled rectangle to the screen.
</p>
<h3 id='------debug-----static_debug-'><code>.debug</code>, <code>.static_debug</code></h3>
<p>
Send any Primitive to this collection which represents things you render to the screen for debugging purposes. Primitives in this collection will not be rendered in a production release of your game.
</p>
<h2 id='----args-geometry-'><code>args.geometry</code></h2>
<p>
This property contains geometric functions. Functions can be invoked via <code>args.geometry.FUNCTION</code>.
</p>
<p>
Here are some general notes with regards to the arguments these geometric functions accept.
</p>
<ol>
<li> <code>Rectangles</code> can be represented as an <code>Array</code> with four (or more) values <code>[x, y, w, h]</code>, as a <code>Hash</code> <code>{ x:, y:, w:, h: }</code> or an object that responds to <code>x</code>, <code>y</code>, <code>w</code>, and <code>h</code>.</li>
<li> <code>Points</code> can be represent as an <code>Array</code> with two (or more) values <code>[x, y]</code>, as a <code>Hash</code> <code>{ x:, y:}</code> or an object that responds to <code>x</code>, and <code>y</code>.</li>
<li> <code>Lines</code> can be represented as an <code>Array</code> with four (or more) values <code>[x, y, x2, y2]</code>, as a <code>Hash</code> <code>{ x:, y:, x2:, y2: }</code> or an object that responds to <code>x</code>, <code>y</code>, <code>x2</code>, and <code>y2</code>.</li>
<li> <code>Angles</code> are represented as degrees (not radians).</li>
</ol>
<h3 id='------inside_rect--rect_1--rect_2-'><code>.inside_rect? rect_1, rect_2</code></h3>
<p>
Returns <code>true</code> if <code>rect_1</code> is inside <code>rect_2</code>.
</p>
<h3 id='------intersect_rect--rect_2--rect_2-'><code>.intersect_rect? rect_2, rect_2</code></h3>
<p>
Returns <code>true</code> if <code>rect_1</code> intersects <code>rect_2</code>.
</p>
<h3 id='------scale_rect-rect--x_percentage--y_percentage-'><code>.scale_rect rect, x_percentage, y_percentage</code></h3>
<p>
Returns a new rectangle that is scaled by the percentages provided.
</p>
<h3 id='------angle_to-start_point--end_point-'><code>.angle_to start_point, end_point</code></h3>
<p>
Returns the angle in degrees between two points <code>start_point</code> to <code>end_point</code>.
</p>
<h3 id='------angle_from-start_point--end_point-'><code>.angle_from start_point, end_point</code></h3>
<p>
Returns the angle in degrees between two points <code>start_point</code> from <code>end_point</code>.
</p>
<h3 id='------point_inside_circle--point--circle_center_point--radius-'><code>.point_inside_circle? point, circle_center_point, radius</code></h3>
<p>
Returns <code>true</code> if a point is inside a circle defined by its center and radius.
</p>
<h3 id='------center_inside_rect-rect--other_rect-'><code>.center_inside_rect rect, other_rect</code></h3>
<p>
Returns a new rectangle based of off <code>rect</code> that is centered inside of <code>other_rect</code>.
</p>
<h3 id='------center_inside_rect_x-rect--other_rect-'><code>.center_inside_rect_x rect, other_rect</code></h3>
<p>
Returns a new rectangle based of off <code>rect</code> that is centered horizontally inside of <code>other_rect</code>.
</p>
<h3 id='------center_inside_rect_y-rect--other_rect-'><code>.center_inside_rect_y rect, other_rect</code></h3>
<p>
Returns a new rectangle based of off <code>rect</code> that is centered vertically inside of <code>other_rect</code>.
</p>
<h3 id='------anchor_rect-rect--anchor_x--anchor_y-'><code>.anchor_rect rect, anchor_x, anchor_y</code></h3>
<p>
Returns a new rectangle based of off <code>rect</code> that has been repositioned based on the percentages passed into anchor_x, and anchor_y.
</p>
<h3 id='------shift_line-line--x--y-'><code>.shift_line line, x, y</code></h3>
<p>
Returns a line that is offset by <code>x</code>, and <code>y</code>.
</p>
<h3 id='------line_y_intercept-line-'><code>.line_y_intercept line</code></h3>
<p>
Given a line, the <code>b</code> value is determined for the point slope form equation: <code>y = mx + b</code>.
</p>
<h3 id='------angle_between_lines-line_one--line_two--replace_infinity--'><code>.angle_between_lines line_one, line_two, replace_infinity:</code></h3>
<p>
Returns the angle between two lines as if they were infinitely long. A numeric value can be passed in for the last parameter which would represent lines that do not intersect.
</p>
<h3 id='------line_slope-line--replace_infinity--'><code>.line_slope line, replace_infinity:</code></h3>
<p>
Given a line, the <code>m</code> value is determined for the point slope form equation: <code>y = mx + b</code>.
</p>
<h3 id='------line_rise_run-'><code>.line_rise_run</code></h3>
<p>
Given a line, a <code>Hash</code> is returned that returns the slope as <code>x</code> and <code>y</code> properties with normalized values (the number is between -1 and 1).
</p>
<h3 id='------ray_test-point--line-'><code>.ray_test point, line</code></h3>
<p>
Given a point and a line, <code>:on</code>, <code>:left</code>, or <code>:right</code> which represents the location of the point relative to the line.
</p>
<h3 id='------line_rect-line-'><code>.line_rect line</code></h3>
<p>
Returns the bounding rectangle for a line.
</p>
<h3 id='------line_intersect-line_one--line_two-'><code>.line_intersect line_one, line_two</code></h3>
<p>
Returns a point that represents the intersection of the lines.
</p>
<h3 id='------distance-point_one--point_two-'><code>.distance point_one, point_two</code></h3>
<p>
Returns the distance between two points.
</p>
<h3 id='------cubic_bezier-t--a--b--c--d-'><code>.cubic_bezier t, a, b, c, d</code></h3>
<p>
Returns the cubic bezier function for tick_count <code>t</code> with anchors <code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code>.
</p>
<h2 id='----args-easing-'><code>args.easing</code></h2>
<p>
A set of functions that allow you to determine the current progression of an easing function.
</p>
<h3 id='------ease-start_tick--current_tick--duration--easing_functions-'><code>.ease start_tick, current_tick, duration, easing_functions</code></h3>
<p>
Given a start, current, duration, and easing function names, <code>ease</code> returns a number between 0 and 1 that represents the progress of an easing function.
</p>
<p>
The built in easing definitions you have access to are <code>:identity</code>, <code>:flip</code>, <code>:quad</code>, <code>:cube</code>, <code>:quart</code>, and <code>:quint</code>.
</p>
<p>
This example will move a box at a linear speed from 0 to 1280.
</p>
<pre><code class="language-ruby">def tick args
start_time = 10
duration = 60
current_progress = args.easing.ease start_time,
args.state.tick_count,
duration,
:identity
args.outputs.solids << { x: 1280 * current_progress, y: 360, w: 10, h: 10 }
end
</code></pre>
<h3 id='------ease_spline-start_tick--current_tick--duration--spline-'><code>.ease_spline start_tick, current_tick, duration, spline</code></h3>
<p>
Given a start, current, duration, and a multiple bezier values, this function returns a number between 0 and 1 that represents the progress of an easing function.
</p>
<p>
This example will move a box at a linear speed from 0 to 1280 and then back to 0 using two bezier definitions (represented as an array with four values).
</p>
<pre><code class="language-ruby">def tick args
start_time = 10
duration = 60
spline = [
[ 0, 0.25, 0.75, 1.0],
[1.0, 0.75, 0.25, 0]
]
current_progress = args.easing.ease_spline start_time,
args.state.tick_count,
duration,
spline
args.outputs.solids << { x: 1280 * current_progress, y: 360, w: 10, h: 10 }
end
</code></pre>
<h2 id='----args-string-'><code>args.string</code></h2>
<p>
Useful string functions not included in Ruby core libraries.
</p>
<h3 id='------wrapped_lines-string--max_character_length-'><code>.wrapped_lines string, max_character_length</code></h3>
<p>
This function will return a collection of strings given an input <code>string</code> and <code>max_character_length</code>. The collection of strings returned will split the input string into strings of <code>length <= max_character_length</code>.
</p>
<p>
The following example takes a string with new lines and creates a label for each one. Labels (<code>args.outputs.labels</code>) ignore newline characters <code>\n</code>.
</p>
<pre><code class="language-ruby">def tick args
long_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.
teger dolor velit, ultricies vitae libero vel, aliquam imperdiet enim."
max_character_length = 30
long_strings_split = args.string.wrapped_lines long_string, max_character_length
args.outputs.labels << long_strings_split.map_with_index do |s, i|
{ x: 10, y: 600 - (i * 20), text: s }
end
end
</code></pre>
<h2 id='----args-grid-'><code>args.grid</code></h2>
<p>
Returns the virtual grid for the game.
</p>
<h3 id='------name-'><code>.name</code></h3>
<p>
Returns either <code>:origin_bottom_left</code> or <code>:origin_center</code>.
</p>
<h3 id='------bottom-'><code>.bottom</code></h3>
<p>
Returns the <code>y</code> value that represents the bottom of the grid.
</p>
<h3 id='------top-'><code>.top</code></h3>
<p>
Returns the <code>y</code> value that represents the top of the grid.
</p>
<h3 id='------left-'><code>.left</code></h3>
<p>
Returns the <code>x</code> value that represents the left of the grid.
</p>
<h3 id='------right-'><code>.right</code></h3>
<p>
Returns the <code>x</code> value that represents the right of the grid.
</p>
<h3 id='------rect-'><code>.rect</code></h3>
<p>
Returns a rectangle Primitive that represents the grid.
</p>
<h3 id='------origin_bottom_left!-'><code>.origin_bottom_left!</code></h3>
<p>
Change the grids coordinate system to 0, 0 at the bottom left corner.
</p>
<h3 id='------origin_center!-'><code>.origin_center!</code></h3>
<p>
Change the grids coordinate system to 0, 0 at the center of the screen.
</p>
<h3 id='------w-'><code>.w</code></h3>
<p>
Returns the grid's width (always 1280).
</p>
<h3 id='------h-'><code>.h</code></h3>
<p>
Returns the grid's height (always 720).
</p>
<h2 id='----args-gtk-'><code>args.gtk</code></h2>
<p>
This represents the DragonRuby Game Toolkit's Runtime Environment and can be accessed via <code>args.gtk.METHOD</code>.
</p>
<h3 id='------argv-'><code>.argv</code></h3>
<p>
Returns a <code>String</code> that represents the parameters passed into the <code>./dragonruby</code> binary.
</p>
<h3 id='------platform-'><code>.platform</code></h3>
<p>
Returns a <code>String</code> representing the operating system the game is running on.
</p>
<h3 id='------request_quit-'><code>.request_quit</code></h3>
<p>
Request that the runtime quit the game.
</p>
<h3 id='------write_file-path--contents-'><code>.write_file path, contents</code></h3>
<p>
Writes/overwrites a file within the game directory + path.
</p>
<h3 id='------write_file_root-'><code>.write_file_root</code></h3>
<p>
Writes/overwrites a file within the root dragonruby binary directory + path.
</p>
<h3 id='------append_file-path--contents-'><code>.append_file path, contents</code></h3>
<p>
Append content to a file located at the game directory + path.
</p>
<h3 id='------append_file_root-path--contents-'><code>.append_file_root path, contents</code></h3>
<p>
Append content to a file located at the root dragonruby binary directory + path.
</p>
<h3 id='------read_file-path-'><code>.read_file path</code></h3>
<p>
Reads a file from the sandboxed file system.
</p>
<h3 id='------parse_xml-string--parse_xml_file-path-'><code>.parse_xml string, parse_xml_file path</code></h3>
<p>
Returns a <code>Hash</code> for a <code>String</code> that represents XML.
</p>
<h3 id='------parse_json-string--parse_json_file-path-'><code>.parse_json string, parse_json_file path</code></h3>
<p>
Returns a <code>Hash</code> for a <code>String</code> that represents JSON.
</p>
<h3 id='------http_get-url--extra_headers-=-{}-'><code>.http_get url, extra_headers = {}</code></h3>
<p>
Creates an async task to perform an HTTP GET.
</p>
<h3 id='------http_post-url--form_fields-=-{}--extra_headers-=-{}-'><code>.http_post url, form_fields = {}, extra_headers = {}</code></h3>
<p>
Creates an async task to perform an HTTP POST.
</p>
<h3 id='------reset-'><code>.reset</code></h3>
<p>
Resets the game by deleting all data in <code>args.state</code> and setting <code>args.state.tick_count</code> back to <code>0</code>.
</p>
<h3 id='------stop_music-'><code>.stop_music</code></h3>
<p>
Stops all background music.
</p>
<h3 id='------calcstringbox-str--size_enum--font-'><code>.calcstringbox str, size_enum, font</code></h3>
<p>
Returns a tuple with width and height of a string being rendered.
</p>
<h3 id='------slowmo!-factor-'><code>.slowmo! factor</code></h3>
<p>
Slows the game down by the factor provided.
</p>
<h3 id='------notify!-string-'><code>.notify! string</code></h3>
<p>
Renders a toast message at the bottom of the screen.
</p>
<h3 id='------system-'><code>.system</code></h3>
<p>
Invokes a shell command and prints the result to the console.
</p>
<h3 id='------exec-'><code>.exec</code></h3>
<p>
Invokes a shell command and returns a <code>String</code> that represents the result.
</p>
<h3 id='------save_state-'><code>.save_state</code></h3>
<p>
Saves the game state to <code>game_state.txt</code>.
</p>
<h3 id='------load_state-'><code>.load_state</code></h3>
<p>
Load <code>args.state</code> from <code>game_state.txt</code>.
</p>
<h3 id='------serialize_state-file--state-'><code>.serialize_state file, state</code></h3>
<p>
Saves entity state to a file. If only one parameter is provided a string is returned for state instead of writing to a file.
</p>
<h3 id='------deserialize_state-file-'><code>.deserialize_state file</code></h3>
<p>
Returns entity state from a file or serialization data represented as a <code>String</code>.
</p>
<h3 id='------reset_sprite-path-'><code>.reset_sprite path</code></h3>
<p>
Invalids the texture cache of a sprite.
</p>
<h3 id='------show_cursor-'><code>.show_cursor</code></h3>
<p>
Shows the mouse cursor.
</p>
<h3 id='------hide_cursor-'><code>.hide_cursor</code></h3>
<p>
Hides the mouse cursor.
</p>
<h3 id='------cursor_shown--'><code>.cursor_shown?</code></h3>
<p>
Returns <code>true</code> if the mouse cursor is shown.
</p>
<h3 id='------set_window_fullscreen-enabled-'><code>.set_window_fullscreen enabled</code></h3>
<p>
Sets the game to either fullscreen (<code>enabled=true</code>) or windowed (<code>enabled=false)</code>.
</p>
<h3 id='------openurl-url-'><code>.openurl url</code></h3>
<p>
Opens a url using the Operating System's default browser.
</p>
<h3 id='------get_base_dir-'><code>.get_base_dir</code></h3>
<p>
Returns the full path of the DragonRuby binary directory.
</p>
<h3 id='------get_game_dir-'><code>.get_game_dir</code></h3>
<p>
Returns the full path of the game directory in its sandboxed environment.
</p>
<h1 id='--docs---gtk--runtime#reset-'>DOCS: <code>GTK::Runtime#reset</code></h1>
<p>
This function will reset Kernel.tick_count to 0 and will remove all data from args.state.
</p>
<h1 id='--docs---gtk--runtime#calcstringbox-'>DOCS: <code>GTK::Runtime#calcstringbox</code></h1>
<p>
This function returns the width and height of a string.
</p>
<pre><code class="language-ruby">def tick args
args.state.string_size ||= args.gtk.calcstringbox "Hello World"
args.state.string_size_font_size ||= args.gtk.calcstringbox "Hello World"
end
</code></pre>
<h1 id='--docs---gtk--runtime#write_file-'>DOCS: <code>GTK::Runtime#write_file</code></h1>
<p>
This function takes in two parameters. The first parameter is the file path and assumes the the game directory is the root. The second parameter is the string that will be written. The method overwrites whatever is currently in the file. Use <code>GTK::Runtime#append_file</code> to append to the file as opposed to overwriting.
</p>
<pre><code class="language-ruby">def tick args
if args.inputs.mouse.click
args.gtk.write_file "last-mouse-click.txt", "Mouse was clicked at #{args.state.tick_count}."
end
end
</code></pre>
<h1 id='--docs---array-'>DOCS: <code>Array</code></h1>
<p>
The Array class has been extend to provide methods that will help in common game development tasks. Array is one of the most powerful classes in Ruby and a very fundamental component of Game Toolkit.
</p>
<h1 id='--docs---array#map-'>DOCS: <code>Array#map</code></h1>
<p>
The function given a block returns a new <code>Enumerable</code> of values.
</p>
<p>
Example of using <code>Array#map</code> in conjunction with <code>args.state</code> and <code>args.outputs.sprites</code> to render sprites to the screen.
</p>
<pre><code class="language-ruby">def tick args
# define the colors of the rainbow in ~args.state~
# as an ~Array~ of ~Hash~es with :order and :name.
# :order will be used to determine render location
# and :name will be used to determine sprite path.
args.state.rainbow_colors ||= [
{ order: 0, name: :red },
{ order: 1, name: :orange },
{ order: 2, name: :yellow },
{ order: 3, name: :green },
{ order: 4, name: :blue },
{ order: 5, name: :indigo },
{ order: 6, name: :violet },
]
# render sprites diagonally to the screen
# with a width and height of 50.
args.outputs
.sprites << args.state
.rainbow_colors
.map do |color| # <-- ~Array#map~ usage
[
color[:order] * 50,
color[:order] * 50,
50,
50,
"sprites/square-#{color[:name]}.png"
]
end
end
</code></pre>
<h1 id='--docs---array#each-'>DOCS: <code>Array#each</code></h1>
<p>
The function, given a block, invokes the block for each item in the <code>Array</code>. <code>Array#each</code> is synonymous to foreach constructs in other languages.
</p>
<p>
Example of using <code>Array#each</code> in conjunction with <code>args.state</code> and <code>args.outputs.sprites</code> to render sprites to the screen:
</p>
<pre><code class="language-ruby">def tick args
# define the colors of the rainbow in ~args.state~
# as an ~Array~ of ~Hash~es with :order and :name.
# :order will be used to determine render location
# and :name will be used to determine sprite path.
args.state.rainbow_colors ||= [
{ order: 0, name: :red },
{ order: 1, name: :orange },
{ order: 2, name: :yellow },
{ order: 3, name: :green },
{ order: 4, name: :blue },
{ order: 5, name: :indigo },
{ order: 6, name: :violet },
]
# render sprites diagonally to the screen
# with a width and height of 50.
args.state
.rainbow_colors
.map do |color| # <-- ~Array#each~ usage
args.outputs.sprites << [
color[:order] * 50,
color[:order] * 50,
50,
50,
"sprites/square-#{color[:name]}.png"
]
end
end
</code></pre>
<h1 id='--docs---array#reject_nil-'>DOCS: <code>Array#reject_nil</code></h1>
<p>
Returns an <code>Enumerable</code> rejecting items that are <code>nil</code>, this is an alias for <code>Array#compact</code>:
</p>
<pre><code class="language-ruby">repl do
a = [1, nil, 4, false, :a]
puts a.reject_nil
# => [1, 4, false, :a]
puts a.compact
# => [1, 4, false, :a]
end
</code></pre>
<h1 id='--docs---array#reject_false-'>DOCS: <code>Array#reject_false</code></h1>
<p>
Returns an `Enumerable` rejecting items that are `nil` or `false`.
</p>
<pre><code class="language-ruby">repl do
a = [1, nil, 4, false, :a]
puts a.reject_false
# => [1, 4, :a]
end
</code></pre>
<h1 id='--docs---array#product-'>DOCS: <code>Array#product</code></h1>
<p>
Returns all combinations of values between two arrays.
</p>
<p>
Here are some examples of using <code>product</code>. Paste the following code at the bottom of main.rb and save the file to see the results:
</p>
<pre><code class="language-ruby">repl do
a = [0, 1]
puts a.product
# => [[0, 0], [0, 1], [1, 0], [1, 1]]
end
</code></pre>
<pre><code class="language-ruby">repl do
a = [ 0, 1]
b = [:a, :b]
puts a.product b
# => [[0, :a], [0, :b], [1, :a], [1, :b]]
end
</code></pre>
<h1 id='--docs---array#map_2d-'>DOCS: <code>Array#map_2d</code></h1>
<p>
Assuming the array is an array of arrays, Given a block, each 2D array index invoked against the block. A 2D array is a common way to store data/layout for a stage.
</p>
<pre><code class="language-ruby">repl do
stage = [
[:enemy, :empty, :player],
[:empty, :empty, :empty],
[:enemy, :empty, :enemy],
]
occupied_tiles = stage.map_2d do |row, col, tile|
if tile == :empty
nil
else
[row, col, tile]
end
end.reject_nil
puts "Stage:"
puts stage
puts "Occupied Tiles"
puts occupied_tiles
end
</code></pre>
<h1 id='--docs---array#include_any--'>DOCS: <code>Array#include_any?</code></h1>
<p>
Given a collection of items, the function will return <code>true</code> if any of <code>self</code>'s items exists in the collection of items passed in:
</p>
<h1 id='--docs---array#any_intersect_rect--'>DOCS: <code>Array#any_intersect_rect?</code></h1>
<p>
Assuming the array contains objects that respond to <code>left</code>, <code>right</code>, <code>top</code>, <code>bottom</code>, this method returns <code>true</code> if any of the elements within the array intersect the object being passed in. You are given an optional parameter called <code>tolerance</code> which informs how close to the other rectangles the elements need to be for it to be considered intersecting.
</p>
<p>
The default tolerance is set to <code>0.1</code>, which means that the primitives are not considered intersecting unless they are overlapping by more than <code>0.1</code>.
</p>
<pre><code class="language-ruby">repl do
# Here is a player class that has position and implement
# the ~attr_rect~ contract.
class Player
attr_rect
attr_accessor :x, :y, :w, :h
def initialize x, y, w, h
@x = x
@y = y
@w = w
@h = h
end
def serialize
{ x: @x, y: @y, w: @w, h: @h }
end
def inspect
"#{serialize}"
end
def to_s
"#{serialize}"
end
end
# Here is a definition of two walls.
walls = [
[10, 10, 10, 10],
{ x: 20, y: 20, w: 10, h: 10 },
]
# Display the walls.
puts "Walls."
puts walls
puts ""
# Check any_intersect_rect? on player
player = Player.new 30, 20, 10, 10
puts "Is Player #{player} touching wall?"
puts (walls.any_intersect_rect? player)
# => false
# The value is false because of the default tolerance is 0.1.
# The overlap of the player rect and any of the wall rects is
# less than 0.1 (for those that intersect).
puts ""
player = Player.new 9, 10, 10, 10
puts "Is Player #{player} touching wall?"
puts (walls.any_intersect_rect? player)
# => true
puts ""
end
</code></pre>
<h1 id='--docs---gtk--args#audio-'>DOCS: <code>GTK::Args#audio</code></h1>
<p>
Hash that contains audio sources that are playing. If you want to add a new sound add a hash with keys/values as in the following example:
</p>
<pre><code class="language-ruby">def tick args
# The values below (except for input of course) are the default values that apply if you don't
# specify the value in the hash.
args.audio[:my_audio] = {
input: 'sound/boom.wav', # Filename
x: 0.0, y: 0.0, z: 0.0, # Relative position to the listener, x, y, z from -1.0 to 1.0
gain: 1.0, # Volume (0.0 to 1.0)
pitch: 1.0, # Pitch of the sound (1.0 = original pitch)
paused: false, # Set to true to pause the sound at the current playback position
looping: false, # Set to true to loop the sound/music until you stop it
}
end
</code></pre>
<p>
Sounds that don't specify <code>looping: true</code> will be removed automatically from the hash after the playback ends. Looping sounds or sounds that should stop early must be removed manually.
</p>
<h2 id='---audio-synthesis-(pro-only)'>Audio synthesis (Pro only)</h2>
<p>
Instead of a path to an audio file you can specify an array <code>[channels, sample_rate, sound_source]</code> for <code>input</code> to procedurally generate sound. You do this by providing an array of float values between -1.0 and 1.0 that describe the waveform you want to play.
</p>
<ul>
<li><code>channels</code> is the number of channels: 1 = mono, 2 = stereo</li>
<li><code>sample_rate</code> is the number of values per seconds you will provide to describe the audio wave</li>
<li><code>sound_source</code> The source of your sound. See below</li>
</ul>
<h3 id='----sound-source'>Sound source</h3>
<p>
A sound source can be one of two things:
</p>
<ul>
<li>A <code>Proc</code> object that is called on demand to generate the next samples to play. Every call should generate
enough samples for at least 0.1 to 0.5 seconds to get continuous playback without audio skips. The audio will continue playing endlessly until removed, so the <code>looping</code> option will have no effect.</li>
<li>An array of sample values that will be played back once. This is useful for procedurally generated one-off SFX.
<code>looping</code> will work as expected</li>
</ul>
<p>
When you specify 2 for <code>channels</code>, then the generated sample array will be played back in an interleaved manner. The first element is the first sample for the left channel, the second element is the first sample for the right channel, the third element is the second sample for the left channel etc.
</p>
<h3 id='----example-'>Example:</h3>
<pre><code class="language-ruby">def tick args
sample_rate = 48000
generate_sine_wave = lambda do
frequency = 440.0 # A5
samples_per_period = (sample_rate / frequency).ceil
one_period = samples_per_period.map_with_index { |i|
Math.sin((2 * Math::PI) * (i / samples_per_period))
}
one_period * frequency # Generate 1 second worth of sound
end
args.audio[:my_audio] ||= {
input: [1, sample_rate, generate_sine_wave]
}
end
</code></pre>
<h1 id='--docs---gtk--outputs-'>DOCS: <code>GTK::Outputs</code></h1>
<p>
Outputs is how you render primitives to the screen. The minimal setup for rendering something to the screen is via a <code>tick</code> method defined in mygame/app/main.rb
</p>
<pre><code class="language-ruby">def tick args
# code goes here
end
</code></pre>
<h1 id='--docs---gtk--outputs#solids-'>DOCS: <code>GTK::Outputs#solids</code></h1>
<p>
Add primitives to this collection to render a solid to the screen.
</p>
<h2 id='---rendering-a-solid-using-an-array'>Rendering a solid using an Array</h2>
<p>
Creates a solid black rectangle located at 100, 100. 160 pixels wide and 90 pixels tall.
</p>
<pre><code class="language-ruby">def tick args
# X Y WIDTH HEIGHT
args.outputs.solids << [100, 100, 160, 90]
end
</code></pre>
<h2 id='---rendering-a-solid-using-an-array-with-colors-and-alpha'>Rendering a solid using an Array with colors and alpha</h2>
<p>
The value for the color and alpha is a number between <code>0</code> and <code>255</code>. The alpha property is optional and will be set to <code>255</code> if not specified.
</p>
<p>
Creates a green solid rectangle with an opacity of 50%.
</p>
<pre><code class="language-ruby">def tick args
# X Y WIDTH HEIGHT RED GREEN BLUE ALPHA
args.outputs.solids << [100, 100, 160, 90, 0, 255, 0, 128]
end
</code></pre>
<h2 id='---rendering-a-solid-using-a-hash'>Rendering a solid using a Hash</h2>
<p>
If you want a more readable invocation. You can use the following hash to create a solid. Any parameters that are not specified will be given a default value. The keys of the hash can be provided in any order.
</p>
<pre><code class="language-ruby">def tick args
args.outputs.solids << {
x: 0,
y: 0,
w: 100,
h: 100,
r: 0,
g: 255,
b: 0,
a: 255
}
end
</code></pre>
<h2 id='---rendering-a-solid-using-a-class'>Rendering a solid using a Class</h2>
<p>
You can also create a class with solid/border properties and render it as a primitive. ALL properties must be on the class. *Additionally*, a method called <code>primitive_marker</code> must be defined on the class.
</p>
<p>
Here is an example:
</p>
<pre><code class="language-ruby"># Create type with ALL solid properties AND primitive_marker
class Solid
attr_accessor :x, :y, :w, :h, :r, :g, :b, :a
def primitive_marker
:solid
end
end
# Inherit from type
class Square < Solid
# constructor
def initialize x, y, size
self.x = x
self.y = y
self.w = size
self.h = size
end
end
def tick args
# render solid/border
args.outputs.solids << Square.new(10, 10, 32)
end
</code></pre>
<h1 id='--docs---gtk--outputs#borders-'>DOCS: <code>GTK::Outputs#borders</code></h1>
<p>
Add primitives to this collection to render an unfilled solid to the screen. Take a look at the documentation for Outputs#solids.
</p>
<p>
The only difference between the two primitives is where they are added.
</p>
<p>
Instead of using <code>args.outputs.solids</code>:
</p>
<pre><code class="language-ruby">def tick args
# X Y WIDTH HEIGHT
args.outputs.solids << [100, 100, 160, 90]
end
</code></pre>
<p>
You have to use <code>args.outputs.borders</code>:
</p>
<pre><code class="language-ruby">def tick args
# X Y WIDTH HEIGHT
args.outputs.borders << [100, 100, 160, 90]
end
</code></pre>
<h1 id='--docs---gtk--outputs#sprites-'>DOCS: <code>GTK::Outputs#sprites</code></h1>
<p>
Add primitives to this collection to render a sprite to the screen.
</p>
<h2 id='---rendering-a-sprite-using-an-array'>Rendering a sprite using an Array</h2>
<p>
Creates a sprite of a white circle located at 100, 100. 160 pixels wide and 90 pixels tall.
</p>
<pre><code class="language-ruby">def tick args
# X Y WIDTH HEIGHT PATH
args.outputs.sprites << [100, 100, 160, 90, "sprites/circle/white.png]
end
</code></pre>
<h2 id='---rendering-a-sprite-using-an-array-with-colors-and-alpha'>Rendering a sprite using an Array with colors and alpha</h2>
<p>
The value for the color and alpha is a number between <code>0</code> and <code>255</code>. The alpha property is optional and will be set to <code>255</code> if not specified.
</p>
<p>
Creates a green circle sprite with an opacity of 50%.
</p>
<pre><code class="language-ruby">def tick args
# X Y WIDTH HEIGHT PATH ANGLE ALPHA RED GREEN BLUE
args.outputs.sprites << [100, 100, 160, 90, "sprites/circle/white.png", 0, 128, 0, 255, 0]
end
</code></pre>
<h2 id='---rendering-a-sprite-using-a-hash'>Rendering a sprite using a Hash</h2>
<p>
If you want a more readable invocation. You can use the following hash to create a sprite. Any parameters that are not specified will be given a default value. The keys of the hash can be provided in any order.
</p>
<pre><code class="language-ruby">def tick args
args.outputs.sprites << {
x: 0,
y: 0,
w: 100,
h: 100,
path: "sprites/circle/white.png",
angle: 0,
a: 255,
r: 0,
g: 255,
b: 0
}
end
</code></pre>
<h2 id='---rendering-a-solid-using-a-class'>Rendering a solid using a Class</h2>
<p>
You can also create a class with solid/border properties and render it as a primitive. ALL properties must be on the class. *Additionally*, a method called <code>primitive_marker</code> must be defined on the class.
</p>
<p>
Here is an example:
</p>
<pre><code class="language-ruby"># Create type with ALL sprite properties AND primitive_marker
class Sprite
attr_accessor :x, :y, :w, :h, :path, :angle, :angle_anchor_x, :angle_anchor_y, :tile_x, :tile_y, :tile_w, :tile_h, :source_x, :source_y, :source_w, :source_h, :flip_horizontally, :flip_vertically, :a, :r, :g, :b
def primitive_marker
:sprite
end
end
# Inherit from type
class Circle < Sprite
# constructor
def initialize x, y, size, path
self.x = x
self.y = y
self.w = size
self.h = size
self.path = path
end
def serlialize
{x:self.x, y:self.y, w:self.w, h:self.h, path:self.path}
end
def inspect
serlialize.to_s
end
def to_s
serlialize.to_s
end
end
def tick args
# render circle sprite
args.outputs.sprites << Circle.new(10, 10, 32,"sprites/circle/white.png")
end
</code></pre>
<h1 id='--docs---gtk--outputs#screenshots-'>DOCS: <code>GTK::Outputs#screenshots</code></h1>
<p>
Add a hash to this collection to take a screenshot and save as png file. The keys of the hash can be provided in any order.
</p>
<pre><code class="language-ruby">def tick args
args.outputs.screenshots << {
x: 0, y: 0, w: 100, h: 100, # Which portion of the screen should be captured
path: 'screenshot.png', # Output path of PNG file (inside game directory)
r: 255, g: 255, b: 255, a: 0 # Optional chroma key
}
end
</code></pre>
<h2 id='---chroma-key-(making-a-color-transparent)'>Chroma key (Making a color transparent)</h2>
<p>
By specifying the r, g, b and a keys of the hash you change the transparency of a color in the resulting PNG file. This can be useful if you want to create files with transparent background like spritesheets. The transparency of the color specified by <code>r</code>, <code>g</code>, <code>b</code> will be set to the transparency specified by <code>a</code>.
</p>
<p>
The example above sets the color white (255, 255, 255) as transparent.
</p>
<h1 id='--docs---gtk--mouse-'>DOCS: <code>GTK::Mouse</code></h1>
<p>
The mouse is accessible via <code>args.inputs.mouse</code>:
</p>
<pre><code class="language-ruby">def tick args
# Rendering a label that shows the mouse's x and y position (via args.inputs.mouse).
args.outputs.labels << [
10,
710,
"The mouse's position is: #{args.inputs.mouse.x} #{args.inputs.mouse.y}."
]
end
</code></pre>
<p>
The mouse has the following properties.
</p>
<ul>
<li><code>args.inputs.mouse.x</code>: Returns the x position of the mouse.</li>
<li><code>args.inputs.mouse.y</code>: Returns the y position of the mouse.</li>
<li><code>args.inputs.mouse.moved</code>: Returns true if the mouse moved during the tick.</li>
<li><code>args.inputs.mouse.moved_at</code>: Returns the tick_count (<code>args.state.tick_count</code>) that the mouse was moved at. This property will be <code>nil</code> if the mouse didn't move.</li>
<li><code>args.inputs.mouse.global_moved_at</code>: Returns the global tick_count (<code>Kernel.global_tick_count</code>) that the mouse was moved at. This property will be <code>nil</code> if the mouse didn't move.</li>
<li><code>args.inputs.mouse.click</code>: Returns a <code>GTK::MousePoint</code> for that specific frame (<code>args.state.tick_count</code>) if the mouse button was pressed.</li>
<li><code>args.inputs.mouse.previous_click</code>: Returns a <code>GTK::MousePoint</code> for the previous frame (<code>args.state.tick_count - 1</code>) if the mouse button was pressed.</li>
<li><code>args.inputs.mouse.up</code>: Returns true if for that specific frame (<code>args.state.tick_count</code>) if the mouse button was released.</li>
<li><code>args.inputs.mouse.point</code> | <code>args.inputs.mouse.position</code>: Returns an <code>Array</code> which contains the <code>x</code> and <code>y</code> position of the mouse.</li>
<li><code>args.inputs.mouse.has_focus</code>: Returns true if the game window has the mouse's focus.</li>
<li><code>args.inputs.mouse.wheel</code>: Returns an <code>GTK::OpenEntity</code> that contains an <code>x</code> and <code>y</code> property which represents how much the wheel has moved. If the wheel has not moved within the tick, this property will be <code>nil</code>.</li>
<li><code>args.inputs.mouse.button_left</code>: Returns true if the left mouse button is down.</li>
<li><code>args.inputs.mouse.button_right</code>: Returns true if the right mouse button is down.</li>
<li><code>args.inputs.mouse.button_middle</code>: Returns true if the middle mouse button is down.</li>
<li><code>args.inputs.mouse.button_bits</code>: Gives the bits for each mouse button and its current state.</li>
</ul>
<h1 id='--docs---gtk--mousepoint-'>DOCS: <code>GTK::MousePoint</code></h1>
<p>
The <code>GTK::MousePoint</code> has the following properties.
</p>
<ul>
<li><code>x</code>: Integer representing the mouse's x.</li>
<li><code>y</code>: Integer representing the mouse's y.</li>
<li><code>point</code>: Array with the <code>x</code> and <code>y</code> values.</li>
<li><code>w</code>: Width of the point that always returns <code>0</code> (included so that it can seamlessly work with <code>GTK::Geometry</code> functions).</li>
<li><code>h</code>: Height of the point that always returns <code>0</code> (included so that it can seamlessly work with <code>GTK::Geometry</code> functions).</li>
<li><code>left</code>: This value is the same as <code>x</code> (included so that it can seamlessly work with <code>GTK::Geometry</code> functions).</li>
<li><code>right</code>: This value is the same as <code>x</code> (included so that it can seamlessly work with <code>GTK::Geometry</code> functions).</li>
<li><code>top</code>: This value is the same as <code>y</code> (included so that it can seamlessly work with <code>GTK::Geometry</code> functions).</li>
<li><code>bottom</code>: This value is the same as <code>y</code> (included so that it can seamlessly work with <code>GTK::Geometry</code> functions).</li>
<li><code>created_at</code>: The tick (<code>args.state.tick_count</code>) that this structure was created.</li>
<li><code>global_created_at</code>: The global tick (<code>Kernel.global_tick_count</code>) that this structure was created.</li>
</ul>
<h1 id='--docs---gtk--openentity-'>DOCS: <code>GTK::OpenEntity</code></h1>
<p>
<code>GTK::OpenEntity</code> is accessible within the DragonRuby's top level <code>tick</code> function via the <code>args.state</code> property.
</p>
<pre><code class="language-ruby">def tick args
args.state.x ||= 100
args.outputs.labels << [10, 710, "value of x is: #{args.state.x}."]
end
</code></pre>
<p>
The primary benefit of using <code>args.state</code> as opposed to instance variables is that <code>GTK::OpenEntity</code> allows for arbitrary nesting of properties without the need to create intermediate objects.
</p>
<p>
For example:
</p>
<pre><code class="language-ruby">def tick args
# intermediate player object does not need to be created
args.state.player.x ||= 100
args.state.player.y ||= 100
args.outputs.labels << [
10,
710,
"player x, y is:#{args.state.player.x}, #{args.state.player.y}."
]
end
</code></pre>
<h1 id='--docs---gtk--openentity#as_hash-'>DOCS: <code>GTK::OpenEntity#as_hash</code></h1>
<p>
Returns a reference to the <code>GTK::OpenEntity</code> as a <code>Hash</code>. This property is useful when you want to treat <code>args.state</code> as a <code>Hash</code> and invoke methods such as <code>Hash#each</code>.
</p>
<p>
Example:
</p>
<pre><code class="language-ruby">def tick args
args.state.x ||= 100
args.state.y ||= 100
values = args.state
.as_hash
.map { |k, v| "#{k} #{v}" }
args.outputs.labels << values.map.with_index do |v, i|
[
10,
710 - (30 * i),
v
]
end
end
</code></pre>
<h1 id='--docs---numeric#frame_index-'>DOCS: <code>Numeric#frame_index</code></h1>
<p>
This function is helpful for determining the index of frame-by-frame sprite animation. The numeric value <code>self</code> represents the moment the animation started.
</p>
<p>
<code>frame_index</code> takes three additional parameters:
</p>
<ul>
<li>How many frames exist in the sprite animation.</li>
<li>How long to hold each animation for.</li>
<li>Whether the animation should repeat.</li>
</ul>
<p>
<code>frame_index</code> will return <code>nil</code> if the time for the animation is out of bounds of the parameter specification.
</p>
<p>
Example using variables:
</p>
<pre><code class="language-ruby">def tick args
start_looping_at = 0
number_of_sprites = 6
number_of_frames_to_show_each_sprite = 4
does_sprite_loop = true
sprite_index =
start_looping_at.frame_index number_of_sprites,
number_of_frames_to_show_each_sprite,
does_sprite_loop
sprite_index ||= 0
args.outputs.sprites << [
640 - 50,
360 - 50,
100,
100,
"sprites/dragon-#{sprite_index}.png"
]
end
</code></pre>
<p>
Example using named parameters:
</p>
<pre><code class="language-ruby">def tick args
start_looping_at = 0
sprite_index =
start_looping_at.frame_index count: 6,
hold_for: 4,
repeat: true,
tick_count_override: args.state.tick_count
sprite_index ||= 0
args.outputs.sprites << [
640 - 50,
360 - 50,
100,
100,
"sprites/dragon-#{sprite_index}.png"
]
end
</code></pre>
<h1 id='--docs---numeric#elapsed_time-'>DOCS: <code>Numeric#elapsed_time</code></h1>
<p>
For a given number, the elapsed frames since that number is returned. `Kernel.tick_count` is used to determine how many frames have elapsed. An optional numeric argument can be passed in which will be used instead of `Kernel.tick_count`.
</p>
<p>
Here is an example of how elapsed_time can be used.
</p>
<pre><code class="language-ruby">def tick args
args.state.last_click_at ||= 0
# record when a mouse click occurs
if args.inputs.mouse.click
args.state.last_click_at = args.state.tick_count
end
# Use Numeric#elapsed_time to determine how long it's been
if args.state.last_click_at.elapsed_time > 120
args.outputs.labels << [10, 710, "It has been over 2 seconds since the mouse was clicked."]
end
end
</code></pre>
<p>
And here is an example where the override parameter is passed in:
</p>
<pre><code class="language-ruby">def tick args
args.state.last_click_at ||= 0
# create a state variable that tracks time at half the speed of args.state.tick_count
args.state.simulation_tick = args.state.tick_count.idiv 2
# record when a mouse click occurs
if args.inputs.mouse.click
args.state.last_click_at = args.state.simulation_tick
end
# Use Numeric#elapsed_time to determine how long it's been
if (args.state.last_click_at.elapsed_time args.state.simulation_tick) > 120
args.outputs.labels << [10, 710, "It has been over 4 seconds since the mouse was clicked."]
end
end
</code></pre>
<h1 id='--docs---numeric#elapsed--'>DOCS: <code>Numeric#elapsed?</code></h1>
<p>
Returns true if <code>Numeric#elapsed_time</code> is greater than the number. An optional parameter can be passed into <code>elapsed?</code> which is added to the number before evaluating whether <code>elapsed?</code> is true.
</p>
<p>
Example usage (no optional parameter):
</p>
<pre><code class="language-ruby">def tick args
args.state.box_queue ||= []
if args.state.box_queue.empty?
args.state.box_queue << { name: :red,
destroy_at: args.state.tick_count + 60 }
args.state.box_queue << { name: :green,
destroy_at: args.state.tick_count + 60 }
args.state.box_queue << { name: :blue,
destroy_at: args.state.tick_count + 120 }
end
boxes_to_destroy = args.state
.box_queue
.find_all { |b| b[:destroy_at].elapsed? }
if !boxes_to_destroy.empty?
puts "boxes to destroy count: #{boxes_to_destroy.length}"
end
boxes_to_destroy.each { |b| puts "box #{b} was elapsed? on #{args.state.tick_count}." }
args.state.box_queue -= boxes_to_destroy
end
</code></pre>
<p>
Example usage (with optional parameter):
</p>
<pre><code class="language-ruby">def tick args
args.state.box_queue ||= []
if args.state.box_queue.empty?
args.state.box_queue << { name: :red,
create_at: args.state.tick_count + 120,
lifespan: 60 }
args.state.box_queue << { name: :green,
create_at: args.state.tick_count + 120,
lifespan: 60 }
args.state.box_queue << { name: :blue,
create_at: args.state.tick_count + 120,
lifespan: 120 }
end
# lifespan is passed in as a parameter to ~elapsed?~
boxes_to_destroy = args.state
.box_queue
.find_all { |b| b[:create_at].elapsed? b[:lifespan] }
if !boxes_to_destroy.empty?
puts "boxes to destroy count: #{boxes_to_destroy.length}"
end
boxes_to_destroy.each { |b| puts "box #{b} was elapsed? on #{args.state.tick_count}." }
args.state.box_queue -= boxes_to_destroy
end
</code></pre>
<h1 id='--docs---numeric#created--'>DOCS: <code>Numeric#created?</code></h1>
<p>
Returns true if <code>Numeric#elapsed_time == 0</code>. Essentially communicating that number is equal to the current frame.
</p>
<p>
Example usage:
</p>
<pre><code class="language-ruby">def tick args
args.state.box_queue ||= []
if args.state.box_queue.empty?
args.state.box_queue << { name: :red,
create_at: args.state.tick_count + 60 }
end
boxes_to_spawn_this_frame = args.state
.box_queue
.find_all { |b| b[:create_at].new? }
boxes_to_spawn_this_frame.each { |b| puts "box #{b} was new? on #{args.state.tick_count}." }
args.state.box_queue -= boxes_to_spawn_this_frame
end
</code></pre>
<h1 id='--docs---kernel-'>DOCS: <code>Kernel</code></h1>
<p>
Kernel in the DragonRuby Runtime has patches for how standard out is handled and also contains a unit of time in games called a tick.
</p>
<h1 id='--docs---kernel--tick_count-'>DOCS: <code>Kernel::tick_count</code></h1>
<p>
Returns the current tick of the game. This value is reset if you call $gtk.reset.
</p>
<h1 id='--docs---kernel--global_tick_count-'>DOCS: <code>Kernel::global_tick_count</code></h1>
<p>
Returns the current tick of the application from the point it was started. This value is never reset.
</p>
<h1 id='--docs---geometry-'>DOCS: <code>Geometry</code></h1>
<p>
The Geometry module contains methods for calculations that are frequently used in game development.
</p>
<h1 id='--docs---gtk--geometry#scale_rect-'>DOCS: <code>GTK::Geometry#scale_rect</code></h1>
<p>
Given an array with 4 elements representing a rect [x, y, w, h], this function returns a scaled rect. It accepts three arguments:
</p>
<p>
<code>ratio</code>: the ratio by which to scale the rect. A ratio of 2 will double the dimensions of the rect while a ratio of 0.5 will halve its dimensions.
</p>
<p>
<code>anchor_x</code> and <code>anchor_y</code> specify the point within the rect from which to resize it. Setting both to 0 will affect the width and height of the rect, leaving x and y unchanged. Setting both to 0.5 will scale all sides of the rect proportionally from the center.
</p>
<p>
The <code>scale_rect</code> method can be applied directly to a sprite or other primitives. See CHEATSHEET: How to Scale a Sprite.
</p>
<pre><code class="language-ruby">def tick args
# x, y, w, h
my_rect = [100, 100, 200, 200]
# halve the dimensions of the rect:
# ratio, anchor_x, anchor_y
new_rect = my_rect.scale_rect(0.5, 0.5, 0.5)
puts new_rect # => [150.0, 150.0, 100.0, 100.0]
end
</code></pre>
<h1 id='--source-code'>Source Code</h1>
<p>
Follows is a source code listing for all files that have been open sourced. This code can be found in the <code>./samples</code> directory.
</p>
<h2 id='---samples'>Samples</h2>
<h3 id='----learn-ruby-optional---beginner-ruby-primer---automation-rb'>Learn Ruby Optional - Beginner Ruby Primer - automation.rb</h3>
<pre><code class="language-ruby"># ./samples/00_learn_ruby_optional/00_beginner_ruby_primer/app/automation.rb
# ==========================================================================
# _ _ ________ __ _ _____ _____ _______ ______ _ _ _ _ _ _
# | | | | ____\ \ / / | | |_ _|/ ____|__ __| ____| \ | | | | | |
# | |__| | |__ \ \_/ / | | | | | (___ | | | |__ | \| | | | | |
# | __ | __| \ / | | | | \___ \ | | | __| | . ` | | | | |
# | | | | |____ | | | |____ _| |_ ____) | | | | |____| |\ |_|_|_|_|
# |_| |_|______| |_| |______|_____|_____/ |_| |______|_| \_(_|_|_|_)
#
#
# |
# |
# |
# |
# |
# |
# |
# |
# |
# |
# \ | /
# \ | /
# +
#
# If you are new to the programming language Ruby, then you may find the
# following code a bit overwhelming. Come back to this file when you have
# a better grasp of Ruby and Game Toolkit.
#
# What follows is an automations script # that can be run via terminal:
# ./samples/00_beginner_ruby_primer $ ../../dragonruby . --eval app/automation.rb
# ==========================================================================
$gtk.reset
$gtk.scheduled_callbacks.clear
$gtk.schedule_callback 10 do
$gtk.console.set_command 'puts "Hello DragonRuby!"'
end
$gtk.schedule_callback 20 do
$gtk.console.eval_the_set_command
end
$gtk.schedule_callback 30 do
$gtk.console.set_command 'outputs.solids << [910, 200, 100, 100, 255, 0, 0]'
end
$gtk.schedule_callback 40 do
$gtk.console.eval_the_set_command
end
$gtk.schedule_callback 50 do
$gtk.console.set_command 'outputs.solids << [1010, 200, 100, 100, 0, 0, 255]'
end
$gtk.schedule_callback 60 do
$gtk.console.eval_the_set_command
end
$gtk.schedule_callback 70 do
$gtk.console.set_command 'outputs.sprites << [1110, 200, 100, 100, "sprites/dragon_fly_0.png"]'
end
$gtk.schedule_callback 80 do
$gtk.console.eval_the_set_command
end
$gtk.schedule_callback 90 do
$gtk.console.set_command "outputs.labels << [1210, 200, state.tick_count, 0, 255, 0]"
end
$gtk.schedule_callback 100 do
$gtk.console.eval_the_set_command
end
$gtk.schedule_callback 110 do
$gtk.console.set_command "state.sprite_frame = state.tick_count.idiv(4).mod(6)"
end
$gtk.schedule_callback 120 do
$gtk.console.eval_the_set_command
end
$gtk.schedule_callback 130 do
$gtk.console.set_command "outputs.labels << [1210, 170, state.sprite_frame, 0, 255, 0]"
end
$gtk.schedule_callback 140 do
$gtk.console.eval_the_set_command
end
$gtk.schedule_callback 150 do
$gtk.console.set_command "state.sprite_path = \"sprites/dragon_fly_\#{state.sprite_frame}.png\""
end
$gtk.schedule_callback 160 do
$gtk.console.eval_the_set_command
end
$gtk.schedule_callback 170 do
$gtk.console.set_command "outputs.labels << [910, 330, \"path: \#{state.sprite_path}\", 0, 255, 0]"
end
$gtk.schedule_callback 180 do
$gtk.console.eval_the_set_command
end
$gtk.schedule_callback 190 do
$gtk.console.set_command "outputs.sprites << [910, 330, 370, 370, state.sprite_path]"
end
$gtk.schedule_callback 200 do
$gtk.console.eval_the_set_command
end
$gtk.schedule_callback 300 do
$gtk.console.set_command ":wq"
end
$gtk.schedule_callback 400 do
$gtk.console.eval_the_set_command
end
</code></pre>
<h3 id='----learn-ruby-optional---beginner-ruby-primer---main-rb'>Learn Ruby Optional - Beginner Ruby Primer - main.rb</h3>
<pre><code class="language-ruby"># ./samples/00_learn_ruby_optional/00_beginner_ruby_primer/app/main.rb
# ==========================================================================
# _ _ ________ __ _ _____ _____ _______ ______ _ _ _ _ _ _
# | | | | ____\ \ / / | | |_ _|/ ____|__ __| ____| \ | | | | | |
# | |__| | |__ \ \_/ / | | | | | (___ | | | |__ | \| | | | | |
# | __ | __| \ / | | | | \___ \ | | | __| | . ` | | | | |
# | | | | |____ | | | |____ _| |_ ____) | | | | |____| |\ |_|_|_|_|
# |_| |_|______| |_| |______|_____|_____/ |_| |______|_| \_(_|_|_|_)
#
#
# |
# |
# |
# |
# |
# |
# |
# |
# |
# |
# \ | /
# \ | /
# +
#
# If you are new to the programming language Ruby, then you may find the
# following code a bit overwhelming. This sample is only designed to be
# run interactively (as opposed to being manipulated via source code).
#
# Start up this sample and follow along by visiting:
# https://s3.amazonaws.com/s3.dragonruby.org/dragonruby-gtk-primer.mp4
#
# It is STRONGLY recommended that you work through all the samples before
# looking at the code in this file.
# ==========================================================================
class TutorialOutputs
attr_accessor :solids, :sprites, :labels, :lines, :borders
def initialize
@solids = []
@sprites = []
@labels = []
@lines = []
@borders = []
end
def tick
@solids ||= []
@sprites ||= []
@labels ||= []
@lines ||= []
@borders ||= []
@solids.each { |p| $gtk.args.outputs.reserved << p.solid }
@sprites.each { |p| $gtk.args.outputs.reserved << p.sprite }
@labels.each { |p| $gtk.args.outputs.reserved << p.label }
@lines.each { |p| $gtk.args.outputs.reserved << p.line }
@borders.each { |p| $gtk.args.outputs.reserved << p.border }
end
def clear
@solids.clear
@sprites.clear
@labels.clear
@borders.clear
end
end
def defaults
state.reset_button ||=
state.new_entity(
:button,
label: [1190, 68, "RESTART", -2, 0, 0, 0, 0].label,
background: [1160, 38, 120, 50, 255, 255, 255].solid
)
$gtk.log_level = :off
end
def tick_reset_button
return unless state.hello_dragonruby_confirmed
$gtk.args.outputs.reserved << state.reset_button.background
$gtk.args.outputs.reserved << state.reset_button.label
if inputs.mouse.click && inputs.mouse.click.point.inside_rect?(state.reset_button.background)
restart_tutorial
end
end
def seperator
@seperator = "=" * 80
end
def tick_intro
queue_message "Welcome to the DragonRuby GTK primer! Try typing the
code below and press ENTER:
puts \"Hello DragonRuby!\"
"
end
def tick_hello_dragonruby
return unless console_has? "Hello DragonRuby!"
$gtk.args.state.hello_dragonruby_confirmed = true
queue_message "Well HELLO to you too!
If you ever want to RESTART the tutorial, just click the \"RESTART\"
button in the bottom right-hand corner.
Let's continue shall we? Type the code below and press ENTER:
outputs.solids << [910, 200, 100, 100, 255, 0, 0]
"
end
def tick_explain_solid
return unless $tutorial_outputs.solids.any? {|s| s == [910, 200, 100, 100, 255, 0, 0]}
queue_message "Sweet!
The code: outputs.solids << [910, 200, 100, 100, 255, 0, 0]
Does the following:
1. GET the place where SOLIDS go: outputs.solids
2. Request that a new SOLID be ADDED: <<
3. The DEFINITION of a SOLID is the ARRAY:
[910, 200, 100, 100, 255, 0, 0]
GET ADD X Y WIDTH HEIGHT RED GREEN BLUE
| | | | | | | | |
| | | | | | | | |
outputs.solids << [910, 200, 100, 100, 255, 0, 0]
|_________________________________________|
|
|
ARRAY
Now let's create a blue SOLID. Type:
outputs.solids << [1010, 200, 100, 100, 0, 0, 255]
"
state.explain_solid_confirmed = true
end
def tick_explain_solid_blue
return unless state.explain_solid_confirmed
return unless $tutorial_outputs.solids.any? {|s| s == [1010, 200, 100, 100, 0, 0, 255]}
state.explain_solid_blue_confirmed = true
queue_message "And there is our blue SOLID!
The ARRAY is the MOST important thing in DragonRuby GTK.
Let's create a SPRITE using an ARRAY:
outputs.sprites << [1110, 200, 100, 100, 'sprites/dragon_fly_0.png']
"
end
def tick_explain_tick_count
return unless $tutorial_outputs.sprites.any? {|s| s == [1110, 200, 100, 100, 'sprites/dragon_fly_0.png']}
return if $tutorial_outputs.labels.any? {|l| l == [1210, 200, state.tick_count, 255, 255, 255]}
state.explain_tick_count_confirmed = true
queue_message "Look at the cute little dragon!
We can create a LABEL with ARRAYS too. Let's create a LABEL showing
THE PASSAGE OF TIME, which is called TICK_COUNT.
outputs.labels << [1210, 200, state.tick_count, 0, 255, 0]
"
end
def tick_explain_mod
return unless $tutorial_outputs.labels.any? {|l| l == [1210, 200, state.tick_count, 0, 255, 0]}
state.explain_mod_confirmed = true
queue_message "
The code: outputs.labels << [1210, 200, state.tick_count, 0, 255, 0]
Does the following:
1. GET the place where labels go: outputs.labels
2. Request that a new label be ADDED: <<
3. The DEFINITION of a LABEL is the ARRAY:
[1210, 200, state.tick_count, 0, 255, 0]
GET ADD X Y TEXT RED GREEN BLUE
| | | | | | | |
| | | | | | | |
outputs.labels << [1210, 200, state.tick_count, 0, 255, 0]
|______________________________________________|
|
|
ARRAY
Now let's do some MATH, save the result to STATE, and create a LABEL:
state.sprite_frame = state.tick_count.idiv(4).mod(6)
outputs.labels << [1210, 170, state.sprite_frame, 0, 255, 0]
Type the lines above (pressing ENTER after each line).
"
end
def tick_explain_string_interpolation
return unless state.explain_mod_confirmed
return unless state.sprite_frame == state.tick_count.idiv(4).mod(6)
return unless $tutorial_outputs.labels.any? {|l| l == [1210, 170, state.sprite_frame, 0, 255, 0]}
queue_message "Here is what the mathematical computation you just typed does:
1. Create an item of STATE named SPRITE_FRAME: state.sprite_frame =
2. Set this SPRITE_FRAME to the PASSAGE OF TIME (tick_count),
DIVIDED EVENLY (idiv) into 4,
and then compute the REMAINDER (mod) of 6.
STATE SPRITE_FRAME PASSAGE OF HOW LONG HOW MANY
| | TIME TO SHOW IMAGES
| | | AN IMAGE TO FLIP THROUGH
| | | | |
state.sprite_frame = state.tick_count.idiv(4).mod(6)
| |
| +- REMAINDER OF DIVIDE
DIVIDE EVENLY
(NO DECIMALS)
With the information above, we can animate a SPRITE
using STRING INTERPOLATION: \#{}
which creates a unique SPRITE_PATH:
state.sprite_path = \"sprites/dragon_fly_\#{state.sprite_frame}.png\"
outputs.labels << [910, 330, \"path: \#{state.sprite_path}\", 0, 255, 0]
outputs.sprites << [910, 330, 370, 370, state.sprite_path]
Type the lines above (pressing ENTER after each line).
"
end
def tick_reprint_on_error
return unless console.last_command_errored
puts $gtk.state.messages.last
puts "\nWhoops! Try again."
console.last_command_errored = false
end
def tick_evals
state.evals ||= []
if console.last_command && (console.last_command.start_with?("outputs.") || console.last_command.start_with?("state."))
state.evals << console.last_command
console.last_command = nil
end
state.evals.each do |l|
Kernel.eval l
end
rescue Exception => e
state.evals = state.evals[0..-2]
end
$tutorial_outputs ||= TutorialOutputs.new
def tick args
$gtk.log_level = :off
defaults
console.show
$tutorial_outputs.clear
$tutorial_outputs.solids << [900, 37, 480, 700, 0, 0, 0, 255]
$tutorial_outputs.borders << [900, 37, 380, 683, 255, 255, 255]
tick_evals
$tutorial_outputs.tick
tick_intro
tick_hello_dragonruby
tick_reset_button
tick_explain_solid
tick_explain_solid_blue
tick_reprint_on_error
tick_explain_tick_count
tick_explain_mod
tick_explain_string_interpolation
end
def console
$gtk.console
end
def queue_message message
$gtk.args.state.messages ||= []
return if $gtk.args.state.messages.include? message
$gtk.args.state.messages << message
last_three = [$gtk.console.log[-3], $gtk.console.log[-2], $gtk.console.log[-1]].reject_nil
$gtk.console.log.clear
puts seperator
$gtk.console.log += last_three
puts seperator
puts message
puts seperator
end
def console_has? message
console.log.map(&:upcase).include? "#{message.upcase}\n"
end
def restart_tutorial
$tutorial_outputs.clear
$gtk.console.log.clear
$gtk.reset
puts "Starting the tutorial over!"
end
def state
$gtk.args.state
end
def inputs
$gtk.args.inputs
end
def outputs
$tutorial_outputs
end
</code></pre>
<h3 id='----learn-ruby-optional---intermediate-ruby-primer---printing-txt'>Learn Ruby Optional - Intermediate Ruby Primer - printing.txt</h3>
<pre><code class="language-ruby"># ./samples/00_learn_ruby_optional/00_intermediate_ruby_primer/app/01_printing.txt
# ====================================================================================
# Commenting Code
# ====================================================================================
#
# Prefixing text with a pound sign (#) is how you comment code in Ruby. Example:
#
# I am commented code. And so are the lines above.
#
# I you want more than a quick primer on Ruby, check out https://poignant.guide/. It's
# an entertaining read. Otherwise, go to the next txt file.
#
# Follow along by visiting:
# https://s3.amazonaws.com/s3.dragonruby.org/dragonruby-gtk-intermediate.mp4
# ====================================================================================
# Printing to the Console:
# ====================================================================================
#
# Every time you save repl.rb file, DragonRuby runs the code within it. Copy this text
# to repl.rb and save to see Hello World printed to the console.
repl do
puts '* RUBY PRIMER: Printing to the console using the ~puts~ function.'
puts '===='
puts '======'
puts '================================'
puts 'Hello World'
puts '================================'
puts '======'
puts '===='
end
</code></pre>
<h3 id='----learn-ruby-optional---intermediate-ruby-primer---strings-txt'>Learn Ruby Optional - Intermediate Ruby Primer - strings.txt</h3>
<pre><code class="language-ruby"># ./samples/00_learn_ruby_optional/00_intermediate_ruby_primer/app/02_strings.txt
# ====================================================================================
# Strings
# ====================================================================================
#
# Here is how you work with strings in Ruby. Take the text
# in this file and paste it into repl.rb and save:
repl do
puts '* RUBY PRIMER: strings'
message = "Hello World"
puts "The value of message is: " + message
puts "Any value can be interpolated within a string using \#{}."
puts "Interpolated message: #{message}."
puts 'This #{message} is not interpolated because the string uses single quotes.'
end
</code></pre>
<h3 id='----learn-ruby-optional---intermediate-ruby-primer---numbers-txt'>Learn Ruby Optional - Intermediate Ruby Primer - numbers.txt</h3>
<pre><code class="language-ruby"># ./samples/00_learn_ruby_optional/00_intermediate_ruby_primer/app/03_numbers.txt
# ====================================================================================
# Numerics
# ====================================================================================
#
# Here is how you work with numbers in Ruby. Take the text
# in this file and paste it into repl.rb and save:
repl do
puts '* RUBY PRIMER: Fixnum and Floats'
a = 10
puts "The value of a is: #{a}"
puts "a + 1 is: #{a + 1}"
puts "a / 3 is: #{a / 3}"
puts ''
b = 10.12
puts "The value of b is: #{b}"
puts "b + 1 is: #{b + 1}"
puts "b as an integer is: #{b.to_i}"
puts ''
end
</code></pre>
<h3 id='----learn-ruby-optional---intermediate-ruby-primer---booleans-txt'>Learn Ruby Optional - Intermediate Ruby Primer - booleans.txt</h3>
<pre><code class="language-ruby"># ./samples/00_learn_ruby_optional/00_intermediate_ruby_primer/app/04_booleans.txt
# ====================================================================================
# Booleans
# ====================================================================================
#
# Here is how you work with numbers in Ruby. Take the text
# in this file and paste it into repl.rb and save:
repl do
puts '* RUBY PRIMER: TrueClass, FalseClass, NilClass (truthy / falsey values)'
puts "Anything that *isn't* false or nil is true."
c = 30
puts "The value of c is #{c}."
if c
puts "This if statement ran because c is truthy."
end
d = false
puts "The value if d is #{d}. The type for d is #{d.class}."
if !d
puts "This if statement ran because d is falsey, using the not operator (!)."
end
e = nil
puts "Nil is also considered falsey. The value of e is: #{e} (a blank string when printed). Which is of type #{e.class}."
if !e
puts "This if statement ran because e is nil and the if statement applied the NOT operator. !e yields a type of #{(!e).class}."
end
end
</code></pre>
<h3 id='----learn-ruby-optional---intermediate-ruby-primer---conditionals-txt'>Learn Ruby Optional - Intermediate Ruby Primer - conditionals.txt</h3>
<pre><code class="language-ruby"># ./samples/00_learn_ruby_optional/00_intermediate_ruby_primer/app/05_conditionals.txt
# ====================================================================================
# Conditionals
# ====================================================================================
#
# Here is how you create conditionals in Ruby. Take the text
# in this file and paste it into repl.rb and save:
repl do
puts "* RUBY PRIMER: Conditionals"
end
# ====================================================================================
# if
# ====================================================================================
repl do
puts "** INFO: if statement"
i_am_one = 1
if i_am_one
puts "This was printed because i_am_one is truthy."
end
end
# ====================================================================================
# if/else
# ====================================================================================
repl do
puts "** INFO: if/else statement"
i_am_false = false
if i_am_false
puts "This will NOT get printed because i_am_false is false."
else
puts "This was printed because i_am_false is false."
end
end
# ====================================================================================
# if/elsif/else
# ====================================================================================
repl do
puts "** INFO: if/elsif/else statement"
i_am_false = false
i_am_true = true
if i_am_false
puts "This will NOT get printed because i_am_false is false."
elsif i_am_true
puts "This was printed because i_am_true is true."
else
puts "This will NOT get printed i_am_true was true."
end
end
# ====================================================================================
# case
# ====================================================================================
repl do
puts "** INFO case statement"
i_am_one = 1 # change this value to see different results
case i_am_one
when 10
puts "the value of i_am_one is 10"
when 9
puts "the value of i_am_one is 9"
when 5
puts "the value of i_am_one is 5"
when 1
puts "the value of i_am_one is 1"
else
puts "Value wasn't cased."
end
end
# ====================================================================================
# comparison operators
# ====================================================================================
repl do
puts "** INFO: Different types of comparisons"
if 4 == 4
puts "4 equals 4 (==)"
end
if 4 != 3
puts "4 does not equal 3 (!=)"
end
if 3 < 4
puts "3 is less than 4 (<)"
end
if 4 > 3
puts "4 is greater than 3 (>)"
end
end
# ====================================================================================
# and/or conditionals
# ====================================================================================
repl do
puts "** INFO: AND, OR operator (&&, ||)"
if (4 > 3) || (3 < 4) || false
puts "print this if 4 is greater than 3 OR 3 is less than 4 OR false is true (||)"
end
if (4 > 3) && (3 < 4)
puts "print this if 4 is greater than 3 AND 3 is less than 4 (&&)"
end
end
</code></pre>
<h3 id='----learn-ruby-optional---intermediate-ruby-primer---looping-txt'>Learn Ruby Optional - Intermediate Ruby Primer - looping.txt</h3>
<pre><code class="language-ruby"># ./samples/00_learn_ruby_optional/00_intermediate_ruby_primer/app/06_looping.txt
# ====================================================================================
# Looping
# ====================================================================================
#
# Looping looks a whole lot different than other languages.
# But it's pretty awesome when you get used to it.
repl do
puts "* RUBY PRIMER: Loops"
end
# ====================================================================================
# times
# ====================================================================================
repl do
puts "** INFO: ~Numeric#times~ (for loop)"
3.times do |i|
puts i
end
end
# ====================================================================================
# foreach
# ====================================================================================
repl do
puts "** INFO: ~Array#each~ (for each loop)"
array = ["a", "b", "c", "d"]
array.each do |char|
puts char
end
puts "** INFO: ~Array#each_with_index~ (for each loop)"
array = ["a", "b", "c", "d"]
array.each do |char, i|
puts "index #{i}: #{char}"
end
end
# ====================================================================================
# ranges
# ====================================================================================
repl do
puts "** INFO: range block exclusive (three dots)"
(0...3).each do |i|
puts i
end
puts "** INFO: range block inclusive (two dots)"
(0..3).each do |i|
puts i
end
end
</code></pre>
<h3 id='----learn-ruby-optional---intermediate-ruby-primer---functions-txt'>Learn Ruby Optional - Intermediate Ruby Primer - functions.txt</h3>
<pre><code class="language-ruby"># ./samples/00_learn_ruby_optional/00_intermediate_ruby_primer/app/07_functions.txt
# ====================================================================================
# Functions
# ====================================================================================
# The last statement of a function is implictly returned. Parenthesis for functions
# are optional as long as the statement can be envaluated disambiguously.
repl do
puts "* RUBY PRIMER: Functions"
end
# ====================================================================================
# Functions single parameter
# ====================================================================================
repl do
puts "* INFO: Function with one parameter"
# function definition
def add_one_to n
n + 1
end
# Parenthesis are optional in Ruby as long as the
# parsing is disambiguous. Here are a couple of variations.
# Generally speaking, don't put parenthesis is you don't have to.
# Conventional Usage of Parenthesis.
puts add_one_to(3)
# DragonRuby's recommended use of parenthesis (inner function has parenthesis).
puts (add_one_to 3)
# Full parens.
puts(add_one_to(3))
# Outer function has parenthesis
puts(add_one_to 3)
end
# ====================================================================================
# Functions with default parameter values
# ====================================================================================
repl do
puts "* INFO: Function with default value"
def function_with_default_value v = 10
v * 10
end
puts "Passing the argument three yields: #{function_with_default_value 3}"
puts "Passing no argument yields: #{function_with_default_value}"
end
# ====================================================================================
# Nil default parameter value and ||= operator.
# ====================================================================================
repl do
puts "* INFO: Using the OR EQUAL operator (||=)"
def function_with_nil_default_with_local a = nil
result = a
result ||= "DEFAULT_VALUE_OF_A_IS_NIL_OR_FALSE"
"value is #{result}."
end
puts "Passing 'hi' as the argument yields: #{function_with_nil_default_with_local 'hi'}"
puts "Passing nil: #{function_with_nil_default_with_local}"
end
</code></pre>
<h3 id='----learn-ruby-optional---intermediate-ruby-primer---arrays-txt'>Learn Ruby Optional - Intermediate Ruby Primer - arrays.txt</h3>
<pre><code class="language-ruby"># ./samples/00_learn_ruby_optional/00_intermediate_ruby_primer/app/08_arrays.txt
# ====================================================================================
# Arrays
# ====================================================================================
# Arrays are incredibly powerful in Ruby. Learn to use them well.
repl do
puts "* RUBY PRIMER: ARRAYS"
end
# ====================================================================================
# Enumerable ranges and .to_a
# ====================================================================================
repl do
puts "** INFO: Create an array with the numbers 1 to 10."
one_to_ten = (1..10).to_a
puts one_to_ten
end
# ====================================================================================
# Finding elements
# ====================================================================================
repl do
puts "** INFO: Finding elements in an array using ~Array#find_all~."
puts "Create a new array that only contains even numbers from the previous array."
one_to_ten = (1..10).to_a
evens = one_to_ten.find_all do |number|
number % 2 == 0
end
puts evens
end
# ====================================================================================
# Rejecting elements
# ====================================================================================
repl do
puts "** INFO: Removing elements in an array using ~Array#reject~."
puts "Create a new array that rejects odd numbers."
one_to_ten = (1..10).to_a
also_even = one_to_ten.reject do |number|
number % 2 != 0
end
puts also_even
end
# ====================================================================================
# Array transform using the map function.
# ====================================================================================
repl do
puts "** INFO: Creating new derived values from an array using ~Array#map~."
puts "Create an array that doubles every number."
one_to_ten = (1..10).to_a
doubled = one_to_ten.map do |number|
number * 2
end
puts doubled
end
# ====================================================================================
# Combining array functions.
# ====================================================================================
repl do
puts "** INFO: Combining ~Array#find_all~ along with ~Array#map~."
puts "Create an array that selects only odd numbers and then multiply those by 10."
one_to_ten = (1..10).to_a
odd_doubled = one_to_ten.find_all do |number|
number % 2 != 0
end.map do |odd_number|
odd_number * 10
end
puts odd_doubled
end
# ====================================================================================
# Product function.
# ====================================================================================
repl do
puts "** INFO: Create all combinations of array values using ~Array#product~."
puts "All two-item pairs of numbers 1 to 10."
one_to_ten = (1..10).to_a
all_combinations = one_to_ten.product(one_to_ten)
puts all_combinations
end
# ====================================================================================
# Uniq and sort function.
# ====================================================================================
repl do
puts "** INFO: Providing uniq values using ~Array#uniq~ and ~Array#sort~."
puts "All uniq combinations of numbers regardless of order."
puts "For example: [1, 2] is the same as [2, 1]."
one_to_ten = (1..10).to_a
uniq_combinations =
one_to_ten.product(one_to_ten)
.map do |unsorted_number|
unsorted_number.sort
end.uniq
puts uniq_combinations
end
# ====================================================================================
# Example of an advanced array transform.
# ====================================================================================
repl do
puts "** INFO: Advanced chaining. Combining ~Array's ~map~, ~find_all~, ~sort~, and ~sort_by~."
puts "All unique Pythagorean Triples between 1 and 100 sorted by area of the triangle."
one_to_hundred = (1..100).to_a
triples =
one_to_hundred.product(one_to_hundred).map do |width, height|
[width, height, Math.sqrt(width ** 2 + height ** 2)]
end.find_all do |_, _, hypotenuse|
hypotenuse.to_i == hypotenuse
end.map do |triangle|
triangle.map(&:to_i)
end.uniq do |triangle|
triangle.sort
end.map do |width, height, hypotenuse|
[width, height, hypotenuse, (width * height) / 2]
end.sort_by do |_, _, _, area|
area
end
triples.each do |width, height, hypotenuse, _|
puts "(#{width}, #{height}, #{hypotenuse})"
end
end
# ====================================================================================
# Example of an sorting.
# ====================================================================================
repl do
puts "** INFO: Implementing a custom sort function that operates on the ~Hash~ datatype."
things_to_sort = [
{ type: :background, order: 1 },
{ type: :foreground, order: 1 },
{ type: :foreground, order: 2 }
]
puts "*** Original array."
puts things_to_sort
puts "*** Simple sort using key."
# For a simple sort, you can use sort_by
results = things_to_sort.sort_by do |hash|
hash[:order]
end
puts results
puts "*** Custom sort."
puts "**** Sorting process."
# for a more complicated sort, you can provide a block that returns
# -1, 0, 1 for a left and right operand
results = things_to_sort.sort do |l, r|
sort_result = 0
puts "here is l: #{l}"
puts "here is r: #{r || "nil"}"
# if either value is nil/false return 0
if !l || !r
sort_result = 0
# if the type of "left" is background and the
# type of "right" is foreground, then return
# -1 (which means "left" is less than "right"
elsif l[:type] == :background && r[:type] == :foreground
sort_result = -1
# if the type of "left" is foreground and the
# type of "right" is background, then return
# 1 (which means "left" is greater than "right"
elsif l[:type] == :foreground && r[:type] == :background
sort_result = 1
# if "left" and "right"'s type are the same, then
# use the order as the tie breaker
elsif l[:order] < r[:order]
sort_result = -1
elsif l[:order] > r[:order]
sort_result = 1
# returning 0 means both values are equal
else
sort_result = 0
end
sort_result
end.to_a
puts "**** Sort result."
puts results
end
# ====================================================================================
# Api documention for Array that is worth commiting to memory because arrays are so
# awesome in Ruby: https://docs.ruby-lang.org/en/2.0.0/Array.html
# ====================================================================================
</code></pre>
<h3 id='----learn-ruby-optional---intermediate-ruby-primer---main-rb'>Learn Ruby Optional - Intermediate Ruby Primer - main.rb</h3>
<pre><code class="language-ruby"># ./samples/00_learn_ruby_optional/00_intermediate_ruby_primer/app/main.rb
def tick args
args.outputs.labels << [640, 380, "Open repl.rb in the text editor of your choice and follow the document.", 0, 1]
end
</code></pre>
<h3 id='----rendering-basics---labels---main-rb'>Rendering Basics - Labels - main.rb</h3>
<pre><code class="language-ruby"># ./samples/01_rendering_basics/01_labels/app/main.rb
=begin
APIs listing that haven't been encountered in a previous sample apps:
- args.outputs.labels: An array. Values in this array generate labels
the screen.
- args.grid.(left|right|top|bottom): Pixel value for the boundaries of the virtual
720 p screen (Dragon Ruby Game Toolkits's virtual resolution is always 1280x720).
- Numeric#shift_(left|right|up|down): Shifts the Numeric in the correct direction
by adding or subracting.
=end
# Labels are used to represent text elements in DragonRuby
# An example of creating a label is:
# args.outputs.labels << [320, 640, "Example", 3, 1, 255, 0, 0, 200, manaspace.ttf]
# The code above does the following:
# 1. GET the place where labels go: args.outputs.labels
# 2. Request a new LABEL be ADDED: <<
# 3. The DEFINITION of a SOLID is the ARRAY:
# [320, 640, "Example", 3, 1, 255, 0, 0, 200, manaspace.ttf]
# [ X , Y, TEXT, SIZE, ALIGN, RED, GREEN, BLUE, ALPHA, FONT STYLE]
# The tick method is called by DragonRuby every frame
# args contains all the information regarding the game.
def tick args
tick_instructions args, "Sample app shows different version of label sizes and alignments. And how to use hashes instead of arrays."
# Here are some examples of simple labels, with the minimum number of parameters
# Note that the default values for the other parameters are 0, except for Alpha which is 255 and Font Style which is the default font
args.outputs.labels << [400, 620, "Here is a label with just an x, y, and text"]
args.outputs.labels << [args.grid.left.shift_right(5), args.grid.top.shift_down(5), "This is a label located at the top left."]
args.outputs.labels << [args.grid.left.shift_right(5), args.grid.bottom.shift_up(30), "This is a label located at the bottom left."]
args.outputs.labels << [args.grid.right.shift_left(420), args.grid.top.shift_down(5), "This is a label located at the top right."]
args.outputs.labels << [args.grid.right.shift_left(440), args.grid.bottom.shift_up(30), "This is a label located at the bottom right."]
# Demonstration of the Size Parameter
args.outputs.labels << [175 + 150, 610 - 50, "Smaller label.", -2]
args.outputs.labels << [175 + 150, 580 - 50, "Small label.", -1]
args.outputs.labels << [175 + 150, 550 - 50, "Medium label.", 0]
args.outputs.labels << [175 + 150, 520 - 50, "Large label.", 1]
args.outputs.labels << [175 + 150, 490 - 50, "Larger label.", 2]
# Demonstration of the Align Parameter
args.outputs.labels << [260 + 150, 345 - 50, "Left aligned.", 0, 2]
args.outputs.labels << [260 + 150, 325 - 50, "Center aligned.", 0, 1]
args.outputs.labels << [260 + 150, 305 - 50, "Right aligned.", 0, 0]
# Demonstration of the RGBA parameters
args.outputs.labels << [600 + 150, 590 - 50, "Red Label.", 0, 0, 255, 0, 0]
args.outputs.labels << [600 + 150, 570 - 50, "Green Label.", 0, 0, 0, 255, 0]
args.outputs.labels << [600 + 150, 550 - 50, "Blue Label.", 0, 0, 0, 0, 255]
args.outputs.labels << [600 + 150, 530 - 50, "Faded Label.", 0, 0, 0, 0, 0, 128]
# Demonstration of the Font parameter
# In order to use a font of your choice, add its ttf file to the project folder, where the app folder is
args.outputs.labels << [690 + 150, 330 - 20, "Custom font (Array)", 0, 1, 125, 0, 200, 255, "manaspc.ttf" ]
args.outputs.primitives << { x: 690 + 150,
y: 330 - 50,
text: "Custom font (Hash)",
size_enum: 0,
alignment_enum: 1,
r: 125,
g: 0,
b: 200,
a: 255,
font: "manaspc.ttf" }.label!
# Primitives can hold anything, and can be given a label in the following forms
args.outputs.primitives << [690 + 150, 330 - 80, "Custom font (.primitives Array)", 0, 1, 125, 0, 200, 255, "manaspc.ttf" ].label
args.outputs.primitives << { x: 690 + 150,
y: 330 - 110,
text: "Custom font (.primitives Hash)",
size_enum: 0,
alignment_enum: 1,
r: 125,
g: 0,
b: 200,
a: 255,
font: "manaspc.ttf" }.label!
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----rendering-basics---lines---main-rb'>Rendering Basics - Lines - main.rb</h3>
<pre><code class="language-ruby"># ./samples/01_rendering_basics/02_lines/app/main.rb
=begin
APIs listing that haven't been encountered in a previous sample apps:
- args.outputs.lines: An array. Values in this array generate lines on
the screen.
- args.state.tick_count: This property contains an integer value that
represents the current frame. GTK renders at 60 FPS. A value of 0
for args.state.tick_count represents the initial load of the game.
=end
# The parameters required for lines are:
# 1. The initial point (x, y)
# 2. The end point (x2, y2)
# 3. The rgba values for the color and transparency (r, g, b, a)
# An example of creating a line would be:
# args.outputs.lines << [100, 100, 300, 300, 255, 0, 255, 255]
# This would create a line from (100, 100) to (300, 300)
# The RGB code (255, 0, 255) would determine its color, a purple
# It would have an Alpha value of 255, making it completely opaque
def tick args
tick_instructions args, "Sample app shows how to create lines."
args.outputs.labels << [480, 620, "Lines (x, y, x2, y2, r, g, b, a)"]
# Some simple lines
args.outputs.lines << [380, 450, 675, 450]
args.outputs.lines << [380, 410, 875, 410]
# These examples utilize args.state.tick_count to change the length of the lines over time
# args.state.tick_count is the ticks that have occurred in the game
# This is accomplished by making either the starting or ending point based on the args.state.tick_count
args.outputs.lines << [380, 370, 875, 370, args.state.tick_count % 255, 0, 0, 255]
args.outputs.lines << [380, 330 - args.state.tick_count % 25, 875, 330, 0, 0, 0, 255]
args.outputs.lines << [380 + args.state.tick_count % 400, 290, 875, 290, 0, 0, 0, 255]
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----rendering-basics---solids-borders---main-rb'>Rendering Basics - Solids Borders - main.rb</h3>
<pre><code class="language-ruby"># ./samples/01_rendering_basics/03_solids_borders/app/main.rb
=begin
APIs listing that haven't been encountered in a previous sample apps:
- args.outputs.solids: An array. Values in this array generate
solid/filled rectangles on the screen.
=end
# Rects are outputted in DragonRuby as rectangles
# If filled in, they are solids
# If hollow, they are borders
# Solids are added to args.outputs.solids
# Borders are added to args.outputs.borders
# The parameters required for rects are:
# 1. The upper right corner (x, y)
# 2. The width (w)
# 3. The height (h)
# 4. The rgba values for the color and transparency (r, g, b, a)
# Here is an example of a rect definition:
# [100, 100, 400, 500, 0, 255, 0, 180]
# The example would create a rect from (100, 100)
# Extending 400 pixels across the x axis
# and 500 pixels across the y axis
# The rect would be green (0, 255, 0)
# and mostly opaque with some transparency (180)
# Whether the rect would be filled or not depends on if
# it is added to args.outputs.solids or args.outputs.borders
def tick args
tick_instructions args, "Sample app shows how to create solid squares."
args.outputs.labels << [460, 600, "Solids (x, y, w, h, r, g, b, a)"]
args.outputs.solids << [470, 520, 50, 50]
args.outputs.solids << [530, 520, 50, 50, 0, 0, 0]
args.outputs.solids << [590, 520, 50, 50, 255, 0, 0]
args.outputs.solids << [650, 520, 50, 50, 255, 0, 0, 128]
args.outputs.solids << [710, 520, 50, 50, 0, 0, 0, 128 + args.state.tick_count % 128]
args.outputs.labels << [460, 400, "Borders (x, y, w, h, r, g, b, a)"]
args.outputs.borders << [470, 320, 50, 50]
args.outputs.borders << [530, 320, 50, 50, 0, 0, 0]
args.outputs.borders << [590, 320, 50, 50, 255, 0, 0]
args.outputs.borders << [650, 320, 50, 50, 255, 0, 0, 128]
args.outputs.borders << [710, 320, 50, 50, 0, 0, 0, 128 + args.state.tick_count % 128]
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----rendering-basics---sprites---main-rb'>Rendering Basics - Sprites - main.rb</h3>
<pre><code class="language-ruby"># ./samples/01_rendering_basics/04_sprites/app/main.rb
=begin
APIs listing that haven't been encountered in a previous sample apps:
- args.outputs.sprites: An array. Values in this array generate
sprites on the screen. The location of the sprite is assumed to
be under the mygame/ directory (the exception being dragonruby.png).
=end
# For all other display outputs, Sprites are your solution
# Sprites import images and display them with a certain rectangular area
# The image can be of any usual format and should be located within the folder,
# similar to additional fonts.
# Sprites have the following parameters
# Rectangular area (x, y, width, height)
# The image (path)
# Rotation (angle)
# Alpha (a)
def tick args
tick_instructions args, "Sample app shows how to render a sprite. Set its alpha, and rotate it."
args.outputs.labels << [460, 600, "Sprites (x, y, w, h, path, angle, a)"]
args.outputs.sprites << [460, 470, 128, 101, 'dragonruby.png']
args.outputs.sprites << [610, 470, 128, 101, 'dragonruby.png', args.state.tick_count % 360]
args.outputs.sprites << [760, 470, 128, 101, 'dragonruby.png', 0, args.state.tick_count % 255]
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----rendering-basics---sounds---main-rb'>Rendering Basics - Sounds - main.rb</h3>
<pre><code class="language-ruby"># ./samples/01_rendering_basics/05_sounds/app/main.rb
=begin
APIs Listing that haven't been encountered in previous sample apps:
- sample: Chooses random element from array.
In this sample app, the target note is set by taking a sample from the collection
of available notes.
Reminders:
- String interpolation: Uses #{} syntax; everything between the #{ and the } is evaluated
as Ruby code, and the placeholder is replaced with its corresponding value or result.
- args.outputs.labels: An array. The values generate a label.
The parameters are [X, Y, TEXT, SIZE, ALIGNMENT, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.md.
=end
# This sample app allows users to test their musical skills by matching the piano sound that plays in each
# level to the correct note.
# Runs all the methods necessary for the game to function properly.
def tick args
args.outputs.labels << [640, 360, "Click anywhere to play a random sound.", 0, 1]
args.state.notes ||= [:C3, :D3, :E3, :F3, :G3, :A3, :B3, :C4]
if args.inputs.mouse.click
# Play a sound by adding a string to args.outputs.sounds
args.outputs.sounds << "sounds/#{args.state.notes.sample}.wav" # sound of target note is output
end
end
</code></pre>
<h3 id='----input-basics---keyboard---main-rb'>Input Basics - Keyboard - main.rb</h3>
<pre><code class="language-ruby"># ./samples/02_input_basics/01_keyboard/app/main.rb
=begin
APIs listing that haven't been encountered in a previous sample apps:
- args.inputs.keyboard.key_up.KEY: The value of the properties will be set
to the frame that the key_up event occurred (the frame correlates
to args.state.tick_count). Otherwise the value will be nil. For a
full listing of keys, take a look at mygame/documentation/06-keyboard.md.
- args.state.PROPERTY: The state property on args is a dynamic
structure. You can define ANY property here with ANY type of
arbitrary nesting. Properties defined on args.state will be retained
across frames. If you attempt access a property that doesn't exist
on args.state, it will simply return nil (no exception will be thrown).
=end
# Along with outputs, inputs are also an essential part of video game development
# DragonRuby can take input from keyboards, mouse, and controllers.
# This sample app will cover keyboard input.
# args.inputs.keyboard.key_up.a will check to see if the a key has been pressed
# This will work with the other keys as well
def tick args
tick_instructions args, "Sample app shows how keyboard events are registered and accessed.", 360
# Notice how small_font accounts for all the remaining parameters
args.outputs.labels << { x: 460, y: row_to_px(args, 0), text: "Current game time: #{args.state.tick_count}", size_enum: -1 }
args.outputs.labels << { x: 460, y: row_to_px(args, 2), text: "Keyboard input: args.inputs.keyboard.key_up.h", size_enum: -1 }
args.outputs.labels << { x: 460, y: row_to_px(args, 3), text: "Press \"h\" on the keyboard.", size_enum: -1 }
# Input on a specifc key can be found through args.inputs.keyboard.key_up followed by the key
if args.inputs.keyboard.key_up.h
args.state.h_pressed_at = args.state.tick_count
end
# This code simplifies to if args.state.h_pressed_at has not been initialized, set it to false
args.state.h_pressed_at ||= false
if args.state.h_pressed_at
args.outputs.labels << { x: 460, y: row_to_px(args, 4), text: "\"h\" was pressed at time: #{args.state.h_pressed_at}", size_enum: -1 }
else
args.outputs.labels << { x: 460, y: row_to_px(args, 4), text: "\"h\" has never been pressed.", size_enum: -1 }
end
tick_help_text args
end
def row_to_px args, row_number, y_offset = 20
# This takes a row_number and converts it to pixels DragonRuby understands.
# Row 0 starts 5 units below the top of the grid
# Each row afterward is 20 units lower
args.grid.top - 5 - (y_offset * row_number)
end
# Don't worry about understanding the code within this method just yet.
# This method shows you the help text within the game.
def tick_help_text args
return unless args.state.h_pressed_at
args.state.key_value_history ||= {}
args.state.key_down_value_history ||= {}
args.state.key_held_value_history ||= {}
args.state.key_up_value_history ||= {}
if (args.inputs.keyboard.key_down.truthy_keys.length > 0 ||
args.inputs.keyboard.key_held.truthy_keys.length > 0 ||
args.inputs.keyboard.key_up.truthy_keys.length > 0)
args.state.help_available = true
args.state.no_activity_debounce = nil
else
args.state.no_activity_debounce ||= 5.seconds
args.state.no_activity_debounce -= 1
if args.state.no_activity_debounce <= 0
args.state.help_available = false
args.state.key_value_history = {}
args.state.key_down_value_history = {}
args.state.key_held_value_history = {}
args.state.key_up_value_history = {}
end
end
args.outputs.labels << { x: 10, y: row_to_px(args, 6), text: "This is the api for the keys you've pressed:", size_enum: -1, r: 180 }
if !args.state.help_available
args.outputs.labels << [10, row_to_px(args, 7), "Press a key and I'll show code to access the key and what value will be returned if you used the code.", small_font]
return
end
args.outputs.labels << { x: 10 , y: row_to_px(args, 7), text: "args.inputs.keyboard", size_enum: -2 }
args.outputs.labels << { x: 330, y: row_to_px(args, 7), text: "args.inputs.keyboard.key_down", size_enum: -2 }
args.outputs.labels << { x: 650, y: row_to_px(args, 7), text: "args.inputs.keyboard.key_held", size_enum: -2 }
args.outputs.labels << { x: 990, y: row_to_px(args, 7), text: "args.inputs.keyboard.key_up", size_enum: -2 }
fill_history args, :key_value_history, :down_or_held, nil
fill_history args, :key_down_value_history, :down, :key_down
fill_history args, :key_held_value_history, :held, :key_held
fill_history args, :key_up_value_history, :up, :key_up
render_help_labels args, :key_value_history, :down_or_held, nil, 10
render_help_labels args, :key_down_value_history, :down, :key_down, 330
render_help_labels args, :key_held_value_history, :held, :key_held, 650
render_help_labels args, :key_up_value_history, :up, :key_up, 990
end
def fill_history args, history_key, state_key, keyboard_method
fill_single_history args, history_key, state_key, keyboard_method, :raw_key
fill_single_history args, history_key, state_key, keyboard_method, :char
args.inputs.keyboard.keys[state_key].each do |key_name|
fill_single_history args, history_key, state_key, keyboard_method, key_name
end
end
def fill_single_history args, history_key, state_key, keyboard_method, key_name
current_value = args.inputs.keyboard.send(key_name)
if keyboard_method
current_value = args.inputs.keyboard.send(keyboard_method).send(key_name)
end
args.state.as_hash[history_key][key_name] ||= []
args.state.as_hash[history_key][key_name] << current_value
args.state.as_hash[history_key][key_name] = args.state.as_hash[history_key][key_name].reverse.uniq.take(3).reverse
end
def render_help_labels args, history_key, state_key, keyboard_method, x
idx = 8
args.outputs.labels << args.state
.as_hash[history_key]
.keys
.reverse
.map
.with_index do |k, i|
v = args.state.as_hash[history_key][k]
current_value = args.inputs.keyboard.send(k)
if keyboard_method
current_value = args.inputs.keyboard.send(keyboard_method).send(k)
end
idx += 2
[
{ x: x, y: row_to_px(args, idx + 0, 16), text: " .#{k} is #{current_value || "nil"}", size_enum: -2 },
{ x: x, y: row_to_px(args, idx + 1, 16), text: " was #{v}", size_enum: -2 }
]
end
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << { x: 0, y: y - 50, w: 1280, h: 60 }.solid!
args.outputs.debug << { x: 640, y: y, text: text,
size_enum: 1, alignment_enum: 1, r: 255, g: 255, b: 255 }.label!
args.outputs.debug << { x: 640, y: y - 25, text: "(click to dismiss instructions)",
size_enum: -2, alignment_enum: 1, r: 255, g: 255, b: 255 }.label!
end
</code></pre>
<h3 id='----input-basics---moving-a-sprite---main-rb'>Input Basics - Moving A Sprite - main.rb</h3>
<pre><code class="language-ruby"># ./samples/02_input_basics/01_moving_a_sprite/app/main.rb
def tick args
# create a player and set default values
# for the player's x, y, w (width), and h (height)
args.state.player.x ||= 100
args.state.player.y ||= 100
args.state.player.w ||= 50
args.state.player.h ||= 50
# render the player to the screen
args.outputs.sprites << { x: args.state.player.x,
y: args.state.player.y,
w: args.state.player.w,
h: args.state.player.h,
path: 'sprites/square/green.png' }
# move the player around using the keyboard
if args.inputs.up
args.state.player.y += 10
elsif args.inputs.down
args.state.player.y -= 10
end
if args.inputs.left
args.state.player.x -= 10
elsif args.inputs.right
args.state.player.x += 10
end
end
$gtk.reset
</code></pre>
<h3 id='----input-basics---mouse---main-rb'>Input Basics - Mouse - main.rb</h3>
<pre><code class="language-ruby"># ./samples/02_input_basics/02_mouse/app/main.rb
=begin
APIs that haven't been encountered in a previous sample apps:
- args.inputs.mouse.click: This property will be set if the mouse was clicked.
- args.inputs.mouse.click.point.(x|y): The x and y location of the mouse.
- args.inputs.mouse.click.point.created_at: The frame the mouse click occurred in.
- args.inputs.mouse.click.point.created_at_elapsed: How many frames have passed
since the click event.
Reminder:
- args.state.PROPERTY: The state property on args is a dynamic
structure. You can define ANY property here with ANY type of
arbitrary nesting. Properties defined on args.state will be retained
across frames. If you attempt access a property that doesn't exist
on args.state, it will simply return nil (no exception will be thrown).
=end
# This code demonstrates DragonRuby mouse input
# To see if the a mouse click occurred
# Use args.inputs.mouse.click
# Which returns a boolean
# To see where a mouse click occurred
# Use args.inputs.mouse.click.point.x AND
# args.inputs.mouse.click.point.y
# To see which frame the click occurred
# Use args.inputs.mouse.click.created_at
# To see how many frames its been since the click occurred
# Use args.inputs.mouse.click.creat_at_elapsed
# Saving the click in args.state can be quite useful
def tick args
tick_instructions args, "Sample app shows how mouse events are registered and how to measure elapsed time."
x = 460
args.outputs.labels << small_label(args, x, 11, "Mouse input: args.inputs.mouse")
if args.inputs.mouse.click
args.state.last_mouse_click = args.inputs.mouse.click
end
if args.state.last_mouse_click
click = args.state.last_mouse_click
args.outputs.labels << small_label(args, x, 12, "Mouse click happened at: #{click.created_at}")
args.outputs.labels << small_label(args, x, 13, "Mouse clicked #{click.created_at_elapsed} ticks ago")
args.outputs.labels << small_label(args, x, 14, "Mouse click location: #{click.point.x}, #{click.point.y}")
else
args.outputs.labels << small_label(args, x, 12, "Mouse click has not occurred yet.")
args.outputs.labels << small_label(args, x, 13, "Please click mouse.")
end
end
def small_label args, x, row, message
# This method effectively combines the row_to_px and small_font methods
# It changes the given row value to a DragonRuby pixel value
# and adds the customization parameters
{ x: x, y: row_to_px(args, row), text: message, alignment_enum: -2 }
end
def row_to_px args, row_number
args.grid.top.shift_down(5).shift_down(20 * row_number)
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << { x: 0, y: y - 50, w: 1280, h: 60 }.solid!
args.outputs.debug << { x: 640, y: y, text: text, size_enum: 1, alignment_enum: 1, r: 255, g: 255, b: 255 }.label!
args.outputs.debug << { x: 640, y: y - 25, text: "(click to dismiss instructions)", size_enum: -2, alignment_enum: 1, r: 255, g: 255, b: 255 }.label!
end
</code></pre>
<h3 id='----input-basics---mouse-point-to-rect---main-rb'>Input Basics - Mouse Point To Rect - main.rb</h3>
<pre><code class="language-ruby"># ./samples/02_input_basics/03_mouse_point_to_rect/app/main.rb
=begin
APIs that haven't been encountered in a previous sample apps:
- args.outputus.borders: An array. Values in this array will be rendered as
unfilled rectangles on the screen.
- ARRAY#inside_rect?: An array with at least two values is considered a point. An array
with at least four values is considered a rect. The inside_rect? function returns true
or false depending on if the point is inside the rect.
```
# Point: x: 100, y: 100
# Rect: x: 0, y: 0, w: 500, h: 500
# Result: true
[100, 100].inside_rect? [0, 0, 500, 500]
```
```
# Point: x: 100, y: 100
# Rect: x: 300, y: 300, w: 100, h: 100
# Result: false
[100, 100].inside_rect? [300, 300, 100, 100]
```
- args.inputs.mouse.click.point.created_at: The frame the mouse click occurred in.
- args.inputs.mouse.click.point.created_at_elapsed: How many frames have passed
since the click event.
=end
# To determine whether a point is in a rect
# Use point.inside_rect? rect
# This is useful to determine if a click occurred in a rect
def tick args
tick_instructions args, "Sample app shows how to determing if a click happened inside a rectangle."
x = 460
args.outputs.labels << small_label(args, x, 15, "Click inside the blue box maybe ---->")
box = { x: 785, y: 370, w: 50, h: 50, r: 0, g: 0, b: 170 }
args.outputs.borders << box
# Saves the most recent click into args.state
# Unlike the other components of args,
# args.state does not reset every tick.
if args.inputs.mouse.click
args.state.last_mouse_click = args.inputs.mouse.click
end
if args.state.last_mouse_click
if args.state.last_mouse_click.point.inside_rect? box
args.outputs.labels << small_label(args, x, 16, "Mouse click happened *inside* the box.")
else
args.outputs.labels << small_label(args, x, 16, "Mouse click happened *outside* the box.")
end
else
args.outputs.labels << small_label(args, x, 16, "Mouse click has not occurred yet.")
end
end
def small_label args, x, row, message
{ x: x, y: row_to_px(args, row), text: message, size_enum: -2 }
end
def row_to_px args, row_number
args.grid.top.shift_down(5).shift_down(20 * row_number)
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << { x: 0, y: y - 50, w: 1280, h: 60 }.solid!
args.outputs.debug << { x: 640, y: y, text: text, size_enum: 1, alignment_enum: 1, r: 255, g: 255, b: 255 }.label!
args.outputs.debug << { x: 640, y: y - 25, text: "(click to dismiss instructions)", size_enum: -2, alignment_enum: 1, r: 255, g: 255, b: 255 }.label!
end
</code></pre>
<h3 id='----input-basics---mouse-rect-to-rect---main-rb'>Input Basics - Mouse Rect To Rect - main.rb</h3>
<pre><code class="language-ruby"># ./samples/02_input_basics/04_mouse_rect_to_rect/app/main.rb
=begin
APIs that haven't been encountered in a previous sample apps:
- args.outputs.borders: An array. Values in this array will be rendered as
unfilled rectangles on the screen.
- ARRAY#intersect_rect?: An array with at least four values is
considered a rect. The intersect_rect? function returns true
or false depending on if the two rectangles intersect.
```
# Rect One: x: 100, y: 100, w: 100, h: 100
# Rect Two: x: 0, y: 0, w: 500, h: 500
# Result: true
[100, 100, 100, 100].intersect_rect? [0, 0, 500, 500]
```
```
# Rect One: x: 100, y: 100, w: 10, h: 10
# Rect Two: x: 500, y: 500, w: 10, h: 10
# Result: false
[100, 100, 10, 10].intersect_rect? [500, 500, 10, 10]
```
=end
# Similarly, whether rects intersect can be found through
# rect1.intersect_rect? rect2
def tick args
tick_instructions args, "Sample app shows how to determine if two rectangles intersect."
x = 460
args.outputs.labels << small_label(args, x, 3, "Click anywhere on the screen")
# red_box = [460, 250, 355, 90, 170, 0, 0]
# args.outputs.borders << red_box
# args.state.box_collision_one and args.state.box_collision_two
# Are given values of a solid when they should be rendered
# They are stored in game so that they do not get reset every tick
if args.inputs.mouse.click
if !args.state.box_collision_one
args.state.box_collision_one = { x: args.inputs.mouse.click.point.x - 25,
y: args.inputs.mouse.click.point.y - 25,
w: 125, h: 125,
r: 180, g: 0, b: 0, a: 180 }
elsif !args.state.box_collision_two
args.state.box_collision_two = { x: args.inputs.mouse.click.point.x - 25,
y: args.inputs.mouse.click.point.y - 25,
w: 125, h: 125,
r: 0, g: 0, b: 180, a: 180 }
else
args.state.box_collision_one = nil
args.state.box_collision_two = nil
end
end
if args.state.box_collision_one
args.outputs.solids << args.state.box_collision_one
end
if args.state.box_collision_two
args.outputs.solids << args.state.box_collision_two
end
if args.state.box_collision_one && args.state.box_collision_two
if args.state.box_collision_one.intersect_rect? args.state.box_collision_two
args.outputs.labels << small_label(args, x, 4, 'The boxes intersect.')
else
args.outputs.labels << small_label(args, x, 4, 'The boxes do not intersect.')
end
else
args.outputs.labels << small_label(args, x, 4, '--')
end
end
def small_label args, x, row, message
{ x: x, y: row_to_px(args, row), text: message, size_enum: -2 }
end
def row_to_px args, row_number
args.grid.top - 5 - (20 * row_number)
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----input-basics---controller---main-rb'>Input Basics - Controller - main.rb</h3>
<pre><code class="language-ruby"># ./samples/02_input_basics/05_controller/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- args.inputs.controller_one.key_held.KEY: Will check to see if a specific key
is being held down on the controller.
If there is more than one controller being used, they can be differentiated by
using names like controller_one and controller_two.
For a full listing of buttons, take a look at mygame/documentation/08-controllers.md.
Reminder:
- args.state.PROPERTY: The state property on args is a dynamic
structure. You can define ANY property here with ANY type of
arbitrary nesting. Properties defined on args.state will be retained
across frames. If you attempt to access a property that doesn't exist
on args.state, it will simply return nil (no exception will be thrown).
In this sample app, args.state.BUTTONS is an array that stores the buttons of the controller.
The parameters of a button are:
1. the position (x, y)
2. the input key held on the controller
3. the text or name of the button
=end
# This sample app provides a visual demonstration of a standard controller, including
# the placement and function of all buttons.
class ControllerDemo
attr_accessor :inputs, :state, :outputs
# Calls the methods necessary for the app to run successfully.
def tick
process_inputs
render
end
# Starts with an empty collection of buttons.
# Adds buttons that are on the controller to the collection.
def process_inputs
state.buttons = []
state.buttons << { x: 100, y: 500, active: inputs.controller_one.key_held.l1, text: "L1"}
state.buttons << { x: 100, y: 600, active: inputs.controller_one.key_held.l2, text: "L2"}
state.buttons << { x: 1100, y: 500, active: inputs.controller_one.key_held.r1, text: "R1"}
state.buttons << { x: 1100, y: 600, active: inputs.controller_one.key_held.r2, text: "R2"}
state.buttons << { x: 540, y: 450, active: inputs.controller_one.key_held.select, text: "Select"}
state.buttons << { x: 660, y: 450, active: inputs.controller_one.key_held.start, text: "Start"}
state.buttons << { x: 200, y: 300, active: inputs.controller_one.key_held.left, text: "Left"}
state.buttons << { x: 300, y: 400, active: inputs.controller_one.key_held.up, text: "Up"}
state.buttons << { x: 400, y: 300, active: inputs.controller_one.key_held.right, text: "Right"}
state.buttons << { x: 300, y: 200, active: inputs.controller_one.key_held.down, text: "Down"}
state.buttons << { x: 800, y: 300, active: inputs.controller_one.key_held.x, text: "X"}
state.buttons << { x: 900, y: 400, active: inputs.controller_one.key_held.y, text: "Y"}
state.buttons << { x: 1000, y: 300, active: inputs.controller_one.key_held.a, text: "A"}
state.buttons << { x: 900, y: 200, active: inputs.controller_one.key_held.b, text: "B"}
state.buttons << { x: 450 + inputs.controller_one.left_analog_x_perc * 100,
y: 100 + inputs.controller_one.left_analog_y_perc * 100,
active: inputs.controller_one.key_held.l3,
text: "L3" }
state.buttons << { x: 750 + inputs.controller_one.right_analog_x_perc * 100,
y: 100 + inputs.controller_one.right_analog_y_perc * 100,
active: inputs.controller_one.key_held.r3,
text: "R3" }
end
# Gives each button a square shape.
# If the button is being pressed or held (which means it is considered active),
# the square is filled in. Otherwise, the button simply has a border.
def render
state.buttons.each do |b|
rect = { x: b.x, y: b.y, w: 75, h: 75 }
if b.active # if button is pressed
outputs.solids << rect # rect is output as solid (filled in)
else
outputs.borders << rect # otherwise, output as border
end
# Outputs the text of each button using labels.
outputs.labels << { x: b.x, y: b.y + 95, text: b.text } # add 95 to place label above button
end
outputs.labels << { x: 10, y: 60, text: "Left Analog x: #{inputs.controller_one.left_analog_x_raw} (#{inputs.controller_one.left_analog_x_perc * 100}%)" }
outputs.labels << { x: 10, y: 30, text: "Left Analog y: #{inputs.controller_one.left_analog_y_raw} (#{inputs.controller_one.left_analog_y_perc * 100}%)" }
outputs.labels << { x: 900, y: 60, text: "Right Analog x: #{inputs.controller_one.right_analog_x_raw} (#{inputs.controller_one.right_analog_x_perc * 100}%)" }
outputs.labels << { x: 900, y: 30, text: "Right Analog y: #{inputs.controller_one.right_analog_y_raw} (#{inputs.controller_one.right_analog_y_perc * 100}%)" }
end
end
$controller_demo = ControllerDemo.new
def tick args
tick_instructions args, "Sample app shows how controller input is handled. You'll need to connect a USB controller."
$controller_demo.inputs = args.inputs
$controller_demo.state = args.state
$controller_demo.outputs = args.outputs
$controller_demo.tick
end
# Resets the app.
def r
$gtk.reset
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----input-basics---touch---main-rb'>Input Basics - Touch - main.rb</h3>
<pre><code class="language-ruby"># ./samples/02_input_basics/06_touch/app/main.rb
def tick args
args.outputs.background_color = [ 0, 0, 0 ]
args.outputs.primitives << [640, 700, "Touch your screen.", 5, 1, 255, 255, 255].label
# If you don't want to get fancy, you can just look for finger_one
# (and _two, if you like), which are assigned in the order new touches hit
# the screen. If not nil, they are touching right now, and are just
# references to specific items in the args.input.touch hash.
# If finger_one lifts off, it will become nil, but finger_two, if it was
# touching, remains until it also lifts off. When all fingers lift off, the
# the next new touch will be finger_one again, but until then, new touches
# don't fill in earlier slots.
if !args.inputs.finger_one.nil?
args.outputs.primitives << { x: 640, y: 650, text: "Finger #1 is touching at (#{args.inputs.finger_one.x}, #{args.inputs.finger_one.y}).",
size_enum: 5, alignment_enum: 1, r: 255, g: 255, b: 255 }.label!
end
if !args.inputs.finger_two.nil?
args.outputs.primitives << { x: 640, y: 600, text: "Finger #2 is touching at (#{args.inputs.finger_two.x}, #{args.inputs.finger_two.y}).",
size_enum: 5, alignment_enum: 1, r: 255, g: 255, b: 255 }.label!
end
# Here's the more flexible interface: this will report as many simultaneous
# touches as the system can handle, but it's a little more effort to track
# them. Each item in the args.input.touch hash has a unique key (an
# incrementing integer) that exists until the finger lifts off. You can
# tell which order the touches happened globally by the key value, or
# by the touch[id].touch_order field, which resets to zero each time all
# touches have lifted.
args.state.colors ||= [
0xFF0000, 0x00FF00, 0x1010FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0xFFFFFF
]
size = 100
args.inputs.touch.each { |k,v|
color = args.state.colors[v.touch_order % 7]
r = (color & 0xFF0000) >> 16
g = (color & 0x00FF00) >> 8
b = (color & 0x0000FF)
args.outputs.primitives << { x: v.x - (size / 2), y: v.y + (size / 2), w: size, h: size, r: r, g: g, b: b, a: 255 }.solid!
args.outputs.primitives << { x: v.x, y: v.y + size, text: k.to_s, alignment_enum: 1 }.label!
}
end
</code></pre>
<h3 id='----rendering-sprites---animation-using-separate-pngs---main-rb'>Rendering Sprites - Animation Using Separate Pngs - main.rb</h3>
<pre><code class="language-ruby"># ./samples/03_rendering_sprites/01_animation_using_separate_pngs/app/main.rb
=begin
Reminders:
- String interpolation: Uses #{} syntax; everything between the #{ and the } is evaluated
as Ruby code, and the placeholder is replaced with its corresponding value or result.
In this sample app, we're using string interpolation to iterate through images in the
sprites folder using their image path names.
- args.outputs.sprites: An array. Values in this array generate sprites on the screen.
The parameters are [X, Y, WIDTH, HEIGHT, IMAGE PATH]
For more information about sprites, go to mygame/documentation/05-sprites.md.
- args.outputs.labels: An array. Values in the array generate labels on the screen.
The parameters are [X, Y, TEXT, SIZE, ALIGNMENT, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.md.
- args.inputs.keyboard.key_down.KEY: Determines if a key is in the down state, or pressed.
Stores the frame that key was pressed on.
For more information about the keyboard, go to mygame/documentation/06-keyboard.md.
=end
# This sample app demonstrates how sprite animations work.
# There are two sprites that animate forever and one sprite
# that *only* animates when you press the "f" key on the keyboard.
# This is the entry point to your game. The `tick` method
# executes at 60 frames per second. There are two methods
# in this tick "entry point": `looping_animation`, and the
# second method is `one_time_animation`.
def tick args
# uncomment the line below to see animation play out in slow motion
# args.gtk.slowmo! 6
looping_animation args
one_time_animation args
end
# This function shows how to animate a sprite that loops forever.
def looping_animation args
# Here we define a few local variables that will be sent
# into the magic function that gives us the correct sprite image
# over time. There are four things we need in order to figure
# out which sprite to show.
# 1. When to start the animation.
start_looping_at = 0
# 2. The number of pngs that represent the full animation.
number_of_sprites = 6
# 3. How long to show each png.
number_of_frames_to_show_each_sprite = 4
# 4. Whether the animation should loop once, or forever.
does_sprite_loop = true
# With the variables defined above, we can get a number
# which represents the sprite to show by calling the `frame_index` function.
# In this case the number will be between 0, and 5 (you can see the sprites
# in the ./sprites directory).
sprite_index = start_looping_at.frame_index number_of_sprites,
number_of_frames_to_show_each_sprite,
does_sprite_loop
# Now that we have `sprite_index, we can present the correct file.
args.outputs.sprites << { x: 100, y: 100, w: 100, h: 100, path: "sprites/dragon_fly_#{sprite_index}.png" }
# Try changing the numbers below to see how the animation changes:
args.outputs.sprites << { x: 100, y: 200, w: 100, h: 100, path: "sprites/dragon_fly_#{0.frame_index 6, 4, true}.png" }
end
# This function shows how to animate a sprite that executes
# only once when the "f" key is pressed.
def one_time_animation args
# This is just a label the shows instructions within the game.
args.outputs.labels << { x: 220, y: 350, text: "(press f to animate)" }
# If "f" is pressed on the keyboard...
if args.inputs.keyboard.key_down.f
# Print the frame that "f" was pressed on.
puts "Hello from main.rb! The \"f\" key was in the down state on frame: #{args.state.tick_count}"
# And MOST IMPORTANTLY set the point it time to start the animation,
# equal to "now" which is represented as args.state.tick_count.
# Also IMPORTANT, you'll notice that the value of when to start looping
# is stored in `args.state`. This construct's values are retained across
# executions of the `tick` method.
args.state.start_looping_at = args.state.tick_count
end
# These are the same local variables that were defined
# for the `looping_animation` function.
number_of_sprites = 6
number_of_frames_to_show_each_sprite = 4
# Except this sprite does not loop again. If the animation time has passed,
# then the frame_index function returns nil.
does_sprite_loop = false
sprite_index = args.state
.start_looping_at
.frame_index number_of_sprites,
number_of_frames_to_show_each_sprite,
does_sprite_loop
# This line sets the frame index to zero, if
# the animation duration has passed (frame_index returned nil).
# Remeber: we are not looping forever here.
sprite_index ||= 0
# Present the sprite.
args.outputs.sprites << { x: 100, y: 300, w: 100, h: 100, path: "sprites/dragon_fly_#{sprite_index}.png" }
tick_instructions args, "Sample app shows how to use Numeric#frame_index and string interpolation to animate a sprite over time."
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----rendering-sprites---animation-using-sprite-sheet---main-rb'>Rendering Sprites - Animation Using Sprite Sheet - main.rb</h3>
<pre><code class="language-ruby"># ./samples/03_rendering_sprites/02_animation_using_sprite_sheet/app/main.rb
def tick args
args.state.player.x ||= 100
args.state.player.y ||= 100
args.state.player.w ||= 64
args.state.player.h ||= 64
args.state.player.direction ||= 1
args.state.player.is_moving = false
# get the keyboard input and set player properties
if args.inputs.keyboard.right
args.state.player.x += 3
args.state.player.direction = 1
args.state.player.started_running_at ||= args.state.tick_count
elsif args.inputs.keyboard.left
args.state.player.x -= 3
args.state.player.direction = -1
args.state.player.started_running_at ||= args.state.tick_count
end
if args.inputs.keyboard.up
args.state.player.y += 1
args.state.player.started_running_at ||= args.state.tick_count
elsif args.inputs.keyboard.down
args.state.player.y -= 1
args.state.player.started_running_at ||= args.state.tick_count
end
# if no arrow keys are being pressed, set the player as not moving
if !args.inputs.keyboard.directional_vector
args.state.player.started_running_at = nil
end
# wrap player around the stage
if args.state.player.x > 1280
args.state.player.x = -64
args.state.player.started_running_at ||= args.state.tick_count
elsif args.state.player.x < -64
args.state.player.x = 1280
args.state.player.started_running_at ||= args.state.tick_count
end
if args.state.player.y > 720
args.state.player.y = -64
args.state.player.started_running_at ||= args.state.tick_count
elsif args.state.player.y < -64
args.state.player.y = 720
args.state.player.started_running_at ||= args.state.tick_count
end
# render player as standing or running
if args.state.player.started_running_at
args.outputs.sprites << running_sprite(args)
else
args.outputs.sprites << standing_sprite(args)
end
args.outputs.labels << [30, 700, "Use arrow keys to move around."]
end
def standing_sprite args
{
x: args.state.player.x,
y: args.state.player.y,
w: args.state.player.w,
h: args.state.player.h,
path: "sprites/horizontal-stand.png",
flip_horizontally: args.state.player.direction > 0
}
end
def running_sprite args
if !args.state.player.started_running_at
tile_index = 0
else
how_many_frames_in_sprite_sheet = 6
how_many_ticks_to_hold_each_frame = 3
should_the_index_repeat = true
tile_index = args.state
.player
.started_running_at
.frame_index(how_many_frames_in_sprite_sheet,
how_many_ticks_to_hold_each_frame,
should_the_index_repeat)
end
{
x: args.state.player.x,
y: args.state.player.y,
w: args.state.player.w,
h: args.state.player.h,
path: 'sprites/horizontal-run.png',
tile_x: 0 + (tile_index * args.state.player.w),
tile_y: 0,
tile_w: args.state.player.w,
tile_h: args.state.player.h,
flip_horizontally: args.state.player.direction > 0,
}
end
</code></pre>
<h3 id='----rendering-sprites---animation-states---main-rb'>Rendering Sprites - Animation States - main.rb</h3>
<pre><code class="language-ruby"># ./samples/03_rendering_sprites/03_animation_states/app/main.rb
class Game
attr_gtk
def defaults
state.show_debug_layer = true if state.tick_count == 0
player.tile_size = 64
player.speed = 3
player.slash_frames = 15
player.x ||= 50
player.y ||= 400
player.dir_x ||= 1
player.dir_y ||= -1
player.is_moving ||= false
state.watch_list ||= {}
state.enemies ||= []
end
def add_enemy
state.enemies << { x: 1200 * rand, y: 600 * rand, w: 64, h: 64 }
end
def sprite_horizontal_run
tile_index = 0.frame_index(6, 3, true)
tile_index = 0 if !player.is_moving
{
x: player.x,
y: player.y,
w: player.tile_size,
h: player.tile_size,
path: 'sprites/horizontal-run.png',
tile_x: 0 + (tile_index * player.tile_size),
tile_y: 0,
tile_w: player.tile_size,
tile_h: player.tile_size,
flip_horizontally: player.dir_x > 0,
# a: 40
}
end
def sprite_horizontal_stand
{
x: player.x,
y: player.y,
w: player.tile_size,
h: player.tile_size,
path: 'sprites/horizontal-stand.png',
flip_horizontally: player.dir_x > 0,
# a: 40
}
end
def sprite_horizontal_slash
tile_index = player.slash_at.frame_index(5, player.slash_frames.idiv(5), false) || 0
{
x: player.x - 41.25,
y: player.y - 41.25,
w: 165,
h: 165,
path: 'sprites/horizontal-slash.png',
tile_x: 0 + (tile_index * 128),
tile_y: 0,
tile_w: 128,
tile_h: 128,
flip_horizontally: player.dir_x > 0
}
end
def render_player
if player.slash_at
outputs.sprites << sprite_horizontal_slash
elsif player.is_moving
outputs.sprites << sprite_horizontal_run
else
outputs.sprites << sprite_horizontal_stand
end
end
def render_enemies
outputs.borders << state.enemies
end
def render_debug_layer
return if !state.show_debug_layer
outputs.labels << state.watch_list.map.with_index do |(k, v), i|
[30, 710 - i * 28, "#{k}: #{v || "(nil)"}"]
end
outputs.borders << player.slash_collision_rect
end
def slash_initiate?
# buffalo usb controller has a button and b button swapped lol
inputs.controller_one.key_down.a || inputs.keyboard.key_down.j
end
def input
# player movement
if slash_complete? && (vector = inputs.directional_vector)
player.x += vector.x * player.speed
player.y += vector.y * player.speed
end
player.slash_at = slash_initiate? if slash_initiate?
end
def calc_movement
# movement
if vector = inputs.directional_vector
state.debug_label = vector
player.dir_x = vector.x
player.dir_y = vector.y
player.is_moving = true
else
state.debug_label = vector
player.is_moving = false
end
end
def calc_slash
# re-calc the location of the swords collision box
if player.dir_x.positive?
player.slash_collision_rect = [player.x + player.tile_size,
player.y + player.tile_size.half - 10,
40, 20]
else
player.slash_collision_rect = [player.x - 32 - 8,
player.y + player.tile_size.half - 10,
40, 20]
end
# recalc sword's slash state
player.slash_at = nil if slash_complete?
# determine collision if the sword is at it's point of damaging
return unless slash_can_damage?
state.enemies.reject! { |e| e.intersect_rect? player.slash_collision_rect }
end
def slash_complete?
!player.slash_at || player.slash_at.elapsed?(player.slash_frames)
end
def slash_can_damage?
# damage occurs half way into the slash animation
return false if slash_complete?
return false if (player.slash_at + player.slash_frames.idiv(2)) != state.tick_count
return true
end
def calc
# generate an enemy if there aren't any on the screen
add_enemy if state.enemies.length == 0
calc_movement
calc_slash
end
# source is at http://github.com/amirrajan/dragonruby-link-to-the-past
def tick
defaults
render_enemies
render_player
outputs.labels << [30, 30, "Gamepad: D-Pad to move. B button to attack."]
outputs.labels << [30, 52, "Keyboard: WASD/Arrow keys to move. J to attack."]
render_debug_layer
input
calc
end
def player
state.player
end
end
$game = Game.new
def tick args
$game.args = args
$game.tick
end
$gtk.reset
</code></pre>
<h3 id='----rendering-sprites---color-and-rotation---main-rb'>Rendering Sprites - Color And Rotation - main.rb</h3>
<pre><code class="language-ruby"># ./samples/03_rendering_sprites/04_color_and_rotation/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- merge: Returns a hash containing the contents of two original hashes.
Merge does not allow duplicate keys, so the value of a repeated key
will be overwritten.
For example, if we had two hashes
h1 = { "a" => 1, "b" => 2}
h2 = { "b" => 3, "c" => 3}
and we called the command
h1.merge(h2)
the result would the following hash
{ "a" => 1, "b" => 3, "c" => 3}.
Reminders:
- Hashes: Collection of unique keys and their corresponding values. The value can be found
using their keys.
In this sample app, we're using a hash to create a sprite.
- args.outputs.sprites: An array. The values generate a sprite.
The parameters are [X, Y, WIDTH, HEIGHT, PATH, ANGLE, ALPHA, RED, GREEN, BLUE]
Before continuing with this sample app, it is HIGHLY recommended that you look
at mygame/documentation/05-sprites.md.
- args.inputs.keyboard.key_held.KEY: Determines if a key is being pressed.
For more information about the keyboard, go to mygame/documentation/06-keyboard.md.
- args.inputs.controller_one: Takes input from the controller based on what key is pressed.
For more information about the controller, go to mygame/documentation/08-controllers.md.
- num1.lesser(num2): Finds the lower value of the given options.
=end
# This sample app shows a car moving across the screen. It loops back around if it exceeds the dimensions of the screen,
# and also can be moved in different directions through keyboard input from the user.
# Calls the methods necessary for the game to run successfully.
def tick args
default args
render args.grid, args.outputs, args.state
calc args.state
process_inputs args
end
# Sets default values for the car sprite
# Initialization ||= only happens in the first frame
def default args
args.state.sprite.width = 19
args.state.sprite.height = 10
args.state.sprite.scale = 4
args.state.max_speed = 5
args.state.x ||= 100
args.state.y ||= 100
args.state.speed ||= 1
args.state.angle ||= 0
end
# Outputs sprite onto screen
def render grid, outputs, state
outputs.solids << [grid.rect, 70, 70, 70] # outputs gray background
outputs.sprites << [destination_rect(state), # sets first four parameters of car sprite
'sprites/86.png', # image path of car
state.angle,
opacity, # transparency
saturation,
source_rect(state), # sprite sub division/tile (tile x, y, w, h)
false, false, # don't flip sprites
rotation_anchor]
# also look at the create_sprite helper method
#
# For example:
#
# dest = destination_rect(state)
# source = source_rect(state),
# outputs.sprites << create_sprite(
# 'sprites/86.png',
# x: dest.x,
# y: dest.y,
# w: dest.w,
# h: dest.h,
# angle: state.angle,
# source_x: source.x,
# source_y: source.y,
# source_w: source.w,
# source_h: source.h,
# flip_h: false,
# flip_v: false,
# rotation_anchor_x: 0.7,
# rotation_anchor_y: 0.5
# )
end
# Creates sprite by setting values inside of a hash
def create_sprite path, options = {}
options = {
# dest x, y, w, h
x: 0,
y: 0,
w: 100,
h: 100,
# angle, rotation
angle: 0,
rotation_anchor_x: 0.5,
rotation_anchor_y: 0.5,
# color saturation (red, green, blue), transparency
r: 255,
g: 255,
b: 255,
a: 255,
# source x, y, width, height
source_x: 0,
source_y: 0,
source_w: -1,
source_h: -1,
# flip horiztonally, flip vertically
flip_h: false,
flip_v: false,
}.merge options
[
options[:x], options[:y], options[:w], options[:h], # dest rect keys
path,
options[:angle], options[:a], options[:r], options[:g], options[:b], # angle, color, alpha
options[:source_x], options[:source_y], options[:source_w], options[:source_h], # source rect keys
options[:flip_h], options[:flip_v], # flip
options[:rotation_anchor_x], options[:rotation_anchor_y], # rotation anchor
] # hash keys contain corresponding values
end
# Calls the calc_pos and calc_wrap methods.
def calc state
calc_pos state
calc_wrap state
end
# Changes sprite's position on screen
# Vectors have magnitude and direction, so the incremented x and y values give the car direction
def calc_pos state
state.x += state.angle.vector_x * state.speed # increments x by product of angle's x vector and speed
state.y += state.angle.vector_y * state.speed # increments y by product of angle's y vector and speed
state.speed *= 1.1 # scales speed up
state.speed = state.speed.lesser(state.max_speed) # speed is either current speed or max speed, whichever has a lesser value (ensures that the car doesn't go too fast or exceed the max speed)
end
# The screen's dimensions are 1280x720. If the car goes out of scope,
# it loops back around on the screen.
def calc_wrap state
# car returns to left side of screen if it disappears on right side of screen
# sprite.width refers to tile's size, which is multipled by scale (4) to make it bigger
state.x = -state.sprite.width * state.sprite.scale if state.x - 20 > 1280
# car wraps around to right side of screen if it disappears on the left side
state.x = 1280 if state.x + state.sprite.width * state.sprite.scale + 20 < 0
# car wraps around to bottom of screen if it disappears at the top of the screen
# if you subtract 520 pixels instead of 20 pixels, the car takes longer to reappear (try it!)
state.y = 0 if state.y - 20 > 720 # if 20 pixels less than car's y position is greater than vertical scope
# car wraps around to top of screen if it disappears at the bottom of the screen
state.y = 720 if state.y + state.sprite.height * state.sprite.scale + 20 < 0
end
# Changes angle of sprite based on user input from keyboard or controller
def process_inputs args
# NOTE: increasing the angle doesn't mean that the car will continue to go
# in a specific direction. The angle is increasing, which means that if the
# left key was kept in the "down" state, the change in the angle would cause
# the car to go in a counter-clockwise direction and form a circle (360 degrees)
if args.inputs.keyboard.key_held.left # if left key is pressed
args.state.angle += 2 # car's angle is incremented by 2
# The same applies to decreasing the angle. If the right key was kept in the
# "down" state, the decreasing angle would cause the car to go in a clockwise
# direction and form a circle (360 degrees)
elsif args.inputs.keyboard.key_held.right # if right key is pressed
args.state.angle -= 2 # car's angle is decremented by 2
# Input from a controller can also change the angle of the car
elsif args.inputs.controller_one.left_analog_x_perc != 0
args.state.angle += 2 * args.inputs.controller_one.left_analog_x_perc * -1
end
end
# A sprite's center of rotation can be altered
# Increasing either of these numbers would dramatically increase the
# car's drift when it turns!
def rotation_anchor
[0.7, 0.5]
end
# Sets opacity value of sprite to 255 so that it is not transparent at all
# Change it to 0 and you won't be able to see the car sprite on the screen
def opacity
255
end
# Sets the color of the sprite to white.
def saturation
[255, 255, 255]
end
# Sets definition of destination_rect (used to define the car sprite)
def destination_rect state
[state.x, state.y,
state.sprite.width * state.sprite.scale, # multiplies by 4 to set size
state.sprite.height * state.sprite.scale]
end
# Portion of a sprite (a tile)
# Sub division of sprite is denoted as a rectangle directly related to original size of .png
# Tile is located at bottom left corner within a 19x10 pixel rectangle (based on sprite.width, sprite.height)
def source_rect state
[0, 0, state.sprite.width, state.sprite.height]
end
</code></pre>
<h3 id='----physics-and-collisions---simple---main-rb'>Physics And Collisions - Simple - main.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/01_simple/app/main.rb
=begin
Reminders:
- ARRAY#intersect_rect?: Returns true or false depending on if the two rectangles intersect.
- args.outputs.solids: An array. The values generate a solid.
The parameters are [X, Y, WIDTH, HEIGHT, RED, GREEN, BLUE]
=end
# This sample app shows collisions between two boxes.
# Runs methods needed for game to run properly.
def tick args
tick_instructions args, "Sample app shows how to move a square over time and determine collision."
defaults args
render args
calc args
end
# Sets default values.
def defaults args
# These values represent the moving box.
args.state.moving_box_speed = 10
args.state.moving_box_size = 100
args.state.moving_box_dx ||= 1
args.state.moving_box_dy ||= 1
args.state.moving_box ||= [0, 0, args.state.moving_box_size, args.state.moving_box_size] # moving_box_size is set as the width and height
# These values represent the center box.
args.state.center_box ||= [540, 260, 200, 200, 180]
args.state.center_box_collision ||= false # initially no collision
end
def render args
# If the game state denotes that a collision has occured,
# render a solid square, otherwise render a border instead.
if args.state.center_box_collision
args.outputs.solids << args.state.center_box
else
args.outputs.borders << args.state.center_box
end
# Then render the moving box.
args.outputs.solids << args.state.moving_box
end
# Generally in a pipeline for a game engine, you have rendering,
# game simulation (calculation), and input processing.
# This fuction represents the game simulation.
def calc args
position_moving_box args
determine_collision_center_box args
end
# Changes the position of the moving box on the screen by multiplying the change in x (dx) and change in y (dy) by the speed,
# and adding it to the current position.
# dx and dy are positive if the box is moving right and up, respectively
# dx and dy are negative if the box is moving left and down, respectively
def position_moving_box args
args.state.moving_box.x += args.state.moving_box_dx * args.state.moving_box_speed
args.state.moving_box.y += args.state.moving_box_dy * args.state.moving_box_speed
# 1280x720 are the virtual pixels you work with (essentially 720p).
screen_width = 1280
screen_height = 720
# Position of the box is denoted by the bottom left hand corner, in
# that case, we have to subtract the width of the box so that it stays
# in the scene (you can try deleting the subtraction to see how it
# impacts the box's movement).
if args.state.moving_box.x > screen_width - args.state.moving_box_size
args.state.moving_box_dx = -1 # moves left
elsif args.state.moving_box.x < 0
args.state.moving_box_dx = 1 # moves right
end
# Here, we're making sure the moving box remains within the vertical scope of the screen
if args.state.moving_box.y > screen_height - args.state.moving_box_size # if the box moves too high
args.state.moving_box_dy = -1 # moves down
elsif args.state.moving_box.y < 0 # if the box moves too low
args.state.moving_box_dy = 1 # moves up
end
end
def determine_collision_center_box args
# Collision is handled by the engine. You simply have to call the
# `intersect_rect?` function.
if args.state.moving_box.intersect_rect? args.state.center_box # if the two boxes intersect
args.state.center_box_collision = true # then a collision happened
else
args.state.center_box_collision = false # otherwise, no collision happened
end
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----physics-and-collisions---moving-objects---main-rb'>Physics And Collisions - Moving Objects - main.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/02_moving_objects/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- Hashes: Collection of unique keys and their corresponding values. The value can be found
using their keys.
For example, if we have a "numbers" hash that stores numbers in English as the
key and numbers in Spanish as the value, we'd have a hash that looks like this...
numbers = { "one" => "uno", "two" => "dos", "three" => "tres" }
and on it goes.
Now if we wanted to find the corresponding value of the "one" key, we could say
puts numbers["one"]
which would print "uno" to the console.
- num1.greater(num2): Returns the greater value.
For example, if we have the command
puts 4.greater(3)
the number 4 would be printed to the console since it has a greater value than 3.
Similar to lesser, which returns the lesser value.
- num1.lesser(num2): Finds the lower value of the given options.
For example, in the statement
a = 4.lesser(3)
3 has a lower value than 4, which means that the value of a would be set to 3,
but if the statement had been
a = 4.lesser(5)
4 has a lower value than 5, which means that the value of a would be set to 4.
- reject: Removes elements from a collection if they meet certain requirements.
For example, you can derive an array of odd numbers from an original array of
numbers 1 through 10 by rejecting all elements that are even (or divisible by 2).
- find_all: Finds all values that satisfy specific requirements.
For example, you can find all elements of a collection that are divisible by 2
or find all objects that have intersected with another object.
- abs: Returns the absolute value.
For example, the command
(-30).abs
would return 30 as a result.
- map: Ruby method used to transform data; used in arrays, hashes, and collections.
Can be used to perform an action on every element of a collection, such as multiplying
each element by 2 or declaring every element as a new entity.
Reminders:
- args.inputs.keyboard.KEY: Determines if a key has been pressed.
For more information about the keyboard, take a look at mygame/documentation/06-keyboard.md.
- ARRAY#intersect_rect?: Returns true or false depending on if the two rectangles intersect.
- args.outputs.solids: An array. The values generate a solid.
The parameters are [X, Y, WIDTH, HEIGHT, RED, GREEN, BLUE]
For more information about solids, go to mygame/documentation/03-solids-and-borders.md.
=end
# Calls methods needed for game to run properly
def tick args
tick_instructions args, "Use LEFT and RIGHT arrow keys to move and SPACE to jump."
defaults args
render args
calc args
input args
end
# sets default values and creates empty collections
# initialization only happens in the first frame
def defaults args
fiddle args
args.state.enemy.hammers ||= []
args.state.enemy.hammer_queue ||= []
args.state.tick_count = args.state.tick_count
args.state.bridge_top = 128
args.state.player.x ||= 0 # initializes player's properties
args.state.player.y ||= args.state.bridge_top
args.state.player.w ||= 64
args.state.player.h ||= 64
args.state.player.dy ||= 0
args.state.player.dx ||= 0
args.state.enemy.x ||= 800 # initializes enemy's properties
args.state.enemy.y ||= 0
args.state.enemy.w ||= 128
args.state.enemy.h ||= 128
args.state.enemy.dy ||= 0
args.state.enemy.dx ||= 0
args.state.game_over_at ||= 0
end
# sets enemy, player, hammer values
def fiddle args
args.state.gravity = -0.3
args.state.enemy_jump_power = 10 # sets enemy values
args.state.enemy_jump_interval = 60
args.state.hammer_throw_interval = 40 # sets hammer values
args.state.hammer_launch_power_default = 5
args.state.hammer_launch_power_near = 2
args.state.hammer_launch_power_far = 7
args.state.hammer_upward_launch_power = 15
args.state.max_hammers_per_volley = 10
args.state.gap_between_hammers = 10
args.state.player_jump_power = 10 # sets player values
args.state.player_jump_power_duration = 10
args.state.player_max_run_speed = 10
args.state.player_speed_slowdown_rate = 0.9
args.state.player_acceleration = 1
args.state.hammer_size = 32
end
# outputs objects onto the screen
def render args
args.outputs.solids << 20.map_with_index do |i| # uses 20 squares to form bridge
# sets x by multiplying 64 to index to find pixel value (places all squares side by side)
# subtracts 64 from bridge_top because position is denoted by bottom left corner
[i * 64, args.state.bridge_top - 64, 64, 64]
end
args.outputs.solids << [args.state.x, args.state.y, args.state.w, args.state.h, 255, 0, 0]
args.outputs.solids << [args.state.player.x, args.state.player.y, args.state.player.w, args.state.player.h, 255, 0, 0] # outputs player onto screen (red box)
args.outputs.solids << [args.state.enemy.x, args.state.enemy.y, args.state.enemy.w, args.state.enemy.h, 0, 255, 0] # outputs enemy onto screen (green box)
args.outputs.solids << args.state.enemy.hammers # outputs enemy's hammers onto screen
end
# Performs calculations to move objects on the screen
def calc args
# Since velocity is the change in position, the change in x increases by dx. Same with y and dy.
args.state.player.x += args.state.player.dx
args.state.player.y += args.state.player.dy
# Since acceleration is the change in velocity, the change in y (dy) increases every frame
args.state.player.dy += args.state.gravity
# player's y position is either current y position or y position of top of
# bridge, whichever has a greater value
# ensures that the player never goes below the bridge
args.state.player.y = args.state.player.y.greater(args.state.bridge_top)
# player's x position is either the current x position or 0, whichever has a greater value
# ensures that the player doesn't go too far left (out of the screen's scope)
args.state.player.x = args.state.player.x.greater(0)
# player is not falling if it is located on the top of the bridge
args.state.player.falling = false if args.state.player.y == args.state.bridge_top
args.state.player.rect = [args.state.player.x, args.state.player.y, args.state.player.h, args.state.player.w] # sets definition for player
args.state.enemy.x += args.state.enemy.dx # velocity; change in x increases by dx
args.state.enemy.y += args.state.enemy.dy # same with y and dy
# ensures that the enemy never goes below the bridge
args.state.enemy.y = args.state.enemy.y.greater(args.state.bridge_top)
# ensures that the enemy never goes too far left (outside the screen's scope)
args.state.enemy.x = args.state.enemy.x.greater(0)
# objects that go up must come down because of gravity
args.state.enemy.dy += args.state.gravity
args.state.enemy.y = args.state.enemy.y.greater(args.state.bridge_top)
#sets definition of enemy
args.state.enemy.rect = [args.state.enemy.x, args.state.enemy.y, args.state.enemy.h, args.state.enemy.w]
if args.state.enemy.y == args.state.bridge_top # if enemy is located on the top of the bridge
args.state.enemy.dy = 0 # there is no change in y
end
# if 60 frames have passed and the enemy is not moving vertically
if args.state.tick_count.mod_zero?(args.state.enemy_jump_interval) && args.state.enemy.dy == 0
args.state.enemy.dy = args.state.enemy_jump_power # the enemy jumps up
end
# if 40 frames have passed or 5 frames have passed since the game ended
if args.state.tick_count.mod_zero?(args.state.hammer_throw_interval) || args.state.game_over_at.elapsed_time == 5
# rand will return a number greater than or equal to 0 and less than given variable's value (since max is excluded)
# that is why we're adding 1, to include the max possibility
volley_dx = (rand(args.state.hammer_launch_power_default) + 1) * -1 # horizontal movement (follow order of operations)
# if the horizontal distance between the player and enemy is less than 128 pixels
if (args.state.player.x - args.state.enemy.x).abs < 128
# the change in x won't be that great since the enemy and player are closer to each other
volley_dx = (rand(args.state.hammer_launch_power_near) + 1) * -1
end
# if the horizontal distance between the player and enemy is greater than 300 pixels
if (args.state.player.x - args.state.enemy.x).abs > 300
# change in x will be more drastic since player and enemy are so far apart
volley_dx = (rand(args.state.hammer_launch_power_far) + 1) * -1 # more drastic change
end
(rand(args.state.max_hammers_per_volley) + 1).map_with_index do |i|
args.state.enemy.hammer_queue << { # stores hammer values in a hash
x: args.state.enemy.x,
w: args.state.hammer_size,
h: args.state.hammer_size,
dx: volley_dx, # change in horizontal position
# multiplication operator takes precedence over addition operator
throw_at: args.state.tick_count + i * args.state.gap_between_hammers
}
end
end
# add elements from hammer_queue collection to the hammers collection by
# finding all hammers that were thrown before the current frame (have already been thrown)
args.state.enemy.hammers += args.state.enemy.hammer_queue.find_all do |h|
h[:throw_at] < args.state.tick_count
end
args.state.enemy.hammers.each do |h| # sets values for all hammers in collection
h[:y] ||= args.state.enemy.y + 130
h[:dy] ||= args.state.hammer_upward_launch_power
h[:dy] += args.state.gravity # acceleration is change in gravity
h[:x] += h[:dx] # incremented by change in position
h[:y] += h[:dy]
h[:rect] = [h[:x], h[:y], h[:w], h[:h]] # sets definition of hammer's rect
end
# reject hammers that have been thrown before current frame (have already been thrown)
args.state.enemy.hammer_queue = args.state.enemy.hammer_queue.reject do |h|
h[:throw_at] < args.state.tick_count
end
# any hammers with a y position less than 0 are rejected from the hammers collection
# since they have gone too far down (outside the scope's screen)
args.state.enemy.hammers = args.state.enemy.hammers.reject { |h| h[:y] < 0 }
# if there are any hammers that intersect with (or hit) the player,
# the reset_player method is called (so the game can start over)
if args.state.enemy.hammers.any? { |h| h[:rect].intersect_rect?(args.state.player.rect) }
reset_player args
end
# if the enemy's rect intersects with (or hits) the player,
# the reset_player method is called (so the game can start over)
if args.state.enemy.rect.intersect_rect? args.state.player.rect
reset_player args
end
end
# Resets the player by changing its properties back to the values they had at initialization
def reset_player args
args.state.player.x = 0
args.state.player.y = args.state.bridge_top
args.state.player.dy = 0
args.state.player.dx = 0
args.state.enemy.hammers.clear # empties hammer collection
args.state.enemy.hammer_queue.clear # empties hammer_queue
args.state.game_over_at = args.state.tick_count # game_over_at set to current frame (or passage of time)
end
# Processes input from the user to move the player
def input args
if args.inputs.keyboard.space # if the user presses the space bar
args.state.player.jumped_at ||= args.state.tick_count # jumped_at is set to current frame
# if the time that has passed since the jump is less than the player's jump duration and
# the player is not falling
if args.state.player.jumped_at.elapsed_time < args.state.player_jump_power_duration && !args.state.player.falling
args.state.player.dy = args.state.player_jump_power # change in y is set to power of player's jump
end
end
# if the space bar is in the "up" state (or not being pressed down)
if args.inputs.keyboard.key_up.space
args.state.player.jumped_at = nil # jumped_at is empty
args.state.player.falling = true # the player is falling
end
if args.inputs.keyboard.left # if left key is pressed
args.state.player.dx -= args.state.player_acceleration # dx decreases by acceleration (player goes left)
# dx is either set to current dx or the negative max run speed (which would be -10),
# whichever has a greater value
args.state.player.dx = args.state.player.dx.greater(-args.state.player_max_run_speed)
elsif args.inputs.keyboard.right # if right key is pressed
args.state.player.dx += args.state.player_acceleration # dx increases by acceleration (player goes right)
# dx is either set to current dx or max run speed (which would be 10),
# whichever has a lesser value
args.state.player.dx = args.state.player.dx.lesser(args.state.player_max_run_speed)
else
args.state.player.dx *= args.state.player_speed_slowdown_rate # dx is scaled down
end
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.space ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----physics-and-collisions---entities---main-rb'>Physics And Collisions - Entities - main.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/03_entities/app/main.rb
=begin
Reminders:
- map: Ruby method used to transform data; used in arrays, hashes, and collections.
Can be used to perform an action on every element of a collection, such as multiplying
each element by 2 or declaring every element as a new entity.
- reject: Removes elements from a collection if they meet certain requirements.
For example, you can derive an array of odd numbers from an original array of
numbers 1 through 10 by rejecting all elements that are even (or divisible by 2).
- args.state.new_entity: Used when we want to create a new object, like a sprite or button.
In this sample app, new_entity is used to define the properties of enemies and bullets.
(Remember, you can use state to define ANY property and it will be retained across frames.)
- args.outputs.labels: An array. The values generate a label on the screen.
The parameters are [X, Y, TEXT, SIZE, ALIGN, RED, GREEN, BLUE, ALPHA, FONT STYLE]
- ARRAY#intersect_rect?: Returns true or false depending on if the two rectangles intersect.
- args.inputs.mouse.click.point.(x|y): The x and y location of the mouse.
=end
# This sample app shows enemies that contain an id value and the time they were created.
# These enemies can be removed by shooting at them with bullets.
# Calls all methods necessary for the game to function properly.
def tick args
tick_instructions args, "Sample app shows how to use args.state.new_entity along with collisions. CLICK to shoot a bullet."
defaults args
render args
calc args
process_inputs args
end
# Sets default values
# Enemies and bullets start off as empty collections
def defaults args
args.state.enemies ||= []
args.state.bullets ||= []
end
# Provides each enemy in enemies collection with rectangular border,
# as well as a label showing id and when they were created
def render args
# When you're calling a method that takes no arguments, you can use this & syntax on map.
# Numbers are being added to x and y in order to keep the text within the enemy's borders.
args.outputs.borders << args.state.enemies.map(&:rect)
args.outputs.labels << args.state.enemies.flat_map do |enemy|
[
[enemy.x + 4, enemy.y + 29, "id: #{enemy.entity_id}", -3, 0],
[enemy.x + 4, enemy.y + 17, "created_at: #{enemy.created_at}", -3, 0] # frame enemy was created
]
end
# Outputs bullets in bullets collection as rectangular solids
args.outputs.solids << args.state.bullets.map(&:rect)
end
# Calls all methods necessary for performing calculations
def calc args
add_new_enemies_if_needed args
move_bullets args
calculate_collisions args
remove_bullets_of_screen args
end
# Adds enemies to the enemies collection and sets their values
def add_new_enemies_if_needed args
return if args.state.enemies.length >= 10 # if 10 or more enemies, enemies are not added
return unless args.state.bullets.length == 0 # if user has not yet shot bullet, no enemies are added
args.state.enemies += (10 - args.state.enemies.length).map do # adds enemies so there are 10 total
args.state.new_entity(:enemy) do |e| # each enemy is declared as a new entity
e.x = 640 + 500 * rand # each enemy is given random position on screen
e.y = 600 * rand + 50
e.rect = [e.x, e.y, 130, 30] # sets definition for enemy's rect
end
end
end
# Moves bullets across screen
# Sets definition of the bullets
def move_bullets args
args.state.bullets.each do |bullet| # perform action on each bullet in collection
bullet.x += bullet.speed # increment x by speed (bullets fly horizontally across screen)
# By randomizing the value that increments bullet.y, the bullet does not fly straight up and out
# of the scope of the screen. Try removing what follows bullet.speed, or changing 0.25 to 1.25 to
# see what happens to the bullet's movement.
bullet.y += bullet.speed.*(0.25).randomize(:ratio, :sign)
bullet.rect = [bullet.x, bullet.y, bullet.size, bullet.size] # sets definition of bullet's rect
end
end
# Determines if a bullet hits an enemy
def calculate_collisions args
args.state.bullets.each do |bullet| # perform action on every bullet and enemy in collections
args.state.enemies.each do |enemy|
# if bullet has not exploded yet and the bullet hits an enemy
if !bullet.exploded && bullet.rect.intersect_rect?(enemy.rect)
bullet.exploded = true # bullet explodes
enemy.dead = true # enemy is killed
end
end
end
# All exploded bullets are rejected or removed from the bullets collection
# and any dead enemy is rejected from the enemies collection.
args.state.bullets = args.state.bullets.reject(&:exploded)
args.state.enemies = args.state.enemies.reject(&:dead)
end
# Bullets are rejected from bullets collection once their position exceeds the width of screen
def remove_bullets_of_screen args
args.state.bullets = args.state.bullets.reject { |bullet| bullet.x > 1280 } # screen width is 1280
end
# Calls fire_bullet method
def process_inputs args
fire_bullet args
end
# Once mouse is clicked by the user to fire a bullet, a new bullet is added to bullets collection
def fire_bullet args
return unless args.inputs.mouse.click # return unless mouse is clicked
args.state.bullets << args.state.new_entity(:bullet) do |bullet| # new bullet is declared a new entity
bullet.y = args.inputs.mouse.click.point.y # set to the y value of where the mouse was clicked
bullet.x = 0 # starts on the left side of the screen
bullet.size = 10
bullet.speed = 10 * rand + 2 # speed of a bullet is randomized
bullet.rect = [bullet.x, bullet.y, bullet.size, bullet.size] # definition is set
end
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.space ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----physics-and-collisions---box-collision---main-rb'>Physics And Collisions - Box Collision - main.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/04_box_collision/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- first: Returns the first element of the array.
For example, if we have an array
numbers = [1, 2, 3, 4, 5]
and we call first by saying
numbers.first
the number 1 will be returned because it is the first element of the numbers array.
- num1.idiv(num2): Divides two numbers and returns an integer.
For example,
16.idiv(3) = 5, because 16 / 3 is 5.33333 returned as an integer.
16.idiv(4) = 4, because 16 / 4 is 4 and already has no decimal.
Reminders:
- find_all: Finds all values that satisfy specific requirements.
- ARRAY#intersect_rect?: An array with at least four values is
considered a rect. The intersect_rect? function returns true
or false depending on if the two rectangles intersect.
- reject: Removes elements from a collection if they meet certain requirements.
=end
# This sample app allows users to create tiles and place them anywhere on the screen as obstacles.
# The player can then move and maneuver around them.
class PoorManPlatformerPhysics
attr_accessor :grid, :inputs, :state, :outputs
# Calls all methods necessary for the app to run successfully.
def tick
defaults
render
calc
process_inputs
end
# Sets default values for variables.
# The ||= sign means that the variable will only be set to the value following the = sign if the value has
# not already been set before. Intialization happens only in the first frame.
def defaults
state.tile_size = 64
state.gravity = -0.2
state.previous_tile_size ||= state.tile_size
state.x ||= 0
state.y ||= 800
state.dy ||= 0
state.dx ||= 0
state.world ||= []
state.world_lookup ||= {}
state.world_collision_rects ||= []
end
# Outputs solids and borders of different colors for the world and collision_rects collections.
def render
# Sets a black background on the screen (Comment this line out and the background will become white.)
# Also note that black is the default color for when no color is assigned.
outputs.solids << grid.rect
# The position, size, and color (white) are set for borders given to the world collection.
# Try changing the color by assigning different numbers (between 0 and 255) to the last three parameters.
outputs.borders << state.world.map do |x, y|
[x * state.tile_size,
y * state.tile_size,
state.tile_size,
state.tile_size, 255, 255, 255]
end
# The top, bottom, and sides of the borders for collision_rects are different colors.
outputs.borders << state.world_collision_rects.map do |e|
[
[e[:top], 0, 170, 0], # top is a shade of green
[e[:bottom], 0, 100, 170], # bottom is a shade of greenish-blue
[e[:left_right], 170, 0, 0], # left and right are a shade of red
]
end
# Sets the position, size, and color (a shade of green) of the borders of only the player's
# box and outputs it. If you change the 180 to 0, the player's box will be black and you
# won't be able to see it (because it will match the black background).
outputs.borders << [state.x,
state.y,
state.tile_size,
state.tile_size, 0, 180, 0]
end
# Calls methods needed to perform calculations.
def calc
calc_world_lookup
calc_player
end
# Performs calculations on world_lookup and sets values.
def calc_world_lookup
# If the tile size isn't equal to the previous tile size,
# the previous tile size is set to the tile size,
# and world_lookup hash is set to empty.
if state.tile_size != state.previous_tile_size
state.previous_tile_size = state.tile_size
state.world_lookup = {} # empty hash
end
# return if the world_lookup hash has keys (or, in other words, is not empty)
# return unless the world collection has values inside of it (or is not empty)
return if state.world_lookup.keys.length > 0
return unless state.world.length > 0
# Starts with an empty hash for world_lookup.
# Searches through the world and finds the coordinates that exist.
state.world_lookup = {}
state.world.each { |x, y| state.world_lookup[[x, y]] = true }
# Assigns world_collision_rects for every sprite drawn.
state.world_collision_rects =
state.world_lookup
.keys
.map do |coord_x, coord_y|
s = state.tile_size
# multiply by tile size so the grid coordinates; sets pixel value
# don't forget that position is denoted by bottom left corner
# set x = coord_x or y = coord_y and see what happens!
x = s * coord_x
y = s * coord_y
{
# The values added to x, y, and s position the world_collision_rects so they all appear
# stacked (on top of world rects) but don't directly overlap.
# Remove these added values and mess around with the rect placement!
args: [coord_x, coord_y],
left_right: [x, y + 4, s, s - 6], # hash keys and values
top: [x + 4, y + 6, s - 8, s - 6],
bottom: [x + 1, y - 1, s - 2, s - 8],
}
end
end
# Performs calculations to change the x and y values of the player's box.
def calc_player
# Since acceleration is the change in velocity, the change in y (dy) increases every frame.
# What goes up must come down because of gravity.
state.dy += state.gravity
# Calls the calc_box_collision and calc_edge_collision methods.
calc_box_collision
calc_edge_collision
# Since velocity is the change in position, the change in y increases by dy. Same with x and dx.
state.y += state.dy
state.x += state.dx
# Scales dx down.
state.dx *= 0.8
end
# Calls methods needed to determine collisions between player and world_collision rects.
def calc_box_collision
return unless state.world_lookup.keys.length > 0 # return unless hash has atleast 1 key
collision_floor!
collision_left!
collision_right!
collision_ceiling!
end
# Finds collisions between the bottom of the player's rect and the top of a world_collision_rect.
def collision_floor!
return unless state.dy <= 0 # return unless player is going down or is as far down as possible
player_rect = [state.x, state.y - 0.1, state.tile_size, state.tile_size] # definition of player
# Goes through world_collision_rects to find all intersections between the bottom of player's rect and
# the top of a world_collision_rect (hence the "-0.1" above)
floor_collisions = state.world_collision_rects
.find_all { |r| r[:top].intersect_rect?(player_rect, collision_tollerance) }
.first
return unless floor_collisions # return unless collision occurred
state.y = floor_collisions[:top].top # player's y is set to the y of the top of the collided rect
state.dy = 0 # if a collision occurred, the player's rect isn't moving because its path is blocked
end
# Finds collisions between the player's left side and the right side of a world_collision_rect.
def collision_left!
return unless state.dx < 0 # return unless player is moving left
player_rect = [state.x - 0.1, state.y, state.tile_size, state.tile_size]
# Goes through world_collision_rects to find all intersections beween the player's left side and the
# right side of a world_collision_rect.
left_side_collisions = state.world_collision_rects
.find_all { |r| r[:left_right].intersect_rect?(player_rect, collision_tollerance) }
.first
return unless left_side_collisions # return unless collision occurred
# player's x is set to the value of the x of the collided rect's right side
state.x = left_side_collisions[:left_right].right
state.dx = 0 # player isn't moving left because its path is blocked
end
# Finds collisions between the right side of the player and the left side of a world_collision_rect.
def collision_right!
return unless state.dx > 0 # return unless player is moving right
player_rect = [state.x + 0.1, state.y, state.tile_size, state.tile_size]
# Goes through world_collision_rects to find all intersections between the player's right side
# and the left side of a world_collision_rect (hence the "+0.1" above)
right_side_collisions = state.world_collision_rects
.find_all { |r| r[:left_right].intersect_rect?(player_rect, collision_tollerance) }
.first
return unless right_side_collisions # return unless collision occurred
# player's x is set to the value of the collided rect's left, minus the size of a rect
# tile size is subtracted because player's position is denoted by bottom left corner
state.x = right_side_collisions[:left_right].left - state.tile_size
state.dx = 0 # player isn't moving right because its path is blocked
end
# Finds collisions between the top of the player's rect and the bottom of a world_collision_rect.
def collision_ceiling!
return unless state.dy > 0 # return unless player is moving up
player_rect = [state.x, state.y + 0.1, state.tile_size, state.tile_size]
# Goes through world_collision_rects to find intersections between the bottom of a
# world_collision_rect and the top of the player's rect (hence the "+0.1" above)
ceil_collisions = state.world_collision_rects
.find_all { |r| r[:bottom].intersect_rect?(player_rect, collision_tollerance) }
.first
return unless ceil_collisions # return unless collision occurred
# player's y is set to the bottom y of the rect it collided with, minus the size of a rect
state.y = ceil_collisions[:bottom].y - state.tile_size
state.dy = 0 # if a collision occurred, the player isn't moving up because its path is blocked
end
# Makes sure the player remains within the screen's dimensions.
def calc_edge_collision
#Ensures that the player doesn't fall below the map.
if state.y < 0
state.y = 0
state.dy = 0
#Ensures that the player doesn't go too high.
# Position of player is denoted by bottom left hand corner, which is why we have to subtract the
# size of the player's box (so it remains visible on the screen)
elsif state.y > 720 - state.tile_size # if the player's y position exceeds the height of screen
state.y = 720 - state.tile_size # the player will remain as high as possible while staying on screen
state.dy = 0
end
# Ensures that the player remains in the horizontal range that it is supposed to.
if state.x >= 1280 - state.tile_size && state.dx > 0 # if player moves too far right
state.x = 1280 - state.tile_size # player will remain as right as possible while staying on screen
state.dx = 0
elsif state.x <= 0 && state.dx < 0 # if player moves too far left
state.x = 0 # player will remain as left as possible while remaining on screen
state.dx = 0
end
end
# Processes input from the user on the keyboard.
def process_inputs
if inputs.mouse.down
state.world_lookup = {}
x, y = to_coord inputs.mouse.down.point # gets x, y coordinates for the grid
if state.world.any? { |loc| loc == [x, y] } # checks if coordinates duplicate
state.world = state.world.reject { |loc| loc == [x, y] } # erases tile space
else
state.world << [x, y] # If no duplicates, adds to world collection
end
end
# Sets dx to 0 if the player lets go of arrow keys.
if inputs.keyboard.key_up.right
state.dx = 0
elsif inputs.keyboard.key_up.left
state.dx = 0
end
# Sets dx to 3 in whatever direction the player chooses.
if inputs.keyboard.key_held.right # if right key is pressed
state.dx = 3
elsif inputs.keyboard.key_held.left # if left key is pressed
state.dx = -3
end
#Sets dy to 5 to make the player ~fly~ when they press the space bar
if inputs.keyboard.key_held.space
state.dy = 5
end
end
def to_coord point
# Integer divides (idiv) point.x to turn into grid
# Then, you can just multiply each integer by state.tile_size later so the grid coordinates.
[point.x.idiv(state.tile_size), point.y.idiv(state.tile_size)]
end
# Represents the tolerance for a collision between the player's rect and another rect.
def collision_tollerance
0.0
end
end
$platformer_physics = PoorManPlatformerPhysics.new
def tick args
$platformer_physics.grid = args.grid
$platformer_physics.inputs = args.inputs
$platformer_physics.state = args.state
$platformer_physics.outputs = args.outputs
$platformer_physics.tick
tick_instructions args, "Sample app shows platformer collisions. CLICK to place box. ARROW keys to move around. SPACE to jump."
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----physics-and-collisions---box-collision-2---main-rb'>Physics And Collisions - Box Collision 2 - main.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/05_box_collision_2/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- times: Performs an action a specific number of times.
For example, if we said
5.times puts "Hello DragonRuby",
then we'd see the words "Hello DragonRuby" printed on the console 5 times.
- split: Divides a string into substrings based on a delimiter.
For example, if we had a command
"DragonRuby is awesome".split(" ")
then the result would be
["DragonRuby", "is", "awesome"] because the words are separated by a space delimiter.
- join: Opposite of split; converts each element of array to a string separated by delimiter.
For example, if we had a command
["DragonRuby","is","awesome"].join(" ")
then the result would be
"DragonRuby is awesome".
Reminders:
- to_s: Returns a string representation of an object.
For example, if we had
500.to_s
the string "500" would be returned.
Similar to to_i, which returns an integer representation of an object.
- elapsed_time: How many frames have passed since the click event.
- args.outputs.labels: An array. Values in the array generate labels on the screen.
The parameters are: [X, Y, TEXT, SIZE, ALIGN, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.md.
- inputs.mouse.down: Determines whether or not the mouse is being pressed down.
The position of the mouse when it is pressed down can be found using inputs.mouse.down.point.(x|y).
- first: Returns the first element of the array.
- num1.idiv(num2): Divides two numbers and returns an integer.
- find_all: Finds all values that satisfy specific requirements.
- ARRAY#intersect_rect?: Returns true or false depending on if two rectangles intersect.
- reject: Removes elements from a collection if they meet certain requirements.
- String interpolation: Uses #{} syntax; everything between the #{ and the } is evaluated
as Ruby code, and the placeholder is replaced with its corresponding value or result.
=end
MAP_FILE_PATH = 'app/map.txt' # the map.txt file in the app folder contains exported map
class MetroidvaniaStarter
attr_accessor :grid, :inputs, :state, :outputs, :gtk
# Calls methods needed to run the game properly.
def tick
defaults
render
calc
process_inputs
end
# Sets all the default variables.
# '||' states that initialization occurs only in the first frame.
def defaults
state.tile_size = 64
state.gravity = -0.2
state.player_width = 60
state.player_height = 64
state.collision_tolerance = 0.0
state.previous_tile_size ||= state.tile_size
state.x ||= 0
state.y ||= 800
state.dy ||= 0
state.dx ||= 0
attempt_load_world_from_file
state.world_lookup ||= { }
state.world_collision_rects ||= []
state.mode ||= :creating # alternates between :creating and :selecting for sprite selection
state.select_menu ||= [0, 720, 1280, 720]
#=======================================IMPORTANT=======================================#
# When adding sprites, please label them "image1.png", "image2.png", image3".png", etc.
# Once you have done that, adjust "state.sprite_quantity" to how many sprites you have.
#=======================================================================================#
state.sprite_quantity ||= 20 # IMPORTANT TO ALTER IF SPRITES ADDED IF YOU ADD MORE SPRITES
state.sprite_coords ||= []
state.banner_coords ||= [640, 680 + 720]
state.sprite_selected ||= 1
state.map_saved_at ||= 0
# Sets all the cordinate values for the sprite selection screen into a grid
# Displayed when 's' is pressed by player to access sprites
if state.sprite_coords == [] # if sprite_coords is an empty array
count = 1
temp_x = 165 # sets a starting x and y position for display
temp_y = 500 + 720
state.sprite_quantity.times do # for the number of sprites you have
state.sprite_coords += [[temp_x, temp_y, count]] # add element to sprite_coords array
temp_x += 100 # increment temp_x
count += 1 # increment count
if temp_x > 1280 - (165 + 50) # if exceeding specific horizontal width on screen
temp_x = 165 # a new row of sprites starts
temp_y -= 75 # new row of sprites starts 75 units lower than the previous row
end
end
end
end
# Places sprites
def render
# Sets the x, y, width, height, and image path for each sprite in the world collection.
outputs.sprites << state.world.map do |x, y, sprite|
[x * state.tile_size, # multiply by size so grid coordinates; pixel value of location
y * state.tile_size,
state.tile_size,
state.tile_size,
'sprites/image' + sprite.to_s + '.png'] # uses concatenation to create unique image path
end
# Outputs sprite for the player by setting x, y, width, height, and image path
outputs.sprites << [state.x,
state.y,
state.player_width,
state.player_height,'sprites/player.png']
# Outputs labels as primitives in top right of the screen
outputs.primitives << [920, 700, 'Press \'s\' to access sprites.', 1, 0].label
outputs.primitives << [920, 675, 'Click existing sprite to delete.', 1, 0].label
outputs.primitives << [920, 640, '<- and -> to move.', 1, 0].label
outputs.primitives << [920, 615, 'Press and hold space to jump.', 1, 0].label
outputs.primitives << [920, 580, 'Press \'e\' to export current map.', 1, 0].label
# if the map is saved and less than 120 frames have passed, the label is displayed
if state.map_saved_at > 0 && state.map_saved_at.elapsed_time < 120
outputs.primitives << [920, 555, 'Map has been exported!', 1, 0, 50, 100, 50].label
end
# If player hits 's', following appears
if state.mode == :selecting
# White background for sprite selection
outputs.primitives << [state.select_menu, 255, 255, 255].solid
# Select tile label at the top of the screen
outputs.primitives << [state.banner_coords.x, state.banner_coords.y, "Select Sprite (sprites located in \"sprites\" folder)", 10, 1, 0, 0, 0, 255].label
# Places sprites in locations calculated in the defaults function
outputs.primitives << state.sprite_coords.map do |x, y, order|
[x, y, 50, 50, 'sprites/image' + order.to_s + ".png"].sprite
end
end
# Creates sprite following mouse to help indicate which sprite you have selected
# 10 is subtracted from the mouse's x position so that the sprite is not covered by the mouse icon
outputs.primitives << [inputs.mouse.position.x - 10, inputs.mouse.position.y,
10, 10, 'sprites/image' + state.sprite_selected.to_s + ".png"].sprite
end
# Calls methods that perform calculations
def calc
calc_in_game
calc_sprite_selection
end
# Calls methods that perform calculations (if in creating mode)
def calc_in_game
return unless state.mode == :creating
calc_world_lookup
calc_player
end
def calc_world_lookup
# If the tile size isn't equal to the previous tile size,
# the previous tile size is set to the tile size,
# and world_lookup hash is set to empty.
if state.tile_size != state.previous_tile_size
state.previous_tile_size = state.tile_size
state.world_lookup = {}
end
# return if world_lookup is not empty or if world is empty
return if state.world_lookup.keys.length > 0
return unless state.world.length > 0
# Searches through the world and finds the coordinates that exist
state.world_lookup = {}
state.world.each { |x, y| state.world_lookup[[x, y]] = true }
# Assigns collision rects for every sprite drawn
state.world_collision_rects =
state.world_lookup
.keys
.map do |coord_x, coord_y|
s = state.tile_size
# Multiplying by s (the size of a tile) ensures that the rect is
# placed exactly where you want it to be placed (causes grid to coordinate)
# How many pixels horizontally across and vertically up and down
x = s * coord_x
y = s * coord_y
{
args: [coord_x, coord_y],
left_right: [x, y + 4, s, s - 6], # hash keys and values
top: [x + 4, y + 6, s - 8, s - 6],
bottom: [x + 1, y - 1, s - 2, s - 8],
}
end
end
# Calculates movement of player and calls methods that perform collision calculations
def calc_player
state.dy += state.gravity # what goes up must come down because of gravity
calc_box_collision
calc_edge_collision
state.y += state.dy # Since velocity is the change in position, the change in y increases by dy
state.x += state.dx # Ditto line above but dx and x
state.dx *= 0.8 # Scales dx down
end
# Calls methods that determine whether the player collides with any world_collision_rects.
def calc_box_collision
return unless state.world_lookup.keys.length > 0 # return unless hash has atleast 1 key
collision_floor
collision_left
collision_right
collision_ceiling
end
# Finds collisions between the bottom of the player's rect and the top of a world_collision_rect.
def collision_floor
return unless state.dy <= 0 # return unless player is going down or is as far down as possible
player_rect = [state.x, next_y, state.tile_size, state.tile_size] # definition of player
# Runs through all the sprites on the field and finds all intersections between player's
# bottom and the top of a rect.
floor_collisions = state.world_collision_rects
.find_all { |r| r[:top].intersect_rect?(player_rect, state.collision_tolerance) }
.first
return unless floor_collisions # performs following changes if a collision has occurred
state.y = floor_collisions[:top].top # y of player is set to the y of the colliding rect's top
state.dy = 0 # no change in y because the player's path is blocked
end
# Finds collisions between the player's left side and the right side of a world_collision_rect.
def collision_left
return unless state.dx < 0 # return unless player is moving left
player_rect = [next_x, state.y, state.tile_size, state.tile_size]
# Runs through all the sprites on the field and finds all intersections between the player's left side
# and the right side of a rect.
left_side_collisions = state.world_collision_rects
.find_all { |r| r[:left_right].intersect_rect?(player_rect, state.collision_tolerance) }
.first
return unless left_side_collisions # return unless collision occurred
state.x = left_side_collisions[:left_right].right # sets player's x to the x of the colliding rect's right side
state.dx = 0 # no change in x because the player's path is blocked
end
# Finds collisions between the right side of the player and the left side of a world_collision_rect.
def collision_right
return unless state.dx > 0 # return unless player is moving right
player_rect = [next_x, state.y, state.tile_size, state.tile_size]
# Runs through all the sprites on the field and finds all intersections between the player's
# right side and the left side of a rect.
right_side_collisions = state.world_collision_rects
.find_all { |r| r[:left_right].intersect_rect?(player_rect, state.collision_tolerance) }
.first
return unless right_side_collisions # return unless collision occurred
state.x = right_side_collisions[:left_right].left - state.tile_size # player's x is set to the x of colliding rect's left side (minus tile size since x is the player's bottom left corner)
state.dx = 0 # no change in x because the player's path is blocked
end
# Finds collisions between the top of the player's rect and the bottom of a world_collision_rect.
def collision_ceiling
return unless state.dy > 0 # return unless player is moving up
player_rect = [state.x, next_y, state.player_width, state.player_height]
# Runs through all the sprites on the field and finds all intersections between the player's top
# and the bottom of a rect.
ceil_collisions = state.world_collision_rects
.find_all { |r| r[:bottom].intersect_rect?(player_rect, state.collision_tolerance) }
.first
return unless ceil_collisions # return unless collision occurred
state.y = ceil_collisions[:bottom].y - state.tile_size # player's y is set to the y of the colliding rect's bottom (minus tile size)
state.dy = 0 # no change in y because the player's path is blocked
end
# Makes sure the player remains within the screen's dimensions.
def calc_edge_collision
# Ensures that player doesn't fall below the map
if next_y < 0 && state.dy < 0 # if player is moving down and is about to fall (next_y) below the map's scope
state.y = 0 # 0 is the lowest the player can be while staying on the screen
state.dy = 0
# Ensures player doesn't go insanely high
elsif next_y > 720 - state.tile_size && state.dy > 0 # if player is moving up, about to exceed map's scope
state.y = 720 - state.tile_size # if we don't subtract tile_size, we won't be able to see the player on the screen
state.dy = 0
end
# Ensures that player remains in the horizontal range its supposed to
if state.x >= 1280 - state.tile_size && state.dx > 0 # if the player is moving too far right
state.x = 1280 - state.tile_size # farthest right the player can be while remaining in the screen's scope
state.dx = 0
elsif state.x <= 0 && state.dx < 0 # if the player is moving too far left
state.x = 0 # farthest left the player can be while remaining in the screen's scope
state.dx = 0
end
end
def calc_sprite_selection
# Does the transition to bring down the select sprite screen
if state.mode == :selecting && state.select_menu.y != 0
state.select_menu.y = 0 # sets y position of select menu (shown when 's' is pressed)
state.banner_coords.y = 680 # sets y position of Select Sprite banner
state.sprite_coords = state.sprite_coords.map do |x, y, w, h|
[x, y - 720, w, h] # sets definition of sprites (change '-' to '+' and the sprites can't be seen)
end
end
# Does the transition to leave the select sprite screen
if state.mode == :creating && state.select_menu.y != 720
state.select_menu.y = 720 # sets y position of select menu (menu is retreated back up)
state.banner_coords.y = 1000 # sets y position of Select Sprite banner
state.sprite_coords = state.sprite_coords.map do |x, y, w, h|
[x, y + 720, w, h] # sets definition of all elements in collection
end
end
end
def process_inputs
# If the state.mode is back and if the menu has retreated back up
# call methods that process user inputs
if state.mode == :creating
process_inputs_player_movement
process_inputs_place_tile
end
# For each sprite_coordinate added, check what sprite was selected
if state.mode == :selecting
state.sprite_coords.map do |x, y, order| # goes through all sprites in collection
# checks that a specific sprite was pressed based on x, y position
if inputs.mouse.down && # the && (and) sign means ALL statements must be true for the evaluation to be true
inputs.mouse.down.point.x >= x && # x is greater than or equal to sprite's x and
inputs.mouse.down.point.x <= x + 50 && # x is less than or equal to 50 pixels to the right
inputs.mouse.down.point.y >= y && # y is greater than or equal to sprite's y
inputs.mouse.down.point.y <= y + 50 # y is less than or equal to 50 pixels up
state.sprite_selected = order # sprite is chosen
end
end
end
inputs_export_stage
process_inputs_show_available_sprites
end
# Moves the player based on the keys they press on their keyboard
def process_inputs_player_movement
# Sets dx to 0 if the player lets go of arrow keys (player won't move left or right)
if inputs.keyboard.key_up.right
state.dx = 0
elsif inputs.keyboard.key_up.left
state.dx = 0
end
# Sets dx to 3 in whatever direction the player chooses when they hold down (or press) the left or right keys
if inputs.keyboard.key_held.right
state.dx = 3
elsif inputs.keyboard.key_held.left
state.dx = -3
end
# Sets dy to 5 to make the player ~fly~ when they press the space bar on their keyboard
if inputs.keyboard.key_held.space
state.dy = 5
end
end
# Adds tile in the place the user holds down the mouse
def process_inputs_place_tile
if inputs.mouse.down # if mouse is pressed
state.world_lookup = {}
x, y = to_coord inputs.mouse.down.point # gets x, y coordinates for the grid
# Checks if any coordinates duplicate (already exist in world)
if state.world.any? { |existing_x, existing_y, n| existing_x == x && existing_y == y }
#erases existing tile space by rejecting them from world
state.world = state.world.reject do |existing_x, existing_y, n|
existing_x == x && existing_y == y
end
else
state.world << [x, y, state.sprite_selected] # If no duplicates, add the sprite
end
end
end
# Stores/exports world collection's info (coordinates, sprite number) into a file
def inputs_export_stage
if inputs.keyboard.key_down.e # if "e" is pressed
export_string = state.world.map do |x, y, sprite_number| # stores world info in a string
"#{x},#{y},#{sprite_number}" # using string interpolation
end
gtk.write_file(MAP_FILE_PATH, export_string.join("\n")) # writes string into a file
state.map_saved_at = state.tick_count # frame number (passage of time) when the map was saved
end
end
def process_inputs_show_available_sprites
# Based on keyboard input, the entity (:creating and :selecting) switch
if inputs.keyboard.key_held.s && state.mode == :creating # if "s" is pressed and currently creating
state.mode = :selecting # will change to selecting
inputs.keyboard.clear # VERY IMPORTANT! If not present, it'll flicker between on and off
elsif inputs.keyboard.key_held.s && state.mode == :selecting # if "s" is pressed and currently selecting
state.mode = :creating # will change to creating
inputs.keyboard.clear # VERY IMPORTANT! If not present, it'll flicker between on and off
end
end
# Loads the world collection by reading from the map.txt file in the app folder
def attempt_load_world_from_file
return if state.world # return if the world collection is already populated
state.world ||= [] # initialized as an empty collection
exported_world = gtk.read_file(MAP_FILE_PATH) # reads the file using the path mentioned at top of code
return unless exported_world # return unless the file read was successful
state.world = exported_world.each_line.map do |l| # perform action on each line of exported_world
l.split(',').map(&:to_i) # calls split using ',' as a delimiter, and invokes .map on the collection,
# calling to_i (converts to integers) on each element
end
end
# Adds the change in y to y to determine the next y position of the player.
def next_y
state.y + state.dy
end
# Determines next x position of player
def next_x
if state.dx < 0 # if the player moves left
return state.x - (state.tile_size - state.player_width) # subtracts since the change in x is negative (player is moving left)
else
return state.x + (state.tile_size - state.player_width) # adds since the change in x is positive (player is moving right)
end
end
def to_coord point
# Integer divides (idiv) point.x to turn into grid
# Then, you can just multiply each integer by state.tile_size
# later and huzzah. Grid coordinates
[point.x.idiv(state.tile_size), point.y.idiv(state.tile_size)]
end
end
$metroidvania_starter = MetroidvaniaStarter.new
def tick args
$metroidvania_starter.grid = args.grid
$metroidvania_starter.inputs = args.inputs
$metroidvania_starter.state = args.state
$metroidvania_starter.outputs = args.outputs
$metroidvania_starter.gtk = args.gtk
$metroidvania_starter.tick
end
</code></pre>
<h3 id='----physics-and-collisions---box-collision-3---main-rb'>Physics And Collisions - Box Collision 3 - main.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/06_box_collision_3/app/main.rb
class Game
attr_gtk
def tick
defaults
render
input_edit_map
input_player
calc_player
end
def defaults
state.gravity = -0.4
state.drag = 0.15
state.tile_size = 32
state.player.size = 16
state.player.jump_power = 12
state.tiles ||= []
state.player.y ||= 800
state.player.x ||= 100
state.player.dy ||= 0
state.player.dx ||= 0
state.player.jumped_down_at ||= 0
state.player.jumped_at ||= 0
calc_player_rect if !state.player.rect
end
def render
outputs.labels << [10, 10.from_top, "tile: click to add a tile, hold X key and click to delete a tile."]
outputs.labels << [10, 35.from_top, "move: use left and right to move, space to jump, down and space to jump down."]
outputs.labels << [10, 55.from_top, " You can jump through or jump down through tiles with a height of 1."]
outputs.background_color = [80, 80, 80]
outputs.sprites << tiles.map(&:sprite)
outputs.sprites << (player.rect.merge path: 'sprites/square/green.png')
mouse_overlay = {
x: (inputs.mouse.x.ifloor state.tile_size),
y: (inputs.mouse.y.ifloor state.tile_size),
w: state.tile_size,
h: state.tile_size,
a: 100
}
mouse_overlay = mouse_overlay.merge r: 255 if state.delete_mode
if state.mouse_held
outputs.primitives << mouse_overlay.border!
else
outputs.primitives << mouse_overlay.solid!
end
end
def input_edit_map
state.mouse_held = true if inputs.mouse.down
state.mouse_held = false if inputs.mouse.up
if inputs.keyboard.x
state.delete_mode = true
elsif inputs.keyboard.key_up.x
state.delete_mode = false
end
return unless state.mouse_held
ordinal = { x: (inputs.mouse.x.idiv state.tile_size),
y: (inputs.mouse.y.idiv state.tile_size) }
found = find_tile ordinal
if !found && !state.delete_mode
tiles << (state.new_entity :tile, ordinal)
recompute_tiles
elsif found && state.delete_mode
tiles.delete found
recompute_tiles
end
end
def input_player
player.dx += inputs.left_right
if inputs.keyboard.key_down.space && inputs.keyboard.down
player.dy = player.jump_power * -1
player.jumped_at = 0
player.jumped_down_at = state.tick_count
elsif inputs.keyboard.key_down.space
player.dy = player.jump_power
player.jumped_at = state.tick_count
player.jumped_down_at = 0
end
end
def calc_player
calc_player_rect
calc_below
calc_left
calc_right
calc_above
calc_player_dy
calc_player_dx
reset_player if player_off_stage?
end
def calc_player_rect
player.rect = current_player_rect
player.next_rect = player.rect.merge x: player.x + player.dx,
y: player.y + player.dy
player.prev_rect = player.rect.merge x: player.x - player.dx,
y: player.y - player.dy
end
def calc_below
return unless player.dy <= 0
tiles_below = find_tiles { |t| t.rect.top <= player.y }
collision = find_colliding_tile tiles_below, (player.rect.merge y: player.next_rect.y)
return unless collision
if collision.neighbors.b == :none && player.jumped_down_at.elapsed_time < 10
player.dy = -1
else
player.y = collision.rect.y + state.tile_size
player.dy = 0
end
end
def calc_left
return unless player.dx < 0
tiles_left = find_tiles { |t| t.rect.right <= player.prev_rect.left }
collision = find_colliding_tile tiles_left, (player.rect.merge x: player.next_rect.x)
return unless collision
player.x = collision.rect.right
player.dx = 0
end
def calc_right
return unless player.dx > 0
tiles_right = find_tiles { |t| t.rect.left >= player.prev_rect.right }
collision = find_colliding_tile tiles_right, (player.rect.merge x: player.next_rect.x)
return unless collision
player.x = collision.rect.left - player.rect.w
player.dx = 0
end
def calc_above
return unless player.dy > 0
tiles_above = find_tiles { |t| t.rect.y >= player.y }
collision = find_colliding_tile tiles_above, (player.rect.merge y: player.next_rect.y)
return unless collision
return if collision.neighbors.t == :none
player.dy = 0
player.y = collision.rect.bottom - player.rect.h
end
def calc_player_dx
player.y += player.dy
player.dy += state.gravity
player.dy += player.dy * state.drag ** 2 * -1
end
def calc_player_dy
player.dx = player.dx.clamp(-5, 5)
player.dx *= 0.9
player.x += player.dx
end
def reset_player
player.x = 100
player.y = 720
player.dy = 0
end
def recompute_tiles
tiles.each do |t|
t.w = state.tile_size
t.h = state.tile_size
t.neighbors = tile_neighbors t, tiles
t.rect = [t.x * state.tile_size,
t.y * state.tile_size,
state.tile_size,
state.tile_size].rect.to_hash
sprite_sub_path = t.neighbors.mask.map { |m| flip_bit m }.join("")
t.sprite = {
x: t.x * state.tile_size,
y: t.y * state.tile_size,
w: state.tile_size,
h: state.tile_size,
path: "sprites/tile/wall-#{sprite_sub_path}.png"
}
end
end
def flip_bit bit
return 0 if bit == 1
return 1
end
def player
state.player
end
def player_off_stage?
player.rect.top < grid.bottom ||
player.rect.right < grid.left ||
player.rect.left > grid.right
end
def current_player_rect
{ x: player.x, y: player.y, w: player.size, h: player.size }
end
def tiles
state.tiles
end
def find_tile ordinal
tiles.find { |t| t.x == ordinal.x && t.y == ordinal.y }
end
def find_tiles &block
tiles.find_all(&block)
end
def find_colliding_tile tiles, target
tiles.find { |t| t.rect.intersect_rect? target }
end
def tile_neighbors tile, other_points
t = find_tile x: tile.x + 0, y: tile.y + 1
r = find_tile x: tile.x + 1, y: tile.y + 0
b = find_tile x: tile.x + 0, y: tile.y - 1
l = find_tile x: tile.x - 1, y: tile.y + 0
tile_t, tile_r, tile_b, tile_l = 0
tile_t = 1 if t
tile_r = 1 if r
tile_b = 1 if b
tile_l = 1 if l
state.new_entity :neighbors, mask: [tile_t, tile_r, tile_b, tile_l],
t: t ? :some : :none,
b: b ? :some : :none,
l: l ? :some : :none,
r: r ? :some : :none
end
end
def tick args
$game ||= Game.new
$game.args = args
$game.tick
end
</code></pre>
<h3 id='----physics-and-collisions---jump-physics---main-rb'>Physics And Collisions - Jump Physics - main.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/07_jump_physics/app/main.rb
=begin
Reminders:
- args.state.new_entity: Used when we want to create a new object, like a sprite or button.
For example, if we want to create a new button, we would declare it as a new entity and
then define its properties. (Remember, you can use state to define ANY property and it will
be retained across frames.)
- args.outputs.solids: An array. The values generate a solid.
The parameters for a solid are [X, Y, WIDTH, HEIGHT, RED, GREEN, BLUE]
For more information about solids, go to mygame/documentation/03-solids-and-borders.md.
- num1.greater(num2): Returns the greater value.
- Hashes: Collection of unique keys and their corresponding values. The value can be found
using their keys.
- ARRAY#inside_rect?: Returns true or false depending on if the point is inside the rect.
=end
# This sample app is a game that requires the user to jump from one platform to the next.
# As the player successfully clears platforms, they become smaller and move faster.
class VerticalPlatformer
attr_gtk
# declares vertical platformer as new entity
def s
state.vertical_platformer ||= state.new_entity(:vertical_platformer)
state.vertical_platformer
end
# creates a new platform using a hash
def new_platform hash
s.new_entity_strict(:platform, hash) # platform key
end
# calls methods needed for game to run properly
def tick
defaults
render
calc
input
end
# Sets default values
def defaults
s.platforms ||= [ # initializes platforms collection with two platforms using hashes
new_platform(x: 0, y: 0, w: 700, h: 32, dx: 1, speed: 0, rect: nil),
new_platform(x: 0, y: 300, w: 700, h: 32, dx: 1, speed: 0, rect: nil), # 300 pixels higher
]
s.tick_count = args.state.tick_count
s.gravity = -0.3 # what goes up must come down because of gravity
s.player.platforms_cleared ||= 0 # counts how many platforms the player has successfully cleared
s.player.x ||= 0 # sets player values
s.player.y ||= 100
s.player.w ||= 64
s.player.h ||= 64
s.player.dy ||= 0 # change in position
s.player.dx ||= 0
s.player_jump_power = 15
s.player_jump_power_duration = 10
s.player_max_run_speed = 5
s.player_speed_slowdown_rate = 0.9
s.player_acceleration = 1
s.camera ||= { y: -100 } # shows view on screen (as the player moves upward, the camera does too)
end
# Outputs objects onto the screen
def render
outputs.solids << s.platforms.map do |p| # outputs platforms onto screen
[p.x + 300, p.y - s.camera[:y], p.w, p.h] # add 300 to place platform in horizontal center
# don't forget, position of platform is denoted by bottom left hand corner
end
# outputs player using hash
outputs.solids << {
x: s.player.x + 300, # player positioned on top of platform
y: s.player.y - s.camera[:y],
w: s.player.w,
h: s.player.h,
r: 100, # color saturation
g: 100,
b: 200
}
end
# Performs calculations
def calc
s.platforms.each do |p| # for each platform in the collection
p.rect = [p.x, p.y, p.w, p.h] # set the definition
end
# sets player point by adding half the player's width to the player's x
s.player.point = [s.player.x + s.player.w.half, s.player.y] # change + to - and see what happens!
# search the platforms collection to find if the player's point is inside the rect of a platform
collision = s.platforms.find { |p| s.player.point.inside_rect? p.rect }
# if collision occurred and player is moving down (or not moving vertically at all)
if collision && s.player.dy <= 0
s.player.y = collision.rect.y + collision.rect.h - 2 # player positioned on top of platform
s.player.dy = 0 if s.player.dy < 0 # player stops moving vertically
if !s.player.platform
s.player.dx = 0 # no horizontal movement
end
# changes horizontal position of player by multiplying collision change in x (dx) by speed and adding it to current x
s.player.x += collision.dx * collision.speed
s.player.platform = collision # player is on the platform that it collided with (or landed on)
if s.player.falling # if player is falling
s.player.dx = 0 # no horizontal movement
end
s.player.falling = false
s.player.jumped_at = nil
else
s.player.platform = nil # player is not on a platform
s.player.y += s.player.dy # velocity is the change in position
s.player.dy += s.gravity # acceleration is the change in velocity; what goes up must come down
end
s.platforms.each do |p| # for each platform in the collection
p.x += p.dx * p.speed # x is incremented by product of dx and speed (causes platform to move horizontally)
# changes platform's x so it moves left and right across the screen (between -300 and 300 pixels)
if p.x < -300 # if platform goes too far left
p.dx *= -1 # dx is scaled down
p.x = -300 # as far left as possible within scope
elsif p.x > (1000 - p.w) # if platform's x is greater than 300
p.dx *= -1
p.x = (1000 - p.w) # set to 300 (as far right as possible within scope)
end
end
delta = (s.player.y - s.camera[:y] - 100) # used to position camera view
if delta > -200
s.camera[:y] += delta * 0.01 # allows player to see view as they move upwards
s.player.x += s.player.dx # velocity is change in position; change in x increases by dx
# searches platform collection to find platforms located more than 300 pixels above the player
has_platforms = s.platforms.find { |p| p.y > (s.player.y + 300) }
if !has_platforms # if there are no platforms 300 pixels above the player
width = 700 - (700 * (0.1 * s.player.platforms_cleared)) # the next platform is smaller than previous
s.player.platforms_cleared += 1 # player successfully cleared another platform
last_platform = s.platforms[-1] # platform just cleared becomes last platform
# another platform is created 300 pixels above the last platform, and this
# new platform has a smaller width and moves faster than all previous platforms
s.platforms << new_platform(x: (700 - width) * rand, # random x position
y: last_platform.y + 300,
w: width,
h: 32,
dx: 1.randomize(:sign), # random change in x
speed: 2 * s.player.platforms_cleared,
rect: nil)
end
else
s.as_hash.clear # otherwise clear the hash (no new platform is necessary)
end
end
# Takes input from the user to move the player
def input
if inputs.keyboard.space # if the space bar is pressed
s.player.jumped_at ||= s.tick_count # set to current frame
# if the time that has passed since the jump is less than the duration of a jump (10 frames)
# and the player is not falling
if s.player.jumped_at.elapsed_time < s.player_jump_power_duration && !s.player.falling
s.player.dy = s.player_jump_power # player jumps up
end
end
if inputs.keyboard.key_up.space # if space bar is in "up" state
s.player.falling = true # player is falling
end
if inputs.keyboard.left # if left key is pressed
s.player.dx -= s.player_acceleration # player's position changes, decremented by acceleration
s.player.dx = s.player.dx.greater(-s.player_max_run_speed) # dx is either current dx or -5, whichever is greater
elsif inputs.keyboard.right # if right key is pressed
s.player.dx += s.player_acceleration # player's position changes, incremented by acceleration
s.player.dx = s.player.dx.lesser(s.player_max_run_speed) # dx is either current dx or 5, whichever is lesser
else
s.player.dx *= s.player_speed_slowdown_rate # scales dx down
end
end
end
$game = VerticalPlatformer.new
def tick args
$game.args = args
$game.tick
end
</code></pre>
<h3 id='----physics-and-collisions---bouncing-on-collision---ball-rb'>Physics And Collisions - Bouncing On Collision - ball.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/08_bouncing_on_collision/app/ball.rb
GRAVITY = -0.08
class Ball
attr_accessor :velocity, :center, :radius, :collision_enabled
def initialize args
#Start the ball in the top center
#@x = args.grid.w / 2
#@y = args.grid.h - 20
@velocity = {x: 0, y: 0}
#@width = 20
#@height = @width
@radius = 20.0 / 2.0
@center = {x: (args.grid.w / 2), y: (args.grid.h)}
#@left_wall = (args.state.board_width + args.grid.w / 8)
#@right_wall = @left_wall + args.state.board_width
@left_wall = 0
@right_wall = $args.grid.right
@max_velocity = 7
@collision_enabled = true
end
#Move the ball according to its velocity
def update args
@center.x += @velocity.x
@center.y += @velocity.y
@velocity.y += GRAVITY
alpha = 0.2
if @center.y-@radius <= 0
@velocity.y = (@velocity.y.abs*0.7).abs
@velocity.x = (@velocity.x.abs*0.9).abs * ((@velocity.x < 0) ? -1 : 1)
if @velocity.y.abs() < alpha
@velocity.y=0
end
if @velocity.x.abs() < alpha
@velocity.x=0
end
end
if @center.x > args.grid.right+@radius*2
@center.x = 0-@radius
elsif @center.x< 0-@radius*2
@center.x = args.grid.right + @radius
end
end
def wallBounds args
#if @x < @left_wall || @x + @width > @right_wall
#@velocity.x *= -1.1
#if @velocity.x > @max_velocity
#@velocity.x = @max_velocity
#elsif @velocity.x < @max_velocity * -1
#@velocity.x = @max_velocity * -1
#end
#end
#if @y < 0 || @y + @height > args.grid.h
#@velocity.y *= -1.1
#if @velocity.y > @max_velocity
#@velocity.y = @max_velocity
#elsif @velocity.y < @max_velocity * -1
#@velocity.y = @max_velocity * -1
#end
#end
end
#render the ball to the screen
def draw args
#args.outputs.solids << [@x, @y, @width, @height, 255, 255, 0];
args.outputs.sprites << [
@center.x-@radius,
@center.y-@radius,
@radius*2,
@radius*2,
"sprites/circle-white.png",
0,
255,
255, #r
0, #g
255 #b
]
end
end
</code></pre>
<h3 id='----physics-and-collisions---bouncing-on-collision---block-rb'>Physics And Collisions - Bouncing On Collision - block.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/08_bouncing_on_collision/app/block.rb
DEGREES_TO_RADIANS = Math::PI / 180
class Block
def initialize(x, y, block_size, rotation)
@x = x
@y = y
@block_size = block_size
@rotation = rotation
#The repel velocity?
@velocity = {x: 2, y: 0}
horizontal_offset = (3 * block_size) * Math.cos(rotation * DEGREES_TO_RADIANS)
vertical_offset = block_size * Math.sin(rotation * DEGREES_TO_RADIANS)
if rotation >= 0
theta = 90 - rotation
#The line doesn't visually line up exactly with the edge of the sprite, so artificially move it a bit
modifier = 5
x_offset = modifier * Math.cos(theta * DEGREES_TO_RADIANS)
y_offset = modifier * Math.sin(theta * DEGREES_TO_RADIANS)
@x1 = @x - x_offset
@y1 = @y + y_offset
@x2 = @x1 + horizontal_offset
@y2 = @y1 + (vertical_offset * 3)
@imaginary_line = [ @x1, @y1, @x2, @y2 ]
else
theta = 90 + rotation
x_offset = @block_size * Math.cos(theta * DEGREES_TO_RADIANS)
y_offset = @block_size * Math.sin(theta * DEGREES_TO_RADIANS)
@x1 = @x + x_offset
@y1 = @y + y_offset + 19
@x2 = @x1 + horizontal_offset
@y2 = @y1 + (vertical_offset * 3)
@imaginary_line = [ @x1, @y1, @x2, @y2 ]
end
end
def draw args
args.outputs.sprites << [
@x,
@y,
@block_size*3,
@block_size,
"sprites/square-green.png",
@rotation
]
args.outputs.lines << @imaginary_line
args.outputs.solids << @debug_shape
end
def multiply_matricies
end
def calc args
if collision? args
collide args
end
end
#Determine if the ball and block are touching
def collision? args
#The minimum area enclosed by the center of the ball and the 2 corners of the block
#If the area ever drops below this value, we know there is a collision
min_area = ((@block_size * 3) * args.state.ball.radius) / 2
#https://www.mathopenref.com/coordtrianglearea.html
ax = @x1
ay = @y1
bx = @x2
by = @y2
cx = args.state.ball.center.x
cy = args.state.ball.center.y
current_area = (ax*(by-cy)+bx*(cy-ay)+cx*(ay-by))/2
collision = false
if @rotation >= 0
if (current_area < min_area &&
current_area > 0 &&
args.state.ball.center.y > @y1 &&
args.state.ball.center.x < @x2)
collision = true
end
else
if (current_area < min_area &&
current_area > 0 &&
args.state.ball.center.y > @y2 &&
args.state.ball.center.x > @x1)
collision = true
end
end
return collision
end
def collide args
#Slope of the block
slope = (@y2 - @y1) / (@x2 - @x1)
#Create a unit vector and tilt it (@rotation) number of degrees
x = -Math.cos(@rotation * DEGREES_TO_RADIANS)
y = Math.sin(@rotation * DEGREES_TO_RADIANS)
#Find the vector that is perpendicular to the slope
perpVect = { x: x, y: y }
mag = (perpVect.x**2 + perpVect.y**2)**0.5 # find the magniude of the perpVect
perpVect = {x: perpVect.x/(mag), y: perpVect.y/(mag)} # divide the perpVect by the magniude to make it a unit vector
previousPosition = { # calculate an ESTIMATE of the previousPosition of the ball
x:args.state.ball.center.x-args.state.ball.velocity.x,
y:args.state.ball.center.y-args.state.ball.velocity.y
}
velocityMag = (args.state.ball.velocity.x**2 + args.state.ball.velocity.y**2)**0.5 # the current velocity magnitude of the ball
theta_ball = Math.atan2(args.state.ball.velocity.y, args.state.ball.velocity.x) #the angle of the ball's velocity
theta_repel = (180 * DEGREES_TO_RADIANS) - theta_ball + (@rotation * DEGREES_TO_RADIANS)
fbx = velocityMag * Math.cos(theta_ball) #the x component of the ball's velocity
fby = velocityMag * Math.sin(theta_ball) #the y component of the ball's velocity
frx = velocityMag * Math.cos(theta_repel) #the x component of the repel's velocity | magnitude is set to twice of fbx
fry = velocityMag * Math.sin(theta_repel) #the y component of the repel's velocity | magnitude is set to twice of fby
args.state.display_value = velocityMag
fsumx = fbx+frx #sum of x forces
fsumy = fby+fry #sum of y forces
fr = velocityMag #fr is the resulting magnitude
thetaNew = Math.atan2(fsumy, fsumx) #thetaNew is the resulting angle
xnew = fr*Math.cos(thetaNew) #resulting x velocity
ynew = fr*Math.sin(thetaNew) #resulting y velocity
dampener = 0.3
ynew *= dampener * 0.5
#If the bounce is very low, that means the ball is rolling and we don't want to dampenen the X velocity
if ynew > -0.1
xnew *= dampener
end
#Add the sine component of gravity back in (X component)
gravity_x = 4 * Math.sin(@rotation * DEGREES_TO_RADIANS)
xnew += gravity_x
args.state.ball.velocity.x = -xnew
args.state.ball.velocity.y = -ynew
#Set the position of the ball to the previous position so it doesn't warp throught the block
args.state.ball.center.x = previousPosition.x
args.state.ball.center.y = previousPosition.y
end
end
</code></pre>
<h3 id='----physics-and-collisions---bouncing-on-collision---cannon-rb'>Physics And Collisions - Bouncing On Collision - cannon.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/08_bouncing_on_collision/app/cannon.rb
class Cannon
def initialize args
@pointA = {x: args.grid.right/2,y: args.grid.top}
@pointB = {x: args.inputs.mouse.x, y: args.inputs.mouse.y}
end
def update args
activeBall = args.state.ball
@pointB = {x: args.inputs.mouse.x, y: args.inputs.mouse.y}
if args.inputs.mouse.click
alpha = 0.01
activeBall.velocity.y = (@pointB.y - @pointA.y) * alpha
activeBall.velocity.x = (@pointB.x - @pointA.x) * alpha
activeBall.center = {x: (args.grid.w / 2), y: (args.grid.h)}
end
end
def render args
args.outputs.lines << [@pointA.x, @pointA.y, @pointB.x, @pointB.y]
end
end
</code></pre>
<h3 id='----physics-and-collisions---bouncing-on-collision---main-rb'>Physics And Collisions - Bouncing On Collision - main.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/08_bouncing_on_collision/app/main.rb
INFINITY= 10**10
require 'app/vector2d.rb'
require 'app/peg.rb'
require 'app/block.rb'
require 'app/ball.rb'
require 'app/cannon.rb'
#Method to init default values
def defaults args
args.state.pegs ||= []
args.state.blocks ||= []
args.state.cannon ||= Cannon.new args
args.state.ball ||= Ball.new args
args.state.horizontal_offset ||= 0
init_pegs args
init_blocks args
args.state.display_value ||= "test"
end
begin :default_methods
def init_pegs args
num_horizontal_pegs = 14
num_rows = 5
return unless args.state.pegs.count < num_rows * num_horizontal_pegs
block_size = 32
block_spacing = 50
total_width = num_horizontal_pegs * (block_size + block_spacing)
starting_offset = (args.grid.w - total_width) / 2 + block_size
for i in (0...num_rows)
for j in (0...num_horizontal_pegs)
row_offset = 0
if i % 2 == 0
row_offset = 20
else
row_offset = -20
end
args.state.pegs.append(Peg.new(j * (block_size+block_spacing) + starting_offset + row_offset, (args.grid.h - block_size * 2) - (i * block_size * 2)-90, block_size))
end
end
end
def init_blocks args
return unless args.state.blocks.count < 10
#Sprites are rotated in degrees, but the Ruby math functions work on radians
radians_to_degrees = Math::PI / 180
block_size = 25
#Rotation angle (in degrees) of the blocks
rotation = 30
vertical_offset = block_size * Math.sin(rotation * radians_to_degrees)
horizontal_offset = (3 * block_size) * Math.cos(rotation * radians_to_degrees)
center = args.grid.w / 2
for i in (0...5)
#Create a ramp of blocks. Not going to be perfect because of the float to integer conversion and anisotropic to isotropic coversion
args.state.blocks.append(Block.new((center + 100 + (i * horizontal_offset)).to_i, 100 + (vertical_offset * i) + (i * block_size), block_size, rotation))
args.state.blocks.append(Block.new((center - 100 - (i * horizontal_offset)).to_i, 100 + (vertical_offset * i) + (i * block_size), block_size, -rotation))
end
end
end
#Render loop
def render args
args.outputs.borders << args.state.game_area
render_pegs args
render_blocks args
args.state.cannon.render args
args.state.ball.draw args
end
begin :render_methods
#Draw the pegs in a grid pattern
def render_pegs args
args.state.pegs.each do |peg|
peg.draw args
end
end
def render_blocks args
args.state.blocks.each do |block|
block.draw args
end
end
end
#Calls all methods necessary for performing calculations
def calc args
args.state.pegs.each do |peg|
peg.calc args
end
args.state.blocks.each do |block|
block.calc args
end
args.state.ball.update args
args.state.cannon.update args
end
begin :calc_methods
end
def tick args
defaults args
render args
calc args
end
</code></pre>
<h3 id='----physics-and-collisions---bouncing-on-collision---peg-rb'>Physics And Collisions - Bouncing On Collision - peg.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/08_bouncing_on_collision/app/peg.rb
class Peg
def initialize(x, y, block_size)
@x = x # x cordinate of the LEFT side of the peg
@y = y # y cordinate of the RIGHT side of the peg
@block_size = block_size # diameter of the peg
@radius = @block_size/2.0 # radius of the peg
@center = { # cordinatees of the CENTER of the peg
x: @x+@block_size/2.0,
y: @y+@block_size/2.0
}
@r = 255 # color of the peg
@g = 0
@b = 0
@velocity = {x: 2, y: 0}
end
def draw args
args.outputs.sprites << [ # draw the peg according to the @x, @y, @radius, and the RGB
@x,
@y,
@radius*2.0,
@radius*2.0,
"sprites/circle-white.png",
0,
255,
@r, #r
@g, #g
@b #b
]
end
def calc args
if collisionWithBounce? args # if the is a collision with the bouncing ball
collide args
@r = 0
@b = 0
@g = 255
else
end
end
# do two circles (the ball and this peg) intersect
def collisionWithBounce? args
squareDistance = ( # the squared distance between the ball's center and this peg's center
(args.state.ball.center.x - @center.x) ** 2.0 +
(args.state.ball.center.y - @center.y) ** 2.0
)
radiusSum = ( # the sum of the radius squared of the this peg and the ball
(args.state.ball.radius + @radius) ** 2.0
)
# if the squareDistance is less or equal to radiusSum, then there is a radial intersection between the ball and this peg
return (squareDistance <= radiusSum)
end
# ! The following links explain the getRepelMagnitude function !
# https://raw.githubusercontent.com/DragonRuby/dragonruby-game-toolkit-physics/master/docs/docImages/LinearCollider_4.png
# https://raw.githubusercontent.com/DragonRuby/dragonruby-game-toolkit-physics/master/docs/docImages/LinearCollider_5.png
# https://github.com/DragonRuby/dragonruby-game-toolkit-physics/blob/master/docs/LinearCollider.md
def getRepelMagnitude (args, fbx, fby, vrx, vry, ballMag)
a = fbx ; b = vrx ; c = fby
d = vry ; e = ballMag
if b**2 + d**2 == 0
#unexpected
end
x1 = (-a*b+-c*d + (e**2 * b**2 - b**2 * c**2 + 2*a*b*c*d + e**2 + d**2 - a**2 * d**2)**0.5)/(b**2 + d**2)
x2 = -((a*b + c*d + (e**2 * b**2 - b**2 * c**2 + 2*a*b*c*d + e**2 * d**2 - a**2 * d**2)**0.5)/(b**2 + d**2))
err = 0.00001
o = ((fbx + x1*vrx)**2 + (fby + x1*vry)**2 ) ** 0.5
p = ((fbx + x2*vrx)**2 + (fby + x2*vry)**2 ) ** 0.5
r = 0
if (ballMag >= o-err and ballMag <= o+err)
r = x1
elsif (ballMag >= p-err and ballMag <= p+err)
r = x2
else
#unexpected
end
if (args.state.ball.center.x > @center.x)
return x2*-1
end
return x2
#return r
end
#this sets the new velocity of the ball once it has collided with this peg
def collide args
normalOfRCCollision = [ #this is the normal of the collision in COMPONENT FORM
{x: @center.x, y: @center.y}, #see https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.mathscard.co.uk%2Fonline%2Fcircle-coordinate-geometry%2F&psig=AOvVaw2GcD-e2-nJR_IUKpw3hO98&ust=1605731315521000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCMjBo7e1iu0CFQAAAAAdAAAAABAD
{x: args.state.ball.center.x, y: args.state.ball.center.y},
]
normalSlope = ( #normalSlope is the slope of normalOfRCCollision
(normalOfRCCollision[1].y - normalOfRCCollision[0].y) /
(normalOfRCCollision[1].x - normalOfRCCollision[0].x)
)
slope = normalSlope**-1.0 * -1 # slope is the slope of the tangent
# args.state.display_value = slope
pointA = { # pointA and pointB are using the var slope to tangent in COMPONENT FORM
x: args.state.ball.center.x-1,
y: -(slope-args.state.ball.center.y)
}
pointB = {
x: args.state.ball.center.x+1,
y: slope+args.state.ball.center.y
}
perpVect = {x: pointB.x - pointA.x, y:pointB.y - pointA.y} # perpVect is to be VECTOR of the perpendicular tangent
mag = (perpVect.x**2 + perpVect.y**2)**0.5 # find the magniude of the perpVect
perpVect = {x: perpVect.x/(mag), y: perpVect.y/(mag)} # divide the perpVect by the magniude to make it a unit vector
perpVect = {x: -perpVect.y, y: perpVect.x} # swap the x and y and multiply by -1 to make the vector perpendicular
args.state.display_value = perpVect
if perpVect.y > 0 #ensure perpVect points upward
perpVect = {x: perpVect.x*-1, y: perpVect.y*-1}
end
previousPosition = { # calculate an ESTIMATE of the previousPosition of the ball
x:args.state.ball.center.x-args.state.ball.velocity.x,
y:args.state.ball.center.y-args.state.ball.velocity.y
}
yInterc = pointA.y + -slope*pointA.x
if slope == INFINITY # the perpVect presently either points in the correct dirrection or it is 180 degrees off we need to correct this
if previousPosition.x < pointA.x
perpVect = {x: perpVect.x*-1, y: perpVect.y*-1}
yInterc = -INFINITY
end
elsif previousPosition.y < slope*previousPosition.x + yInterc # check if ball is bellow or above the collider to determine if perpVect is - or +
perpVect = {x: perpVect.x*-1, y: perpVect.y*-1}
end
velocityMag = # the current velocity magnitude of the ball
(args.state.ball.velocity.x**2 + args.state.ball.velocity.y**2)**0.5
theta_ball=
Math.atan2(args.state.ball.velocity.y,args.state.ball.velocity.x) #the angle of the ball's velocity
theta_repel=
Math.atan2(args.state.ball.center.y,args.state.ball.center.x) #the angle of the repelling force(perpVect)
fbx = velocityMag * Math.cos(theta_ball) #the x component of the ball's velocity
fby = velocityMag * Math.sin(theta_ball) #the y component of the ball's velocity
repelMag = getRepelMagnitude( # the magniude of the collision vector
args,
fbx,
fby,
perpVect.x,
perpVect.y,
(args.state.ball.velocity.x**2 + args.state.ball.velocity.y**2)**0.5
)
frx = repelMag* Math.cos(theta_repel) #the x component of the repel's velocity | magnitude is set to twice of fbx
fry = repelMag* Math.sin(theta_repel) #the y component of the repel's velocity | magnitude is set to twice of fby
fsumx = fbx+frx # sum of x forces
fsumy = fby+fry # sum of y forces
fr = velocityMag # fr is the resulting magnitude
thetaNew = Math.atan2(fsumy, fsumx) # thetaNew is the resulting angle
xnew = fr*Math.cos(thetaNew) # resulting x velocity
ynew = fr*Math.sin(thetaNew) # resulting y velocity
if (args.state.ball.center.x >= @center.x) # this is necessary for the ball colliding on the right side of the peg
xnew=xnew.abs
end
args.state.ball.velocity.x = xnew # set the x-velocity to the new velocity
if args.state.ball.center.y > @center.y # if the ball is above the middle of the peg we need to temporarily ignore some of the gravity
args.state.ball.velocity.y = ynew + GRAVITY * 0.01
else
args.state.ball.velocity.y = ynew - GRAVITY * 0.01 # if the ball is bellow the middle of the peg we need to temporarily increase the power of the gravity
end
args.state.ball.center.x+= args.state.ball.velocity.x # update the position of the ball so it never looks like the ball is intersecting the circle
args.state.ball.center.y+= args.state.ball.velocity.y
end
end
</code></pre>
<h3 id='----physics-and-collisions---bouncing-on-collision---vector2d-rb'>Physics And Collisions - Bouncing On Collision - vector2d.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/08_bouncing_on_collision/app/vector2d.rb
class Vector2d
attr_accessor :x, :y
def initialize x=0, y=0
@x=x
@y=y
end
#returns a vector multiplied by scalar x
#x [float] scalar
def mult x
r = Vector2d.new(0,0)
r.x=@x*x
r.y=@y*x
r
end
# vect [Vector2d] vector to copy
def copy vect
Vector2d.new(@x, @y)
end
#returns a new vector equivalent to this+vect
#vect [Vector2d] vector to add to self
def add vect
Vector2d.new(@x+vect.x,@y+vect.y)
end
#returns a new vector equivalent to this-vect
#vect [Vector2d] vector to subtract to self
def sub vect
Vector2d.new(@x-vect.c, @y-vect.y)
end
#return the magnitude of the vector
def mag
((@x**2)+(@y**2))**0.5
end
#returns a new normalize version of the vector
def normalize
Vector2d.new(@x/mag, @y/mag)
end
#TODO delet?
def distABS vect
(((vect.x-@x)**2+(vect.y-@y)**2)**0.5).abs()
end
end
</code></pre>
<h3 id='----physics-and-collisions---arbitrary-collision---ball-rb'>Physics And Collisions - Arbitrary Collision - ball.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/09_arbitrary_collision/app/ball.rb
class Ball
attr_accessor :velocity, :child, :parent, :number, :leastChain
attr_reader :x, :y, :hypotenuse, :width, :height
def initialize args, number, leastChain, parent, child
#Start the ball in the top center
@number = number
@leastChain = leastChain
@x = args.grid.w / 2
@y = args.grid.h - 20
@velocity = Vector2d.new(2, -2)
@width = 10
@height = 10
@left_wall = (args.state.board_width + args.grid.w / 8)
@right_wall = @left_wall + args.state.board_width
@max_velocity = MAX_VELOCITY
@child = child
@parent = parent
@past = [{x: @x, y: @y}]
@next = nil
end
def reassignLeastChain (lc=nil)
if (lc == nil)
lc = @number
end
@leastChain = lc
if (parent != nil)
@parent.reassignLeastChain(lc)
end
end
def makeLeader args
if isLeader
return
end
@parent.reassignLeastChain
args.state.ballParents.push(self)
@parent = nil
end
def isLeader
return (parent == nil)
end
def receiveNext (p)
#trace!
if parent != nil
@x = p[:x]
@y = p[:y]
@velocity = p[:velocity]
#puts @x.to_s + "|" + @y.to_s + "|"[email protected]_s
@past.append(p)
if (@past.length >= BALL_DISTANCE)
if (@child != nil)
@child.receiveNext(@past[0])
@past.shift
end
end
end
end
#Move the ball according to its velocity
def update args
if isLeader
wallBounds args
@x += @velocity.x
@y += @velocity.y
@past.append({x: @x, y: @y, velocity: @velocity})
#puts @past
if (@past.length >= BALL_DISTANCE)
if (@child != nil)
@child.receiveNext(@past[0])
@past.shift
end
end
else
puts "unexpected"
raise "unexpected"
end
end
def wallBounds args
b= false
if @x < @left_wall
@velocity.x = @velocity.x.abs() * 1
b=true
elsif @x + @width > @right_wall
@velocity.x = @velocity.x.abs() * -1
b=true
end
if @y < 0
@velocity.y = @velocity.y.abs() * 1
b=true
elsif @y + @height > args.grid.h
@velocity.y = @velocity.y.abs() * -1
b=true
end
mag = (@velocity.x**2.0 + @velocity.y**2.0)**0.5
if (b == true && mag < MAX_VELOCITY)
@velocity.x*=1.1;
@velocity.y*=1.1;
end
end
#render the ball to the screen
def draw args
#update args
#args.outputs.solids << [@x, @y, @width, @height, 255, 255, 0];
#args.outputs.sprits << {
#x: @x,
#y: @y,
#w: @width,
#h: @height,
#path: "sprites/ball10.png"
#}
#args.outputs.sprites <<[@x, @y, @width, @height, "sprites/ball10.png"]
args.outputs.sprites << {x: @x, y: @y, w: @width, h: @height, path:"sprites/ball10.png" }
end
def getDraw args
#wallBounds args
#update args
#args.outputs.labels << [@x, @y, @number.to_s + "|" + @leastChain.to_s]
return [@x, @y, @width, @height, "sprites/ball10.png"]
end
def getPoints args
points = [
{x:@x+@width/2, y: @y},
{x:@x+@width, y:@y+@height/2},
{x:@x+@width/2,y:@y+@height},
{x:@x,y:@y+@height/2}
]
#psize = 5.0
#for p in points
#args.outputs.solids << [p.x-psize/2.0, p.y-psize/2.0, psize, psize, 0, 0, 0];
#end
return points
end
def serialize
{x: @x, y:@y}
end
def inspect
serialize.to_s
end
def to_s
serialize.to_s
end
end
</code></pre>
<h3 id='----physics-and-collisions---arbitrary-collision---blocks-rb'>Physics And Collisions - Arbitrary Collision - blocks.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/09_arbitrary_collision/app/blocks.rb
MAX_COUNT=100
def universalUpdateOne args, shape
didHit = false
hitters = []
#puts shape.to_s
toCollide = nil
for b in args.state.balls
if [b.x, b.y, b.width, b.height].intersect_rect?(shape.bold)
didSquare = false
for s in shape.squareColliders
if (s.collision?(args, b))
didSquare = true
didHit = true
#s.collide(args, b)
toCollide = s
#hitter = b
hitters.append(b)
end #end if
end #end for
if (didSquare == false)
for c in shape.colliders
#puts args.state.ball.velocity
if c.collision?(args, b.getPoints(args),b)
#c.collide args, b
toCollide = c
didHit = true
hitters.append(b)
end #end if
end #end for
end #end if
end#end if
end#end for
if (didHit)
shape.count=0
hitters = hitters.uniq
for hitter in hitters
hitter.makeLeader args
#toCollide.collide(args, hitter)
if shape.home == "squares"
args.state.squares.delete(shape)
elsif shape.home == "tshapes"
args.state.tshapes.delete(shape)
else shape.home == "lines"
args.state.lines.delete(shape)
end
end
#puts "HIT!" + hitter.number
end
end
def universalUpdate args, shape
#puts shape.home
if (shape.count <= 1)
universalUpdateOne args, shape
return
end
didHit = false
hitter = nil
for b in args.state.ballParents
if [b.x, b.y, b.width, b.height].intersect_rect?(shape.bold)
didSquare = false
for s in shape.squareColliders
if (s.collision?(args, b))
didSquare = true
didHit = true
s.collide(args, b)
hitter = b
end
end
if (didSquare == false)
for c in shape.colliders
#puts args.state.ball.velocity
if c.collision?(args, b.getPoints(args),b)
c.collide args, b
didHit = true
hitter = b
end
end
end
end
end
if (didHit)
shape.count=shape.count-1
shape.damageCount.append([(hitter.leastChain+1 - hitter.number)-1, args.state.tick_count])
end
i=0
while i < shape.damageCount.length
if shape.damageCount[i][0] <= 0
shape.damageCount.delete_at(i)
i-=1
elsif shape.damageCount[i][1].elapsed_time > BALL_DISTANCE and shape.damageCount[i][0] > 1
shape.count-=1
shape.damageCount[i][0]-=1
shape.damageCount[i][1] = args.state.tick_count
end
i+=1
end
end
class Square
attr_accessor :count, :x, :y, :home, :bold, :squareColliders, :colliders, :damageCount
def initialize(args, x, y, block_size, orientation, block_offset)
@x = x * block_size
@y = y * block_size
@block_size = block_size
@block_offset = block_offset
@orientation = orientation
@damageCount = []
@home = 'squares'
Kernel.srand()
@r = rand(255)
@g = rand(255)
@b = rand(255)
@count = rand(MAX_COUNT)+1
x_offset = (args.state.board_width + args.grid.w / 8) + @block_offset / 2
@x_adjusted = @x + x_offset
@y_adjusted = @y
@size_adjusted = @block_size * 2 - @block_offset
hypotenuse=args.state.ball_hypotenuse
@bold = [(@x_adjusted-hypotenuse/2)-1, (@y_adjusted-hypotenuse/2)-1, @size_adjusted + hypotenuse + 2, @size_adjusted + hypotenuse + 2]
@points = [
{x:@x_adjusted, y:@y_adjusted},
{x:@x_adjusted+@size_adjusted, y:@y_adjusted},
{x:@x_adjusted+@size_adjusted, y:@y_adjusted+@size_adjusted},
{x:@x_adjusted, y:@y_adjusted+@size_adjusted}
]
@squareColliders = [
SquareCollider.new(@points[0].x,@points[0].y,{x:-1,y:-1}),
SquareCollider.new(@points[1].x-COLLISIONWIDTH,@points[1].y,{x:1,y:-1}),
SquareCollider.new(@points[2].x-COLLISIONWIDTH,@points[2].y-COLLISIONWIDTH,{x:1,y:1}),
SquareCollider.new(@points[3].x,@points[3].y-COLLISIONWIDTH,{x:-1,y:1}),
]
@colliders = [
LinearCollider.new(@points[0],@points[1], :neg),
LinearCollider.new(@points[1],@points[2], :neg),
LinearCollider.new(@points[2],@points[3], :pos),
LinearCollider.new(@points[0],@points[3], :pos)
]
end
def draw(args)
#Offset the coordinates to the edge of the game area
x_offset = (args.state.board_width + args.grid.w / 8) + @block_offset / 2
#args.outputs.solids << [@x + x_offset, @y, @block_size * 2 - @block_offset, @block_size * 2 - @block_offset, @r, @g, @b]
args.outputs.solids <<{x: (@x + x_offset), y: (@y), w: (@block_size * 2 - @block_offset), h: (@block_size * 2 - @block_offset), r: @r , g: @g , b: @b }
#args.outputs.solids << @bold.append([255,0,0])
args.outputs.labels << [@x + x_offset + (@block_size * 2 - @block_offset)/2, (@y) + (@block_size * 2 - @block_offset)/2, @count.to_s]
end
def update args
universalUpdate args, self
end
end
class TShape
attr_accessor :count, :x, :y, :home, :bold, :squareColliders, :colliders, :damageCount
def initialize(args, x, y, block_size, orientation, block_offset)
@x = x * block_size
@y = y * block_size
@block_size = block_size
@block_offset = block_offset
@orientation = orientation
@damageCount = []
@home = "tshapes"
Kernel.srand()
@r = rand(255)
@g = rand(255)
@b = rand(255)
@count = rand(MAX_COUNT)+1
@shapePoints = getShapePoints(args)
minX={x:INFINITY, y:0}
minY={x:0, y:INFINITY}
maxX={x:-INFINITY, y:0}
maxY={x:0, y:-INFINITY}
for p in @shapePoints
if p.x < minX.x
minX = p
end
if p.x > maxX.x
maxX = p
end
if p.y < minY.y
minY = p
end
if p.y > maxY.y
maxY = p
end
end
hypotenuse=args.state.ball_hypotenuse
@bold = [(minX.x-hypotenuse/2)-1, (minY.y-hypotenuse/2)-1, -((minX.x-hypotenuse/2)-1)+(maxX.x + hypotenuse + 2), -((minY.y-hypotenuse/2)-1)+(maxY.y + hypotenuse + 2)]
end
def getShapePoints(args)
points=[]
x_offset = (args.state.board_width + args.grid.w / 8) + (@block_offset / 2)
if @orientation == :right
#args.outputs.solids << [@x + x_offset, @y, @block_size - @block_offset, @block_size * 3 - @block_offset, @r, @g, @b]
#args.outputs.solids << [@x + x_offset, @y + @block_size, @block_size * 2, @block_size, @r, @g, @b]
points = [
{x:@x + x_offset, y:@y},
{x:(@x + x_offset)+(@block_size - @block_offset), y:@y},
{x:(@x + x_offset)+(@block_size - @block_offset),y:@y + @block_size},
{x:(@x + x_offset)+ @block_size * 2,y:@y + @block_size},
{x:(@x + x_offset)+ @block_size * 2,y:@y + @block_size+@block_size},
{x:(@x + x_offset)+(@block_size - @block_offset),y:@y + @block_size+@block_size},
{x:(@x + x_offset)+(@block_size - @block_offset), y:@y+ @block_size * 3 - @block_offset},
{x:@x + x_offset , y:@y+ @block_size * 3 - @block_offset}
]
@squareColliders = [
SquareCollider.new(points[0].x,points[0].y,{x:-1,y:-1}),
SquareCollider.new(points[1].x-COLLISIONWIDTH,points[1].y,{x:1,y:-1}),
SquareCollider.new(points[2].x,points[2].y-COLLISIONWIDTH,{x:1,y:-1}),
SquareCollider.new(points[3].x-COLLISIONWIDTH,points[3].y,{x:1,y:-1}),
SquareCollider.new(points[4].x-COLLISIONWIDTH,points[4].y-COLLISIONWIDTH,{x:1,y:1}),
SquareCollider.new(points[5].x,points[5].y,{x:1,y:1}),
SquareCollider.new(points[6].x-COLLISIONWIDTH,points[6].y-COLLISIONWIDTH,{x:1,y:1}),
SquareCollider.new(points[7].x,points[7].y-COLLISIONWIDTH,{x:-1,y:1}),
]
@colliders = [
LinearCollider.new(points[0],points[1], :neg),
LinearCollider.new(points[1],points[2], :neg),
LinearCollider.new(points[2],points[3], :neg),
LinearCollider.new(points[3],points[4], :neg),
LinearCollider.new(points[4],points[5], :pos),
LinearCollider.new(points[5],points[6], :neg),
LinearCollider.new(points[6],points[7], :pos),
LinearCollider.new(points[0],points[7], :pos)
]
elsif @orientation == :up
#args.outputs.solids << [@x + x_offset, @y, @block_size * 3 - @block_offset, @block_size - @block_offset, @r, @g, @b]
#args.outputs.solids << [@x + x_offset + @block_size, @y, @block_size, @block_size * 2, @r, @g, @b]
points = [
{x:@x + x_offset, y:@y},
{x:(@x + x_offset)+(@block_size * 3 - @block_offset), y:@y},
{x:(@x + x_offset)+(@block_size * 3 - @block_offset), y:@y+(@block_size - @block_offset)},
{x:@x + x_offset + @block_size + @block_size, y:@y+(@block_size - @block_offset)},
{x:@x + x_offset + @block_size + @block_size, y:@y+@block_size*2},
{x:@x + x_offset + @block_size, y:@y+@block_size*2},
{x:@x + x_offset + @block_size, y:@y+(@block_size - @block_offset)},
{x:@x + x_offset, y:@y+(@block_size - @block_offset)}
]
@squareColliders = [
SquareCollider.new(points[0].x,points[0].y,{x:-1,y:-1}),
SquareCollider.new(points[1].x-COLLISIONWIDTH,points[1].y,{x:1,y:-1}),
SquareCollider.new(points[2].x-COLLISIONWIDTH,points[2].y-COLLISIONWIDTH,{x:1,y:1}),
SquareCollider.new(points[3].x,points[3].y,{x:1,y:1}),
SquareCollider.new(points[4].x-COLLISIONWIDTH,points[4].y-COLLISIONWIDTH,{x:1,y:1}),
SquareCollider.new(points[5].x,points[5].y-COLLISIONWIDTH,{x:-1,y:1}),
SquareCollider.new(points[6].x-COLLISIONWIDTH,points[6].y,{x:-1,y:1}),
SquareCollider.new(points[7].x,points[7].y-COLLISIONWIDTH,{x:-1,y:1}),
]
@colliders = [
LinearCollider.new(points[0],points[1], :neg),
LinearCollider.new(points[1],points[2], :neg),
LinearCollider.new(points[2],points[3], :pos),
LinearCollider.new(points[3],points[4], :neg),
LinearCollider.new(points[4],points[5], :pos),
LinearCollider.new(points[5],points[6], :neg),
LinearCollider.new(points[6],points[7], :pos),
LinearCollider.new(points[0],points[7], :pos)
]
elsif @orientation == :left
#args.outputs.solids << [@x + x_offset + @block_size, @y, @block_size - @block_offset, @block_size * 3 - @block_offset, @r, @g, @b]
#args.outputs.solids << [@x + x_offset, @y + @block_size, @block_size * 2 - @block_offset, @block_size - @block_offset, @r, @g, @b]
xh = @x + x_offset
#points = [
#{x:@x + x_offset, y:@y},
#{x:(@x + x_offset)+(@block_size - @block_offset), y:@y},
#{x:(@x + x_offset)+(@block_size - @block_offset),y:@y + @block_size},
#{x:(@x + x_offset)+ @block_size * 2,y:@y + @block_size},
#{x:(@x + x_offset)+ @block_size * 2,y:@y + @block_size+@block_size},
#{x:(@x + x_offset)+(@block_size - @block_offset),y:@y + @block_size+@block_size},
#{x:(@x + x_offset)+(@block_size - @block_offset), y:@y+ @block_size * 3 - @block_offset},
#{x:@x + x_offset , y:@y+ @block_size * 3 - @block_offset}
#]
points = [
{x:@x + x_offset + @block_size, y:@y},
{x:@x + x_offset + @block_size + (@block_size - @block_offset), y:@y},
{x:@x + x_offset + @block_size + (@block_size - @block_offset),y:@y+@block_size*3- @block_offset},
{x:@x + x_offset + @block_size, y:@y+@block_size*3- @block_offset},
{x:@x + x_offset+@block_size, y:@y+@block_size*2- @block_offset},
{x:@x + x_offset, y:@y+@block_size*2- @block_offset},
{x:@x + x_offset, y:@y+@block_size},
{x:@x + x_offset+@block_size, y:@y+@block_size}
]
@squareColliders = [
SquareCollider.new(points[0].x,points[0].y,{x:-1,y:-1}),
SquareCollider.new(points[1].x-COLLISIONWIDTH,points[1].y,{x:1,y:-1}),
SquareCollider.new(points[2].x-COLLISIONWIDTH,points[2].y-COLLISIONWIDTH,{x:1,y:1}),
SquareCollider.new(points[3].x,points[3].y-COLLISIONWIDTH,{x:-1,y:1}),
SquareCollider.new(points[4].x-COLLISIONWIDTH,points[4].y,{x:-1,y:1}),
SquareCollider.new(points[5].x,points[5].y-COLLISIONWIDTH,{x:-1,y:1}),
SquareCollider.new(points[6].x,points[6].y,{x:-1,y:-1}),
SquareCollider.new(points[7].x-COLLISIONWIDTH,points[7].y-COLLISIONWIDTH,{x:-1,y:-1}),
]
@colliders = [
LinearCollider.new(points[0],points[1], :neg),
LinearCollider.new(points[1],points[2], :neg),
LinearCollider.new(points[2],points[3], :pos),
LinearCollider.new(points[3],points[4], :neg),
LinearCollider.new(points[4],points[5], :pos),
LinearCollider.new(points[5],points[6], :neg),
LinearCollider.new(points[6],points[7], :neg),
LinearCollider.new(points[0],points[7], :pos)
]
elsif @orientation == :down
#args.outputs.solids << [@x + x_offset, @y + @block_size, @block_size * 3 - @block_offset, @block_size - @block_offset, @r, @g, @b]
#args.outputs.solids << [@x + x_offset + @block_size, @y, @block_size - @block_offset, @block_size * 2 - @block_offset, @r, @g, @b]
points = [
{x:@x + x_offset, y:@y+(@block_size*2)-@block_offset},
{x:@x + x_offset+ @block_size*3-@block_offset, y:@y+(@block_size*2)-@block_offset},
{x:@x + x_offset+ @block_size*3-@block_offset, y:@y+(@block_size)},
{x:@x + x_offset+ @block_size*2-@block_offset, y:@y+(@block_size)},
{x:@x + x_offset+ @block_size*2-@block_offset, y:@y},#
{x:@x + x_offset+ @block_size, y:@y},#
{x:@x + x_offset + @block_size, y:@y+(@block_size)},
{x:@x + x_offset, y:@y+(@block_size)}
]
@squareColliders = [
SquareCollider.new(points[0].x,points[0].y-COLLISIONWIDTH,{x:-1,y:1}),
SquareCollider.new(points[1].x-COLLISIONWIDTH,points[1].y-COLLISIONWIDTH,{x:1,y:1}),
SquareCollider.new(points[2].x-COLLISIONWIDTH,points[2].y,{x:1,y:-1}),
SquareCollider.new(points[3].x,points[3].y-COLLISIONWIDTH,{x:1,y:-1}),
SquareCollider.new(points[4].x-COLLISIONWIDTH,points[4].y,{x:1,y:-1}),
SquareCollider.new(points[5].x,points[5].y,{x:-1,y:-1}),
SquareCollider.new(points[6].x-COLLISIONWIDTH,points[6].y-COLLISIONWIDTH,{x:-1,y:-1}),
SquareCollider.new(points[7].x,points[7].y,{x:-1,y:-1}),
]
@colliders = [
LinearCollider.new(points[0],points[1], :pos),
LinearCollider.new(points[1],points[2], :pos),
LinearCollider.new(points[2],points[3], :neg),
LinearCollider.new(points[3],points[4], :pos),
LinearCollider.new(points[4],points[5], :neg),
LinearCollider.new(points[5],points[6], :pos),
LinearCollider.new(points[6],points[7], :neg),
LinearCollider.new(points[0],points[7], :neg)
]
end
return points
end
def draw(args)
#Offset the coordinates to the edge of the game area
x_offset = (args.state.board_width + args.grid.w / 8) + (@block_offset / 2)
if @orientation == :right
#args.outputs.solids << [@x + x_offset, @y, @block_size - @block_offset, @block_size * 3 - @block_offset, @r, @g, @b]
args.outputs.solids << {x: (@x + x_offset), y: @y, w: @block_size - @block_offset, h: (@block_size * 3 - @block_offset), r: @r , g: @g, b: @b}
#args.outputs.solids << [@x + x_offset, @y + @block_size, @block_size * 2, @block_size, @r, @g, @b]
args.outputs.solids << {x: (@x + x_offset), y: (@y + @block_size), w: (@block_size * 2), h: (@block_size), r: @r , g: @g, b: @b }
elsif @orientation == :up
#args.outputs.solids << [@x + x_offset, @y, @block_size * 3 - @block_offset, @block_size - @block_offset, @r, @g, @b]
args.outputs.solids << {x: (@x + x_offset), y: (@y), w: (@block_size * 3 - @block_offset), h: (@block_size - @block_offset), r: @r , g: @g, b: @b}
#args.outputs.solids << [@x + x_offset + @block_size, @y, @block_size, @block_size * 2, @r, @g, @b]
args.outputs.solids << {x: (@x + x_offset + @block_size), y: (@y), w: (@block_size), h: (@block_size * 2), r: @r , g: @g, b: @b}
elsif @orientation == :left
#args.outputs.solids << [@x + x_offset + @block_size, @y, @block_size - @block_offset, @block_size * 3 - @block_offset, @r, @g, @b]
args.outputs.solids << {x: (@x + x_offset + @block_size), y: (@y), w: (@block_size - @block_offset), h: (@block_size * 3 - @block_offset), r: @r , g: @g, b: @b}
#args.outputs.solids << [@x + x_offset, @y + @block_size, @block_size * 2 - @block_offset, @block_size - @block_offset, @r, @g, @b]
args.outputs.solids << {x: (@x + x_offset), y: (@y + @block_size), w: (@block_size * 2 - @block_offset), h: (@block_size - @block_offset), r: @r , g: @g, b: @b}
elsif @orientation == :down
#args.outputs.solids << [@x + x_offset, @y + @block_size, @block_size * 3 - @block_offset, @block_size - @block_offset, @r, @g, @b]
args.outputs.solids << {x: (@x + x_offset), y: (@y + @block_size), w: (@block_size * 3 - @block_offset), h: (@block_size - @block_offset), r: @r , g: @g, b: @b}
#args.outputs.solids << [@x + x_offset + @block_size, @y, @block_size - @block_offset, @block_size * 2 - @block_offset, @r, @g, @b]
args.outputs.solids << {x: (@x + x_offset + @block_size), y: (@y), w: (@block_size - @block_offset), h: ( @block_size * 2 - @block_offset), r: @r , g: @g, b: @b}
end
#psize = 5.0
#for p in @shapePoints
#args.outputs.solids << [p.x-psize/2, p.y-psize/2, psize, psize, 0, 0, 0]
#end
args.outputs.labels << [@x + x_offset + (@block_size * 2 - @block_offset)/2, (@y) + (@block_size * 2 - @block_offset)/2, @count.to_s]
end
def updateOne_old args
didHit = false
hitter = nil
toCollide = nil
for b in args.state.balls
if [b.x, b.y, b.width, b.height].intersect_rect?(@bold)
didSquare = false
for s in @squareColliders
if (s.collision?(args, b))
didSquare = true
didHit = true
#s.collide(args, b)
toCollide = s
hitter = b
break
end
end
if (didSquare == false)
for c in @colliders
#puts args.state.ball.velocity
if c.collision?(args, b.getPoints(args),b)
#c.collide args, b
toCollide = c
didHit = true
hitter = b
break
end
end
end
end
if didHit
break
end
end
if (didHit)
@count=0
hitter.makeLeader args
#toCollide.collide(args, hitter)
args.state.tshapes.delete(self)
#puts "HIT!" + hitter.number
end
end
def update_old args
if (@count == 1)
updateOne args
return
end
didHit = false
hitter = nil
for b in args.state.ballParents
if [b.x, b.y, b.width, b.height].intersect_rect?(@bold)
didSquare = false
for s in @squareColliders
if (s.collision?(args, b))
didSquare = true
didHit=true
s.collide(args, b)
hitter = b
end
end
if (didSquare == false)
for c in @colliders
#puts args.state.ball.velocity
if c.collision?(args, b.getPoints(args), b)
c.collide args, b
didHit=true
hitter = b
end
end
end
end
end
if (didHit)
@count=@count-1
@damageCount.append([(hitter.leastChain+1 - hitter.number)-1, args.state.tick_count])
if (@count == 0)
args.state.tshapes.delete(self)
return
end
end
i=0
while i < @damageCount.length
if @damageCount[i][0] <= 0
@damageCount.delete_at(i)
i-=1
elsif @damageCount[i][1].elapsed_time > BALL_DISTANCE
@count-=1
@damageCount[i][0]-=1
end
if (@count == 0)
args.state.tshapes.delete(self)
return
end
i+=1
end
end #end update
def update args
universalUpdate args, self
end
end
class Line
attr_accessor :count, :x, :y, :home, :bold, :squareColliders, :colliders, :damageCount
def initialize(args, x, y, block_size, orientation, block_offset)
@x = x * block_size
@y = y * block_size
@block_size = block_size
@block_offset = block_offset
@orientation = orientation
@damageCount = []
@home = "lines"
Kernel.srand()
@r = rand(255)
@g = rand(255)
@b = rand(255)
@count = rand(MAX_COUNT)+1
@shapePoints = getShapePoints(args)
minX={x:INFINITY, y:0}
minY={x:0, y:INFINITY}
maxX={x:-INFINITY, y:0}
maxY={x:0, y:-INFINITY}
for p in @shapePoints
if p.x < minX.x
minX = p
end
if p.x > maxX.x
maxX = p
end
if p.y < minY.y
minY = p
end
if p.y > maxY.y
maxY = p
end
end
hypotenuse=args.state.ball_hypotenuse
@bold = [(minX.x-hypotenuse/2)-1, (minY.y-hypotenuse/2)-1, -((minX.x-hypotenuse/2)-1)+(maxX.x + hypotenuse + 2), -((minY.y-hypotenuse/2)-1)+(maxY.y + hypotenuse + 2)]
end
def getShapePoints(args)
points=[]
x_offset = (args.state.board_width + args.grid.w / 8) + (@block_offset / 2)
if @orientation == :right
#args.outputs.solids << [@x + x_offset, @y, @block_size * 3 - @block_offset, @block_size - @block_offset, @r, @g, @b]
xa =@x + x_offset
ya =@y
wa =@block_size * 3 - @block_offset
ha =(@block_size - @block_offset)
elsif @orientation == :up
#args.outputs.solids << [@x + x_offset, @y, @block_size - @block_offset, @block_size * 3 - @block_offset, @r, @g, @b]
xa =@x + x_offset
ya =@y
wa =@block_size - @block_offset
ha =@block_size * 3 - @block_offset
elsif @orientation == :left
#args.outputs.solids << [@x + x_offset, @y, @block_size * 3 - @block_offset, @block_size - @block_offset, @r, @g, @b]
xa =@x + x_offset
ya =@y
wa =@block_size * 3 - @block_offset
ha =@block_size - @block_offset
elsif @orientation == :down
#args.outputs.solids << [@x + x_offset, @y, @block_size - @block_offset, @block_size * 3 - @block_offset, @r, @g, @b]
xa =@x + x_offset
ya =@y
wa =@block_size - @block_offset
ha =@block_size * 3 - @block_offset
end
points = [
{x: xa, y:ya},
{x: xa + wa,y:ya},
{x: xa + wa,y:ya+ha},
{x: xa, y:ya+ha},
]
@squareColliders = [
SquareCollider.new(points[0].x,points[0].y,{x:-1,y:-1}),
SquareCollider.new(points[1].x-COLLISIONWIDTH,points[1].y,{x:1,y:-1}),
SquareCollider.new(points[2].x-COLLISIONWIDTH,points[2].y-COLLISIONWIDTH,{x:1,y:1}),
SquareCollider.new(points[3].x,points[3].y-COLLISIONWIDTH,{x:-1,y:1}),
]
@colliders = [
LinearCollider.new(points[0],points[1], :neg),
LinearCollider.new(points[1],points[2], :neg),
LinearCollider.new(points[2],points[3], :pos),
LinearCollider.new(points[0],points[3], :pos),
]
return points
end
def update args
universalUpdate args, self
end
def draw(args)
x_offset = (args.state.board_width + args.grid.w / 8) + @block_offset / 2
if @orientation == :right
args.outputs.solids << [@x + x_offset, @y, @block_size * 3 - @block_offset, @block_size - @block_offset, @r, @g, @b]
elsif @orientation == :up
args.outputs.solids << [@x + x_offset, @y, @block_size - @block_offset, @block_size * 3 - @block_offset, @r, @g, @b]
elsif @orientation == :left
args.outputs.solids << [@x + x_offset, @y, @block_size * 3 - @block_offset, @block_size - @block_offset, @r, @g, @b]
elsif @orientation == :down
args.outputs.solids << [@x + x_offset, @y, @block_size - @block_offset, @block_size * 3 - @block_offset, @r, @g, @b]
end
args.outputs.labels << [@x + x_offset + (@block_size * 2 - @block_offset)/2, (@y) + (@block_size * 2 - @block_offset)/2, @count.to_s]
end
end
</code></pre>
<h3 id='----physics-and-collisions---arbitrary-collision---linear_collider-rb'>Physics And Collisions - Arbitrary Collision - linear_collider.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/09_arbitrary_collision/app/linear_collider.rb
COLLISIONWIDTH=8
class LinearCollider
attr_reader :pointA, :pointB
def initialize (pointA, pointB, mode,collisionWidth=COLLISIONWIDTH)
@pointA = pointA
@pointB = pointB
@mode = mode
@collisionWidth = collisionWidth
if (@pointA.x > @pointB.x)
@pointA, @pointB = @pointB, @pointA
end
@linearCollider_collision_once = false
end
def collisionSlope args
if (@[email protected] == 0)
return INFINITY
end
return (@pointB.y - @pointA.y) / (@pointB.x - @pointA.x)
end
def collision? (args, points, ball=nil)
slope = collisionSlope args
result = false
# calculate a vector with a magnitude of (1/2)collisionWidth and a direction perpendicular to the collision line
vect=nil;mag=nil;vect=nil;
if @mode == :both
vect = {x: @pointB.x - @pointA.x, y:@pointB.y - @pointA.y}
mag = (vect.x**2 + vect.y**2)**0.5
vect = {y: -1*(vect.x/(mag))*@collisionWidth*0.5, x: (vect.y/(mag))*@collisionWidth*0.5}
else
vect = {x: @pointB.x - @pointA.x, y:@pointB.y - @pointA.y}
mag = (vect.x**2 + vect.y**2)**0.5
vect = {y: -1*(vect.x/(mag))*@collisionWidth, x: (vect.y/(mag))*@collisionWidth}
end
rpointA=nil;rpointB=nil;rpointC=nil;rpointD=nil;
if @mode == :pos
rpointA = {x:@pointA.x + vect.x, y:@pointA.y + vect.y}
rpointB = {x:@pointB.x + vect.x, y:@pointB.y + vect.y}
rpointC = {x:@pointB.x, y:@pointB.y}
rpointD = {x:@pointA.x, y:@pointA.y}
elsif @mode == :neg
rpointA = {x:@pointA.x, y:@pointA.y}
rpointB = {x:@pointB.x, y:@pointB.y}
rpointC = {x:@pointB.x - vect.x, y:@pointB.y - vect.y}
rpointD = {x:@pointA.x - vect.x, y:@pointA.y - vect.y}
elsif @mode == :both
rpointA = {x:@pointA.x + vect.x, y:@pointA.y + vect.y}
rpointB = {x:@pointB.x + vect.x, y:@pointB.y + vect.y}
rpointC = {x:@pointB.x - vect.x, y:@pointB.y - vect.y}
rpointD = {x:@pointA.x - vect.x, y:@pointA.y - vect.y}
end
#four point rectangle
if ball != nil
xs = [rpointA.x,rpointB.x,rpointC.x,rpointD.x]
ys = [rpointA.y,rpointB.y,rpointC.y,rpointD.y]
correct = 1
rect1 = [ball.x, ball.y, ball.width, ball.height]
#$r1 = rect1
rect2 = [xs.min-correct,ys.min-correct,(xs.max-xs.min)+correct*2,(ys.max-ys.min)+correct*2]
#$r2 = rect2
if rect1.intersect_rect?(rect2) == false
return false
end
end
#area of a triangle
triArea = -> (a,b,c) { ((a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y))/2.0).abs }
#if at least on point is in the rectangle then collision? is true - otherwise false
for point in points
#Check whether a given point lies inside a rectangle or not:
#if the sum of the area of traingls, PAB, PBC, PCD, PAD equal the area of the rec, then an intersection has occured
areaRec = triArea.call(rpointA, rpointB, rpointC)+triArea.call(rpointA, rpointC, rpointD)
areaSum = [
triArea.call(point, rpointA, rpointB),triArea.call(point, rpointB, rpointC),
triArea.call(point, rpointC, rpointD),triArea.call(point, rpointA, rpointD)
].inject(0){|sum,x| sum + x }
e = 0.0001 #allow for minor error
if areaRec>= areaSum-e and areaRec<= areaSum+e
result = true
#return true
break
end
end
#args.outputs.lines << [@pointA.x, @pointA.y, @pointB.x, @pointB.y, 000, 000, 000]
#args.outputs.lines << [rpointA.x, rpointA.y, rpointB.x, rpointB.y, 255, 000, 000]
#args.outputs.lines << [rpointC.x, rpointC.y, rpointD.x, rpointD.y, 000, 000, 255]
#puts (rpointA.x.to_s + " " + rpointA.y.to_s + " " + rpointB.x.to_s + " "+ rpointB.y.to_s)
return result
end #end collision?
def getRepelMagnitude (fbx, fby, vrx, vry, ballMag)
a = fbx ; b = vrx ; c = fby
d = vry ; e = ballMag
if b**2 + d**2 == 0
#unexpected
end
x1 = (-a*b+-c*d + (e**2 * b**2 - b**2 * c**2 + 2*a*b*c*d + e**2 + d**2 - a**2 * d**2)**0.5)/(b**2 + d**2)
x2 = -((a*b + c*d + (e**2 * b**2 - b**2 * c**2 + 2*a*b*c*d + e**2 * d**2 - a**2 * d**2)**0.5)/(b**2 + d**2))
err = 0.00001
o = ((fbx + x1*vrx)**2 + (fby + x1*vry)**2 ) ** 0.5
p = ((fbx + x2*vrx)**2 + (fby + x2*vry)**2 ) ** 0.5
r = 0
if (ballMag >= o-err and ballMag <= o+err)
r = x1
elsif (ballMag >= p-err and ballMag <= p+err)
r = x2
else
#unexpected
end
return r
end
def collide args, ball
slope = collisionSlope args
# perpVect: normal vector perpendicular to collision
perpVect = {x: @pointB.x - @pointA.x, y:@pointB.y - @pointA.y}
mag = (perpVect.x**2 + perpVect.y**2)**0.5
perpVect = {x: perpVect.x/(mag), y: perpVect.y/(mag)}
perpVect = {x: -perpVect.y, y: perpVect.x}
if perpVect.y > 0 #ensure perpVect points upward
perpVect = {x: perpVect.x*-1, y: perpVect.y*-1}
end
previousPosition = {
x:ball.x-ball.velocity.x,
y:ball.y-ball.velocity.y
}
yInterc = @pointA.y + -slope*@pointA.x
if slope == INFINITY
if previousPosition.x < @pointA.x
perpVect = {x: perpVect.x*-1, y: perpVect.y*-1}
yInterc = -INFINITY
end
elsif previousPosition.y < slope*previousPosition.x + yInterc #check if ball is bellow or above the collider to determine if perpVect is - or +
perpVect = {x: perpVect.x*-1, y: perpVect.y*-1}
end
velocityMag = (ball.velocity.x**2 + ball.velocity.y**2)**0.5
theta_ball=Math.atan2(ball.velocity.y,ball.velocity.x) #the angle of the ball's velocity
theta_repel=Math.atan2(perpVect.y,perpVect.x) #the angle of the repelling force(perpVect)
fbx = velocityMag * Math.cos(theta_ball) #the x component of the ball's velocity
fby = velocityMag * Math.sin(theta_ball) #the y component of the ball's velocity
#the magnitude of the repelling force
repelMag = getRepelMagnitude(fbx, fby, perpVect.x, perpVect.y, (ball.velocity.x**2 + ball.velocity.y**2)**0.5)
frx = repelMag* Math.cos(theta_repel) #the x component of the repel's velocity | magnitude is set to twice of fbx
fry = repelMag* Math.sin(theta_repel) #the y component of the repel's velocity | magnitude is set to twice of fby
fsumx = fbx+frx #sum of x forces
fsumy = fby+fry #sum of y forces
fr = velocityMag#fr is the resulting magnitude
thetaNew = Math.atan2(fsumy, fsumx) #thetaNew is the resulting angle
xnew = fr*Math.cos(thetaNew)#resulting x velocity
ynew = fr*Math.sin(thetaNew)#resulting y velocity
if (velocityMag < MAX_VELOCITY)
ball.velocity = Vector2d.new(xnew*1.1, ynew*1.1)
else
ball.velocity = Vector2d.new(xnew, ynew)
end
end
end
</code></pre>
<h3 id='----physics-and-collisions---arbitrary-collision---main-rb'>Physics And Collisions - Arbitrary Collision - main.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/09_arbitrary_collision/app/main.rb
INFINITY= 10**10
MAX_VELOCITY = 8.0
BALL_COUNT = 90
BALL_DISTANCE = 20
require 'app/vector2d.rb'
require 'app/blocks.rb'
require 'app/ball.rb'
require 'app/rectangle.rb'
require 'app/linear_collider.rb'
require 'app/square_collider.rb'
#Method to init default values
def defaults args
args.state.board_width ||= args.grid.w / 4
args.state.board_height ||= args.grid.h
args.state.game_area ||= [(args.state.board_width + args.grid.w / 8), 0, args.state.board_width, args.grid.h]
args.state.balls ||= []
args.state.num_balls ||= 0
args.state.ball_created_at ||= args.state.tick_count
args.state.ball_hypotenuse = (10**2 + 10**2)**0.5
args.state.ballParents ||=nil
init_blocks args
init_balls args
end
begin :default_methods
def init_blocks args
block_size = args.state.board_width / 8
#Space inbetween each block
block_offset = 4
args.state.squares ||=[
Square.new(args, 2, 0, block_size, :right, block_offset),
Square.new(args, 5, 0, block_size, :right, block_offset),
Square.new(args, 6, 7, block_size, :right, block_offset)
]
#Possible orientations are :right, :left, :up, :down
args.state.tshapes ||= [
TShape.new(args, 0, 6, block_size, :left, block_offset),
TShape.new(args, 3, 3, block_size, :down, block_offset),
TShape.new(args, 0, 3, block_size, :right, block_offset),
TShape.new(args, 0, 11, block_size, :up, block_offset)
]
args.state.lines ||= [
Line.new(args,3, 8, block_size, :down, block_offset),
Line.new(args, 7, 3, block_size, :up, block_offset),
Line.new(args, 3, 7, block_size, :right, block_offset)
]
#exit()
end
def init_balls args
return unless args.state.num_balls < BALL_COUNT
#only create a new ball every 10 ticks
return unless args.state.ball_created_at.elapsed_time > 10
if (args.state.num_balls == 0)
args.state.balls.append(Ball.new(args,args.state.num_balls,BALL_COUNT-1, nil, nil))
args.state.ballParents = [args.state.balls[0]]
else
args.state.balls.append(Ball.new(args,args.state.num_balls,BALL_COUNT-1, args.state.balls.last, nil) )
args.state.balls[-2].child = args.state.balls[-1]
end
args.state.ball_created_at = args.state.tick_count
args.state.num_balls += 1
end
end
#Render loop
def render args
bgClr = {r:10, g:10, b:200}
bgClr = {r:255-30, g:255-30, b:255-30}
args.outputs.solids << [0, 0, $args.grid.right, $args.grid.top, bgClr[:r], bgClr[:g], bgClr[:b]];
args.outputs.borders << args.state.game_area
render_instructions args
render_shapes args
render_balls args
#args.state.rectangle.draw args
args.outputs.sprites << [$args.grid.right-(args.state.board_width + args.grid.w / 8), 0, $args.grid.right, $args.grid.top, "sprites/square-white-2.png", 0, 255, bgClr[:r], bgClr[:g], bgClr[:b]]
args.outputs.sprites << [0, 0, (args.state.board_width + args.grid.w / 8), $args.grid.top, "sprites/square-white-2.png", 0, 255, bgClr[:r], bgClr[:g], bgClr[:b]]
end
begin :render_methods
def render_instructions args
#gtk.current_framerate
args.outputs.labels << [20, $args.grid.top-20, "FPS: " + $gtk.current_framerate.to_s]
if (args.state.balls != nil && args.state.balls[0] != nil)
bx = args.state.balls[0].velocity.x
by = args.state.balls[0].velocity.y
bmg = (bx**2.0 + by**2.0)**0.5
args.outputs.labels << [20, $args.grid.top-20-20, "V: " + bmg.to_s ]
end
end
def render_shapes args
for s in args.state.squares
s.draw args
end
for l in args.state.lines
l.draw args
end
for t in args.state.tshapes
t.draw args
end
end
def render_balls args
#args.state.balls.each do |ball|
#ball.draw args
#end
args.outputs.sprites << args.state.balls.map do |ball|
ball.getDraw args
end
end
end
#Calls all methods necessary for performing calculations
def calc args
for b in args.state.ballParents
b.update args
end
for s in args.state.squares
s.update args
end
for l in args.state.lines
l.update args
end
for t in args.state.tshapes
t.update args
end
end
begin :calc_methods
end
def tick args
defaults args
render args
calc args
end
</code></pre>
<h3 id='----physics-and-collisions---arbitrary-collision---paddle-rb'>Physics And Collisions - Arbitrary Collision - paddle.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/09_arbitrary_collision/app/paddle.rb
class Paddle
attr_accessor :enabled
def initialize ()
@x=WIDTH/2
@y=100
@width=100
@height=20
@speed=10
@xyCollision = LinearCollider.new({x: @x,y: @y+@height+5}, {x: @x+@width, y: @y+@height+5})
@xyCollision2 = LinearCollider.new({x: @x,y: @y}, {x: @x+@width, y: @y}, :pos)
@xyCollision3 = LinearCollider.new({x: @x,y: @y}, {x: @x, y: @y+@height+5})
@xyCollision4 = LinearCollider.new({x: @x+@width,y: @y}, {x: @x+@width, y: @y+@height+5}, :pos)
@enabled = true
end
def update args
@xyCollision.resetPoints({x: @x,y: @y+@height+5}, {x: @x+@width, y: @y+@height+5})
@xyCollision2.resetPoints({x: @x,y: @y}, {x: @x+@width, y: @y})
@xyCollision3.resetPoints({x: @x,y: @y}, {x: @x, y: @y+@height+5})
@xyCollision4.resetPoints({x: @x+@width,y: @y}, {x: @x+@width, y: @y+@height+5})
@xyCollision.update args
@xyCollision2.update args
@xyCollision3.update args
@xyCollision4.update args
args.inputs.keyboard.key_held.left ||= false
args.inputs.keyboard.key_held.right ||= false
if not (args.inputs.keyboard.key_held.left == args.inputs.keyboard.key_held.right)
if args.inputs.keyboard.key_held.left && @enabled
@x-=@speed
elsif args.inputs.keyboard.key_held.right && @enabled
@x+=@speed
end
end
xmin =WIDTH/4
xmax = 3*(WIDTH/4)
@x = (@x+@width > xmax) ? xmax-@width : (@x<xmin) ? xmin : @x;
end
def render args
args.outputs.solids << [@x,@y,@width,@height,255,0,0];
end
def rect
[@x, @y, @width, @height]
end
end
</code></pre>
<h3 id='----physics-and-collisions---arbitrary-collision---rectangle-rb'>Physics And Collisions - Arbitrary Collision - rectangle.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/09_arbitrary_collision/app/rectangle.rb
class Rectangle
def initialize args
@image = "sprites/roundSquare_white.png"
@width = 160.0
@height = 80.0
@x=$args.grid.right/2.0 - @width/2.0
@y=$args.grid.top/2.0 - @height/2.0
@xtmp = @width * (1.0/10.0)
@ytmp = @height * (1.0/10.0)
#ball0 = args.state.balls[0]
#hypotenuse = (args.state.balls[0].width**2 + args.state.balls[0].height**2)**0.5
hypotenuse=args.state.ball_hypotenuse
@boldXY = {x:(@x-hypotenuse/2)-1, y:(@y-hypotenuse/2)-1}
@boldWidth = @width + hypotenuse + 2
@boldHeight = @height + hypotenuse + 2
@bold = [(@x-hypotenuse/2)-1,(@y-hypotenuse/2)-1,@width + hypotenuse + 2,@height + hypotenuse + 2]
@points = [
{x:@x, y:@y+@ytmp},
{x:@x+@xtmp, y:@y},
{x:@x+@width-@xtmp, y:@y},
{x:@x+@width, y:@y+@ytmp},
{x:@x+@width, y:@y+@height-@ytmp},#
{x:@x+@width-@xtmp, y:@y+@height},
{x:@x+@xtmp, y:@y+@height},
{x:@x, y:@y+@height-@ytmp}
]
@colliders = []
#i = 0
#while i < @points.length-1
#@colliders.append(LinearCollider.new(@points[i],@points[i+1],:pos))
#i+=1
#end
@colliders.append(LinearCollider.new(@points[0],@points[1], :neg))
@colliders.append(LinearCollider.new(@points[1],@points[2], :neg))
@colliders.append(LinearCollider.new(@points[2],@points[3], :neg))
@colliders.append(LinearCollider.new(@points[3],@points[4], :neg))
@colliders.append(LinearCollider.new(@points[4],@points[5], :pos))
@colliders.append(LinearCollider.new(@points[5],@points[6], :pos))
@colliders.append(LinearCollider.new(@points[6],@points[7], :pos))
@colliders.append(LinearCollider.new(@points[0],@points[7], :pos))
end
def update args
for b in args.state.balls
if [b.x, b.y, b.width, b.height].intersect_rect?(@bold)
for c in @colliders
if c.collision?(args, b.getPoints(args),b)
c.collide args, b
end
end
end
end
end
def draw args
args.outputs.sprites << [
@x, # X
@y, # Y
@width, # W
@height, # H
@image, # PATH
0, # ANGLE
255, # ALPHA
219, # RED_SATURATION
112, # GREEN_SATURATION
147 # BLUE_SATURATION
]
#args.outputs.sprites << [@x, @y, @width, @height, "sprites/roundSquare_small_black.png"]
end
def serialize
{x: @x, y:@y}
end
def inspect
serialize.to_s
end
def to_s
serialize.to_s
end
end
</code></pre>
<h3 id='----physics-and-collisions---arbitrary-collision---square_collider-rb'>Physics And Collisions - Arbitrary Collision - square_collider.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/09_arbitrary_collision/app/square_collider.rb
class SquareCollider
def initialize x,y,direction,size=COLLISIONWIDTH
@x = x
@y = y
@size = size
@direction = direction
end
def collision? args, ball
#args.outputs.solids << [@x, @y, @size, @size, 000, 255, 255]
return [@x,@y,@size,@size].intersect_rect?([ball.x,ball.y,ball.width,ball.height])
end
def collide args, ball
vmag = (ball.velocity.x**2.0 +ball.velocity.y**2.0)**0.5
a = ((2.0**0.5)*vmag)/2.0
if vmag < MAX_VELOCITY
ball.velocity.x = (a) * @direction.x * 1.1
ball.velocity.y = (a) * @direction.y * 1.1
else
ball.velocity.x = (a) * @direction.x
ball.velocity.y = (a) * @direction.y
end
end
end
</code></pre>
<h3 id='----physics-and-collisions---arbitrary-collision---vector2d-rb'>Physics And Collisions - Arbitrary Collision - vector2d.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/09_arbitrary_collision/app/vector2d.rb
class Vector2d
attr_accessor :x, :y
def initialize x=0, y=0
@x=x
@y=y
end
#returns a vector multiplied by scalar x
#x [float] scalar
def mult x
r = Vector2d.new(0,0)
r.x=@x*x
r.y=@y*x
r
end
# vect [Vector2d] vector to copy
def copy vect
Vector2d.new(@x, @y)
end
#returns a new vector equivalent to this+vect
#vect [Vector2d] vector to add to self
def add vect
Vector2d.new(@x+vect.x,@y+vect.y)
end
#returns a new vector equivalent to this-vect
#vect [Vector2d] vector to subtract to self
def sub vect
Vector2d.new(@x-vect.c, @y-vect.y)
end
#return the magnitude of the vector
def mag
((@x**2)+(@y**2))**0.5
end
#returns a new normalize version of the vector
def normalize
Vector2d.new(@x/mag, @y/mag)
end
#TODO delet?
def distABS vect
(((vect.x-@x)**2+(vect.y-@y)**2)**0.5).abs()
end
end
</code></pre>
<h3 id='----physics-and-collisions---collision-with-object-removal---ball-rb'>Physics And Collisions - Collision With Object Removal - ball.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/10_collision_with_object_removal/app/ball.rb
class Ball
#TODO limit accessors?
attr_accessor :xy, :width, :height, :velocity
#@xy [Vector2d] x,y position
#@velocity [Vector2d] velocity of ball
def initialize
@xy = Vector2d.new(WIDTH/2,500)
@velocity = Vector2d.new(4,-4)
@width = 20
@height = 20
end
#move the ball according to its velocity
def update args
@[email protected]
@[email protected]
end
#render the ball to the screen
def render args
args.outputs.solids << [@xy.x,@xy.y,@width,@height,255,0,255];
#args.outputs.labels << [20,HEIGHT-50,"velocity: " [email protected]_s+","[email protected]_s + " magnitude:" + @velocity.mag.to_s]
end
def rect
[@xy.x,@xy.y,@width,@height]
end
end
</code></pre>
<h3 id='----physics-and-collisions---collision-with-object-removal---linear_collider-rb'>Physics And Collisions - Collision With Object Removal - linear_collider.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/10_collision_with_object_removal/app/linear_collider.rb
#The LinearCollider (theoretically) produces collisions upon a line segment defined point.y two x,y cordinates
class LinearCollider
#start [Array of length 2] start of the line segment as a x,y cordinate
#last [Array of length 2] end of the line segment as a x,y cordinate
#inorder for the LinearCollider to be functional the line segment must be said to have a thickness
#(as it is unlikly that a colliding object will land exactly on the linesegment)
#extension defines if the line's thickness extends negatively or positively
#extension :pos extends positively
#extension :neg extends negatively
#thickness [float] how thick the line should be (should always be atleast as large as the magnitude of the colliding object)
def initialize (pointA, pointB, extension=:neg, thickness=10)
@pointA = pointA
@pointB = pointB
@thickness = thickness
@extension = extension
@pointAExtended={
x: @pointA.x + @thickness*(@extension == :neg ? -1 : 1),
y: @pointA.y + @thickness*(@extension == :neg ? -1 : 1)
}
@pointBExtended={
x: @pointB.x + @thickness*(@extension == :neg ? -1 : 1),
y: @pointB.y + @thickness*(@extension == :neg ? -1 : 1)
}
end
def resetPoints(pointA,pointB)
@pointA = pointA
@pointB = pointB
@pointAExtended={
x:@pointA.x + @thickness*(@extension == :neg ? -1 : 1),
y:@pointA.y + @thickness*(@extension == :neg ? -1 : 1)
}
@pointBExtended={
x:@pointB.x + @thickness*(@extension == :neg ? -1 : 1),
y:@pointB.y + @thickness*(@extension == :neg ? -1 : 1)
}
end
#TODO: Ugly function
def slope (pointA, pointB)
return (pointB.x==pointA.x) ? INFINITY : (pointB.y+-pointA.y)/(pointB.x+-pointA.x)
end
#TODO: Ugly function
def intercept(pointA, pointB)
if (slope(pointA, pointB) == INFINITY)
-INFINITY
elsif slope(pointA, pointB) == -1*INFINITY
INFINITY
else
pointA.y+-1.0*(slope(pointA, pointB)*pointA.x)
end
end
def calcY(pointA, pointB, x)
return slope(pointA, pointB)*x + intercept(pointA, pointB)
end
#test if a collision has occurred
def isCollision? (point)
#INFINITY slop breaks down when trying to determin collision, ergo it requires a special test
if slope(@pointA, @pointB) == INFINITY &&
point.x >= [@pointA.x,@pointB.x].min+(@extension == :pos ? -@thickness : 0) &&
point.x <= [@pointA.x,@pointB.x].max+(@extension == :neg ? @thickness : 0) &&
point.y >= [@pointA.y,@pointB.y].min && point.y <= [@pointA.y,@pointB.y].max
return true
end
isNegInLine = @extension == :neg &&
point.y <= slope(@pointA, @pointB)*point.x+intercept(@pointA,@pointB) &&
point.y >= point.x*slope(@pointAExtended, @pointBExtended)+intercept(@pointAExtended,@pointBExtended)
isPosInLine = @extension == :pos &&
point.y >= slope(@pointA, @pointB)*point.x+intercept(@pointA,@pointB) &&
point.y <= point.x*slope(@pointAExtended, @pointBExtended)+intercept(@pointAExtended,@pointBExtended)
isInBoxBounds = point.x >= [@pointA.x,@pointB.x].min &&
point.x <= [@pointA.x,@pointB.x].max &&
point.y >= [@pointA.y,@pointB.y].min+(@extension == :neg ? -@thickness : 0) &&
point.y <= [@pointA.y,@pointB.y].max+(@extension == :pos ? @thickness : 0)
return isInBoxBounds && (isNegInLine || isPosInLine)
end
def getRepelMagnitude (fbx, fby, vrx, vry, args)
a = fbx ; b = vrx ; c = fby
d = vry ; e = args.state.ball.velocity.mag
if b**2 + d**2 == 0
puts "magnitude error"
end
x1 = (-a*b+-c*d + (e**2 * b**2 - b**2 * c**2 + 2*a*b*c*d + e**2 + d**2 - a**2 * d**2)**0.5)/(b**2 + d**2)
x2 = -((a*b + c*d + (e**2 * b**2 - b**2 * c**2 + 2*a*b*c*d + e**2 * d**2 - a**2 * d**2)**0.5)/(b**2 + d**2))
return ((a+x1*b)**2 + (c+x1*d)**2 == e**2) ? x1 : x2
end
def update args
#each of the four points on the square ball - NOTE simple to extend to a circle
points= [ {x: args.state.ball.xy.x, y: args.state.ball.xy.y},
{x: args.state.ball.xy.x+args.state.ball.width, y: args.state.ball.xy.y},
{x: args.state.ball.xy.x, y: args.state.ball.xy.y+args.state.ball.height},
{x: args.state.ball.xy.x+args.state.ball.width, y: args.state.ball.xy.y + args.state.ball.height}
]
#for each point p in points
for point in points
#isCollision.md has more information on this section
#TODO: section can certainly be simplifyed
if isCollision?(point)
u = Vector2d.new(1.0,((slope(@pointA, @pointB)==0) ? INFINITY : -1/slope(@pointA, @pointB))*1.0).normalize #normal perpendicular (to line segment) vector
#the vector with the repeling force can be u or -u depending of where the ball was coming from in relation to the line segment
previousBallPosition=Vector2d.new(point.x-args.state.ball.velocity.x,point.y-args.state.ball.velocity.y)
choiceA = (u.mult(1))
choiceB = (u.mult(-1))
vectorRepel = nil
if (slope(@pointA, @pointB))!=INFINITY && u.y < 0
choiceA, choiceB = choiceB, choiceA
end
vectorRepel = (previousBallPosition.y > calcY(@pointA, @pointB, previousBallPosition.x)) ? choiceA : choiceB
#vectorRepel = (previousBallPosition.y > slope(@pointA, @pointB)*previousBallPosition.x+intercept(@pointA,@pointB)) ? choiceA : choiceB)
if (slope(@pointA, @pointB) == INFINITY) #slope INFINITY breaks down in the above test, ergo it requires a custom test
vectorRepel = (previousBallPosition.x > @pointA.x) ? (u.mult(1)) : (u.mult(-1))
end
#puts (" " + $t[0].to_s + "," + $t[1].to_s + " " + $t[2].to_s + "," + $t[3].to_s + " " + " " + u.x.to_s + "," + u.y.to_s)
#vectorRepel now has the repeling force
mag = args.state.ball.velocity.mag
theta_ball=Math.atan2(args.state.ball.velocity.y,args.state.ball.velocity.x) #the angle of the ball's velocity
theta_repel=Math.atan2(vectorRepel.y,vectorRepel.x) #the angle of the repeling force
#puts ("theta:" + theta_ball.to_s + " " + theta_repel.to_s) #theta okay
fbx = mag * Math.cos(theta_ball) #the x component of the ball's velocity
fby = mag * Math.sin(theta_ball) #the y component of the ball's velocity
repelMag = getRepelMagnitude(fbx, fby, vectorRepel.x, vectorRepel.y, args)
frx = repelMag* Math.cos(theta_repel) #the x component of the repel's velocity | magnitude is set to twice of fbx
fry = repelMag* Math.sin(theta_repel) #the y component of the repel's velocity | magnitude is set to twice of fby
fsumx = fbx+frx #sum of x forces
fsumy = fby+fry #sum of y forces
fr = mag#fr is the resulting magnitude
thetaNew = Math.atan2(fsumy, fsumx) #thetaNew is the resulting angle
xnew = fr*Math.cos(thetaNew) #resulting x velocity
ynew = fr*Math.sin(thetaNew) #resulting y velocity
args.state.ball.velocity = Vector2d.new(xnew,ynew)
#args.state.ball.xy.add(args.state.ball.velocity)
break #no need to check the other points ?
else
end
end
end #end update
end
</code></pre>
<h3 id='----physics-and-collisions---collision-with-object-removal---main-rb'>Physics And Collisions - Collision With Object Removal - main.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/10_collision_with_object_removal/app/main.rb
# coding: utf-8
INFINITY= 10**10
WIDTH=1280
HEIGHT=720
require 'app/vector2d.rb'
require 'app/paddle.rb'
require 'app/ball.rb'
require 'app/linear_collider.rb'
#Method to init default values
def defaults args
args.state.game_board ||= [(args.grid.w / 2 - args.grid.w / 4), 0, (args.grid.w / 2), args.grid.h]
args.state.bricks ||= []
args.state.num_bricks ||= 0
args.state.game_over_at ||= 0
args.state.paddle ||= Paddle.new
args.state.ball ||= Ball.new
args.state.westWall ||= LinearCollider.new({x: args.grid.w/4, y: 0}, {x: args.grid.w/4, y: args.grid.h}, :pos)
args.state.eastWall ||= LinearCollider.new({x: 3*args.grid.w*0.25, y: 0}, {x: 3*args.grid.w*0.25, y: args.grid.h})
args.state.southWall ||= LinearCollider.new({x: 0, y: 0}, {x: args.grid.w, y: 0})
args.state.northWall ||= LinearCollider.new({x: 0, y:args.grid.h}, {x: args.grid.w, y: args.grid.h}, :pos)
#args.state.testWall ||= LinearCollider.new({x:0 , y:0},{x:args.grid.w, y:args.grid.h})
end
#Render loop
def render args
render_instructions args
render_board args
render_bricks args
end
begin :render_methods
#Method to display the instructions of the game
def render_instructions args
args.outputs.labels << [225, args.grid.h - 30, "← and → to move the paddle left and right", 0, 1]
end
def render_board args
args.outputs.borders << args.state.game_board
end
def render_bricks args
args.outputs.solids << args.state.bricks.map(&:rect)
end
end
#Calls all methods necessary for performing calculations
def calc args
add_new_bricks args
reset_game args
calc_collision args
win_game args
args.state.westWall.update args
args.state.eastWall.update args
args.state.southWall.update args
args.state.northWall.update args
args.state.paddle.update args
args.state.ball.update args
#args.state.testWall.update args
args.state.paddle.render args
args.state.ball.render args
end
begin :calc_methods
def add_new_bricks args
return if args.state.num_bricks > 40
#Width of the game board is 640px
brick_width = (args.grid.w / 2) / 10
brick_height = brick_width / 2
(4).map_with_index do |y|
#Make a box that is 10 bricks wide and 4 bricks tall
args.state.bricks += (10).map_with_index do |x|
args.state.new_entity(:brick) do |b|
b.x = x * brick_width + (args.grid.w / 2 - args.grid.w / 4)
b.y = args.grid.h - ((y + 1) * brick_height)
b.rect = [b.x + 1, b.y - 1, brick_width - 2, brick_height - 2, 235, 50 * y, 52]
#Add linear colliders to the brick
b.collider_bottom = LinearCollider.new([(b.x-2), (b.y-5)], [(b.x+brick_width+1), (b.y-5)], :pos, brick_height)
b.collider_right = LinearCollider.new([(b.x+brick_width+1), (b.y-5)], [(b.x+brick_width+1), (b.y+brick_height+1)], :pos)
b.collider_left = LinearCollider.new([(b.x-2), (b.y-5)], [(b.x-2), (b.y+brick_height+1)], :neg)
b.collider_top = LinearCollider.new([(b.x-2), (b.y+brick_height+1)], [(b.x+brick_width+1), (b.y+brick_height+1)], :neg)
# @xyCollision = LinearCollider.new({x: @x,y: @y+@height}, {x: @x+@width, y: @y+@height})
# @xyCollision2 = LinearCollider.new({x: @x,y: @y}, {x: @x+@width, y: @y}, :pos)
# @xyCollision3 = LinearCollider.new({x: @x,y: @y}, {x: @x, y: @y+@height})
# @xyCollision4 = LinearCollider.new({x: @x+@width,y: @y}, {x: @x+@width, y: @y+@height}, :pos)
b.broken = false
args.state.num_bricks += 1
end
end
end
end
def reset_game args
if args.state.ball.xy.y < 20 && args.state.game_over_at.elapsed_time > 60
#Freeze the ball
args.state.ball.velocity.x = 0
args.state.ball.velocity.y = 0
#Freeze the paddle
args.state.paddle.enabled = false
args.state.game_over_at = args.state.tick_count
end
if args.state.game_over_at.elapsed_time < 60 && args.state.tick_count > 60 && args.state.bricks.count != 0
#Display a "Game over" message
args.outputs.labels << [100, 100, "GAME OVER", 10]
end
#If 60 frames have passed since the game ended, restart the game
if args.state.game_over_at != 0 && args.state.game_over_at.elapsed_time == 60
# FIXME: only put value types in state
args.state.ball = Ball.new
# FIXME: only put value types in state
args.state.paddle = Paddle.new
args.state.bricks = []
args.state.num_bricks = 0
end
end
def calc_collision args
#Remove the brick if it is hit with the ball
ball = args.state.ball
ball_rect = [ball.xy.x, ball.xy.y, 20, 20]
#Loop through each brick to see if the ball is colliding with it
args.state.bricks.each do |b|
if b.rect.intersect_rect?(ball_rect)
#Run the linear collider for the brick if there is a collision
b[:collider_bottom].update args
b[:collider_right].update args
b[:collider_left].update args
b[:collider_top].update args
b.broken = true
end
end
args.state.bricks = args.state.bricks.reject(&:broken)
end
def win_game args
if args.state.bricks.count == 0 && args.state.game_over_at.elapsed_time > 60
#Freeze the ball
args.state.ball.velocity.x = 0
args.state.ball.velocity.y = 0
#Freeze the paddle
args.state.paddle.enabled = false
args.state.game_over_at = args.state.tick_count
end
if args.state.game_over_at.elapsed_time < 60 && args.state.tick_count > 60 && args.state.bricks.count == 0
#Display a "Game over" message
args.outputs.labels << [100, 100, "CONGRATULATIONS!", 10]
end
end
end
def tick args
defaults args
render args
calc args
#args.outputs.lines << [0, 0, args.grid.w, args.grid.h]
#$tc+=1
#if $tc == 5
#$train << [args.state.ball.xy.x, args.state.ball.xy.y]
#$tc = 0
#end
#for t in $train
#args.outputs.solids << [t[0],t[1],5,5,255,0,0];
#end
end
</code></pre>
<h3 id='----physics-and-collisions---collision-with-object-removal---paddle-rb'>Physics And Collisions - Collision With Object Removal - paddle.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/10_collision_with_object_removal/app/paddle.rb
class Paddle
attr_accessor :enabled
def initialize ()
@x=WIDTH/2
@y=100
@width=100
@height=20
@speed=10
@xyCollision = LinearCollider.new({x: @x,y: @y+@height+5}, {x: @x+@width, y: @y+@height+5})
@xyCollision2 = LinearCollider.new({x: @x,y: @y}, {x: @x+@width, y: @y}, :pos)
@xyCollision3 = LinearCollider.new({x: @x,y: @y}, {x: @x, y: @y+@height+5})
@xyCollision4 = LinearCollider.new({x: @x+@width,y: @y}, {x: @x+@width, y: @y+@height+5}, :pos)
@enabled = true
end
def update args
@xyCollision.resetPoints({x: @x,y: @y+@height+5}, {x: @x+@width, y: @y+@height+5})
@xyCollision2.resetPoints({x: @x,y: @y}, {x: @x+@width, y: @y})
@xyCollision3.resetPoints({x: @x,y: @y}, {x: @x, y: @y+@height+5})
@xyCollision4.resetPoints({x: @x+@width,y: @y}, {x: @x+@width, y: @y+@height+5})
@xyCollision.update args
@xyCollision2.update args
@xyCollision3.update args
@xyCollision4.update args
args.inputs.keyboard.key_held.left ||= false
args.inputs.keyboard.key_held.right ||= false
if not (args.inputs.keyboard.key_held.left == args.inputs.keyboard.key_held.right)
if args.inputs.keyboard.key_held.left && @enabled
@x-=@speed
elsif args.inputs.keyboard.key_held.right && @enabled
@x+=@speed
end
end
xmin =WIDTH/4
xmax = 3*(WIDTH/4)
@x = (@x+@width > xmax) ? xmax-@width : (@x<xmin) ? xmin : @x;
end
def render args
args.outputs.solids << [@x,@y,@width,@height,255,0,0];
end
def rect
[@x, @y, @width, @height]
end
end
</code></pre>
<h3 id='----physics-and-collisions---collision-with-object-removal---tests-rb'>Physics And Collisions - Collision With Object Removal - tests.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/10_collision_with_object_removal/app/tests.rb
# For advanced users:
# You can put some quick verification tests here, any method
# that starts with the `test_` will be run when you save this file.
# Here is an example test and game
# To run the test: ./dragonruby mygame --eval app/tests.rb --no-tick
class MySuperHappyFunGame
attr_gtk
def tick
outputs.solids << [100, 100, 300, 300]
end
end
def test_universe args, assert
game = MySuperHappyFunGame.new
game.args = args
game.tick
assert.true! args.outputs.solids.length == 1, "failure: a solid was not added after tick"
assert.false! 1 == 2, "failure: some how, 1 equals 2, the world is ending"
puts "test_universe completed successfully"
end
puts "running tests"
$gtk.reset 100
$gtk.log_level = :off
$gtk.tests.start
</code></pre>
<h3 id='----physics-and-collisions---collision-with-object-removal---vector2d-rb'>Physics And Collisions - Collision With Object Removal - vector2d.rb</h3>
<pre><code class="language-ruby"># ./samples/04_physics_and_collisions/10_collision_with_object_removal/app/vector2d.rb
class Vector2d
attr_accessor :x, :y
def initialize x=0, y=0
@x=x
@y=y
end
#returns a vector multiplied by scalar x
#x [float] scalar
def mult x
r = Vector2d.new(0,0)
r.x=@x*x
r.y=@y*x
r
end
# vect [Vector2d] vector to copy
def copy vect
Vector2d.new(@x, @y)
end
#returns a new vector equivalent to this+vect
#vect [Vector2d] vector to add to self
def add vect
Vector2d.new(@x+vect.x,@y+vect.y)
end
#returns a new vector equivalent to this-vect
#vect [Vector2d] vector to subtract to self
def sub vect
Vector2d.new(@x-vect.c, @y-vect.y)
end
#return the magnitude of the vector
def mag
((@x**2)+(@y**2))**0.5
end
#returns a new normalize version of the vector
def normalize
Vector2d.new(@x/mag, @y/mag)
end
#TODO delet?
def distABS vect
(((vect.x-@x)**2+(vect.y-@y)**2)**0.5).abs()
end
end
</code></pre>
<h3 id='----mouse---mouse-click---main-rb'>Mouse - Mouse Click - main.rb</h3>
<pre><code class="language-ruby"># ./samples/05_mouse/01_mouse_click/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- product: Returns an array of all combinations of elements from all arrays.
For example, [1,2].product([1,2]) would return the following array...
[[1,1], [1,2], [2,1], [2,2]]
More than two arrays can be given to product and it will still work,
such as [1,2].product([1,2],[3,4]). What would product return in this case?
Answer:
[[1,1,3],[1,1,4],[1,2,3],[1,2,4],[2,1,3],[2,1,4],[2,2,3],[2,2,4]]
- num1.fdiv(num2): Returns the float division (will have a decimal) of the two given numbers.
For example, 5.fdiv(2) = 2.5 and 5.fdiv(5) = 1.0
- yield: Allows you to call a method with a code block and yield to that block.
Reminders:
- ARRAY#inside_rect?: Returns true or false depending on if the point is inside the rect.
- String interpolation: Uses #{} syntax; everything between the #{ and the } is evaluated
as Ruby code, and the placeholder is replaced with its corresponding value or result.
- args.inputs.mouse.click: This property will be set if the mouse was clicked.
- Ternary operator (?): Will evaluate a statement (just like an if statement)
and perform an action if the result is true or another action if it is false.
- reject: Removes elements from a collection if they meet certain requirements.
- args.outputs.borders: An array. The values generate a border.
The parameters are [X, Y, WIDTH, HEIGHT, RED, GREEN, BLUE]
For more information about borders, go to mygame/documentation/03-solids-and-borders.md.
- args.outputs.labels: An array. The values generate a label.
The parameters are [X, Y, TEXT, SIZE, ALIGNMENT, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.
=end
# This sample app is a classic game of Tic Tac Toe.
class TicTacToe
attr_accessor :_, :state, :outputs, :inputs, :grid, :gtk
# Starts the game with player x's turn and creates an array (to_a) for space combinations.
# Calls methods necessary for the game to run properly.
def tick
state.current_turn ||= :x
state.space_combinations = [-1, 0, 1].product([-1, 0, 1]).to_a
render_board
input_board
end
# Uses borders to create grid squares for the game's board. Also outputs the game pieces using labels.
def render_board
square_size = 80
# Positions the game's board in the center of the screen.
# Try removing what follows grid.w_half or grid.h_half and see how the position changes!
board_left = grid.w_half - square_size * 1.5
board_top = grid.h_half - square_size * 1.5
# At first glance, the add(1) looks pretty trivial. But if you remove it,
# you'll see that the positioning of the board would be skewed without it!
# Or if you put 2 in the parenthesis, the pieces will be placed in the wrong squares
# due to the change in board placement.
outputs.borders << all_spaces do |x, y, space| # outputs borders for all board spaces
space.border ||= [
board_left + x.add(1) * square_size, # space.border is initialized using this definition
board_top + y.add(1) * square_size,
square_size,
square_size
]
end
# Again, the calculations ensure that the piece is placed in the center of the grid square.
# Remove the '- 20' and the piece will be placed at the top of the grid square instead of the center.
outputs.labels << filled_spaces do |x, y, space| # put label in each filled space of board
label board_left + x.add(1) * square_size + square_size.fdiv(2),
board_top + y.add(1) * square_size + square_size - 20,
space.piece # text of label, either "x" or "o"
end
# Uses a label to output whether x or o won, or if a draw occurred.
# If the game is ongoing, a label shows whose turn it currently is.
outputs.labels << if state.x_won
label grid.w_half, grid.top - 80, "x won" # the '-80' positions the label 80 pixels lower than top
elsif state.o_won
label grid.w_half, grid.top - 80, "o won" # grid.w_half positions the label in the center horizontally
elsif state.draw
label grid.w_half, grid.top - 80, "a draw"
else # if no one won and the game is ongoing
label grid.w_half, grid.top - 80, "turn: #{state.current_turn}"
end
end
# Calls the methods responsible for handling user input and determining the winner.
# Does nothing unless the mouse is clicked.
def input_board
return unless inputs.mouse.click
input_place_piece
input_restart_game
determine_winner
end
# Handles user input for placing pieces on the board.
def input_place_piece
return if state.game_over
# Checks to find the space that the mouse was clicked inside of, and makes sure the space does not already
# have a piece in it.
__, __, space = all_spaces.find do |__, __, space|
inputs.mouse.click.point.inside_rect?(space.border) && !space.piece
end
# The piece that goes into the space belongs to the player whose turn it currently is.
return unless space
space.piece = state.current_turn
# This ternary operator statement allows us to change the current player's turn.
# If it is currently x's turn, it becomes o's turn. If it is not x's turn, it become's x's turn.
state.current_turn = state.current_turn == :x ? :o : :x
end
# Resets the game.
def input_restart_game
return unless state.game_over
gtk.reset
end
# Checks if x or o won the game.
# If neither player wins and all nine squares are filled, a draw happens.
# Once a player is chosen as the winner or a draw happens, the game is over.
def determine_winner
state.x_won = won? :x # evaluates to either true or false (boolean values)
state.o_won = won? :o
state.draw = true if filled_spaces.length == 9 && !state.x_won && !state.o_won
state.game_over = state.x_won || state.o_won || state.draw
end
# Determines if a player won by checking if there is a horizontal match or vertical match.
# Horizontal_match and vertical_match have boolean values. If either is true, the game has been won.
def won? piece
# performs action on all space combinations
won = [[-1, 0, 1]].product([-1, 0, 1]).map do |xs, y|
# Checks if the 3 grid spaces with the same y value (or same row) and
# x values that are next to each other have pieces that belong to the same player.
# Remember, the value of piece is equal to the current turn (which is the player).
horizontal_match = state.spaces[xs[0]][y].piece == piece &&
state.spaces[xs[1]][y].piece == piece &&
state.spaces[xs[2]][y].piece == piece
# Checks if the 3 grid spaces with the same x value (or same column) and
# y values that are next to each other have pieces that belong to the same player.
# The && represents an "and" statement: if even one part of the statement is false,
# the entire statement evaluates to false.
vertical_match = state.spaces[y][xs[0]].piece == piece &&
state.spaces[y][xs[1]].piece == piece &&
state.spaces[y][xs[2]].piece == piece
horizontal_match || vertical_match # if either is true, true is returned
end
# Sees if there is a diagonal match, starting from the bottom left and ending at the top right.
# Is added to won regardless of whether the statement is true or false.
won << (state.spaces[-1][-1].piece == piece && # bottom left
state.spaces[ 0][ 0].piece == piece && # center
state.spaces[ 1][ 1].piece == piece) # top right
# Sees if there is a diagonal match, starting at the bottom right and ending at the top left
# and is added to won.
won << (state.spaces[ 1][-1].piece == piece && # bottom right
state.spaces[ 0][ 0].piece == piece && # center
state.spaces[-1][ 1].piece == piece) # top left
# Any false statements (meaning false diagonal matches) are rejected from won
won.reject_false.any?
end
# Defines filled spaces on the board by rejecting all spaces that do not have game pieces in them.
# The ! before a statement means "not". For example, we are rejecting any space combinations that do
# NOT have pieces in them.
def filled_spaces
state.space_combinations
.reject { |x, y| !state.spaces[x][y].piece } # reject spaces with no pieces in them
.map do |x, y|
if block_given?
yield x, y, state.spaces[x][y]
else
[x, y, state.spaces[x][y]] # sets definition of space
end
end
end
# Defines all spaces on the board.
def all_spaces
if !block_given?
state.space_combinations.map do |x, y|
[x, y, state.spaces[x][y]] # sets definition of space
end
else # if a block is given (block_given? is true)
state.space_combinations.map do |x, y|
yield x, y, state.spaces[x][y] # yield if a block is given
end
end
end
# Sets values for a label, such as the position, value, size, alignment, and color.
def label x, y, value
[x, y + 10, value, 20, 1, 0, 0, 0]
end
end
$tic_tac_toe = TicTacToe.new
def tick args
$tic_tac_toe._ = args
$tic_tac_toe.state = args.state
$tic_tac_toe.outputs = args.outputs
$tic_tac_toe.inputs = args.inputs
$tic_tac_toe.grid = args.grid
$tic_tac_toe.gtk = args.gtk
$tic_tac_toe.tick
tick_instructions args, "Sample app shows how to work with mouse clicks."
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----mouse---mouse-move---main-rb'>Mouse - Mouse Move - main.rb</h3>
<pre><code class="language-ruby"># ./samples/05_mouse/02_mouse_move/app/main.rb
=begin
Reminders:
- num1.greater(num2): Returns the greater value.
For example, if we have the command
puts 4.greater(3)
the number 4 would be printed to the console since it has a greater value than 3.
Similar to lesser, which returns the lesser value.
- find_all: Finds all elements of a collection that meet certain requirements.
For example, in this sample app, we're using find_all to find all zombies that have intersected
or hit the player's sprite since these zombies have been killed.
- args.inputs.keyboard.key_down.KEY: Determines if a key is being held or pressed.
Stores the frame the "down" event occurred.
For more information about the keyboard, go to mygame/documentation/06-keyboard.md.
- args.outputs.sprites: An array. The values generate a sprite.
The parameters are [X, Y, WIDTH, HEIGHT, PATH, ANGLE, ALPHA, RED, GREEN, BLUE]
For more information about sprites, go to mygame/documentation/05-sprites.md.
- args.state.new_entity: Used when we want to create a new object, like a sprite or button.
When we want to create a new object, we can declare it as a new entity and then define
its properties. (Remember, you can use state to define ANY property and it will
be retained across frames.)
- String interpolation: Uses #{} syntax; everything between the #{ and the } is evaluated
as Ruby code, and the placeholder is replaced with its corresponding value or result.
- map: Ruby method used to transform data; used in arrays, hashes, and collections.
Can be used to perform an action on every element of a collection, such as multiplying
each element by 2 or declaring every element as a new entity.
- sample: Chooses a random element from the array.
- reject: Removes elements that meet certain requirements.
In this sample app, we're removing/rejecting zombies that reach the center of the screen. We're also
rejecting zombies that were killed more than 30 frames ago.
=end
# This sample app allows users to move around the screen in order to kill zombies. Zombies appear from every direction so the goal
# is to kill the zombies as fast as possible!
class ProtectThePuppiesFromTheZombies
attr_accessor :grid, :inputs, :state, :outputs
# Calls the methods necessary for the game to run properly.
def tick
defaults
render
calc
input
end
# Sets default values for the zombies and for the player.
# Initialization happens only in the first frame.
def defaults
state.flash_at ||= 0
state.zombie_min_spawn_rate ||= 60
state.zombie_spawn_countdown ||= random_spawn_countdown state.zombie_min_spawn_rate
state.zombies ||= []
state.killed_zombies ||= []
# Declares player as a new entity and sets its properties.
# The player begins the game in the center of the screen, not moving in any direction.
state.player ||= state.new_entity(:player, { x: 640,
y: 360,
attack_angle: 0,
dx: 0,
dy: 0 })
end
# Outputs a gray background.
# Calls the methods needed to output the player, zombies, etc onto the screen.
def render
outputs.solids << [grid.rect, 100, 100, 100]
render_zombies
render_killed_zombies
render_player
render_flash
end
# Outputs the zombies on the screen and sets values for the sprites, such as the position, width, height, and animation.
def render_zombies
outputs.sprites << state.zombies.map do |z| # performs action on all zombies in the collection
z.sprite = [z.x, z.y, 4 * 3, 8 * 3, animation_sprite(z)].sprite # sets definition for sprite, calls animation_sprite method
z.sprite
end
end
# Outputs sprites of killed zombies, and displays a slash image to show that a zombie has been killed.
def render_killed_zombies
outputs.sprites << state.killed_zombies.map do |z| # performs action on all killed zombies in collection
z.sprite = [z.x,
z.y,
4 * 3,
8 * 3,
animation_sprite(z, z.death_at), # calls animation_sprite method
0, # angle
255 * z.death_at.ease(30, :flip)].sprite # transparency of a zombie changes when they die
# change the value of 30 and see what happens when a zombie is killed
# Sets values to output the slash over the zombie's sprite when a zombie is killed.
# The slash is tilted 45 degrees from the angle of the player's attack.
# Change the 3 inside scale_rect to 30 and the slash will be HUGE! Scale_rect positions
# the slash over the killed zombie's sprite.
[z.sprite, [z.sprite.rect, 'sprites/slash.png', 45 + state.player.attack_angle_on_click, z.sprite.a].scale_rect(3, 0.5, 0.5)]
end
end
# Outputs the player sprite using the images in the sprites folder.
def render_player
state.player_sprite = [state.player.x,
state.player.y,
4 * 3,
8 * 3, "sprites/player-#{animation_index(state.player.created_at_elapsed)}.png"] # string interpolation
outputs.sprites << state.player_sprite
# Outputs a small red square that previews the angles that the player can attack in.
# It can be moved in a perfect circle around the player to show possible movements.
# Change the 60 in the parenthesis and see what happens to the movement of the red square.
outputs.solids << [state.player.x + state.player.attack_angle.vector_x(60),
state.player.y + state.player.attack_angle.vector_y(60),
3, 3, 255, 0, 0]
end
# Renders flash as a solid. The screen turns white for 10 frames when a zombie is killed.
def render_flash
return if state.flash_at.elapsed_time > 10 # return if more than 10 frames have passed since flash.
# Transparency gradually changes (or eases) during the 10 frames of flash.
outputs.primitives << [grid.rect, 255, 255, 255, 255 * state.flash_at.ease(10, :flip)].solid
end
# Calls all methods necessary for performing calculations.
def calc
calc_spawn_zombie
calc_move_zombies
calc_player
calc_kill_zombie
end
# Decreases the zombie spawn countdown by 1 if it has a value greater than 0.
def calc_spawn_zombie
if state.zombie_spawn_countdown > 0
state.zombie_spawn_countdown -= 1
return
end
# New zombies are created, positioned on the screen, and added to the zombies collection.
state.zombies << state.new_entity(:zombie) do |z| # each zombie is declared a new entity
if rand > 0.5
z.x = grid.rect.w.randomize(:ratio) # random x position on screen (within grid scope)
z.y = [-10, 730].sample # y position is set to either -10 or 730 (randomly chosen)
# the possible values exceed the screen's scope so zombies appear to be coming from far away
else
z.x = [-10, 1290].sample # x position is set to either -10 or 1290 (randomly chosen)
z.y = grid.rect.w.randomize(:ratio) # random y position on screen
end
end
# Calls random_spawn_countdown method (determines how fast new zombies appear)
state.zombie_spawn_countdown = random_spawn_countdown state.zombie_min_spawn_rate
state.zombie_min_spawn_rate -= 1
# set to either the current zombie_min_spawn_rate or 0, depending on which value is greater
state.zombie_min_spawn_rate = state.zombie_min_spawn_rate.greater(0)
end
# Moves all zombies towards the center of the screen.
# All zombies that reach the center (640, 360) are rejected from the zombies collection and disappear.
def calc_move_zombies
state.zombies.each do |z| # for each zombie in the collection
z.y = z.y.towards(360, 0.1) # move the zombie towards the center (640, 360) at a rate of 0.1
z.x = z.x.towards(640, 0.1) # change 0.1 to 1.1 and see how much faster the zombies move to the center
end
state.zombies = state.zombies.reject { |z| z.y == 360 && z.x == 640 } # remove zombies that are in center
end
# Calculates the position and movement of the player on the screen.
def calc_player
state.player.x += state.player.dx # changes x based on dx (change in x)
state.player.y += state.player.dy # changes y based on dy (change in y)
state.player.dx *= 0.9 # scales dx down
state.player.dy *= 0.9 # scales dy down
# Compares player's x to 1280 to find lesser value, then compares result to 0 to find greater value.
# This ensures that the player remains within the screen's scope.
state.player.x = state.player.x.lesser(1280).greater(0)
state.player.y = state.player.y.lesser(720).greater(0) # same with player's y
end
# Finds all zombies that intersect with the player's sprite. These zombies are removed from the zombies collection
# and added to the killed_zombies collection since any zombie that intersects with the player is killed.
def calc_kill_zombie
# Find all zombies that intersect with the player. They are considered killed.
killed_this_frame = state.zombies.find_all { |z| z.sprite.intersect_rect? state.player_sprite }
state.zombies = state.zombies - killed_this_frame # remove newly killed zombies from zombies collection
state.killed_zombies += killed_this_frame # add newly killed zombies to killed zombies
if killed_this_frame.length > 0 # if atleast one zombie was killed in the frame
state.flash_at = state.tick_count # flash_at set to the frame when the zombie was killed
# Don't forget, the rendered flash lasts for 10 frames after the zombie is killed (look at render_flash method)
end
# Sets the tick_count (passage of time) as the value of the death_at variable for each killed zombie.
# Death_at stores the frame a zombie was killed.
killed_this_frame.each do |z|
z.death_at = state.tick_count
end
# Zombies are rejected from the killed_zombies collection depending on when they were killed.
# They are rejected if more than 30 frames have passed since their death.
state.killed_zombies = state.killed_zombies.reject { |z| state.tick_count - z.death_at > 30 }
end
# Uses input from the user to move the player around the screen.
def input
# If the "a" key or left key is pressed, the x position of the player decreases.
# Otherwise, if the "d" key or right key is pressed, the x position of the player increases.
if inputs.keyboard.key_held.a || inputs.keyboard.key_held.left
state.player.x -= 5
elsif inputs.keyboard.key_held.d || inputs.keyboard.key_held.right
state.player.x += 5
end
# If the "w" or up key is pressed, the y position of the player increases.
# Otherwise, if the "s" or down key is pressed, the y position of the player decreases.
if inputs.keyboard.key_held.w || inputs.keyboard.key_held.up
state.player.y += 5
elsif inputs.keyboard.key_held.s || inputs.keyboard.key_held.down
state.player.y -= 5
end
# Sets the attack angle so the player can move and attack in the precise direction it wants to go.
# If the mouse is moved, the attack angle is changed (based on the player's position and mouse position).
# Attack angle also contributes to the position of red square.
if inputs.mouse.moved
state.player.attack_angle = inputs.mouse.position.angle_from [state.player.x, state.player.y]
end
if inputs.mouse.click && state.player.dx < 0.5 && state.player.dy < 0.5
state.player.attack_angle_on_click = inputs.mouse.position.angle_from [state.player.x, state.player.y]
state.player.attack_angle = state.player.attack_angle_on_click # player's attack angle is set
state.player.dx = state.player.attack_angle.vector_x(25) # change in player's position
state.player.dy = state.player.attack_angle.vector_y(25)
end
end
# Sets the zombie spawn's countdown to a random number.
# How fast zombies appear (change the 60 to 6 and too many zombies will appear at once!)
def random_spawn_countdown minimum
10.randomize(:ratio, :sign).to_i + 60
end
# Helps to iterate through the images in the sprites folder by setting the animation index.
# 3 frames is how long to show an image, and 6 is how many images to flip through.
def animation_index at
at.idiv(3).mod(6)
end
# Animates the zombies by using the animation index to go through the images in the sprites folder.
def animation_sprite zombie, at = nil
at ||= zombie.created_at_elapsed # how long it is has been since a zombie was created
index = animation_index at
"sprites/zombie-#{index}.png" # string interpolation to iterate through images
end
end
$protect_the_puppies_from_the_zombies = ProtectThePuppiesFromTheZombies.new
def tick args
$protect_the_puppies_from_the_zombies.grid = args.grid
$protect_the_puppies_from_the_zombies.inputs = args.inputs
$protect_the_puppies_from_the_zombies.state = args.state
$protect_the_puppies_from_the_zombies.outputs = args.outputs
$protect_the_puppies_from_the_zombies.tick
tick_instructions args, "How to get the mouse position and translate it to an x, y position using .vector_x and .vector_y. CLICK to play."
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----mouse---mouse-move-paint-app---main-rb'>Mouse - Mouse Move Paint App - main.rb</h3>
<pre><code class="language-ruby"># ./samples/05_mouse/03_mouse_move_paint_app/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- Floor: Method that returns an integer number smaller than or equal to the original with no decimal.
For example, if we have a variable, a = 13.7, and we called floor on it, it would look like this...
puts a.floor()
which would print out 13.
(There is also a ceil method, which returns an integer number greater than or equal to the original
with no decimal. If we had called ceil on the variable a, the result would have been 14.)
Reminders:
- Hashes: Collection of unique keys and their corresponding values. The value can be found
using their keys.
For example, if we have a "numbers" hash that stores numbers in English as the
key and numbers in Spanish as the value, we'd have a hash that looks like this...
numbers = { "one" => "uno", "two" => "dos", "three" => "tres" }
and on it goes.
Now if we wanted to find the corresponding value of the "one" key, we could say
puts numbers["one"]
which would print "uno" to the console.
- args.state.new_entity: Used when we want to create a new object, like a sprite or button.
In this sample app, new_entity is used to create a new button that clears the grid.
(Remember, you can use state to define ANY property and it will be retained across frames.)
- args.inputs.mouse.click.point.(x|y): The x and y location of the mouse.
- args.inputs.mouse.click.point.created_at: The frame the mouse click occurred in.
- args.outputs.labels: An array. The values in the array generate a label.
The parameters are [X, Y, TEXT, SIZE, ALIGN, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.md.
- ARRAY#inside_rect?: Returns true or false depending on if the point is inside the rect.
=end
# This sample app shows an empty grid that the user can paint on.
# To paint, the user must keep their mouse presssed and drag it around the grid.
# The "clear" button allows users to clear the grid so they can start over.
class PaintApp
attr_accessor :inputs, :state, :outputs, :grid, :args
# Runs methods necessary for the game to function properly.
def tick
print_title
add_grid
check_click
draw_buttons
end
# Prints the title onto the screen by using a label.
# Also separates the title from the grid with a line as a horizontal separator.
def print_title
args.outputs.labels << [ 640, 700, 'Paint!', 0, 1 ]
outputs.lines << horizontal_separator(660, 0, 1280)
end
# Sets the starting position, ending position, and color for the horizontal separator.
# The starting and ending positions have the same y values.
def horizontal_separator y, x, x2
[x, y, x2, y, 150, 150, 150]
end
# Sets the starting position, ending position, and color for the vertical separator.
# The starting and ending positions have the same x values.
def vertical_separator x, y, y2
[x, y, x, y2, 150, 150, 150]
end
# Outputs a border and a grid containing empty squares onto the screen.
def add_grid
# Sets the x, y, height, and width of the grid.
# There are 31 horizontal lines and 31 vertical lines in the grid.
# Feel free to count them yourself before continuing!
x, y, h, w = 640 - 500/2, 640 - 500, 500, 500 # calculations done so the grid appears in screen's center
lines_h = 31
lines_v = 31
# Sets values for the grid's border, grid lines, and filled squares.
# The filled_squares variable is initially set to an empty array.
state.grid_border ||= [ x, y, h, w ] # definition of grid's outer border
state.grid_lines ||= draw_grid(x, y, h, w, lines_h, lines_v) # calls draw_grid method
state.filled_squares ||= [] # there are no filled squares until the user fills them in
# Outputs the grid lines, border, and filled squares onto the screen.
outputs.lines.concat state.grid_lines
outputs.borders << state.grid_border
outputs.solids << state.filled_squares
end
# Draws the grid by adding in vertical and horizontal separators.
def draw_grid x, y, h, w, lines_h, lines_v
# The grid starts off empty.
grid = []
# Calculates the placement and adds horizontal lines or separators into the grid.
curr_y = y # start at the bottom of the box
dist_y = h / (lines_h + 1) # finds distance to place horizontal lines evenly throughout 500 height of grid
lines_h.times do
curr_y += dist_y # increment curr_y by the distance between the horizontal lines
grid << horizontal_separator(curr_y, x, x + w - 1) # add a separator into the grid
end
# Calculates the placement and adds vertical lines or separators into the grid.
curr_x = x # now start at the left of the box
dist_x = w / (lines_v + 1) # finds distance to place vertical lines evenly throughout 500 width of grid
lines_v.times do
curr_x += dist_x # increment curr_x by the distance between the vertical lines
grid << vertical_separator(curr_x, y + 1, y + h) # add separator
end
# paint_grid uses a hash to assign values to keys.
state.paint_grid ||= {"x" => x, "y" => y, "h" => h, "w" => w, "lines_h" => lines_h,
"lines_v" => lines_v, "dist_x" => dist_x,
"dist_y" => dist_y }
return grid
end
# Checks if the user is keeping the mouse pressed down and sets the mouse_hold variable accordingly using boolean values.
# If the mouse is up, the user cannot drag the mouse.
def check_click
if inputs.mouse.down #is mouse up or down?
state.mouse_held = true # mouse is being held down
elsif inputs.mouse.up # if mouse is up
state.mouse_held = false # mouse is not being held down or dragged
state.mouse_dragging = false
end
if state.mouse_held && # mouse needs to be down
!inputs.mouse.click && # must not be first click
((inputs.mouse.previous_click.point.x - inputs.mouse.position.x).abs > 15) # Need to move 15 pixels before "drag"
state.mouse_dragging = true
end
# If the user clicks their mouse inside the grid, the search_lines method is called with a click input type.
if ((inputs.mouse.click) && (inputs.mouse.click.point.inside_rect? state.grid_border))
search_lines(inputs.mouse.click.point, :click)
# If the user drags their mouse inside the grid, the search_lines method is called with a drag input type.
elsif ((state.mouse_dragging) && (inputs.mouse.position.inside_rect? state.grid_border))
search_lines(inputs.mouse.position, :drag)
end
end
# Sets the definition of a grid box and handles user input to fill in or clear grid boxes.
def search_lines (point, input_type)
point.x -= state.paint_grid["x"] # subtracts the value assigned to the "x" key in the paint_grid hash
point.y -= state.paint_grid["y"] # subtracts the value assigned to the "y" key in the paint_grid hash
# Remove code following the .floor and see what happens when you try to fill in grid squares
point.x = (point.x / state.paint_grid["dist_x"]).floor * state.paint_grid["dist_x"]
point.y = (point.y / state.paint_grid["dist_y"]).floor * state.paint_grid["dist_y"]
point.x += state.paint_grid["x"]
point.y += state.paint_grid["y"]
# Sets definition of a grid box, meaning its x, y, width, and height.
# Floor is called on the point.x and point.y variables.
# Ceil method is called on values of the distance hash keys, setting the width and height of a box.
grid_box = [ point.x.floor, point.y.floor, state.paint_grid["dist_x"].ceil, state.paint_grid["dist_y"].ceil ]
if input_type == :click # if user clicks their mouse
if state.filled_squares.include? grid_box # if grid box is already filled in
state.filled_squares.delete grid_box # box is cleared and removed from filled_squares
else
state.filled_squares << grid_box # otherwise, box is filled in and added to filled_squares
end
elsif input_type == :drag # if user drags mouse
unless state.filled_squares.include? grid_box # unless the grid box dragged over is already filled in
state.filled_squares << grid_box # the box is filled in and added to filled_squares
end
end
end
# Creates and outputs a "Clear" button on the screen using a label and a border.
# If the button is clicked, the filled squares are cleared, making the filled_squares collection empty.
def draw_buttons
x, y, w, h = 390, 50, 240, 50
state.clear_button ||= state.new_entity(:button_with_fade)
# The x and y positions are set to display the label in the center of the button.
# Try changing the first two parameters to simply x, y and see what happens to the text placement!
state.clear_button.label ||= [x + w.half, y + h.half + 10, "Clear", 0, 1] # placed in center of border
state.clear_button.border ||= [x, y, w, h]
# If the mouse is clicked inside the borders of the clear button,
# the filled_squares collection is emptied and the squares are cleared.
if inputs.mouse.click && inputs.mouse.click.point.inside_rect?(state.clear_button.border)
state.clear_button.clicked_at = inputs.mouse.click.created_at # time (frame) the click occurred
state.filled_squares.clear
inputs.mouse.previous_click = nil
end
outputs.labels << state.clear_button.label
outputs.borders << state.clear_button.border
# When the clear button is clicked, the color of the button changes
# and the transparency changes, as well. If you change the time from
# 0.25.seconds to 1.25.seconds or more, the change will last longer.
if state.clear_button.clicked_at
outputs.solids << [x, y, w, h, 0, 180, 80, 255 * state.clear_button.clicked_at.ease(0.25.seconds, :flip)]
end
end
end
$paint_app = PaintApp.new
def tick args
$paint_app.inputs = args.inputs
$paint_app.state = args.state
$paint_app.grid = args.grid
$paint_app.args = args
$paint_app.outputs = args.outputs
$paint_app.tick
tick_instructions args, "How to create a simple paint app. CLICK and HOLD to draw."
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----mouse---coordinate-systems---main-rb'>Mouse - Coordinate Systems - main.rb</h3>
<pre><code class="language-ruby"># ./samples/05_mouse/04_coordinate_systems/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- args.inputs.mouse.click.position: Coordinates of the mouse's position on the screen.
Unlike args.inputs.mouse.click.point, the mouse does not need to be pressed down for
position to know the mouse's coordinates.
For more information about the mouse, go to mygame/documentation/07-mouse.md.
Reminders:
- args.inputs.mouse.click: This property will be set if the mouse was clicked.
- args.inputs.mouse.click.point.(x|y): The x and y location of the mouse.
- String interpolation: Uses #{} syntax; everything between the #{ and the } is evaluated
as Ruby code, and the placeholder is replaced with its corresponding value or result.
In this sample app, string interpolation is used to show the current position of the mouse
in a label.
- args.outputs.labels: An array that generates a label.
The parameters are [X, Y, TEXT, SIZE, ALIGN, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.md.
- args.outputs.solids: An array that generates a solid.
The parameters are [X, Y, WIDTH, HEIGHT, RED, GREEN, BLUE, ALPHA]
For more information about solids, go to mygame/documentation/03-solids-and-borders.md.
- args.outputs.lines: An array that generates a line.
The parameters are [X, Y, X2, Y2, RED, GREEN, BLUE, ALPHA]
For more information about lines, go to mygame/documentation/04-lines.md.
=end
# This sample app shows a coordinate system or grid. The user can move their mouse around the screen and the
# coordinates of their position on the screen will be displayed. Users can choose to view one quadrant or
# four quadrants by pressing the button.
def tick args
# The addition and subtraction in the first two parameters of the label and solid
# ensure that the outputs don't overlap each other. Try removing them and see what happens.
pos = args.inputs.mouse.position # stores coordinates of mouse's position
args.outputs.labels << [pos.x + 10, pos.y + 10, "#{pos}"] # outputs label of coordinates
args.outputs.solids << [pos.x - 2, pos.y - 2, 5, 5] # outputs small blackk box placed where mouse is hovering
button = [0, 0, 370, 50] # sets definition of toggle button
args.outputs.borders << button # outputs button as border (not filled in)
args.outputs.labels << [10, 35, "click here toggle coordinate system"] # label of button
args.outputs.lines << [ 0, -720, 0, 720] # vertical line dividing quadrants
args.outputs.lines << [-1280, 0, 1280, 0] # horizontal line dividing quadrants
if args.inputs.mouse.click # if the user clicks the mouse
pos = args.inputs.mouse.click.point # pos's value is point where user clicked (coordinates)
if pos.inside_rect? button # if the click occurred inside the button
if args.grid.name == :bottom_left # if the grid shows bottom left as origin
args.grid.origin_center! # origin will be shown in center
else
args.grid.origin_bottom_left! # otherwise, the view will change to show bottom left as origin
end
end
end
tick_instructions args, "Sample app shows the two supported coordinate systems in Game Toolkit."
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----save-load---save-load-game---main-rb'>Save Load - Save Load Game - main.rb</h3>
<pre><code class="language-ruby"># ./samples/06_save_load/01_save_load_game/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- Symbol (:): Ruby object with a name and an internal ID. Symbols are useful
because with a given symbol name, you can refer to the same object throughout
a Ruby program.
In this sample app, we're using symbols for our buttons. We have buttons that
light fires, save, load, etc. Each of these buttons has a distinct symbol like
:light_fire, :save_game, :load_game, etc.
- to_sym: Returns the symbol corresponding to the given string; creates the symbol
if it does not already exist.
For example,
'car'.to_sym
would return the symbol :car.
- last: Returns the last element of an array.
Reminders:
- num1.lesser(num2): finds the lower value of the given options.
For example, in the statement
a = 4.lesser(3)
3 has a lower value than 4, which means that the value of a would be set to 3,
but if the statement had been
a = 4.lesser(5)
4 has a lower value than 5, which means that the value of a would be set to 4.
- num1.fdiv(num2): returns the float division (will have a decimal) of the two given numbers.
For example, 5.fdiv(2) = 2.5 and 5.fdiv(5) = 1.0
- String interpolation: uses #{} syntax; everything between the #{ and the } is evaluated
as Ruby code, and the placeholder is replaced with its corresponding value or result.
- args.outputs.labels: An array. Values generate a label.
Parameters are [X, Y, TEXT, SIZE, ALIGN, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information, go to mygame/documentation/02-labels.md.
- ARRAY#inside_rect?: An array with at least two values is considered a point. An array
with at least four values is considered a rect. The inside_rect? function returns true
or false depending on if the point is inside the rect.
=end
# This code allows users to perform different tasks, such as saving and loading the game.
# Users also have options to reset the game and light a fire.
class TextedBasedGame
# Contains methods needed for game to run properly.
# Increments tick count by 1 each time it runs (60 times in a single second)
def tick
default
show_intro
state.engine_tick_count += 1
tick_fire
end
# Sets default values.
# The ||= ensures that a variable's value is only set to the value following the = sign
# if the value has not already been set before. Intialization happens only in the first frame.
def default
state.engine_tick_count ||= 0
state.active_module ||= :room
state.fire_progress ||= 0
state.fire_ready_in ||= 10
state.previous_fire ||= :dead
state.fire ||= :dead
end
def show_intro
return unless state.engine_tick_count == 0 # return unless the game just started
set_story_line "awake." # calls set_story_line method, sets to "awake"
end
# Sets story line.
def set_story_line story_line
state.story_line = story_line # story line set to value of parameter
state.active_module = :alert # active module set to alert
end
# Clears story line.
def clear_storyline
state.active_module = :none # active module set to none
state.story_line = nil # story line is cleared, set to nil (or empty)
end
# Determines fire progress (how close the fire is to being ready to light).
def tick_fire
return if state.active_module == :alert # return if active module is alert
state.fire_progress += 1 # increment fire progress
# fire_ready_in is 10. The fire_progress is either the current value or 10, whichever has a lower value.
state.fire_progress = state.fire_progress.lesser(state.fire_ready_in)
end
# Sets the value of fire (whether it is dead or roaring), and the story line
def light_fire
return unless fire_ready? # returns unless the fire is ready to be lit
state.fire = :roaring # fire is lit, set to roaring
state.fire_progress = 0 # the fire progress returns to 0, since the fire has been lit
if state.fire != state.previous_fire
set_story_line "the fire is #{state.fire}." # the story line is set using string interpolation
state.previous_fire = state.fire
end
end
# Checks if the fire is ready to be lit. Returns a boolean value.
def fire_ready?
# If fire_progress (value between 0 and 10) is equal to fire_ready_in (value of 10),
# the fire is ready to be lit.
state.fire_progress == state.fire_ready_in
end
# Divides the value of the fire_progress variable by 10 to determine how close the user is to
# being able to light a fire.
def light_fire_progress
state.fire_progress.fdiv(10) # float division
end
# Defines fire as the state.fire variable.
def fire
state.fire
end
# Sets the title of the room.
def room_title
return "a room that is dark" if state.fire == :dead # room is dark if the fire is dead
return "a room that is lit" # room is lit if the fire is not dead
end
# Sets the active_module to room.
def go_to_room
state.active_module = :room
end
# Defines active_module as the state.active_module variable.
def active_module
state.active_module
end
# Defines story_line as the state.story_line variable.
def story_line
state.story_line
end
# Update every 60 frames (or every second)
def should_tick?
state.tick_count.mod_zero?(60)
end
# Sets the value of the game state provider.
def initialize game_state_provider
@game_state_provider = game_state_provider
end
# Defines the game state.
# Any variable prefixed with an @ symbol is an instance variable.
def state
@game_state_provider.state
end
# Saves the state of the game in a text file called game_state.txt.
def save
$gtk.serialize_state('game_state.txt', state)
end
# Loads the game state from the game_state.txt text file.
# If the load is unsuccessful, the user is informed since the story line indicates the failure.
def load
parsed_state = $gtk.deserialize_state('game_state.txt')
if !parsed_state
set_story_line "no game to load. press save first."
else
$gtk.args.state = parsed_state
end
end
# Resets the game.
def reset
$gtk.reset
end
end
class TextedBasedGamePresenter
attr_accessor :state, :outputs, :inputs
# Creates empty collection called highlights.
# Calls methods necessary to run the game.
def tick
state.layout.highlights ||= []
game.tick if game.should_tick?
render
process_input
end
# Outputs a label of the tick count (passage of time) and calls all render methods.
def render
outputs.labels << [10, 30, state.tick_count]
render_alert
render_room
render_highlights
end
# Outputs a label onto the screen that shows the story line, and also outputs a "close" button.
def render_alert
return unless game.active_module == :alert
outputs.labels << [640, 480, game.story_line, 5, 1] # outputs story line label
outputs.primitives << button(:alert_dismiss, 490, 380, "close") # positions "close" button under story line
end
def render_room
return unless game.active_module == :room
outputs.labels << [640, 700, game.room_title, 4, 1] # outputs room title label at top of screen
# The parameters for these outputs are (symbol, x, y, text, value/percentage) and each has a y value
# that positions it 60 pixels lower than the previous output.
# outputs the light_fire_progress bar, uses light_fire_progress for its percentage (which changes bar's appearance)
outputs.primitives << progress_bar(:light_fire, 490, 600, "light fire", game.light_fire_progress)
outputs.primitives << button( :save_game, 490, 540, "save") # outputs save button
outputs.primitives << button( :load_game, 490, 480, "load") # outputs load button
outputs.primitives << button( :reset_game, 490, 420, "reset") # outputs reset button
outputs.labels << [640, 30, "the fire is #{game.fire}", 0, 1] # outputs fire label at bottom of screen
end
# Outputs a collection of highlights using an array to set their values, and also rejects certain values from the collection.
def render_highlights
state.layout.highlights.each do |h| # for each highlight in the collection
h.lifetime -= 1 # decrease the value of its lifetime
end
outputs.solids << state.layout.highlights.map do |h| # outputs highlights collection
[h.x, h.y, h.w, h.h, h.color, 255 * h.lifetime / h.max_lifetime] # sets definition for each highlight
# transparency changes; divide lifetime by max_lifetime, multiply result by 255
end
# reject highlights from collection that have no remaining lifetime
state.layout.highlights = state.layout.highlights.reject { |h| h.lifetime <= 0 }
end
# Checks whether or not a button was clicked.
# Returns a boolean value.
def process_input
button = button_clicked? # calls button_clicked? method
end
# Returns a boolean value.
# Finds the button that was clicked from the button list and determines what method to call.
# Adds a highlight to the highlights collection.
def button_clicked?
return nil unless click_pos # return nil unless click_pos holds coordinates of mouse click
button = @button_list.find do |k, v| # goes through button_list to find button clicked
click_pos.inside_rect? v[:primitives].last.rect # was the mouse clicked inside the rect of button?
end
return unless button # return unless a button was clicked
method_to_call = "#{button[0]}_clicked".to_sym # sets method_to_call to symbol (like :save_game or :load_game)
if self.respond_to? method_to_call # returns true if self responds to the given method (method actually exists)
border = button[1][:primitives].last # sets border definition using value of last key in button list hash
# declares each highlight as a new entity, sets properties
state.layout.highlights << state.new_entity(:highlight) do |h|
h.x = border.x
h.y = border.y
h.w = border.w
h.h = border.h
h.max_lifetime = 10
h.lifetime = h.max_lifetime
h.color = [120, 120, 180] # sets color to shade of purple
end
self.send method_to_call # invoke method identified by symbol
else # otherwise, if self doesn't respond to given method
border = button[1][:primitives].last # sets border definition using value of last key in hash
# declares each highlight as a new entity, sets properties
state.layout.highlights << state.new_entity(:highlight) do |h|
h.x = border.x
h.y = border.y
h.w = border.w
h.h = border.h
h.max_lifetime = 4 # different max_lifetime than the one set if respond_to? had been true
h.lifetime = h.max_lifetime
h.color = [120, 80, 80] # sets color to dark color
end
# instructions for users on how to add the missing method_to_call to the code
puts "It looks like #{method_to_call} doesn't exists on TextedBasedGamePresenter. Please add this method:"
puts "Just copy the code below and put it in the #{TextedBasedGamePresenter} class definition."
puts ""
puts "```"
puts "class TextedBasedGamePresenter <--- find this class and put the method below in it"
puts ""
puts " def #{method_to_call}"
puts " puts 'Yay that worked!'"
puts " end"
puts ""
puts "end <-- make sure to put the #{method_to_call} method in between the `class` word and the final `end` statement."
puts "```"
puts ""
end
end
# Returns the position of the mouse when it is clicked.
def click_pos
return nil unless inputs.mouse.click # returns nil unless the mouse was clicked
return inputs.mouse.click.point # returns location of mouse click (coordinates)
end
# Creates buttons for the button_list and sets their values using a hash (uses symbols as keys)
def button id, x, y, text
@button_list[id] ||= { # assigns values to hash keys
id: id,
text: text,
primitives: [
[x + 10, y + 30, text, 2, 0].label, # positions label inside border
[x, y, 300, 50].border, # sets definition of border
]
}
@button_list[id][:primitives] # returns label and border for buttons
end
# Creates a progress bar (used for lighting the fire) and sets its values.
def progress_bar id, x, y, text, percentage
@button_list[id] = { # assigns values to hash keys
id: id,
text: text,
primitives: [
[x, y, 300, 50, 100, 100, 100].solid, # sets definition for solid (which fills the bar with gray)
[x + 10, y + 30, text, 2, 0].label, # sets definition for label, positions inside border
[x, y, 300, 50].border, # sets definition of border
]
}
# Fills progress bar based on percentage. If the fire was ready to be lit (100%) and we multiplied by
# 100, only 1/3 of the bar would only be filled in. 200 would cause only 2/3 to be filled in.
@button_list[id][:primitives][0][2] = 300 * percentage
@button_list[id][:primitives]
end
# Defines the game.
def game
@game
end
# Initalizes the game and creates an empty list of buttons.
def initialize
@game = TextedBasedGame.new self
@button_list ||= {}
end
# Clears the storyline and takes the user to the room.
def alert_dismiss_clicked
game.clear_storyline
game.go_to_room
end
# Lights the fire when the user clicks the "light fire" option.
def light_fire_clicked
game.light_fire
end
# Saves the game when the user clicks the "save" option.
def save_game_clicked
game.save
end
# Resets the game when the user clicks the "reset" option.
def reset_game_clicked
game.reset
end
# Loads the game when the user clicks the "load" option.
def load_game_clicked
game.load
end
end
$text_based_rpg = TextedBasedGamePresenter.new
def tick args
$text_based_rpg.state = args.state
$text_based_rpg.outputs = args.outputs
$text_based_rpg.inputs = args.inputs
$text_based_rpg.tick
end
</code></pre>
<h3 id='----advanced-audio---audio-mixer---main-rb'>Advanced Audio - Audio Mixer - main.rb</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_audio/01_audio_mixer/app/main.rb
# these are the properties that you can sent on args.audio
def spawn_new_sound args, name, path
# Spawn randomly in an area that won't be covered by UI.
screenx = (rand * 600.0) + 200.0
screeny = (rand * 400.0) + 100.0
id = new_sound_id! args
# you can hang anything on the audio hashes you want, so we store the
# actual screen position in here for convenience.
args.audio[id] = {
name: name,
input: path,
screenx: screenx,
screeny: screeny,
x: ((screenx / 1279.0) * 2.0) - 1.0, # scale to -1.0 - 1.0 range
y: ((screeny / 719.0) * 2.0) - 1.0, # scale to -1.0 - 1.0 range
z: 0.0,
gain: 1.0,
pitch: 1.0,
looping: true,
paused: false
}
args.state.selected = id
end
# these are values you can change on the ~args.audio~ data structure
def input_panel args
return unless args.state.panel
return if args.state.dragging
audio_entry = args.audio[args.state.selected]
results = args.state.panel
if args.state.mouse_state == :held && args.inputs.mouse.position.inside_rect?(results.pitch_slider_rect.rect)
audio_entry.pitch = 2.0 * ((args.inputs.mouse.x - results.pitch_slider_rect.x).to_f / (results.pitch_slider_rect.w - 1.0))
elsif args.state.mouse_state == :held && args.inputs.mouse.position.inside_rect?(results.playtime_slider_rect.rect)
audio_entry.playtime = audio_entry.length_ * ((args.inputs.mouse.x - results.playtime_slider_rect.x).to_f / (results.playtime_slider_rect.w - 1.0))
elsif args.state.mouse_state == :held && args.inputs.mouse.position.inside_rect?(results.gain_slider_rect.rect)
audio_entry.gain = (args.inputs.mouse.x - results.gain_slider_rect.x).to_f / (results.gain_slider_rect.w - 1.0)
elsif args.inputs.mouse.click && args.inputs.mouse.position.inside_rect?(results.looping_checkbox_rect.rect)
audio_entry.looping = !audio_entry.looping
elsif args.inputs.mouse.click && args.inputs.mouse.position.inside_rect?(results.paused_checkbox_rect.rect)
audio_entry.paused = !audio_entry.paused
elsif args.inputs.mouse.click && args.inputs.mouse.position.inside_rect?(results.delete_button_rect.rect)
args.audio.delete args.state.selected
end
end
def render_sources args
args.outputs.primitives << args.audio.keys.map do |k|
s = args.audio[k]
isselected = (k == args.state.selected)
color = isselected ? [ 0, 255, 0, 255 ] : [ 0, 0, 255, 255 ]
[
[s.screenx, s.screeny, args.state.boxsize, args.state.boxsize, *color].solid,
{
x: s.screenx + args.state.boxsize.half,
y: s.screeny,
text: s.name,
r: 255,
g: 255,
b: 255,
alignment_enum: 1
}.label!
]
end
end
def playtime_str t
minutes = (t / 60.0).floor
seconds = t - (minutes * 60.0).to_f
return minutes.to_s + ':' + seconds.floor.to_s + ((seconds - seconds.floor).to_s + "000")[1..3]
end
def label_with_drop_shadow x, y, text
[
{ x: x + 1, y: y + 1, text: text, vertical_alignment_enum: 1, alignment_enum: 1, r: 0, g: 0, b: 0 }.label!,
{ x: x + 2, y: y + 0, text: text, vertical_alignment_enum: 1, alignment_enum: 1, r: 0, g: 0, b: 0 }.label!,
{ x: x + 0, y: y + 1, text: text, vertical_alignment_enum: 1, alignment_enum: 1, r: 200, g: 200, b: 200 }.label!
]
end
def check_box opts = {}
checkbox_template = opts.args.layout.rect(w: 0.5, h: 0.5, col: 2)
final_rect = checkbox_template.center_inside_rect_y(opts.args.layout.rect(row: opts.row, col: opts.col))
color = { r: 0, g: 0, b: 0 }
color = { r: 255, g: 255, b: 255 } if opts.checked
{
rect: final_rect,
primitives: [
(final_rect.to_solid color)
]
}
end
def progress_bar opts = {}
outer_rect = opts.args.layout.rect(row: opts.row, col: opts.col, w: 5, h: 1)
color = opts.percentage * 255
baseline_progress_bar = opts.args
.layout
.rect(w: 5, h: 0.5)
final_rect = baseline_progress_bar.center_inside_rect(outer_rect)
center = final_rect.rect_center_point
{
rect: final_rect,
primitives: [
final_rect.merge(r: color, g: color, b: color, a: 128).solid!,
label_with_drop_shadow(center.x, center.y, opts.text)
]
}
end
def panel_primitives args, audio_entry
results = { primitives: [] }
return results unless audio_entry
# this uses DRGTK's layout apis to layout the controls
# imagine the screen is split into equal cells (24 cells across, 12 cells up and down)
# args.layout.rect returns a hash which we merge values with to create primitives
# using args.layout.rect removes the need for pixel pushing
# args.outputs.debug << args.layout.debug_primitives(r: 255, g: 255, b: 255)
white_color = { r: 255, g: 255, b: 255 }
label_style = white_color.merge(vertical_alignment_enum: 1)
# panel background
results.primitives << args.layout.rect(row: 0, col: 0, w: 7, h: 6, include_col_gutter: true, include_row_gutter: true)
.border!(r: 255, g: 255, b: 255)
# title
results.primitives << args.layout.point(row: 0, col: 3.5, row_anchor: 0.5)
.merge(label_style)
.merge(text: "Source #{args.state.selected} (#{args.audio[args.state.selected].name})",
size_enum: 3,
alignment_enum: 1)
# seperator line
results.primitives << args.layout.rect(row: 1, col: 0, w: 7, h: 0)
.line!(white_color)
# screen location
results.primitives << args.layout.point(row: 1.0, col: 0, row_anchor: 0.5)
.merge(label_style)
.merge(text: "screen:")
results.primitives << args.layout.point(row: 1.0, col: 2, row_anchor: 0.5)
.merge(label_style)
.merge(text: "(#{audio_entry.screenx.to_i}, #{audio_entry.screeny.to_i})")
# position
results.primitives << args.layout.point(row: 1.5, col: 0, row_anchor: 0.5)
.merge(label_style)
.merge(text: "position:")
results.primitives << args.layout.point(row: 1.5, col: 2, row_anchor: 0.5)
.merge(label_style)
.merge(text: "(#{audio_entry[:x].round(5).to_s[0..6]}, #{audio_entry[:y].round(5).to_s[0..6]})")
results.primitives << args.layout.point(row: 2.0, col: 0, row_anchor: 0.5)
.merge(label_style)
.merge(text: "pitch:")
results.pitch_slider_rect = progress_bar(row: 2.0, col: 2,
percentage: audio_entry.pitch / 2.0,
text: "#{audio_entry.pitch.to_sf}",
args: args)
results.primitives << results.pitch_slider_rect.primitives
results.primitives << args.layout.point(row: 2.5, col: 0, row_anchor: 0.5)
.merge(label_style)
.merge(text: "playtime:")
results.playtime_slider_rect = progress_bar(args: args,
row: 2.5,
col: 2,
percentage: audio_entry.playtime / audio_entry.length_,
text: "#{playtime_str(audio_entry.playtime)} / #{playtime_str(audio_entry.length_)}")
results.primitives << results.playtime_slider_rect.primitives
results.primitives << args.layout.point(row: 3.0, col: 0, row_anchor: 0.5)
.merge(label_style)
.merge(text: "gain:")
results.gain_slider_rect = progress_bar(args: args,
row: 3.0,
col: 2,
percentage: audio_entry.gain,
text: "#{audio_entry.gain.to_sf}")
results.primitives << results.gain_slider_rect.primitives
results.primitives << args.layout.point(row: 3.5, col: 0, row_anchor: 0.5)
.merge(label_style)
.merge(text: "looping:")
checkbox_template = args.layout.rect(w: 0.5, h: 0.5, col: 2)
results.looping_checkbox_rect = check_box(args: args, row: 3.5, col: 2, checked: audio_entry.looping)
results.primitives << results.looping_checkbox_rect.primitives
results.primitives << args.layout.point(row: 4.0, col: 0, row_anchor: 0.5)
.merge(label_style)
.merge(text: "paused:")
checkbox_template = args.layout.rect(w: 0.5, h: 0.5, col: 2)
results.paused_checkbox_rect = check_box(args: args, row: 4.0, col: 2, checked: !audio_entry.paused)
results.primitives << results.paused_checkbox_rect.primitives
results.delete_button_rect = { rect: args.layout.rect(row: 5, col: 0, w: 7, h: 1) }
results.primitives << results.delete_button_rect.to_solid(r: 180)
results.primitives << args.layout.point(row: 5, col: 3.5, row_anchor: 0.5)
.merge(label_style)
.merge(text: "DELETE", alignment_enum: 1)
return results
end
def render_panel args
args.state.panel = nil
audio_entry = args.audio[args.state.selected]
return unless audio_entry
mouse_down = (args.state.mouse_held >= 0)
args.state.panel = panel_primitives args, audio_entry
args.outputs.primitives << args.state.panel.primitives
end
def new_sound_id! args
args.state.sound_id ||= 0
args.state.sound_id += 1
args.state.sound_id
end
def render_launcher args
args.outputs.primitives << args.state.spawn_sound_buttons.map(&:primitives)
end
def render_ui args
render_launcher args
render_panel args
end
def tick args
defaults args
render args
input args
end
def input args
if !args.audio[args.state.selected]
args.state.selected = nil
args.state.dragging = nil
end
# spawn button and node interaction
if args.inputs.mouse.click
spawn_sound_button = args.state.spawn_sound_buttons.find { |b| args.inputs.mouse.inside_rect? b.rect }
audio_click_key, audio_click_value = args.audio.find do |k, v|
args.inputs.mouse.inside_rect? [v.screenx, v.screeny, args.state.boxsize, args.state.boxsize]
end
if spawn_sound_button
args.state.selected = nil
spawn_new_sound args, spawn_sound_button.name, spawn_sound_button.path
elsif audio_click_key
args.state.selected = audio_click_key
end
end
if args.state.mouse_state == :held && args.state.selected
v = args.audio[args.state.selected]
if args.inputs.mouse.inside_rect? [v.screenx, v.screeny, args.state.boxsize, args.state.boxsize]
args.state.dragging = args.state.selected
end
if args.state.dragging
s = args.audio[args.state.selected]
# you can hang anything on the audio hashes you want, so we store the
# actual screen position so it doesn't scale weirdly vs your mouse.
s.screenx = args.inputs.mouse.x - (args.state.boxsize / 2)
s.screeny = args.inputs.mouse.y - (args.state.boxsize / 2)
s.screeny = 50 if s.screeny < 50
s.screeny = (719 - args.state.boxsize) if s.screeny > (719 - args.state.boxsize)
s.screenx = 0 if s.screenx < 0
s.screenx = (1279 - args.state.boxsize) if s.screenx > (1279 - args.state.boxsize)
s.x = ((s.screenx / 1279.0) * 2.0) - 1.0 # scale to -1.0 - 1.0 range
s.y = ((s.screeny / 719.0) * 2.0) - 1.0 # scale to -1.0 - 1.0 range
end
elsif args.state.mouse_state == :released
args.state.dragging = nil
end
input_panel args
end
def defaults args
args.state.mouse_state ||= :released
args.state.dragging_source ||= false
args.state.selected ||= 0
args.state.next_sound_index ||= 0
args.state.boxsize ||= 30
args.state.sound_files ||= [
{ name: :tada, path: "sounds/tada.wav" },
{ name: :splash, path: "sounds/splash.wav" },
{ name: :drum, path: "sounds/drum.wav" },
{ name: :spring, path: "sounds/spring.wav" },
{ name: :music, path: "sounds/music.ogg" }
]
# generate buttons based off the sound collection above
args.state.spawn_sound_buttons ||= begin
# create a group of buttons
# column centered (using col_offset to calculate the column offset)
# where each item is 2 columns apart
rects = args.layout.rect_group row: 11,
col_offset: {
count: args.state.sound_files.length,
w: 2
},
dcol: 2,
w: 2,
h: 1,
group: args.state.sound_files
# now that you have the rects
# construct the metadata for the buttons
rects.map do |rect|
{
rect: rect,
name: rect.name,
path: rect.path,
primitives: [
rect.to_border(r: 255, g: 255, b: 255),
rect.to_label(x: rect.center_x,
y: rect.center_y,
text: "#{rect.name}",
alignment_enum: 1,
vertical_alignment_enum: 1,
r: 255, g: 255, b: 255)
]
}
end
end
if args.inputs.mouse.up
args.state.mouse_state = :released
args.state.dragging_source = false
elsif args.inputs.mouse.down
args.state.mouse_state = :held
end
args.outputs.background_color = [ 0, 0, 0, 255 ]
end
def render args
render_ui args
render_sources args
end
</code></pre>
<h3 id='----advanced-audio---audio-mixer---server_ip_address-txt'>Advanced Audio - Audio Mixer - server_ip_address.txt</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_audio/01_audio_mixer/app/server_ip_address.txt
192.168.1.65
</code></pre>
<h3 id='----advanced-audio---audio-mixer---metadata---ios_metadata-txt'>Advanced Audio - Audio Mixer - Metadata - ios_metadata.txt</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_audio/01_audio_mixer/metadata/ios_metadata.txt
# ios_metadata.txt is used by the Pro version of DragonRuby Game Toolkit to create iOS apps.
# Information about the Pro version can be found at: http://dragonruby.org/toolkit/game#purchase
# teamid needs to be set to your assigned Team Id which can be found at https://developer.apple.com/account/#/membership/
teamid=
# appid needs to be set to your application identifier which can be found at https://developer.apple.com/account/resources/identifiers/list
appid=
# appname is the name you want to show up underneath the app icon on the device. Keep it under 10 characters.
appname=
</code></pre>
<h3 id='----advanced-audio---sound-synthesis---main-rb'>Advanced Audio - Sound Synthesis - main.rb</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_audio/02_sound_synthesis/app/main.rb
begin # region: top level tick methods
def tick args
defaults args
render args
input args
process_audio_queue args
end
def defaults args
args.state.sine_waves ||= {}
args.state.square_waves ||= {}
args.state.saw_tooth_waves ||= {}
args.state.triangle_waves ||= {}
args.state.audio_queue ||= []
args.state.buttons ||= [
(frequency_buttons args),
(sine_wave_note_buttons args),
(bell_buttons args),
(square_wave_note_buttons args),
(saw_tooth_wave_note_buttons args),
(triangle_wave_note_buttons args),
].flatten
end
def render args
args.outputs.borders << args.state.buttons.map { |b| b[:border] }
args.outputs.labels << args.state.buttons.map { |b| b[:label] }
args.outputs.labels << args.layout
.rect(row: 0, col: 11.5)
.yield_self { |r| r.merge y: r.y + r.h }
.merge(text: "This is a Pro only feature. Click here to watch the YouTube video if you are on the Standard License.",
alignment_enum: 1)
end
def input args
args.state.buttons.each do |b|
if args.inputs.mouse.click && (args.inputs.mouse.click.inside_rect? b[:rect])
parameter_string = (b.slice :frequency, :note, :octave).map { |k, v| "#{k}: #{v}" }.join ", "
args.gtk.notify! "#{b[:method_to_call]} #{parameter_string}"
send b[:method_to_call], args, b
end
end
if args.inputs.mouse.click && (args.inputs.mouse.click.inside_rect? (args.layout.rect(row: 0).yield_self { |r| r.merge y: r.y + r.h.half, h: r.h.half }))
args.gtk.openurl 'https://www.youtube.com/watch?v=zEzovM5jT-k&ab_channel=AmirRajan'
end
end
def process_audio_queue args
to_queue = args.state.audio_queue.find_all { |v| v[:queue_at] <= args.tick_count }
args.state.audio_queue -= to_queue
to_queue.each { |a| args.audio[a[:id]] = a }
args.audio.find_all { |k, v| v[:decay_rate] }
.each { |k, v| v[:gain] -= v[:decay_rate] }
sounds_to_stop = args.audio
.find_all { |k, v| v[:stop_at] && args.state.tick_count >= v[:stop_at] }
.map { |k, v| k }
sounds_to_stop.each { |k| args.audio.delete k }
end
end
begin # region: button definitions, ui layout, callback functions
def button args, opts
button_def = opts.merge rect: (args.layout.rect (opts.merge w: 2, h: 1))
button_def[:border] = button_def[:rect].merge r: 0, g: 0, b: 0
label_offset_x = 5
label_offset_y = 30
button_def[:label] = button_def[:rect].merge text: opts[:text],
size_enum: -2.5,
x: button_def[:rect].x + label_offset_x,
y: button_def[:rect].y + label_offset_y
button_def
end
def play_sine_wave args, sender
queue_sine_wave args,
frequency: sender[:frequency],
duration: 1.seconds,
fade_out: true
end
def play_note args, sender
method_to_call = :queue_sine_wave
method_to_call = :queue_square_wave if sender[:type] == :square
method_to_call = :queue_saw_tooth_wave if sender[:type] == :saw_tooth
method_to_call = :queue_triangle_wave if sender[:type] == :triangle
method_to_call = :queue_bell if sender[:type] == :bell
send method_to_call, args,
frequency: (frequency_for note: sender[:note], octave: sender[:octave]),
duration: 1.seconds,
fade_out: true
end
def frequency_buttons args
[
(button args,
row: 4.0, col: 0, text: "300hz",
frequency: 300,
method_to_call: :play_sine_wave),
(button args,
row: 5.0, col: 0, text: "400hz",
frequency: 400,
method_to_call: :play_sine_wave),
(button args,
row: 6.0, col: 0, text: "500hz",
frequency: 500,
method_to_call: :play_sine_wave),
]
end
def sine_wave_note_buttons args
[
(button args,
row: 1.5, col: 2, text: "Sine C4",
note: :c, octave: 4, type: :sine, method_to_call: :play_note),
(button args,
row: 2.5, col: 2, text: "Sine D4",
note: :d, octave: 4, type: :sine, method_to_call: :play_note),
(button args,
row: 3.5, col: 2, text: "Sine E4",
note: :e, octave: 4, type: :sine, method_to_call: :play_note),
(button args,
row: 4.5, col: 2, text: "Sine F4",
note: :f, octave: 4, type: :sine, method_to_call: :play_note),
(button args,
row: 5.5, col: 2, text: "Sine G4",
note: :g, octave: 4, type: :sine, method_to_call: :play_note),
(button args,
row: 6.5, col: 2, text: "Sine A5",
note: :a, octave: 5, type: :sine, method_to_call: :play_note),
(button args,
row: 7.5, col: 2, text: "Sine B5",
note: :b, octave: 5, type: :sine, method_to_call: :play_note),
(button args,
row: 8.5, col: 2, text: "Sine C5",
note: :c, octave: 5, type: :sine, method_to_call: :play_note),
]
end
def square_wave_note_buttons args
[
(button args,
row: 1.5, col: 6, text: "Square C4",
note: :c, octave: 4, type: :square, method_to_call: :play_note),
(button args,
row: 2.5, col: 6, text: "Square D4",
note: :d, octave: 4, type: :square, method_to_call: :play_note),
(button args,
row: 3.5, col: 6, text: "Square E4",
note: :e, octave: 4, type: :square, method_to_call: :play_note),
(button args,
row: 4.5, col: 6, text: "Square F4",
note: :f, octave: 4, type: :square, method_to_call: :play_note),
(button args,
row: 5.5, col: 6, text: "Square G4",
note: :g, octave: 4, type: :square, method_to_call: :play_note),
(button args,
row: 6.5, col: 6, text: "Square A5",
note: :a, octave: 5, type: :square, method_to_call: :play_note),
(button args,
row: 7.5, col: 6, text: "Square B5",
note: :b, octave: 5, type: :square, method_to_call: :play_note),
(button args,
row: 8.5, col: 6, text: "Square C5",
note: :c, octave: 5, type: :square, method_to_call: :play_note),
]
end
def saw_tooth_wave_note_buttons args
[
(button args,
row: 1.5, col: 8, text: "Saw C4",
note: :c, octave: 4, type: :saw_tooth, method_to_call: :play_note),
(button args,
row: 2.5, col: 8, text: "Saw D4",
note: :d, octave: 4, type: :saw_tooth, method_to_call: :play_note),
(button args,
row: 3.5, col: 8, text: "Saw E4",
note: :e, octave: 4, type: :saw_tooth, method_to_call: :play_note),
(button args,
row: 4.5, col: 8, text: "Saw F4",
note: :f, octave: 4, type: :saw_tooth, method_to_call: :play_note),
(button args,
row: 5.5, col: 8, text: "Saw G4",
note: :g, octave: 4, type: :saw_tooth, method_to_call: :play_note),
(button args,
row: 6.5, col: 8, text: "Saw A5",
note: :a, octave: 5, type: :saw_tooth, method_to_call: :play_note),
(button args,
row: 7.5, col: 8, text: "Saw B5",
note: :b, octave: 5, type: :saw_tooth, method_to_call: :play_note),
(button args,
row: 8.5, col: 8, text: "Saw C5",
note: :c, octave: 5, type: :saw_tooth, method_to_call: :play_note),
]
end
def triangle_wave_note_buttons args
[
(button args,
row: 1.5, col: 10, text: "Triangle C4",
note: :c, octave: 4, type: :triangle, method_to_call: :play_note),
(button args,
row: 2.5, col: 10, text: "Triangle D4",
note: :d, octave: 4, type: :triangle, method_to_call: :play_note),
(button args,
row: 3.5, col: 10, text: "Triangle E4",
note: :e, octave: 4, type: :triangle, method_to_call: :play_note),
(button args,
row: 4.5, col: 10, text: "Triangle F4",
note: :f, octave: 4, type: :triangle, method_to_call: :play_note),
(button args,
row: 5.5, col: 10, text: "Triangle G4",
note: :g, octave: 4, type: :triangle, method_to_call: :play_note),
(button args,
row: 6.5, col: 10, text: "Triangle A5",
note: :a, octave: 5, type: :triangle, method_to_call: :play_note),
(button args,
row: 7.5, col: 10, text: "Triangle B5",
note: :b, octave: 5, type: :triangle, method_to_call: :play_note),
(button args,
row: 8.5, col: 10, text: "Triangle C5",
note: :c, octave: 5, type: :triangle, method_to_call: :play_note),
]
end
def bell_buttons args
[
(button args,
row: 1.5, col: 4, text: "Bell C4",
note: :c, octave: 4, type: :bell, method_to_call: :play_note),
(button args,
row: 2.5, col: 4, text: "Bell D4",
note: :d, octave: 4, type: :bell, method_to_call: :play_note),
(button args,
row: 3.5, col: 4, text: "Bell E4",
note: :e, octave: 4, type: :bell, method_to_call: :play_note),
(button args,
row: 4.5, col: 4, text: "Bell F4",
note: :f, octave: 4, type: :bell, method_to_call: :play_note),
(button args,
row: 5.5, col: 4, text: "Bell G4",
note: :g, octave: 4, type: :bell, method_to_call: :play_note),
(button args,
row: 6.5, col: 4, text: "Bell A5",
note: :a, octave: 5, type: :bell, method_to_call: :play_note),
(button args,
row: 7.5, col: 4, text: "Bell B5",
note: :b, octave: 5, type: :bell, method_to_call: :play_note),
(button args,
row: 8.5, col: 4, text: "Bell C5",
note: :c, octave: 5, type: :bell, method_to_call: :play_note),
]
end
end
begin # region: wave generation
begin # sine wave
def defaults_sine_wave_for
{ frequency: 440, sample_rate: 48000 }
end
def sine_wave_for opts = {}
opts = defaults_sine_wave_for.merge opts
frequency = opts[:frequency]
sample_rate = opts[:sample_rate]
period_size = (sample_rate.fdiv frequency).ceil
period_size.map_with_index do |i|
Math::sin((2.0 * Math::PI) / (sample_rate.to_f / frequency.to_f) * i)
end.to_a
end
def defaults_queue_sine_wave
{ frequency: 440, duration: 60, gain: 1.0, fade_out: false, queue_in: 0 }
end
def queue_sine_wave args, opts = {}
opts = defaults_queue_sine_wave.merge opts
frequency = opts[:frequency]
sample_rate = 48000
sine_wave = sine_wave_for frequency: frequency, sample_rate: sample_rate
args.state.sine_waves[frequency] ||= sine_wave_for frequency: frequency, sample_rate: sample_rate
proc = lambda do
generate_audio_data args.state.sine_waves[frequency], sample_rate
end
audio_state = new_audio_state args, opts
audio_state[:input] = [1, sample_rate, proc]
queue_audio args, audio_state: audio_state, wave: sine_wave
end
end
begin # region: square wave
def defaults_square_wave_for
{ frequency: 440, sample_rate: 48000 }
end
def square_wave_for opts = {}
opts = defaults_square_wave_for.merge opts
sine_wave = sine_wave_for opts
sine_wave.map do |v|
if v >= 0
1.0
else
-1.0
end
end.to_a
end
def defaults_queue_square_wave
{ frequency: 440, duration: 60, gain: 0.3, fade_out: false, queue_in: 0 }
end
def queue_square_wave args, opts = {}
opts = defaults_queue_square_wave.merge opts
frequency = opts[:frequency]
sample_rate = 48000
square_wave = square_wave_for frequency: frequency, sample_rate: sample_rate
args.state.square_waves[frequency] ||= square_wave_for frequency: frequency, sample_rate: sample_rate
proc = lambda do
generate_audio_data args.state.square_waves[frequency], sample_rate
end
audio_state = new_audio_state args, opts
audio_state[:input] = [1, sample_rate, proc]
queue_audio args, audio_state: audio_state, wave: square_wave
end
end
begin # region: saw tooth wave
def defaults_saw_tooth_wave_for
{ frequency: 440, sample_rate: 48000 }
end
def saw_tooth_wave_for opts = {}
opts = defaults_saw_tooth_wave_for.merge opts
sine_wave = sine_wave_for opts
period_size = sine_wave.length
sine_wave.map_with_index do |v, i|
(((i % period_size).fdiv period_size) * 2) - 1
end
end
def defaults_queue_saw_tooth_wave
{ frequency: 440, duration: 60, gain: 0.3, fade_out: false, queue_in: 0 }
end
def queue_saw_tooth_wave args, opts = {}
opts = defaults_queue_saw_tooth_wave.merge opts
frequency = opts[:frequency]
sample_rate = 48000
saw_tooth_wave = saw_tooth_wave_for frequency: frequency, sample_rate: sample_rate
args.state.saw_tooth_waves[frequency] ||= saw_tooth_wave_for frequency: frequency, sample_rate: sample_rate
proc = lambda do
generate_audio_data args.state.saw_tooth_waves[frequency], sample_rate
end
audio_state = new_audio_state args, opts
audio_state[:input] = [1, sample_rate, proc]
queue_audio args, audio_state: audio_state, wave: saw_tooth_wave
end
end
begin # region: triangle wave
def defaults_triangle_wave_for
{ frequency: 440, sample_rate: 48000 }
end
def triangle_wave_for opts = {}
opts = defaults_saw_tooth_wave_for.merge opts
sine_wave = sine_wave_for opts
period_size = sine_wave.length
sine_wave.map_with_index do |v, i|
ratio = (i.fdiv period_size)
if ratio <= 0.5
(ratio * 4) - 1
else
ratio -= 0.5
1 - (ratio * 4)
end
end
end
def defaults_queue_triangle_wave
{ frequency: 440, duration: 60, gain: 1.0, fade_out: false, queue_in: 0 }
end
def queue_triangle_wave args, opts = {}
opts = defaults_queue_triangle_wave.merge opts
frequency = opts[:frequency]
sample_rate = 48000
triangle_wave = triangle_wave_for frequency: frequency, sample_rate: sample_rate
args.state.triangle_waves[frequency] ||= triangle_wave_for frequency: frequency, sample_rate: sample_rate
proc = lambda do
generate_audio_data args.state.triangle_waves[frequency], sample_rate
end
audio_state = new_audio_state args, opts
audio_state[:input] = [1, sample_rate, proc]
queue_audio args, audio_state: audio_state, wave: triangle_wave
end
end
begin # region: bell
def defaults_queue_bell
{ frequency: 440, duration: 1.seconds, queue_in: 0 }
end
def queue_bell args, opts = {}
(bell_to_sine_waves (defaults_queue_bell.merge opts)).each { |b| queue_sine_wave args, b }
end
def bell_harmonics
[
{ frequency_ratio: 0.5, duration_ratio: 1.00 },
{ frequency_ratio: 1.0, duration_ratio: 0.80 },
{ frequency_ratio: 2.0, duration_ratio: 0.60 },
{ frequency_ratio: 3.0, duration_ratio: 0.40 },
{ frequency_ratio: 4.2, duration_ratio: 0.25 },
{ frequency_ratio: 5.4, duration_ratio: 0.20 },
{ frequency_ratio: 6.8, duration_ratio: 0.15 }
]
end
def defaults_bell_to_sine_waves
{ frequency: 440, duration: 1.seconds, queue_in: 0 }
end
def bell_to_sine_waves opts = {}
opts = defaults_bell_to_sine_waves.merge opts
bell_harmonics.map do |b|
{
frequency: opts[:frequency] * b[:frequency_ratio],
duration: opts[:duration] * b[:duration_ratio],
queue_in: opts[:queue_in],
gain: (1.fdiv bell_harmonics.length),
fade_out: true
}
end
end
end
begin # audio entity construction
def generate_audio_data sine_wave, sample_rate
sample_size = (sample_rate.fdiv (1000.fdiv 60)).ceil
copy_count = (sample_size.fdiv sine_wave.length).ceil
sine_wave * copy_count
end
def defaults_new_audio_state
{ frequency: 440, duration: 60, gain: 1.0, fade_out: false, queue_in: 0 }
end
def new_audio_state args, opts = {}
opts = defaults_new_audio_state.merge opts
decay_rate = 0
decay_rate = 1.fdiv(opts[:duration]) * opts[:gain] if opts[:fade_out]
frequency = opts[:frequency]
sample_rate = 48000
{
id: (new_id! args),
frequency: frequency,
sample_rate: 48000,
stop_at: args.tick_count + opts[:queue_in] + opts[:duration],
gain: opts[:gain].to_f,
queue_at: args.state.tick_count + opts[:queue_in],
decay_rate: decay_rate,
pitch: 1.0,
looping: true,
paused: false
}
end
def queue_audio args, opts = {}
graph_wave args, opts[:wave], opts[:audio_state][:frequency]
args.state.audio_queue << opts[:audio_state]
end
def new_id! args
args.state.audio_id ||= 0
args.state.audio_id += 1
end
def graph_wave args, wave, frequency
if args.state.tick_count != args.state.graphed_at
args.outputs.static_lines.clear
args.outputs.static_sprites.clear
end
wave = wave
r, g, b = frequency.to_i % 85,
frequency.to_i % 170,
frequency.to_i % 255
starting_rect = args.layout.rect(row: 5, col: 13)
x_scale = 10
y_scale = 100
max_points = 25
points = wave
if wave.length > max_points
resolution = wave.length.idiv max_points
points = wave.find_all.with_index { |y, i| (i % resolution == 0) }
end
args.outputs.static_lines << points.map_with_index do |y, x|
next_y = points[x + 1]
if next_y
{
x: starting_rect.x + (x * x_scale),
y: starting_rect.y + starting_rect.h.half + y_scale * y,
x2: starting_rect.x + ((x + 1) * x_scale),
y2: starting_rect.y + starting_rect.h.half + y_scale * next_y,
r: r,
g: g,
b: b
}
end
end
args.outputs.static_sprites << points.map_with_index do |y, x|
{
x: (starting_rect.x + (x * x_scale)) - 2,
y: (starting_rect.y + starting_rect.h.half + y_scale * y) - 2,
w: 4,
h: 4,
path: 'sprites/square-white.png',
r: r,
g: g,
b: b
}
end
args.state.graphed_at = args.state.tick_count
end
end
begin # region: musical note mapping
def defaults_frequency_for
{ note: :a, octave: 5, sharp: false, flat: false }
end
def frequency_for opts = {}
opts = defaults_frequency_for.merge opts
octave_offset_multiplier = opts[:octave] - 5
note = note_frequencies_octave_5[opts[:note]]
if octave_offset_multiplier < 0
note = note * 1 / (octave_offset_multiplier.abs + 1)
elsif octave_offset_multiplier > 0
note = note * (octave_offset_multiplier.abs + 1) / 1
end
note
end
def note_frequencies_octave_5
{
a: 440.0,
a_sharp: 466.16, b_flat: 466.16,
b: 493.88,
c: 523.25,
c_sharp: 554.37, d_flat: 587.33,
d: 587.33,
d_sharp: 622.25, e_flat: 659.25,
e: 659.25,
f: 698.25,
f_sharp: 739.99, g_flat: 739.99,
g: 783.99,
g_sharp: 830.61, a_flat: 830.61
}
end
end
end
$gtk.reset
</code></pre>
<h3 id='----advanced-rendering---simple-render-targets---main-rb'>Advanced Rendering - Simple Render Targets - main.rb</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_rendering/01_simple_render_targets/app/main.rb
def tick args
# args.outputs.render_targets are really really powerful.
# They essentially allow you to create a sprite programmatically and cache the result.
# Create a render_target of a :block and a :gradient on tick zero.
if args.state.tick_count == 0
args.render_target(:block).solids << [0, 0, 1280, 100]
# The gradient is actually just a collection of black solids with increasing
# opacities.
args.render_target(:gradient).solids << 90.map_with_index do |x|
50.map_with_index do |y|
[x * 15, y * 15, 15, 15, 0, 0, 0, (x * 3).fdiv(255) * 255]
end
end
end
# Take the :block render_target and present it horizontally centered.
# Use a subsection of the render_targetd specified by source_x,
# source_y, source_w, source_h.
args.outputs.sprites << { x: 0,
y: 310,
w: 1280,
h: 100,
path: :block,
source_x: 0,
source_y: 0,
source_w: 1280,
source_h: 100 }
# After rendering :block, render gradient on top of :block.
args.outputs.sprites << [0, 0, 1280, 720, :gradient]
args.outputs.labels << [1270, 710, args.gtk.current_framerate, 0, 2, 255, 255, 255]
tick_instructions args, "Sample app shows how to use render_targets (programmatically create cached sprites)."
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
$gtk.reset
</code></pre>
<h3 id='----advanced-rendering---render-targets-with-tile-manipulation---main-rb'>Advanced Rendering - Render Targets With Tile Manipulation - main.rb</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_rendering/02_render_targets_with_tile_manipulation/app/main.rb
# This sample is meant to show you how to do that dripping transition thing
# at the start of the original Doom. Most of this file is here to animate
# a scene to wipe away; the actual wipe effect is in the last 20 lines or
# so.
$gtk.reset # reset all game state if reloaded.
def circle_of_blocks pass, xoffset, yoffset, angleoffset, blocksize, distance
numblocks = 10
for i in 1..numblocks do
angle = ((360 / numblocks) * i) + angleoffset
radians = angle * (Math::PI / 180)
x = (xoffset + (distance * Math.cos(radians))).round
y = (yoffset + (distance * Math.sin(radians))).round
pass.solids << [ x, y, blocksize, blocksize, 255, 255, 0 ]
end
end
def draw_scene args, pass
pass.solids << [0, 360, 1280, 360, 0, 0, 200]
pass.solids << [0, 0, 1280, 360, 0, 127, 0]
blocksize = 100
angleoffset = args.state.tick_count * 2.5
centerx = (1280 - blocksize) / 2
centery = (720 - blocksize) / 2
circle_of_blocks pass, centerx, centery, angleoffset, blocksize * 2, 500
circle_of_blocks pass, centerx, centery, angleoffset, blocksize, 325
circle_of_blocks pass, centerx, centery, angleoffset, blocksize / 2, 200
circle_of_blocks pass, centerx, centery, angleoffset, blocksize / 4, 100
end
def tick args
segments = 160
# On the first tick, initialize some stuff.
if !args.state.yoffsets
args.state.baseyoff = 0
args.state.yoffsets = []
for i in 0..segments do
args.state.yoffsets << rand * 100
end
end
# Just draw some random stuff for a few seconds.
args.state.static_debounce ||= 60 * 2.5
if args.state.static_debounce > 0
last_frame = args.state.static_debounce == 1
target = last_frame ? args.render_target(:last_frame) : args.outputs
draw_scene args, target
args.state.static_debounce -= 1
return unless last_frame
end
# build up the wipe...
# this is the thing we're wiping to.
args.outputs.sprites << [ 0, 0, 1280, 720, 'dragonruby.png' ]
return if (args.state.baseyoff > (1280 + 100)) # stop when done sliding
segmentw = 1280 / segments
x = 0
for i in 0..segments do
yoffset = 0
if args.state.yoffsets[i] < args.state.baseyoff
yoffset = args.state.baseyoff - args.state.yoffsets[i]
end
# (720 - yoffset) flips the coordinate system, (- 720) adjusts for the height of the segment.
args.outputs.sprites << [ x, (720 - yoffset) - 720, segmentw, 720, 'last_frame', 0, 255, 255, 255, 255, x, 0, segmentw, 720 ]
x += segmentw
end
args.state.baseyoff += 4
tick_instructions args, "Sample app shows an advanced usage of render_target."
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----advanced-rendering---render-target-viewports---main-rb'>Advanced Rendering - Render Target Viewports - main.rb</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_rendering/03_render_target_viewports/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- args.state.new_entity: Used when we want to create a new object, like a sprite or button.
For example, if we want to create a new button, we would declare it as a new entity and
then define its properties. (Remember, you can use state to define ANY property and it will
be retained across frames.)
If you have a solar system and you're creating args.state.sun and setting its image path to an
image in the sprites folder, you would do the following:
(See samples/99_sample_nddnug_workshop for more details.)
args.state.sun ||= args.state.new_entity(:sun) do |s|
s.path = 'sprites/sun.png'
end
- String interpolation: Uses #{} syntax; everything between the #{ and the } is evaluated
as Ruby code, and the placeholder is replaced with its corresponding value or result.
For example, if we have a variable
name = "Ruby"
then the line
puts "How are you, #{name}?"
would print "How are you, Ruby?" to the console.
(Remember, string interpolation only works with double quotes!)
- Ternary operator (?): Similar to if statement; first evalulates whether a statement is
true or false, and then executes a command depending on that result.
For example, if we had a variable
grade = 75
and used the ternary operator in the command
pass_or_fail = grade > 65 ? "pass" : "fail"
then the value of pass_or_fail would be "pass" since grade's value was greater than 65.
Reminders:
- args.grid.(left|right|top|bottom): Pixel value for the boundaries of the virtual
720 p screen (Dragon Ruby Game Toolkits's virtual resolution is always 1280x720).
- Numeric#shift_(left|right|up|down): Shifts the Numeric in the correct direction
by adding or subracting.
- ARRAY#inside_rect?: An array with at least two values is considered a point. An array
with at least four values is considered a rect. The inside_rect? function returns true
or false depending on if the point is inside the rect.
- ARRAY#intersect_rect?: Returns true or false depending on if the two rectangles intersect.
- args.inputs.mouse.click: This property will be set if the mouse was clicked.
For more information about the mouse, go to mygame/documentation/07-mouse.md.
- args.inputs.keyboard.key_up.KEY: The value of the properties will be set
to the frame that the key_up event occurred (the frame correlates
to args.state.tick_count).
For more information about the keyboard, go to mygame/documentation/06-keyboard.md.
- args.state.labels:
The parameters for a label are
1. the position (x, y)
2. the text
3. the size
4. the alignment
5. the color (red, green, and blue saturations)
6. the alpha (or transparency)
For more information about labels, go to mygame/documentation/02-labels.md.
- args.state.lines:
The parameters for a line are
1. the starting position (x, y)
2. the ending position (x2, y2)
3. the color (red, green, and blue saturations)
4. the alpha (or transparency)
For more information about lines, go to mygame/documentation/04-lines.md.
- args.state.solids (and args.state.borders):
The parameters for a solid (or border) are
1. the position (x, y)
2. the width (w)
3. the height (h)
4. the color (r, g, b)
5. the alpha (or transparency)
For more information about solids and borders, go to mygame/documentation/03-solids-and-borders.md.
- args.state.sprites:
The parameters for a sprite are
1. the position (x, y)
2. the width (w)
3. the height (h)
4. the image path
5. the angle
6. the alpha (or transparency)
For more information about sprites, go to mygame/documentation/05-sprites.md.
=end
# This sample app shows different objects that can be used when making games, such as labels,
# lines, sprites, solids, buttons, etc. Each demo section shows how these objects can be used.
# Also note that state.tick_count refers to the passage of time, or current frame.
class TechDemo
attr_accessor :inputs, :state, :outputs, :grid, :args
# Calls all methods necessary for the app to run properly.
def tick
labels_tech_demo
lines_tech_demo
solids_tech_demo
borders_tech_demo
sprites_tech_demo
keyboards_tech_demo
controller_tech_demo
mouse_tech_demo
point_to_rect_tech_demo
rect_to_rect_tech_demo
button_tech_demo
export_game_state_demo
window_state_demo
render_seperators
end
# Shows output of different kinds of labels on the screen
def labels_tech_demo
outputs.labels << [grid.left.shift_right(5), grid.top.shift_down(5), "This is a label located at the top left."]
outputs.labels << [grid.left.shift_right(5), grid.bottom.shift_up(30), "This is a label located at the bottom left."]
outputs.labels << [ 5, 690, "Labels (x, y, text, size, align, r, g, b, a)"]
outputs.labels << [ 5, 660, "Smaller label.", -2]
outputs.labels << [ 5, 630, "Small label.", -1]
outputs.labels << [ 5, 600, "Medium label.", 0]
outputs.labels << [ 5, 570, "Large label.", 1]
outputs.labels << [ 5, 540, "Larger label.", 2]
outputs.labels << [300, 660, "Left aligned.", 0, 2]
outputs.labels << [300, 640, "Center aligned.", 0, 1]
outputs.labels << [300, 620, "Right aligned.", 0, 0]
outputs.labels << [175, 595, "Red Label.", 0, 0, 255, 0, 0]
outputs.labels << [175, 575, "Green Label.", 0, 0, 0, 255, 0]
outputs.labels << [175, 555, "Blue Label.", 0, 0, 0, 0, 255]
outputs.labels << [175, 535, "Faded Label.", 0, 0, 0, 0, 0, 128]
end
# Shows output of lines on the screen
def lines_tech_demo
outputs.labels << [5, 500, "Lines (x, y, x2, y2, r, g, b, a)"]
outputs.lines << [5, 450, 100, 450]
outputs.lines << [5, 430, 300, 430]
outputs.lines << [5, 410, 300, 410, state.tick_count % 255, 0, 0, 255] # red saturation changes
outputs.lines << [5, 390 - state.tick_count % 25, 300, 390, 0, 0, 0, 255] # y position changes
outputs.lines << [5 + state.tick_count % 200, 360, 300, 360, 0, 0, 0, 255] # x position changes
end
# Shows output of different kinds of solids on the screen
def solids_tech_demo
outputs.labels << [ 5, 350, "Solids (x, y, w, h, r, g, b, a)"]
outputs.solids << [ 10, 270, 50, 50]
outputs.solids << [ 70, 270, 50, 50, 0, 0, 0]
outputs.solids << [130, 270, 50, 50, 255, 0, 0]
outputs.solids << [190, 270, 50, 50, 255, 0, 0, 128]
outputs.solids << [250, 270, 50, 50, 0, 0, 0, 128 + state.tick_count % 128] # transparency changes
end
# Shows output of different kinds of borders on the screen
# The parameters for a border are the same as the parameters for a solid
def borders_tech_demo
outputs.labels << [ 5, 260, "Borders (x, y, w, h, r, g, b, a)"]
outputs.borders << [ 10, 180, 50, 50]
outputs.borders << [ 70, 180, 50, 50, 0, 0, 0]
outputs.borders << [130, 180, 50, 50, 255, 0, 0]
outputs.borders << [190, 180, 50, 50, 255, 0, 0, 128]
outputs.borders << [250, 180, 50, 50, 0, 0, 0, 128 + state.tick_count % 128] # transparency changes
end
# Shows output of different kinds of sprites on the screen
def sprites_tech_demo
outputs.labels << [ 5, 170, "Sprites (x, y, w, h, path, angle, a)"]
outputs.sprites << [ 10, 40, 128, 101, 'dragonruby.png']
outputs.sprites << [ 150, 40, 128, 101, 'dragonruby.png', state.tick_count % 360] # angle changes
outputs.sprites << [ 300, 40, 128, 101, 'dragonruby.png', 0, state.tick_count % 255] # transparency changes
end
# Holds size, alignment, color (black), and alpha (transparency) parameters
# Using small_font as a parameter accounts for all remaining parameters
# so they don't have to be repeatedly typed
def small_font
[-2, 0, 0, 0, 0, 255]
end
# Sets position of each row
# Converts given row value to pixels that DragonRuby understands
def row_to_px row_number
# Row 0 starts 5 units below the top of the grid.
# Each row afterward is 20 units lower.
grid.top.shift_down(5).shift_down(20 * row_number)
end
# Uses labels to output current game time (passage of time), and whether or not "h" was pressed
# If "h" is pressed, the frame is output when the key_up event occurred
def keyboards_tech_demo
outputs.labels << [460, row_to_px(0), "Current game time: #{state.tick_count}", small_font]
outputs.labels << [460, row_to_px(2), "Keyboard input: inputs.keyboard.key_up.h", small_font]
outputs.labels << [460, row_to_px(3), "Press \"h\" on the keyboard.", small_font]
if inputs.keyboard.key_up.h # if "h" key_up event occurs
state.h_pressed_at = state.tick_count # frame it occurred is stored
end
# h_pressed_at is initially set to false, and changes once the user presses the "h" key.
state.h_pressed_at ||= false
if state.h_pressed_at # if h is pressed (pressed_at has a frame number and is no longer false)
outputs.labels << [460, row_to_px(4), "\"h\" was pressed at time: #{state.h_pressed_at}", small_font]
else # otherwise, label says "h" was never pressed
outputs.labels << [460, row_to_px(4), "\"h\" has never been pressed.", small_font]
end
# border around keyboard input demo section
outputs.borders << [455, row_to_px(5), 360, row_to_px(2).shift_up(5) - row_to_px(5)]
end
# Sets definition for a small label
# Makes it easier to position labels in respect to the position of other labels
def small_label x, row, message
[x, row_to_px(row), message, small_font]
end
# Uses small labels to show whether the "a" button on the controller is down, held, or up.
# y value of each small label is set by calling the row_to_px method
def controller_tech_demo
x = 460
outputs.labels << small_label(x, 6, "Controller one input: inputs.controller_one")
outputs.labels << small_label(x, 7, "Current state of the \"a\" button.")
outputs.labels << small_label(x, 8, "Check console window for more info.")
if inputs.controller_one.key_down.a # if "a" is in "down" state
outputs.labels << small_label(x, 9, "\"a\" button down: #{inputs.controller_one.key_down.a}")
puts "\"a\" button down at #{inputs.controller_one.key_down.a}" # prints frame the event occurred
elsif inputs.controller_one.key_held.a # if "a" is held down
outputs.labels << small_label(x, 9, "\"a\" button held: #{inputs.controller_one.key_held.a}")
elsif inputs.controller_one.key_up.a # if "a" is in up state
outputs.labels << small_label(x, 9, "\"a\" button up: #{inputs.controller_one.key_up.a}")
puts "\"a\" key up at #{inputs.controller_one.key_up.a}"
else # if no event has occurred
outputs.labels << small_label(x, 9, "\"a\" button state is nil.")
end
# border around controller input demo section
outputs.borders << [455, row_to_px(10), 360, row_to_px(6).shift_up(5) - row_to_px(10)]
end
# Outputs when the mouse was clicked, as well as the coordinates on the screen
# of where the click occurred
def mouse_tech_demo
x = 460
outputs.labels << small_label(x, 11, "Mouse input: inputs.mouse")
if inputs.mouse.click # if click has a value and is not nil
state.last_mouse_click = inputs.mouse.click # coordinates of click are stored
end
if state.last_mouse_click # if mouse is clicked (has coordinates as value)
# outputs the time (frame) the click occurred, as well as how many frames have passed since the event
outputs.labels << small_label(x, 12, "Mouse click happened at: #{state.last_mouse_click.created_at}, #{state.last_mouse_click.created_at_elapsed}")
# outputs coordinates of click
outputs.labels << small_label(x, 13, "Mouse click location: #{state.last_mouse_click.point.x}, #{state.last_mouse_click.point.y}")
else # otherwise if the mouse has not been clicked
outputs.labels << small_label(x, 12, "Mouse click has not occurred yet.")
outputs.labels << small_label(x, 13, "Please click mouse.")
end
end
# Outputs whether a mouse click occurred inside or outside of a box
def point_to_rect_tech_demo
x = 460
outputs.labels << small_label(x, 15, "Click inside the blue box maybe ---->")
box = [765, 370, 50, 50, 0, 0, 170] # blue box
outputs.borders << box
if state.last_mouse_click # if the mouse was clicked
if state.last_mouse_click.point.inside_rect? box # if mouse clicked inside box
outputs.labels << small_label(x, 16, "Mouse click happened inside the box.")
else # otherwise, if mouse was clicked outside the box
outputs.labels << small_label(x, 16, "Mouse click happened outside the box.")
end
else # otherwise, if was not clicked at all
outputs.labels << small_label(x, 16, "Mouse click has not occurred yet.") # output if the mouse was not clicked
end
# border around mouse input demo section
outputs.borders << [455, row_to_px(14), 360, row_to_px(11).shift_up(5) - row_to_px(14)]
end
# Outputs a red box onto the screen. A mouse click from the user inside of the red box will output
# a smaller box. If two small boxes are inside of the red box, it will be determined whether or not
# they intersect.
def rect_to_rect_tech_demo
x = 460
outputs.labels << small_label(x, 17.5, "Click inside the red box below.") # label with instructions
red_box = [460, 250, 355, 90, 170, 0, 0] # definition of the red box
outputs.borders << red_box # output as a border (not filled in)
# If the mouse is clicked inside the red box, two collision boxes are created.
if inputs.mouse.click
if inputs.mouse.click.point.inside_rect? red_box
if !state.box_collision_one # if the collision_one box does not yet have a definition
# Subtracts 25 from the x and y positions of the click point in order to make the click point the center of the box.
# You can try deleting the subtraction to see how it impacts the box placement.
state.box_collision_one = [inputs.mouse.click.point.x - 25, inputs.mouse.click.point.y - 25, 50, 50, 180, 0, 0, 180] # sets definition
elsif !state.box_collision_two # if collision_two does not yet have a definition
state.box_collision_two = [inputs.mouse.click.point.x - 25, inputs.mouse.click.point.y - 25, 50, 50, 0, 0, 180, 180] # sets definition
else
state.box_collision_one = nil # both boxes are empty
state.box_collision_two = nil
end
end
end
# If collision boxes exist, they are output onto screen inside the red box as solids
if state.box_collision_one
outputs.solids << state.box_collision_one
end
if state.box_collision_two
outputs.solids << state.box_collision_two
end
# Outputs whether or not the two collision boxes intersect.
if state.box_collision_one && state.box_collision_two # if both collision_boxes are defined (and not nil or empty)
if state.box_collision_one.intersect_rect? state.box_collision_two # if the two boxes intersect
outputs.labels << small_label(x, 23.5, 'The boxes intersect.')
else # otherwise, if the two boxes do not intersect
outputs.labels << small_label(x, 23.5, 'The boxes do not intersect.')
end
else
outputs.labels << small_label(x, 23.5, '--') # if the two boxes are not defined (are nil or empty), this label is output
end
end
# Creates a button and outputs it onto the screen using labels and borders.
# If the button is clicked, the color changes to make it look faded.
def button_tech_demo
x, y, w, h = 460, 160, 300, 50
state.button ||= state.new_entity(:button_with_fade)
# Adds w.half to x and h.half + 10 to y in order to display the text inside the button's borders.
state.button.label ||= [x + w.half, y + h.half + 10, "click me and watch me fade", 0, 1]
state.button.border ||= [x, y, w, h]
if inputs.mouse.click && inputs.mouse.click.point.inside_rect?(state.button.border) # if mouse is clicked, and clicked inside button's border
state.button.clicked_at = inputs.mouse.click.created_at # stores the time the click occurred
end
outputs.labels << state.button.label
outputs.borders << state.button.border
if state.button.clicked_at # if button was clicked (variable has a value and is not nil)
# The appearance of the button changes for 0.25 seconds after the time the button is clicked at.
# The color changes (rgb is set to 0, 180, 80) and the transparency gradually changes.
# Change 0.25 to 1.25 and notice that the transparency takes longer to return to normal.
outputs.solids << [x, y, w, h, 0, 180, 80, 255 * state.button.clicked_at.ease(0.25.seconds, :flip)]
end
end
# Creates a new button by declaring it as a new entity, and sets values.
def new_button_prefab x, y, message
w, h = 300, 50
button = state.new_entity(:button_with_fade)
button.label = [x + w.half, y + h.half + 10, message, 0, 1] # '+ 10' keeps label's text within button's borders
button.border = [x, y, w, h] # sets border definition
button
end
# If the mouse has been clicked and the click's location is inside of the button's border, that means
# that the button has been clicked. This method returns a boolean value.
def button_clicked? button
inputs.mouse.click && inputs.mouse.click.point.inside_rect?(button.border)
end
# Determines if button was clicked, and changes its appearance if it is clicked
def tick_button_prefab button
outputs.labels << button.label # outputs button's label and border
outputs.borders << button.border
if button_clicked? button # if button is clicked
button.clicked_at = inputs.mouse.click.created_at # stores the time that the button was clicked
end
if button.clicked_at # if clicked_at has a frame value and is not nil
# button is output; color changes and transparency changes for 0.25 seconds after click occurs
outputs.solids << [button.border.x, button.border.y, button.border.w, button.border.h,
0, 180, 80, 255 * button.clicked_at.ease(0.25.seconds, :flip)] # transparency changes for 0.25 seconds
end
end
# Exports the app's game state if the export button is clicked.
def export_game_state_demo
state.export_game_state_button ||= new_button_prefab(460, 100, "click to export app state")
tick_button_prefab(state.export_game_state_button) # calls method to output button
if button_clicked? state.export_game_state_button # if the export button is clicked
args.gtk.export! "Exported from clicking the export button in the tech demo." # the export occurs
end
end
# The mouse and keyboard focus are set to "yes" when the Dragonruby window is the active window.
def window_state_demo
m = $gtk.args.inputs.mouse.has_focus ? 'Y' : 'N' # ternary operator (similar to if statement)
k = $gtk.args.inputs.keyboard.has_focus ? 'Y' : 'N'
outputs.labels << [460, 20, "mouse focus: #{m} keyboard focus: #{k}", small_font]
end
#Sets values for the horizontal separator (divides demo sections)
def horizontal_seperator y, x, x2
[x, y, x2, y, 150, 150, 150]
end
#Sets the values for the vertical separator (divides demo sections)
def vertical_seperator x, y, y2
[x, y, x, y2, 150, 150, 150]
end
# Outputs vertical and horizontal separators onto the screen to separate each demo section.
def render_seperators
outputs.lines << horizontal_seperator(505, grid.left, 445)
outputs.lines << horizontal_seperator(353, grid.left, 445)
outputs.lines << horizontal_seperator(264, grid.left, 445)
outputs.lines << horizontal_seperator(174, grid.left, 445)
outputs.lines << vertical_seperator(445, grid.top, grid.bottom)
outputs.lines << horizontal_seperator(690, 445, 820)
outputs.lines << horizontal_seperator(426, 445, 820)
outputs.lines << vertical_seperator(820, grid.top, grid.bottom)
end
end
$tech_demo = TechDemo.new
def tick args
$tech_demo.inputs = args.inputs
$tech_demo.state = args.state
$tech_demo.grid = args.grid
$tech_demo.args = args
$tech_demo.outputs = args.render_target(:mini_map)
$tech_demo.tick
args.outputs.labels << [830, 715, "Render target:", [-2, 0, 0, 0, 0, 255]]
args.outputs.sprites << [0, 0, 1280, 720, :mini_map]
args.outputs.sprites << [830, 300, 675, 379, :mini_map]
tick_instructions args, "Sample app shows all the rendering apis available."
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----advanced-rendering---render-primitive-hierarchies---main-rb'>Advanced Rendering - Render Primitive Hierarchies - main.rb</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_rendering/04_render_primitive_hierarchies/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- Nested array: An array whose individual elements are also arrays; useful for
storing groups of similar data. Also called multidimensional arrays.
In this sample app, we see nested arrays being used in object definitions.
Notice the parameters for solids, listed below. Parameters 1-3 set the
definition for the rect, and parameter 4 sets the definition of the color.
Instead of having a solid definition that looks like this,
[X, Y, W, H, R, G, B]
we can separate it into two separate array definitions in one, like this
[[X, Y, W, H], [R, G, B]]
and both options work fine in defining our solid (or any object).
- Collections: Lists of data; useful for organizing large amounts of data.
One element of a collection could be an array (which itself contains many elements).
For example, a collection that stores two solid objects would look like this:
[
[100, 100, 50, 50, 0, 0, 0],
[100, 150, 50, 50, 255, 255, 255]
]
If this collection was added to args.outputs.solids, two solids would be output
next to each other, one black and one white.
Nested arrays can be used in collections, as you will see in this sample app.
Reminders:
- args.outputs.solids: An array. The values generate a solid.
The parameters for a solid are
1. The position on the screen (x, y)
2. The width (w)
3. The height (h)
4. The color (r, g, b) (if a color is not assigned, the object's default color will be black)
NOTE: THE PARAMETERS ARE THE SAME FOR BORDERS!
Here is an example of a (red) border or solid definition:
[100, 100, 400, 500, 255, 0, 0]
It will be a solid or border depending on if it is added to args.outputs.solids or args.outputs.borders.
For more information about solids and borders, go to mygame/documentation/03-solids-and-borders.md.
- args.outputs.sprites: An array. The values generate a sprite.
The parameters for sprites are
1. The position on the screen (x, y)
2. The width (w)
3. The height (h)
4. The image path (p)
Here is an example of a sprite definition:
[100, 100, 400, 500, 'sprites/dragonruby.png']
For more information about sprites, go to mygame/documentation/05-sprites.md.
=end
# This code demonstrates the creation and output of objects like sprites, borders, and solids
# If filled in, they are solids
# If hollow, they are borders
# If images, they are sprites
# Solids are added to args.outputs.solids
# Borders are added to args.outputs.borders
# Sprites are added to args.outputs.sprites
# The tick method runs 60 frames every second.
# Your game is going to happen under this one function.
def tick args
border_as_solid_and_solid_as_border args
sprite_as_border_or_solids args
collection_of_borders_and_solids args
collection_of_sprites args
end
# Shows a border being output onto the screen as a border and a solid
# Also shows how colors can be set
def border_as_solid_and_solid_as_border args
border = [0, 0, 50, 50]
args.outputs.borders << border
args.outputs.solids << border
# Red, green, blue saturations (last three parameters) can be any number between 0 and 255
border_with_color = [0, 100, 50, 50, 255, 0, 0]
args.outputs.borders << border_with_color
args.outputs.solids << border_with_color
border_with_nested_color = [0, 200, 50, 50, [0, 255, 0]] # nested color
args.outputs.borders << border_with_nested_color
args.outputs.solids << border_with_nested_color
border_with_nested_rect = [[0, 300, 50, 50], 0, 0, 255] # nested rect
args.outputs.borders << border_with_nested_rect
args.outputs.solids << border_with_nested_rect
border_with_nested_color_and_rect = [[0, 400, 50, 50], [255, 0, 255]] # nested rect and color
args.outputs.borders << border_with_nested_color_and_rect
args.outputs.solids << border_with_nested_color_and_rect
end
# Shows a sprite output onto the screen as a sprite, border, and solid
# Demonstrates that all three outputs appear differently on screen
def sprite_as_border_or_solids args
sprite = [100, 0, 50, 50, 'sprites/ship.png']
args.outputs.sprites << sprite
# Sprite_as_border variable has same parameters (excluding position) as above object,
# but will appear differently on screen because it is added to args.outputs.borders
sprite_as_border = [100, 100, 50, 50, 'sprites/ship.png']
args.outputs.borders << sprite_as_border
# Sprite_as_solid variable has same parameters (excluding position) as above object,
# but will appear differently on screen because it is added to args.outputs.solids
sprite_as_solid = [100, 200, 50, 50, 'sprites/ship.png']
args.outputs.solids << sprite_as_solid
end
# Holds and outputs a collection of borders and a collection of solids
# Collections are created by using arrays to hold parameters of each individual object
def collection_of_borders_and_solids args
collection_borders = [
[
[200, 0, 50, 50], # black border
[200, 100, 50, 50, 255, 0, 0], # red border
[200, 200, 50, 50, [0, 255, 0]], # nested color
],
[[200, 300, 50, 50], 0, 0, 255], # nested rect
[[200, 400, 50, 50], [255, 0, 255]] # nested rect and nested color
]
args.outputs.borders << collection_borders
collection_solids = [
[
[[300, 300, 50, 50], 0, 0, 255], # nested rect
[[300, 400, 50, 50], [255, 0, 255]] # nested rect and nested color
],
[300, 0, 50, 50],
[300, 100, 50, 50, 255, 0, 0],
[300, 200, 50, 50, [0, 255, 0]], # nested color
]
args.outputs.solids << collection_solids
end
# Holds and outputs a collection of sprites by adding it to args.outputs.sprites
# Also outputs a collection with same parameters (excluding position) by adding
# it to args.outputs.solids and another to args.outputs.borders
def collection_of_sprites args
sprites_collection = [
[
[400, 0, 50, 50, 'sprites/ship.png'],
[400, 100, 50, 50, 'sprites/ship.png'],
],
[400, 200, 50, 50, 'sprites/ship.png']
]
args.outputs.sprites << sprites_collection
args.outputs.solids << [
[500, 0, 50, 50, 'sprites/ship.png'],
[500, 100, 50, 50, 'sprites/ship.png'],
[[[500, 200, 50, 50, 'sprites/ship.png']]]
]
args.outputs.borders << [
[
[600, 0, 50, 50, 'sprites/ship.png'],
[600, 100, 50, 50, 'sprites/ship.png'],
],
[600, 200, 50, 50, 'sprites/ship.png']
]
end
</code></pre>
<h3 id='----advanced-rendering---render-primitives-as-hash---main-rb'>Advanced Rendering - Render Primitives As Hash - main.rb</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_rendering/05_render_primitives_as_hash/app/main.rb
=begin
Reminders:
- Hashes: Collection of unique keys and their corresponding values. The value can be found
using their keys.
For example, if we have a "numbers" hash that stores numbers in English as the
key and numbers in Spanish as the value, we'd have a hash that looks like this...
numbers = { "one" => "uno", "two" => "dos", "three" => "tres" }
and on it goes.
Now if we wanted to find the corresponding value of the "one" key, we could say
puts numbers["one"]
which would print "uno" to the console.
- args.outputs.sprites: An array. The values generate a sprite.
The parameters are [X, Y, WIDTH, HEIGHT, PATH, ANGLE, ALPHA, RED, GREEN, BLUE]
For more information about sprites, go to mygame/documentation/05-sprites.md.
- args.outputs.labels: An array. The values generate a label.
The parameters are [X, Y, TEXT, SIZE, ALIGNMENT, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.md.
- args.outputs.solids: An array. The values generate a solid.
The parameters are [X, Y, WIDTH, HEIGHT, RED, GREEN, BLUE, ALPHA]
For more information about solids, go to mygame/documentation/03-solids-and-borders.md.
- args.outputs.borders: An array. The values generate a border.
The parameters are the same as a solid.
For more information about borders, go to mygame/documentation/03-solids-and-borders.md.
- args.outputs.lines: An array. The values generate a line.
The parameters are [X1, Y1, X2, Y2, RED, GREEN, BLUE]
For more information about labels, go to mygame/documentation/02-labels.md.
=end
# This sample app demonstrates how hashes can be used to output different kinds of objects.
def tick args
args.state.angle ||= 0 # initializes angle to 0
args.state.angle += 1 # increments angle by 1 every frame (60 times a second)
# Outputs sprite using a hash
args.outputs.sprites << {
x: 30, # sprite position
y: 550,
w: 128, # sprite size
h: 101,
path: "dragonruby.png", # image path
angle: args.state.angle, # angle
a: 255, # alpha (transparency)
r: 255, # color saturation
g: 255,
b: 255,
tile_x: 0, # sprite sub division/tile
tile_y: 0,
tile_w: -1,
tile_h: -1,
flip_vertically: false, # don't flip sprite
flip_horizontally: false,
angle_anchor_x: 0.5, # rotation center set to middle
angle_anchor_y: 0.5
}
# Outputs label using a hash
args.outputs.labels << {
x: 200, # label position
y: 550,
text: "dragonruby", # label text
size_enum: 2,
alignment_enum: 1,
r: 155, # color saturation
g: 50,
b: 50,
a: 255, # transparency
font: "fonts/manaspc.ttf" # font style; without mentioned file, label won't output correctly
}
# Outputs solid using a hash
# [X, Y, WIDTH, HEIGHT, RED, GREEN, BLUE, ALPHA]
args.outputs.solids << {
x: 400, # position
y: 550,
w: 160, # size
h: 90,
r: 120, # color saturation
g: 50,
b: 50,
a: 255 # transparency
}
# Outputs border using a hash
# Same parameters as a solid
args.outputs.borders << {
x: 600,
y: 550,
w: 160,
h: 90,
r: 120,
g: 50,
b: 50,
a: 255
}
# Outputs line using a hash
args.outputs.lines << {
x: 900, # starting position
y: 550,
x2: 1200, # ending position
y2: 550,
r: 120, # color saturation
g: 50,
b: 50,
a: 255 # transparency
}
# Outputs sprite as a primitive using a hash
args.outputs.primitives << {
x: 30, # position
y: 200,
w: 128, # size
h: 101,
path: "dragonruby.png", # image path
angle: args.state.angle, # angle
a: 255, # transparency
r: 255, # color saturation
g: 255,
b: 255,
tile_x: 0, # sprite sub division/tile
tile_y: 0,
tile_w: -1,
tile_h: -1,
flip_vertically: false, # don't flip
flip_horizontally: false,
angle_anchor_x: 0.5, # rotation center set to middle
angle_anchor_y: 0.5
}.sprite!
# Outputs label as primitive using a hash
args.outputs.primitives << {
x: 200, # position
y: 200,
text: "dragonruby", # text
size: 2,
alignment: 1,
r: 155, # color saturation
g: 50,
b: 50,
a: 255, # transparency
font: "fonts/manaspc.ttf" # font style
}.label!
# Outputs solid as primitive using a hash
args.outputs.primitives << {
x: 400, # position
y: 200,
w: 160, # size
h: 90,
r: 120, # color saturation
g: 50,
b: 50,
a: 255 # transparency
}.solid!
# Outputs border as primitive using a hash
# Same parameters as solid
args.outputs.primitives << {
x: 600, # position
y: 200,
w: 160, # size
h: 90,
r: 120, # color saturation
g: 50,
b: 50,
a: 255 # transparency
}.border!
# Outputs line as primitive using a hash
args.outputs.primitives << {
x: 900, # starting position
y: 200,
x2: 1200, # ending position
y2: 200,
r: 120, # color saturation
g: 50,
b: 50,
a: 255 # transparency
}.line!
end
</code></pre>
<h3 id='----advanced-rendering---pixel-arrays---main-rb'>Advanced Rendering - Pixel Arrays - main.rb</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_rendering/06_pixel_arrays/app/main.rb
$gtk.reset
def tick args
args.state.posinc ||= 1
args.state.pos ||= 0
args.state.rotation ||= 0
dimension = 10 # keep it small and let the GPU scale it when rendering the sprite.
# Set up our "scanner" pixel array and fill it with black pixels.
args.pixel_array(:scanner).width = dimension
args.pixel_array(:scanner).height = dimension
args.pixel_array(:scanner).pixels.fill(0xFF000000, 0, dimension * dimension) # black, full alpha
# Draw a green line that bounces up and down the sprite.
args.pixel_array(:scanner).pixels.fill(0xFF00FF00, dimension * args.state.pos, dimension) # green, full alpha
# Adjust position for next frame.
args.state.pos += args.state.posinc
if args.state.posinc > 0 && args.state.pos >= dimension
args.state.posinc = -1
args.state.pos = dimension - 1
elsif args.state.posinc < 0 && args.state.pos < 0
args.state.posinc = 1
args.state.pos = 1
end
# New/changed pixel arrays get uploaded to the GPU before we render
# anything. At that point, they can be scaled, rotated, and otherwise
# used like any other sprite.
w = 100
h = 100
x = (1280 - w) / 2
y = (720 - h) / 2
args.outputs.background_color = [64, 0, 128]
args.outputs.primitives << [x, y, w, h, :scanner, args.state.rotation].sprite
args.state.rotation += 1
args.outputs.primitives << args.gtk.current_framerate_primitives
end
</code></pre>
<h3 id='----advanced-rendering---simple-camera---main-rb'>Advanced Rendering - Simple Camera - main.rb</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_rendering/07_simple_camera/app/main.rb
def tick args
# variables you can play around with
args.state.world.w ||= 1280
args.state.world.h ||= 720
args.state.player.x ||= 0
args.state.player.y ||= 0
args.state.player.size ||= 32
args.state.enemy.x ||= 700
args.state.enemy.y ||= 700
args.state.enemy.size ||= 16
args.state.camera.x ||= 640
args.state.camera.y ||= 300
args.state.camera.scale ||= 1.0
args.state.camera.show_empty_space ||= :yes
# instructions
args.outputs.primitives << { x: 0, y: 80.from_top, w: 360, h: 80, r: 0, g: 0, b: 0, a: 128 }.solid!
args.outputs.primitives << { x: 10, y: 10.from_top, text: "arrow keys to move around", r: 255, g: 255, b: 255}.label!
args.outputs.primitives << { x: 10, y: 30.from_top, text: "+/- to change zoom of camera", r: 255, g: 255, b: 255}.label!
args.outputs.primitives << { x: 10, y: 50.from_top, text: "tab to change camera edge behavior", r: 255, g: 255, b: 255}.label!
# render scene
args.outputs[:scene].w = args.state.world.w
args.outputs[:scene].h = args.state.world.h
args.outputs[:scene].solids << { x: 0, y: 0, w: args.state.world.w, h: args.state.world.h, r: 20, g: 60, b: 80 }
args.outputs[:scene].solids << { x: args.state.player.x, y: args.state.player.y,
w: args.state.player.size, h: args.state.player.size, r: 80, g: 155, b: 80 }
args.outputs[:scene].solids << { x: args.state.enemy.x, y: args.state.enemy.y,
w: args.state.enemy.size, h: args.state.enemy.size, r: 155, g: 80, b: 80 }
# render camera
scene_position = calc_scene_position args
args.outputs.sprites << { x: scene_position.x,
y: scene_position.y,
w: scene_position.w,
h: scene_position.h,
path: :scene }
# move player
if args.inputs.directional_angle
args.state.player.x += args.inputs.directional_angle.vector_x * 5
args.state.player.y += args.inputs.directional_angle.vector_y * 5
args.state.player.x = args.state.player.x.clamp(0, args.state.world.w - args.state.player.size)
args.state.player.y = args.state.player.y.clamp(0, args.state.world.h - args.state.player.size)
end
# +/- to zoom in and out
if args.inputs.keyboard.plus && args.state.tick_count.zmod?(3)
args.state.camera.scale += 0.05
elsif args.inputs.keyboard.hyphen && args.state.tick_count.zmod?(3)
args.state.camera.scale -= 0.05
elsif args.inputs.keyboard.key_down.tab
if args.state.camera.show_empty_space == :yes
args.state.camera.show_empty_space = :no
else
args.state.camera.show_empty_space = :yes
end
end
args.state.camera.scale = args.state.camera.scale.greater(0.1)
end
def calc_scene_position args
result = { x: args.state.camera.x - (args.state.player.x * args.state.camera.scale),
y: args.state.camera.y - (args.state.player.y * args.state.camera.scale),
w: args.state.world.w * args.state.camera.scale,
h: args.state.world.h * args.state.camera.scale,
scale: args.state.camera.scale }
return result if args.state.camera.show_empty_space == :yes
if result.w < args.grid.w
result.merge!(x: (args.grid.w - result.w).half)
elsif (args.state.player.x * result.scale) < args.grid.w.half
result.merge!(x: 10)
elsif (result.x + result.w) < args.grid.w
result.merge!(x: - result.w + (args.grid.w - 10))
end
if result.h < args.grid.h
result.merge!(y: (args.grid.h - result.h).half)
elsif (result.y) > 10
result.merge!(y: 10)
elsif (result.y + result.h) < args.grid.h
result.merge!(y: - result.h + (args.grid.h - 10))
end
result
end
</code></pre>
<h3 id='----advanced-rendering---splitscreen-camera---main-rb'>Advanced Rendering - Splitscreen Camera - main.rb</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_rendering/08_splitscreen_camera/app/main.rb
class CameraMovement
attr_accessor :state, :inputs, :outputs, :grid
#==============================================================================================
#Serialize
def serialize
{state: state, inputs: inputs, outputs: outputs, grid: grid }
end
def inspect
serialize.to_s
end
def to_s
serialize.to_s
end
#==============================================================================================
#Tick
def tick
defaults
calc
render
input
end
#==============================================================================================
#Default functions
def defaults
outputs[:scene].background_color = [0,0,0]
state.trauma ||= 0.0
state.trauma_power ||= 2
state.player_cyan ||= new_player_cyan
state.player_magenta ||= new_player_magenta
state.camera_magenta ||= new_camera_magenta
state.camera_cyan ||= new_camera_cyan
state.camera_center ||= new_camera_center
state.room ||= new_room
end
def default_player x, y, w, h, sprite_path
state.new_entity(:player,
{ x: x,
y: y,
dy: 0,
dx: 0,
w: w,
h: h,
damage: 0,
dead: false,
orientation: "down",
max_alpha: 255,
sprite_path: sprite_path})
end
def default_floor_tile x, y, w, h, sprite_path
state.new_entity(:room,
{ x: x,
y: y,
w: w,
h: h,
sprite_path: sprite_path})
end
def default_camera x, y, w, h
state.new_entity(:camera,
{ x: x,
y: y,
dx: 0,
dy: 0,
w: w,
h: h})
end
def new_player_cyan
default_player(0, 0, 64, 64,
"sprites/player/player_#{state.player_cyan.orientation}_standing.png")
end
def new_player_magenta
default_player(64, 0, 64, 64,
"sprites/player/player_#{state.player_magenta.orientation}_standing.png")
end
def new_camera_magenta
default_camera(0,0,720,720)
end
def new_camera_cyan
default_camera(0,0,720,720)
end
def new_camera_center
default_camera(0,0,1280,720)
end
def new_room
default_floor_tile(0,0,1024,1024,'sprites/rooms/camera_room.png')
end
#==============================================================================================
#Calculation functions
def calc
calc_camera_magenta
calc_camera_cyan
calc_camera_center
calc_player_cyan
calc_player_magenta
calc_trauma_decay
end
def center_camera_tolerance
return Math.sqrt(((state.player_magenta.x - state.player_cyan.x) ** 2) +
((state.player_magenta.y - state.player_cyan.y) ** 2)) > 640
end
def calc_player_cyan
state.player_cyan.x += state.player_cyan.dx
state.player_cyan.y += state.player_cyan.dy
end
def calc_player_magenta
state.player_magenta.x += state.player_magenta.dx
state.player_magenta.y += state.player_magenta.dy
end
def calc_camera_center
timeScale = 1
midX = (state.player_magenta.x + state.player_cyan.x)/2
midY = (state.player_magenta.y + state.player_cyan.y)/2
targetX = midX - state.camera_center.w/2
targetY = midY - state.camera_center.h/2
state.camera_center.x += (targetX - state.camera_center.x) * 0.1 * timeScale
state.camera_center.y += (targetY - state.camera_center.y) * 0.1 * timeScale
end
def calc_camera_magenta
timeScale = 1
targetX = state.player_magenta.x + state.player_magenta.w - state.camera_magenta.w/2
targetY = state.player_magenta.y + state.player_magenta.h - state.camera_magenta.h/2
state.camera_magenta.x += (targetX - state.camera_magenta.x) * 0.1 * timeScale
state.camera_magenta.y += (targetY - state.camera_magenta.y) * 0.1 * timeScale
end
def calc_camera_cyan
timeScale = 1
targetX = state.player_cyan.x + state.player_cyan.w - state.camera_cyan.w/2
targetY = state.player_cyan.y + state.player_cyan.h - state.camera_cyan.h/2
state.camera_cyan.x += (targetX - state.camera_cyan.x) * 0.1 * timeScale
state.camera_cyan.y += (targetY - state.camera_cyan.y) * 0.1 * timeScale
end
def calc_player_quadrant angle
if angle < 45 and angle > -45 and state.player_cyan.x < state.player_magenta.x
return 1
elsif angle < 45 and angle > -45 and state.player_cyan.x > state.player_magenta.x
return 3
elsif (angle > 45 or angle < -45) and state.player_cyan.y < state.player_magenta.y
return 2
elsif (angle > 45 or angle < -45) and state.player_cyan.y > state.player_magenta.y
return 4
end
end
def calc_camera_shake
state.trauma
end
def calc_trauma_decay
state.trauma = state.trauma * 0.9
end
def calc_random_float_range(min, max)
rand * (max-min) + min
end
#==============================================================================================
#Render Functions
def render
render_floor
render_player_cyan
render_player_magenta
if center_camera_tolerance
render_split_camera_scene
else
render_camera_center_scene
end
end
def render_player_cyan
outputs[:scene].sprites << {x: state.player_cyan.x,
y: state.player_cyan.y,
w: state.player_cyan.w,
h: state.player_cyan.h,
path: "sprites/player/player_#{state.player_cyan.orientation}_standing.png",
r: 0,
g: 255,
b: 255}
end
def render_player_magenta
outputs[:scene].sprites << {x: state.player_magenta.x,
y: state.player_magenta.y,
w: state.player_magenta.w,
h: state.player_magenta.h,
path: "sprites/player/player_#{state.player_magenta.orientation}_standing.png",
r: 255,
g: 0,
b: 255}
end
def render_floor
outputs[:scene].sprites << [state.room.x, state.room.y,
state.room.w, state.room.h,
state.room.sprite_path]
end
def render_camera_center_scene
zoomFactor = 1
outputs[:scene].width = state.room.w
outputs[:scene].height = state.room.h
maxAngle = 10.0
maxOffset = 20.0
angle = maxAngle * calc_camera_shake * calc_random_float_range(-1,1)
offsetX = 32 - (maxOffset * calc_camera_shake * calc_random_float_range(-1,1))
offsetY = 32 - (maxOffset * calc_camera_shake * calc_random_float_range(-1,1))
outputs.sprites << {x: (-state.camera_center.x - offsetX)/zoomFactor,
y: (-state.camera_center.y - offsetY)/zoomFactor,
w: outputs[:scene].width/zoomFactor,
h: outputs[:scene].height/zoomFactor,
path: :scene,
angle: angle,
source_w: -1,
source_h: -1}
outputs.labels << [128,64,"#{state.trauma.round(1)}",8,2,255,0,255,255]
end
def render_split_camera_scene
outputs[:scene].width = state.room.w
outputs[:scene].height = state.room.h
render_camera_magenta_scene
render_camera_cyan_scene
angle = Math.atan((state.player_magenta.y - state.player_cyan.y)/(state.player_magenta.x- state.player_cyan.x)) * 180/Math::PI
output_split_camera angle
end
def render_camera_magenta_scene
zoomFactor = 1
offsetX = 32
offsetY = 32
outputs[:scene_magenta].sprites << {x: (-state.camera_magenta.x*2),
y: (-state.camera_magenta.y),
w: outputs[:scene].width*2,
h: outputs[:scene].height,
path: :scene}
end
def render_camera_cyan_scene
zoomFactor = 1
offsetX = 32
offsetY = 32
outputs[:scene_cyan].sprites << {x: (-state.camera_cyan.x*2),
y: (-state.camera_cyan.y),
w: outputs[:scene].width*2,
h: outputs[:scene].height,
path: :scene}
end
def output_split_camera angle
#TODO: Clean this up!
quadrant = calc_player_quadrant angle
outputs.labels << [128,64,"#{quadrant}",8,2,255,0,255,255]
if quadrant == 1
set_camera_attributes(w: 640, h: 720, m_x: 640, m_y: 0, c_x: 0, c_y: 0)
elsif quadrant == 2
set_camera_attributes(w: 1280, h: 360, m_x: 0, m_y: 360, c_x: 0, c_y: 0)
elsif quadrant == 3
set_camera_attributes(w: 640, h: 720, m_x: 0, m_y: 0, c_x: 640, c_y: 0)
elsif quadrant == 4
set_camera_attributes(w: 1280, h: 360, m_x: 0, m_y: 0, c_x: 0, c_y: 360)
end
end
def set_camera_attributes(w: 0, h: 0, m_x: 0, m_y: 0, c_x: 0, c_y: 0)
state.camera_cyan.w = w + 64
state.camera_cyan.h = h + 64
outputs[:scene_cyan].width = (w) * 2
outputs[:scene_cyan].height = h
state.camera_magenta.w = w + 64
state.camera_magenta.h = h + 64
outputs[:scene_magenta].width = (w) * 2
outputs[:scene_magenta].height = h
outputs.sprites << {x: m_x,
y: m_y,
w: w,
h: h,
path: :scene_magenta}
outputs.sprites << {x: c_x,
y: c_y,
w: w,
h: h,
path: :scene_cyan}
end
def add_trauma amount
state.trauma = [state.trauma + amount, 1.0].min
end
def remove_trauma amount
state.trauma = [state.trauma - amount, 0.0].max
end
#==============================================================================================
#Input functions
def input
input_move_cyan
input_move_magenta
if inputs.keyboard.key_down.t
add_trauma(0.5)
elsif inputs.keyboard.key_down.y
remove_trauma(0.1)
end
end
def input_move_cyan
if inputs.keyboard.key_held.up
state.player_cyan.dy = 5
state.player_cyan.orientation = "up"
elsif inputs.keyboard.key_held.down
state.player_cyan.dy = -5
state.player_cyan.orientation = "down"
else
state.player_cyan.dy *= 0.8
end
if inputs.keyboard.key_held.left
state.player_cyan.dx = -5
state.player_cyan.orientation = "left"
elsif inputs.keyboard.key_held.right
state.player_cyan.dx = 5
state.player_cyan.orientation = "right"
else
state.player_cyan.dx *= 0.8
end
outputs.labels << [128,512,"#{state.player_cyan.x.round()}",8,2,0,255,255,255]
outputs.labels << [128,480,"#{state.player_cyan.y.round()}",8,2,0,255,255,255]
end
def input_move_magenta
if inputs.keyboard.key_held.w
state.player_magenta.dy = 5
state.player_magenta.orientation = "up"
elsif inputs.keyboard.key_held.s
state.player_magenta.dy = -5
state.player_magenta.orientation = "down"
else
state.player_magenta.dy *= 0.8
end
if inputs.keyboard.key_held.a
state.player_magenta.dx = -5
state.player_magenta.orientation = "left"
elsif inputs.keyboard.key_held.d
state.player_magenta.dx = 5
state.player_magenta.orientation = "right"
else
state.player_magenta.dx *= 0.8
end
outputs.labels << [128,360,"#{state.player_magenta.x.round()}",8,2,255,0,255,255]
outputs.labels << [128,328,"#{state.player_magenta.y.round()}",8,2,255,0,255,255]
end
end
$camera_movement = CameraMovement.new
def tick args
args.outputs.background_color = [0,0,0]
$camera_movement.inputs = args.inputs
$camera_movement.outputs = args.outputs
$camera_movement.state = args.state
$camera_movement.grid = args.grid
$camera_movement.tick
end
</code></pre>
<h3 id='----advanced-rendering---z-targeting-camera---main-rb'>Advanced Rendering - Z Targeting Camera - main.rb</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_rendering/09_z_targeting_camera/app/main.rb
class Game
attr_gtk
def tick
defaults
render
input
calc
end
def defaults
outputs.background_color = [219, 208, 191]
player.x ||= 634
player.y ||= 153
player.angle ||= 90
player.distance ||= arena_radius
target.x ||= 634
target.y ||= 359
end
def render
outputs[:scene].sprites << ([0, 0, 933, 700, 'sprites/arena.png'].center_inside_rect grid.rect)
outputs[:scene].sprites << target_sprite
outputs[:scene].sprites << player_sprite
outputs.sprites << scene
end
def target_sprite
{
x: target.x, y: target.y,
w: 10, h: 10,
path: 'sprites/square/black.png'
}.anchor_rect 0.5, 0.5
end
def input
if inputs.up && player.distance > 30
player.distance -= 2
elsif inputs.down && player.distance < 200
player.distance += 2
end
player.angle += inputs.left_right * -1
end
def calc
player.x = target.x + ((player.angle * 1).vector_x player.distance)
player.y = target.y + ((player.angle * -1).vector_y player.distance)
end
def player_sprite
{
x: player.x,
y: player.y,
w: 50,
h: 100,
path: 'sprites/player.png',
angle: (player.angle * -1) + 90
}.anchor_rect 0.5, 0
end
def center_map
{ x: 634, y: 359 }
end
def zoom_factor_single
2 - ((args.geometry.distance player, center_map).fdiv arena_radius)
end
def zoom_factor
zoom_factor_single ** 2
end
def arena_radius
206
end
def scene
{
x: (640 - player.x) + (640 - (640 * zoom_factor)),
y: (360 - player.y - (75 * zoom_factor)) + (320 - (320 * zoom_factor)),
w: 1280 * zoom_factor,
h: 720 * zoom_factor,
path: :scene,
angle: player.angle - 90,
angle_anchor_x: (player.x.fdiv 1280),
angle_anchor_y: (player.y.fdiv 720)
}
end
def player
state.player
end
def target
state.target
end
end
def tick args
$game ||= Game.new
$game.args = args
$game.tick
end
$gtk.reset
</code></pre>
<h3 id='----advanced-rendering---blend-modes---main-rb'>Advanced Rendering - Blend Modes - main.rb</h3>
<pre><code class="language-ruby"># ./samples/07_advanced_rendering/10_blend_modes/app/main.rb
$gtk.reset
def draw_blendmode args, mode
w = 160
h = w
args.state.x += (1280-w) / (args.state.blendmodes.length + 1)
x = args.state.x
y = (720 - h) / 2
s = 'sprites/blue-feathered.png'
args.outputs.sprites << { blendmode_enum: mode.value, x: x, y: y, w: w, h: h, path: s }
args.outputs.labels << [x + (w/2), y, mode.name.to_s, 1, 1, 255, 255, 255]
end
def tick args
# Different blend modes do different things, depending on what they
# blend against (in this case, the pixels of the background color).
args.state.bg_element ||= 1
args.state.bg_color ||= 255
args.state.bg_color_direction ||= 1
bg_r = (args.state.bg_element == 1) ? args.state.bg_color : 0
bg_g = (args.state.bg_element == 2) ? args.state.bg_color : 0
bg_b = (args.state.bg_element == 3) ? args.state.bg_color : 0
args.state.bg_color += args.state.bg_color_direction
if (args.state.bg_color_direction > 0) && (args.state.bg_color >= 255)
args.state.bg_color_direction = -1
args.state.bg_color = 255
elsif (args.state.bg_color_direction < 0) && (args.state.bg_color <= 0)
args.state.bg_color_direction = 1
args.state.bg_color = 0
args.state.bg_element += 1
if args.state.bg_element >= 4
args.state.bg_element = 1
end
end
args.outputs.background_color = [ bg_r, bg_g, bg_b, 255 ]
args.state.blendmodes ||= [
{ name: :none, value: 0 },
{ name: :blend, value: 1 },
{ name: :add, value: 2 },
{ name: :mod, value: 3 },
{ name: :mul, value: 4 }
]
args.state.x = 0 # reset this, draw_blendmode will increment it.
args.state.blendmodes.each { |blendmode| draw_blendmode args, blendmode }
end
</code></pre>
<h3 id='----tweening-lerping-easing-functions---easing-functions---main-rb'>Tweening Lerping Easing Functions - Easing Functions - main.rb</h3>
<pre><code class="language-ruby"># ./samples/08_tweening_lerping_easing_functions/01_easing_functions/app/main.rb
def tick args
# STOP! Watch the following presentation first!!!!
# Math for Game Programmers: Fast and Funky 1D Nonlinear Transformations
# https://www.youtube.com/watch?v=mr5xkf6zSzk
# You've watched the talk, yes? YES???
# define starting and ending points of properties to animate
args.state.target_x = 1180
args.state.target_y = 620
args.state.target_w = 100
args.state.target_h = 100
args.state.starting_x = 0
args.state.starting_y = 0
args.state.starting_w = 300
args.state.starting_h = 300
# define start time and duration of animation
args.state.start_animate_at = 3.seconds # this is the same as writing 60 * 5 (or 300)
args.state.duration = 2.seconds # this is the same as writing 60 * 2 (or 120)
# define type of animations
# Here are all the options you have for values you can put in the array:
# :identity, :quad, :cube, :quart, :quint, :flip
# Linear is defined as:
# [:identity]
#
# Smooth start variations are:
# [:quad]
# [:cube]
# [:quart]
# [:quint]
# Linear reversed, and smooth stop are the same as the animations defined above, but reversed:
# [:flip, :identity]
# [:flip, :quad, :flip]
# [:flip, :cube, :flip]
# [:flip, :quart, :flip]
# [:flip, :quint, :flip]
# You can also do custom definitions. See the bottom of the file details
# on how to do that. I've defined a couple for you:
# [:smoothest_start]
# [:smoothest_stop]
# CHANGE THIS LINE TO ONE OF THE LINES ABOVE TO SEE VARIATIONS
args.state.animation_type = [:identity]
# args.state.animation_type = [:quad]
# args.state.animation_type = [:cube]
# args.state.animation_type = [:quart]
# args.state.animation_type = [:quint]
# args.state.animation_type = [:flip, :identity]
# args.state.animation_type = [:flip, :quad, :flip]
# args.state.animation_type = [:flip, :cube, :flip]
# args.state.animation_type = [:flip, :quart, :flip]
# args.state.animation_type = [:flip, :quint, :flip]
# args.state.animation_type = [:smoothest_start]
# args.state.animation_type = [:smoothest_stop]
# THIS IS WHERE THE MAGIC HAPPENS!
# Numeric#ease
progress = args.state.start_animate_at.ease(args.state.duration, args.state.animation_type)
# Numeric#ease needs to called:
# 1. On the number that represents the point in time you want to start, and takes two parameters:
# a. The first parameter is how long the animation should take.
# b. The second parameter represents the functions that need to be called.
#
# For example, if I wanted an animate to start 3 seconds in, and last for 10 seconds,
# and I want to animation to start fast and end slow, I would do:
# (60 * 3).ease(60 * 10, :flip, :quint, :flip)
# initial value delta to the final value
calc_x = args.state.starting_x + (args.state.target_x - args.state.starting_x) * progress
calc_y = args.state.starting_y + (args.state.target_y - args.state.starting_y) * progress
calc_w = args.state.starting_w + (args.state.target_w - args.state.starting_w) * progress
calc_h = args.state.starting_h + (args.state.target_h - args.state.starting_h) * progress
args.outputs.solids << [calc_x, calc_y, calc_w, calc_h, 0, 0, 0]
# count down
count_down = args.state.start_animate_at - args.state.tick_count
if count_down > 0
args.outputs.labels << [640, 375, "Running: #{args.state.animation_type} in...", 3, 1]
args.outputs.labels << [640, 345, "%.2f" % count_down.fdiv(60), 3, 1]
elsif progress >= 1
args.outputs.labels << [640, 360, "Click screen to reset.", 3, 1]
if args.inputs.click
$gtk.reset
end
end
end
# $gtk.reset
# you can make own variations of animations using this
module Easing
# you have access to all the built in functions: identity, flip, quad, cube, quart, quint
def self.smoothest_start x
quad(quint(x))
end
def self.smoothest_stop x
flip(quad(quint(flip(x))))
end
# this is the source for the existing easing functions
def self.identity x
x
end
def self.flip x
1 - x
end
def self.quad x
x * x
end
def self.cube x
x * x * x
end
def self.quart x
x * x * x * x * x
end
def self.quint x
x * x * x * x * x * x
end
end
</code></pre>
<h3 id='----tweening-lerping-easing-functions---cubic-bezier---main-rb'>Tweening Lerping Easing Functions - Cubic Bezier - main.rb</h3>
<pre><code class="language-ruby"># ./samples/08_tweening_lerping_easing_functions/02_cubic_bezier/app/main.rb
def tick args
args.outputs.background_color = [33, 33, 33]
args.outputs.lines << bezier(100, 100,
100, 620,
1180, 620,
1180, 100,
0)
args.outputs.lines << bezier(100, 100,
100, 620,
1180, 620,
1180, 100,
20)
end
def bezier x1, y1, x2, y2, x3, y3, x4, y4, step
step ||= 0
color = [200, 200, 200]
points = points_for_bezier [x1, y1], [x2, y2], [x3, y3], [x4, y4], step
points.each_cons(2).map do |p1, p2|
[p1, p2, color]
end
end
def points_for_bezier p1, p2, p3, p4, step
points = []
if step == 0
[p1, p2, p3, p4]
else
t_step = 1.fdiv(step + 1)
t = 0
t += t_step
points = []
while t < 1
points << [
b_for_t(p1.x, p2.x, p3.x, p4.x, t),
b_for_t(p1.y, p2.y, p3.y, p4.y, t),
]
t += t_step
end
[
p1,
*points,
p4
]
end
end
def b_for_t v0, v1, v2, v3, t
pow(1 - t, 3) * v0 +
3 * pow(1 - t, 2) * t * v1 +
3 * (1 - t) * pow(t, 2) * v2 +
pow(t, 3) * v3
end
def pow n, to
n ** to
end
</code></pre>
<h3 id='----tweening-lerping-easing-functions---easing-using-spline---main-rb'>Tweening Lerping Easing Functions - Easing Using Spline - main.rb</h3>
<pre><code class="language-ruby"># ./samples/08_tweening_lerping_easing_functions/03_easing_using_spline/app/main.rb
def tick args
args.state.duration = 10.seconds
args.state.spline = [
[0.0, 0.33, 0.66, 1.0],
[1.0, 1.0, 1.0, 1.0],
[1.0, 0.66, 0.33, 0.0],
]
args.state.simulation_tick = args.state.tick_count % args.state.duration
progress = 0.ease_spline_extended args.state.simulation_tick, args.state.duration, args.state.spline
args.outputs.borders << args.grid.rect
args.outputs.solids << [20 + 1240 * progress,
20 + 680 * progress,
20, 20].anchor_rect(0.5, 0.5)
args.outputs.labels << [10,
710,
"perc: #{"%.2f" % (args.state.simulation_tick / args.state.duration)} t: #{args.state.simulation_tick}"]
end
</code></pre>
<h3 id='----tweening-lerping-easing-functions---parametric-enemy-movement---main-rb'>Tweening Lerping Easing Functions - Parametric Enemy Movement - main.rb</h3>
<pre><code class="language-ruby"># ./samples/08_tweening_lerping_easing_functions/04_parametric_enemy_movement/app/main.rb
def new_star args
{ x: 1280.randomize(:ratio),
starting_y: 800,
distance_to_travel: 900 + 100.randomize(:ratio),
duration: 100.randomize(:ratio) + 60,
created_at: args.state.tick_count,
max_alpha: 128.randomize(:ratio) + 128,
b: 255.randomize(:ratio),
g: 200.randomize(:ratio),
w: 1.randomize(:ratio) + 1,
h: 1.randomize(:ratio) + 1 }
end
def new_enemy args
{ x: 1280.randomize(:ratio),
starting_y: 800,
distance_to_travel: -900,
duration: 60.randomize(:ratio) + 180,
created_at: args.state.tick_count,
w: 32,
h: 32,
fire_rate: (30.randomize(:ratio) + (60 - args.state.score)).to_i }
end
def new_bullet args, starting_x, starting_y, enemy_speed
{ x: starting_x,
starting_y: starting_y,
distance_to_travel: -900,
created_at: args.state.tick_count,
duration: 900 / (enemy_speed.abs + 2.0 + (5.0 * args.state.score.fdiv(100))).abs,
w: 5,
h: 5 }
end
def new_player_bullet args, starting_x, starting_y, player_speed
{ x: starting_x,
starting_y: starting_y,
distance_to_travel: 900,
created_at: args.state.tick_count,
duration: 900 / (player_speed + 2.0),
w: 5,
h: 5 }
end
def defaults args
args.outputs.background_color = [0, 0, 0]
args.state.score ||= 0
args.state.stars ||= []
args.state.enemies ||= []
args.state.bullets ||= []
args.state.player_bullets ||= []
args.state.max_stars = 50
args.state.max_enemies = 10
args.state.player.x ||= 640
args.state.player.y ||= 100
args.state.player.w ||= 32
args.state.player.h ||= 32
if args.state.tick_count == 0
args.state.stars.clear
args.state.max_stars.times do
s = new_star args
s[:created_at] += s[:duration].randomize(:ratio)
args.state.stars << s
end
end
if args.state.tick_count == 0
args.state.enemies.clear
args.state.max_enemies.times do
s = new_enemy args
s[:created_at] += s[:duration].randomize(:ratio)
args.state.enemies << s
end
end
end
def input args
if args.inputs.keyboard.left
args.state.player.x -= 5
elsif args.inputs.keyboard.right
args.state.player.x += 5
end
if args.inputs.keyboard.up
args.state.player.y += 5
elsif args.inputs.keyboard.down
args.state.player.y -= 5
end
if args.inputs.keyboard.key_down.space
args.state.player_bullets << new_player_bullet(args,
args.state.player.x + args.state.player.w.half,
args.state.player.y + args.state.player.h, 5)
end
args.state.player.y = args.state.player.y.greater(0).lesser(720 - args.state.player.w)
args.state.player.x = args.state.player.x.greater(0).lesser(1280 - args.state.player.h)
end
def completed? entity
(entity[:created_at] + entity[:duration]).elapsed_time > 0
end
def calc_stars args
if (stars_to_add = args.state.max_stars - args.state.stars.length) > 0
stars_to_add.times { args.state.stars << new_star(args) }
end
args.state.stars = args.state.stars.reject { |s| completed? s }
end
def move_enemies args
if (enemies_to_add = args.state.max_enemies - args.state.enemies.length) > 0
enemies_to_add.times { args.state.enemies << new_enemy(args) }
end
args.state.enemies = args.state.enemies.reject { |s| completed? s }
end
def move_bullets args
args.state.enemies.each do |e|
if args.state.tick_count.mod_zero?(e[:fire_rate])
args.state.bullets << new_bullet(args, e[:x] + e[:w].half, current_y(e), e[:distance_to_travel] / e[:duration])
end
end
args.state.bullets = args.state.bullets.reject { |s| completed? s }
args.state.player_bullets = args.state.player_bullets.reject { |s| completed? s }
end
def intersect? entity_one, entity_two
entity_one.merge(y: current_y(entity_one))
.intersect_rect? entity_two.merge(y: current_y(entity_two))
end
def kill args
bullets_hitting_enemies = []
dead_bullets = []
dead_enemies = []
args.state.player_bullets.each do |b|
args.state.enemies.each do |e|
if intersect? b, e
dead_bullets << b
dead_enemies << e
end
end
end
args.state.score += dead_enemies.length
args.state.player_bullets.reject! { |b| dead_bullets.include? b }
args.state.enemies.reject! { |e| dead_enemies.include? e }
dead = args.state.bullets.any? do |b|
[args.state.player.x,
args.state.player.y,
args.state.player.w,
args.state.player.h].intersect_rect? b.merge(y: current_y(b))
end
return unless dead
args.gtk.reset
defaults args
end
def calc args
calc_stars args
move_enemies args
move_bullets args
kill args
end
def current_y entity
entity[:starting_y] + (entity[:distance_to_travel] * entity[:created_at].ease(entity[:duration], :identity))
end
def render args
args.outputs.solids << args.state.stars.map do |s|
[s[:x],
current_y(s),
s[:w], s[:h], 0, s[:g], s[:b], s[:max_alpha] * s[:created_at].ease(20, :identity)]
end
args.outputs.borders << args.state.enemies.map do |s|
[s[:x],
current_y(s),
s[:w], s[:h], 255, 0, 0]
end
args.outputs.borders << args.state.bullets.map do |b|
[b[:x],
current_y(b),
b[:w], b[:h], 255, 0, 0]
end
args.outputs.borders << args.state.player_bullets.map do |b|
[b[:x],
current_y(b),
b[:w], b[:h], 255, 255, 255]
end
args.borders << [args.state.player.x,
args.state.player.y,
args.state.player.w,
args.state.player.h, 255, 255, 255]
end
def tick args
defaults args
input args
calc args
render args
end
</code></pre>
<h3 id='----performance---sprites-as-hash---main-rb'>Performance - Sprites As Hash - main.rb</h3>
<pre><code class="language-ruby"># ./samples/09_performance/01_sprites_as_hash/app/main.rb
# Sprites represented as Hashes using the queue ~args.outputs.sprites~
# code up, but are the "slowest" to render.
# The reason for this is the access of the key in the Hash and also
# because the data args.outputs.sprites is cleared every tick.
def random_x args
(args.grid.w.randomize :ratio) * -1
end
def random_y args
(args.grid.h.randomize :ratio) * -1
end
def random_speed
1 + (4.randomize :ratio)
end
def new_star args
{
x: (random_x args),
y: (random_y args),
w: 4, h: 4, path: 'sprites/tiny-star.png',
s: random_speed
}
end
def move_star args, star
star.x += star[:s]
star.y += star[:s]
if star.x > args.grid.w || star.y > args.grid.h
star.x = (random_x args)
star.y = (random_y args)
star[:s] = random_speed
end
end
def tick args
args.state.star_count ||= 0
# sets console command when sample app initially opens
if Kernel.global_tick_count == 0
puts ""
puts ""
puts "========================================================="
puts "* INFO: Sprites, Hashes"
puts "* INFO: Please specify the number of sprites to render."
args.gtk.console.set_command "reset_with count: 100"
end
# init
if args.state.tick_count == 0
args.state.stars = args.state.star_count.map { |i| new_star args }
end
# update
args.state.stars.each { |s| move_star args, s }
# render
args.outputs.sprites << args.state.stars
args.outputs.background_color = [0, 0, 0]
args.outputs.primitives << args.gtk.current_framerate_primitives
end
# resets game, and assigns star count given by user
def reset_with count: count
$gtk.reset
$gtk.args.state.star_count = count
end
</code></pre>
<h3 id='----performance---sprites-as-entities---main-rb'>Performance - Sprites As Entities - main.rb</h3>
<pre><code class="language-ruby"># ./samples/09_performance/02_sprites_as_entities/app/main.rb
# Sprites represented as Entities using the queue ~args.outputs.sprites~
# yields nicer access apis over Hashes, but require a bit more code upfront.
# The hash sample has to use star[:s] to get the speed of the star, but
# an entity can use .s instead.
def random_x args
(args.grid.w.randomize :ratio) * -1
end
def random_y args
(args.grid.h.randomize :ratio) * -1
end
def random_speed
1 + (4.randomize :ratio)
end
def new_star args
args.state.new_entity :star, {
x: (random_x args),
y: (random_y args),
w: 4, h: 4,
path: 'sprites/tiny-star.png',
s: random_speed
}
end
def move_star args, star
star.x += star.s
star.y += star.s
if star.x > args.grid.w || star.y > args.grid.h
star.x = (random_x args)
star.y = (random_y args)
star.s = random_speed
end
end
def tick args
args.state.star_count ||= 0
# sets console command when sample app initially opens
if Kernel.global_tick_count == 0
puts ""
puts ""
puts "========================================================="
puts "* INFO: Sprites, Open Entities"
puts "* INFO: Please specify the number of sprites to render."
args.gtk.console.set_command "reset_with count: 100"
end
# init
if args.state.tick_count == 0
args.state.stars = args.state.star_count.map { |i| new_star args }
end
# update
args.state.stars.each { |s| move_star args, s }
# render
args.outputs.sprites << args.state.stars
args.outputs.background_color = [0, 0, 0]
args.outputs.primitives << args.gtk.current_framerate_primitives
end
# resets game, and assigns star count given by user
def reset_with count: count
$gtk.reset
$gtk.args.state.star_count = count
end
</code></pre>
<h3 id='----performance---sprites-as-strict-entities---main-rb'>Performance - Sprites As Strict Entities - main.rb</h3>
<pre><code class="language-ruby"># ./samples/09_performance/03_sprites_as_strict_entities/app/main.rb
# Sprites represented as StrictEntities using the queue ~args.outputs.sprites~
# yields apis access similar to Entities, but all properties that can be set on the
# entity must be predefined with a default value. Strict entities do not support the
# addition of new properties after the fact. They are more performant than OpenEntities
# because of this constraint.
def random_x args
(args.grid.w.randomize :ratio) * -1
end
def random_y args
(args.grid.h.randomize :ratio) * -1
end
def random_speed
1 + (4.randomize :ratio)
end
def new_star args
args.state.new_entity_strict(:star,
x: (random_x args),
y: (random_y args),
w: 4, h: 4,
path: 'sprites/tiny-star.png',
s: random_speed) do |entity|
# invoke attr_sprite so that it responds to
# all properties that are required to render a sprite
entity.attr_sprite
end
end
def move_star args, star
star.x += star.s
star.y += star.s
if star.x > args.grid.w || star.y > args.grid.h
star.x = (random_x args)
star.y = (random_y args)
star.s = random_speed
end
end
def tick args
args.state.star_count ||= 0
# sets console command when sample app initially opens
if Kernel.global_tick_count == 0
puts ""
puts ""
puts "========================================================="
puts "* INFO: Sprites, Strict Entities"
puts "* INFO: Please specify the number of sprites to render."
args.gtk.console.set_command "reset_with count: 100"
end
# init
if args.state.tick_count == 0
args.state.stars = args.state.star_count.map { |i| new_star args }
end
# update
args.state.stars.each { |s| move_star args, s }
# render
args.outputs.sprites << args.state.stars
args.outputs.background_color = [0, 0, 0]
args.outputs.primitives << args.gtk.current_framerate_primitives
end
# resets game, and assigns star count given by user
def reset_with count: count
$gtk.reset
$gtk.args.state.star_count = count
end
</code></pre>
<h3 id='----performance---sprites-as-classes---main-rb'>Performance - Sprites As Classes - main.rb</h3>
<pre><code class="language-ruby"># ./samples/09_performance/04_sprites_as_classes/app/main.rb
# Sprites represented as Classes using the queue ~args.outputs.sprites~.
# gives you full control of property declaration and method invocation.
# They are more performant than OpenEntities and StrictEntities, but more code upfront.
class Star
attr_sprite
def initialize grid
@grid = grid
@x = (rand @grid.w) * -1
@y = (rand @grid.h) * -1
@w = 4
@h = 4
@s = 1 + (4.randomize :ratio)
@path = 'sprites/tiny-star.png'
end
def move
@x += @s
@y += @s
@x = (rand @grid.w) * -1 if @x > @grid.right
@y = (rand @grid.h) * -1 if @y > @grid.top
end
end
# calls methods needed for game to run properly
def tick args
# sets console command when sample app initially opens
if Kernel.global_tick_count == 0
puts ""
puts ""
puts "========================================================="
puts "* INFO: Sprites, Classes"
puts "* INFO: Please specify the number of sprites to render."
args.gtk.console.set_command "reset_with count: 100"
end
# init
if args.state.tick_count == 0
args.state.stars = args.state.star_count.map { |i| Star.new args.grid }
end
# update
args.state.stars.each(&:move)
# render
args.outputs.sprites << args.state.stars
args.outputs.background_color = [0, 0, 0]
args.outputs.primitives << args.gtk.current_framerate_primitives
end
# resets game, and assigns star count given by user
def reset_with count: count
$gtk.reset
$gtk.args.state.star_count = count
end
</code></pre>
<h3 id='----performance---static-sprites-as-classes---main-rb'>Performance - Static Sprites As Classes - main.rb</h3>
<pre><code class="language-ruby"># ./samples/09_performance/05_static_sprites_as_classes/app/main.rb
# Sprites represented as Classes using the queue ~args.outputs.static_sprites~.
# bypasses the queue behavior of ~args.outputs.sprites~. All instances are held
# by reference. You get better performance, but you are mutating state of held objects
# which is less functional/data oriented.
class Star
attr_sprite
def initialize grid
@grid = grid
@x = (rand @grid.w) * -1
@y = (rand @grid.h) * -1
@w = 4
@h = 4
@s = 1 + (4.randomize :ratio)
@path = 'sprites/tiny-star.png'
end
def move
@x += @s
@y += @s
@x = (rand @grid.w) * -1 if @x > @grid.right
@y = (rand @grid.h) * -1 if @y > @grid.top
end
end
# calls methods needed for game to run properly
def tick args
# sets console command when sample app initially opens
if Kernel.global_tick_count == 0
puts ""
puts ""
puts "========================================================="
puts "* INFO: Static Sprites, Classes"
puts "* INFO: Please specify the number of sprites to render."
args.gtk.console.set_command "reset_with count: 100"
end
# init
if args.state.tick_count == 0
args.state.stars = args.state.star_count.map { |i| Star.new args.grid }
args.outputs.static_sprites << args.state.stars
end
# update
args.state.stars.each(&:move)
# render
args.outputs.background_color = [0, 0, 0]
args.outputs.primitives << args.gtk.current_framerate_primitives
end
# resets game, and assigns star count given by user
def reset_with count: count
$gtk.reset
$gtk.args.state.star_count = count
end
</code></pre>
<h3 id='----performance---static-sprites-as-classes-with-custom-drawing---main-rb'>Performance - Static Sprites As Classes With Custom Drawing - main.rb</h3>
<pre><code class="language-ruby"># ./samples/09_performance/06_static_sprites_as_classes_with_custom_drawing/app/main.rb
# Sprites represented as Classes, with a draw_override method, and using the queue ~args.outputs.static_sprites~.
# is the fastest approach. This is comparable to what other game engines set as the default behavior.
# There are tradeoffs for all this speed if the creation of a full blown class, and bypassing
# functional/data-oriented practices.
class Star
def initialize grid
@grid = grid
@x = (rand @grid.w) * -1
@y = (rand @grid.h) * -1
@w = 4
@h = 4
@s = 1 + (4.randomize :ratio)
@path = 'sprites/tiny-star.png'
end
def move
@x += @s
@y += @s
@x = (rand @grid.w) * -1 if @x > @grid.right
@y = (rand @grid.h) * -1 if @y > @grid.top
end
# if the object that is in args.outputs.sprites (or static_sprites)
# respond_to? :draw_override, then the method is invoked giving you
# access to the class used to draw to the canvas.
def draw_override ffi_draw
# first move then draw
move
# The argument order for ffi.draw_sprite is:
# x, y, w, h, path
ffi_draw.draw_sprite @x, @y, @w, @h, @path
# The argument order for ffi_draw.draw_sprite_2 is (pass in nil for default value):
# x, y, w, h, path,
# angle, alpha
# The argument order for ffi_draw.draw_sprite_3 is:
# x, y, w, h,
# path,
# angle,
# alpha, red_saturation, green_saturation, blue_saturation
# tile_x, tile_y, tile_w, tile_h,
# flip_horizontally, flip_vertically,
# angle_anchor_x, angle_anchor_y,
# source_x, source_y, source_w, source_h
# The argument order for ffi_draw.draw_sprite_4 is:
# x, y, w, h,
# path,
# angle,
# alpha, red_saturation, green_saturation, blue_saturation
# tile_x, tile_y, tile_w, tile_h,
# flip_horizontally, flip_vertically,
# angle_anchor_x, angle_anchor_y,
# source_x, source_y, source_w, source_h,
# blendmode_enum
end
end
# calls methods needed for game to run properly
def tick args
# sets console command when sample app initially opens
if Kernel.global_tick_count == 0
puts ""
puts ""
puts "========================================================="
puts "* INFO: Static Sprites, Classes, Draw Override"
puts "* INFO: Please specify the number of sprites to render."
args.gtk.console.set_command "reset_with count: 100"
end
# init
if args.state.tick_count == 0
args.state.stars = args.state.star_count.map { |i| Star.new args.grid }
args.outputs.static_sprites << args.state.stars
end
# render framerate
args.outputs.background_color = [0, 0, 0]
args.outputs.primitives << args.gtk.current_framerate_primitives
end
# resets game, and assigns star count given by user
def reset_with count: count
$gtk.reset
$gtk.args.state.star_count = count
end
</code></pre>
<h3 id='----performance---collision-limits---main-rb'>Performance - Collision Limits - main.rb</h3>
<pre><code class="language-ruby"># ./samples/09_performance/07_collision_limits/app/main.rb
=begin
Reminders:
- find_all: Finds all elements of a collection that meet certain requirements.
In this sample app, we're finding all bodies that intersect with the center body.
- args.outputs.solids: An array. The values generate a solid.
The parameters are [X, Y, WIDTH, HEIGHT, RED, GREEN, BLUE]
For more information about solids, go to mygame/documentation/03-solids-and-borders.md.
- args.outputs.labels: An array. The values generate a label.
The parameters are [X, Y, TEXT, SIZE, ALIGNMENT, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.md.
- ARRAY#intersect_rect?: Returns true or false depending on if two rectangles intersect.
=end
# This code demonstrates moving objects that loop around once they exceed the scope of the screen,
# which has dimensions of 1280 by 720, and also detects collisions between objects called "bodies".
def body_count num
$gtk.args.state.other_bodies = num.map { [1280 * rand, 720 * rand, 10, 10] } # other_bodies set using num collection
end
def tick args
# Center body's values are set using an array
# Map is used to set values of 2000 other bodies
# All bodies that intersect with center body are stored in collisions collection
args.state.center_body ||= [640 - 100, 360 - 100, 200, 200] # calculations done to place body in center
args.state.other_bodies ||= 2000.map { [1280 * rand, 720 * rand, 10, 10] } # 2000 bodies given random position on screen
# finds all bodies that intersect with center body, stores them in collisions
collisions = args.state.other_bodies.find_all { |b| b.intersect_rect? args.state.center_body }
args.borders << args.state.center_body # outputs center body as a black border
# transparency changes based on number of collisions; the more collisions, the redder (more transparent) the box becomes
args.solids << [args.state.center_body, 255, 0, 0, collisions.length * 5] # center body is red solid
args.solids << args.state.other_bodies # other bodies are output as (black) solids, as well
args.labels << [10, 30, args.gtk.current_framerate] # outputs frame rate in bottom left corner
# Bodies are returned to bottom left corner if positions exceed scope of screen
args.state.other_bodies.each do |b| # for each body in the other_bodies collection
b.x += 5 # x and y are both incremented by 5
b.y += 5
b.x = 0 if b.x > 1280 # x becomes 0 if star exceeds scope of screen (goes too far right)
b.y = 0 if b.y > 720 # y becomes 0 if star exceeds scope of screen (goes too far up)
end
end
# Resets the game.
$gtk.reset
</code></pre>
<h3 id='----advanced-debugging---trace-debugging---main-rb'>Advanced Debugging - Trace Debugging - main.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/01_trace_debugging/app/main.rb
class Game
attr_gtk
def method1 num
method2 num
end
def method2 num
method3 num
end
def method3 num
method4 num
end
def method4 num
if num == 1
puts "UNLUCKY #{num}."
state.unlucky_count += 1
if state.unlucky_count > 3
raise "NAT 1 finally occurred. Check app/trace.txt for all method invocation history."
end
else
puts "LUCKY #{num}."
end
end
def tick
state.roll_history ||= []
state.roll_history << rand(20) + 1
state.countdown ||= 600
state.countdown -= 1
state.unlucky_count ||= 0
outputs.labels << [640, 360, "A dice roll of 1 will cause an exception.", 0, 1]
if state.countdown > 0
outputs.labels << [640, 340, "Dice roll countdown: #{state.countdown}", 0, 1]
else
state.attempts ||= 0
state.attempts += 1
outputs.labels << [640, 340, "ROLLING! #{state.attempts}", 0, 1]
end
return if state.countdown > 0
method1 state.roll_history[-1]
end
end
$game = Game.new
def tick args
trace! $game # <------------------- TRACING ENABLED FOR THIS OBJECT
$game.args = args
$game.tick
end
</code></pre>
<h3 id='----advanced-debugging---trace-debugging-classes---main-rb'>Advanced Debugging - Trace Debugging Classes - main.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/02_trace_debugging_classes/app/main.rb
class Foobar
def initialize
trace! # Trace is added to the constructor.
end
def clicky args
return unless args.inputs.mouse.click
try_rand rand
end
def try_rand num
return if num < 0.9
raise "Exception finally occurred. Take a look at logs/trace.txt #{num}."
end
end
def tick args
args.labels << [640, 360, "Start clicking. Eventually an exception will be thrown. Then look at logs/trace.txt.", 0, 1]
args.state.foobar = Foobar.new if args.tick_count
return unless args.state.foobar
args.state.foobar.clicky args
end
</code></pre>
<h3 id='----advanced-debugging---unit-tests---benchmark_api_tests-rb'>Advanced Debugging - Unit Tests - benchmark_api_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/benchmark_api_tests.rb
def test_benchmark_api args, assert
result = args.gtk.benchmark iterations: 100,
only_one: -> () {
r = 0
(1..100).each do |i|
r += 1
end
}
assert.equal! result.first_place.name, :only_one
result = args.gtk.benchmark iterations: 100,
iterations_100: -> () {
r = 0
(1..100).each do |i|
r += 1
end
},
iterations_50: -> () {
r = 0
(1..50).each do |i|
r += 1
end
}
assert.equal! result.first_place.name, :iterations_50
result = args.gtk.benchmark iterations: 1,
iterations_100: -> () {
r = 0
(1..100).each do |i|
r += 1
end
},
iterations_50: -> () {
r = 0
(1..50).each do |i|
r += 1
end
}
assert.equal! result.too_small_to_measure, true
end
</code></pre>
<h3 id='----advanced-debugging---unit-tests---exception_raising_tests-rb'>Advanced Debugging - Unit Tests - exception_raising_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/exception_raising_tests.rb
begin :shared
class ExceptionalClass
def initialize exception_to_throw = nil
raise exception_to_throw if exception_to_throw
end
end
end
def test_exception_in_newing_object args, assert
begin
ExceptionalClass.new TypeError
raise "Exception wasn't thrown!"
rescue Exception => e
assert.equal! e.class, TypeError, "Exceptions within constructor should be retained."
end
end
$gtk.reset 100
$gtk.log_level = :off
</code></pre>
<h3 id='----advanced-debugging---unit-tests---fn_tests-rb'>Advanced Debugging - Unit Tests - fn_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/fn_tests.rb
def infinity
1 / 0
end
def neg_infinity
-1 / 0
end
def nan
0.0 / 0
end
def test_add args, assert
assert.equal! (args.fn.add), 0
assert.equal! (args.fn.+), 0
assert.equal! (args.fn.+ 1, 2, 3), 6
assert.equal! (args.fn.+ 0), 0
assert.equal! (args.fn.+ 0, nil), 0
assert.equal! (args.fn.+ 0, nan), nil
assert.equal! (args.fn.+ 0, nil, infinity), nil
assert.equal! (args.fn.+ [1, 2, 3, [4, 5, 6]]), 21
assert.equal! (args.fn.+ [nil, [4, 5, 6]]), 15
end
def test_sub args, assert
neg_infinity = infinity * -1
assert.equal! (args.fn.+), 0
assert.equal! (args.fn.- 1, 2, 3), -4
assert.equal! (args.fn.- 4), -4
assert.equal! (args.fn.- 4, nan), nil
assert.equal! (args.fn.- 0, nil), 0
assert.equal! (args.fn.- 0, nil, infinity), nil
assert.equal! (args.fn.- [0, 1, 2, 3, [4, 5, 6]]), -21
assert.equal! (args.fn.- [nil, 0, [4, 5, 6]]), -15
end
def test_div args, assert
assert.equal! (args.fn.div), 1
assert.equal! (args.fn./), 1
assert.equal! (args.fn./ 6, 3), 2
assert.equal! (args.fn./ 6, infinity), nil
assert.equal! (args.fn./ 6, nan), nil
assert.equal! (args.fn./ infinity), nil
assert.equal! (args.fn./ 0), nil
assert.equal! (args.fn./ 6, [3]), 2
end
def test_idiv args, assert
assert.equal! (args.fn.idiv), 1
assert.equal! (args.fn.idiv 7, 3), 2
assert.equal! (args.fn.idiv 6, infinity), nil
assert.equal! (args.fn.idiv 6, nan), nil
assert.equal! (args.fn.idiv infinity), nil
assert.equal! (args.fn.idiv 0), nil
assert.equal! (args.fn.idiv 7, [3]), 2
end
def test_mul args, assert
assert.equal! (args.fn.mul), 1
assert.equal! (args.fn.*), 1
assert.equal! (args.fn.* 7, 3), 21
assert.equal! (args.fn.* 6, nan), nil
assert.equal! (args.fn.* 6, infinity), nil
assert.equal! (args.fn.* infinity), nil
assert.equal! (args.fn.* 0), 0
assert.equal! (args.fn.* 7, [3]), 21
end
def test_lt args, assert
assert.equal! (args.fn.lt 1), 1
assert.equal! (args.fn.lt), nil
assert.equal! (args.fn.lt infinity), nil
assert.equal! (args.fn.lt nan), nil
assert.equal! (args.fn.lt 10, 9, 8), 8
assert.equal! (args.fn.< 10, 9, 8), 8
assert.equal! (args.fn.< [10, 9, [8]]), 8
assert.equal! (args.fn.< 10, 10), nil
end
def test_lte args, assert
assert.equal! (args.fn.lte 1), 1
assert.equal! (args.fn.lte), nil
assert.equal! (args.fn.lte infinity), nil
assert.equal! (args.fn.lte nan), nil
assert.equal! (args.fn.lte 10, 9, 8), 8
assert.equal! (args.fn.lte 10, 10), 10
assert.equal! (args.fn.lte 10, 9, [8]), 8
assert.equal! (args.fn.<= 10, 9, 8), 8
end
def test_gt args, assert
assert.equal! (args.fn.gt 1), 1
assert.equal! (args.fn.gt), nil
assert.equal! (args.fn.gt infinity), nil
assert.equal! (args.fn.gt nan), nil
assert.equal! (args.fn.gt 8, 9, 10), 10
assert.equal! (args.fn.gt [8, 9, [10]]), 10
assert.equal! (args.fn.gt 10, 10), nil
assert.equal! (args.fn.gt 10, 10), nil
assert.equal! (args.fn.gt 10, 9), nil
assert.equal! (args.fn.> 8, 9, 10), 10
end
def test_gte args, assert
assert.equal! (args.fn.gte 1), 1
assert.equal! (args.fn.gte), nil
assert.equal! (args.fn.gte infinity), nil
assert.equal! (args.fn.gte nan), nil
assert.equal! (args.fn.gte 8, 9, 10), 10
assert.equal! (args.fn.gte 10, 10), 10
assert.equal! (args.fn.gte 8, 9, [10]), 10
assert.equal! (args.fn.gte 10, 9), nil
assert.equal! (args.fn.>= 8, 9, 10), 10
end
def test_acopy args, assert
orig = [1, 2, 3]
clone = args.fn.acopy orig
assert.equal! clone, [1, 2, 3]
assert.equal! clone, orig
assert.not_equal! clone.object_id, orig.object_id
end
def test_aget args, assert
assert.equal! (args.fn.aget [:a, :b, :c], 1), :b
assert.equal! (args.fn.aget [:a, :b, :c], nil), nil
assert.equal! (args.fn.aget nil, 1), nil
end
def test_alength args, assert
assert.equal! (args.fn.alength [:a, :b, :c]), 3
assert.equal! (args.fn.alength nil), nil
end
def test_amap args, assert
inc = lambda { |i| i + 1 }
ary = [1, 2, 3]
assert.equal! (args.fn.amap ary, inc), [2, 3, 4]
assert.equal! (args.fn.amap nil, inc), nil
assert.equal! (args.fn.amap ary, nil), nil
assert.equal! (args.fn.amap ary, inc).class, Array
end
def test_and args, assert
assert.equal! (args.fn.and 1, 2, 3, 4), 4
assert.equal! (args.fn.and 1, 2, nil, 4), nil
assert.equal! (args.fn.and), true
end
def test_or args, assert
assert.equal! (args.fn.or 1, 2, 3, 4), 1
assert.equal! (args.fn.or 1, 2, nil, 4), 1
assert.equal! (args.fn.or), nil
assert.equal! (args.fn.or nil, nil, false, 5, 10), 5
end
def test_eq_eq args, assert
assert.equal! (args.fn.eq?), true
assert.equal! (args.fn.eq? 1, 0), false
assert.equal! (args.fn.eq? 1, 1, 1), true
assert.equal! (args.fn.== 1, 1, 1), true
assert.equal! (args.fn.== nil, nil), true
end
def test_apply args, assert
assert.equal! (args.fn.and [nil, nil, nil]), [nil, nil, nil]
assert.equal! (args.fn.apply [nil, nil, nil], args.fn.method(:and)), nil
and_lambda = lambda {|*xs| args.fn.and(*xs)}
assert.equal! (args.fn.apply [nil, nil, nil], and_lambda), nil
end
def test_areduce args, assert
assert.equal! (args.fn.areduce [1, 2, 3], 0, lambda { |i, a| i + a }), 6
end
def test_array_hash args, assert
assert.equal! (args.fn.array_hash :a, 1, :b, 2), { a: 1, b: 2 }
assert.equal! (args.fn.array_hash), { }
end
</code></pre>
<h3 id='----advanced-debugging---unit-tests---gen_docs-rb'>Advanced Debugging - Unit Tests - gen_docs.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/gen_docs.rb
# ./dragonruby mygame --eval samples/99_zz_gtk_unit_tests/gen_docs.rb --no-tick
Kernel.export_docs!
</code></pre>
<h3 id='----advanced-debugging---unit-tests---geometry_tests-rb'>Advanced Debugging - Unit Tests - geometry_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/geometry_tests.rb
begin :shared
def primitive_representations x, y, w, h
[
[x, y, w, h],
{ x: x, y: y, w: w, h: h },
RectForTest.new(x, y, w, h)
]
end
class RectForTest
attr_sprite
def initialize x, y, w, h
@x = x
@y = y
@w = w
@h = h
end
def to_s
"RectForTest: #{[x, y, w, h]}"
end
end
end
begin :intersect_rect?
def test_intersect_rect_point args, assert
assert.true! [16, 13].intersect_rect?([13, 12, 4, 4]), "point intersects with rect."
end
def test_intersect_rect args, assert
intersecting = primitive_representations(0, 0, 100, 100) +
primitive_representations(20, 20, 20, 20)
intersecting.product(intersecting).each do |rect_one, rect_two|
assert.true! rect_one.intersect_rect?(rect_two),
"intersect_rect? assertion failed for #{rect_one}, #{rect_two} (expected true)."
end
not_intersecting = [
[ 0, 0, 5, 5],
{ x: 10, y: 10, w: 5, h: 5 },
RectForTest.new(20, 20, 5, 5)
]
not_intersecting.product(not_intersecting)
.reject { |rect_one, rect_two| rect_one == rect_two }
.each do |rect_one, rect_two|
assert.false! rect_one.intersect_rect?(rect_two),
"intersect_rect? assertion failed for #{rect_one}, #{rect_two} (expected false)."
end
end
end
begin :inside_rect?
def assert_inside_rect outer: nil, inner: nil, expected: nil, assert: nil
assert.true! inner.inside_rect?(outer) == expected,
"inside_rect? assertion failed for outer: #{outer} inner: #{inner} (expected #{expected})."
end
def test_inside_rect args, assert
outer_rects = primitive_representations(0, 0, 10, 10)
inner_rects = primitive_representations(1, 1, 5, 5)
primitive_representations(0, 0, 10, 10).product(primitive_representations(1, 1, 5, 5))
.each do |outer, inner|
assert_inside_rect outer: outer, inner: inner,
expected: true, assert: assert
end
end
end
begin :angle_to
def test_angle_to args, assert
origins = primitive_representations(0, 0, 0, 0)
rights = primitive_representations(1, 0, 0, 0)
aboves = primitive_representations(0, 1, 0, 0)
origins.product(aboves).each do |origin, above|
assert.equal! origin.angle_to(above), 90,
"A point directly above should be 90 degrees."
assert.equal! above.angle_from(origin), 90,
"A point coming from above should be 90 degrees."
end
origins.product(rights).each do |origin, right|
assert.equal! origin.angle_to(right) % 360, 0,
"A point directly to the right should be 0 degrees."
assert.equal! right.angle_from(origin) % 360, 0,
"A point coming from the right should be 0 degrees."
end
end
end
begin :scale_rect
def test_scale_rect args, assert
assert.equal! [0, 0, 100, 100].scale_rect(0.5, 0.5),
[25.0, 25.0, 50.0, 50.0]
assert.equal! [0, 0, 100, 100].scale_rect(0.5),
[0.0, 0.0, 50.0, 50.0]
assert.equal! [0, 0, 100, 100].scale_rect_extended(percentage_x: 0.5, percentage_y: 0.5, anchor_x: 0.5, anchor_y: 0.5),
[25.0, 25.0, 50.0, 50.0]
assert.equal! [0, 0, 100, 100].scale_rect_extended(percentage_x: 0.5, percentage_y: 0.5, anchor_x: 0, anchor_y: 0),
[0.0, 0.0, 50.0, 50.0]
end
end
$gtk.reset 100
$gtk.log_level = :off
</code></pre>
<h3 id='----advanced-debugging---unit-tests---http_tests-rb'>Advanced Debugging - Unit Tests - http_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/http_tests.rb
def try_assert_or_schedule args, assert
if $result[:complete]
log_info "Request completed! Verifying."
if $result[:http_response_code] != 200
log_info "The request yielded a result of #{$result[:http_response_code]} instead of 200."
exit
end
log_info ":try_assert_or_schedule succeeded!"
else
args.gtk.schedule_callback Kernel.tick_count + 10 do
try_assert_or_schedule args, assert
end
end
end
def test_http args, assert
$result = $gtk.http_get 'http://dragonruby.org'
try_assert_or_schedule args, assert
end
$gtk.reset 100
$gtk.log_level = :off
</code></pre>
<h3 id='----advanced-debugging---unit-tests---nil_coercion_tests-rb'>Advanced Debugging - Unit Tests - nil_coercion_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/nil_coercion_tests.rb
# numbers
def test_open_entity_add_number args, assert
assert.nil! args.state.i_value
args.state.i_value += 5
assert.equal! args.state.i_value, 5
assert.nil! args.state.f_value
args.state.f_value += 5.5
assert.equal! args.state.f_value, 5.5
end
def test_open_entity_subtract_number args, assert
assert.nil! args.state.i_value
args.state.i_value -= 5
assert.equal! args.state.i_value, -5
assert.nil! args.state.f_value
args.state.f_value -= 5.5
assert.equal! args.state.f_value, -5.5
end
def test_open_entity_multiply_number args, assert
assert.nil! args.state.i_value
args.state.i_value *= 5
assert.equal! args.state.i_value, 0
assert.nil! args.state.f_value
args.state.f_value *= 5.5
assert.equal! args.state.f_value, 0
end
def test_open_entity_divide_number args, assert
assert.nil! args.state.i_value
args.state.i_value /= 5
assert.equal! args.state.i_value, 0
assert.nil! args.state.f_value
args.state.f_value /= 5.5
assert.equal! args.state.f_value, 0
end
# array
def test_open_entity_add_array args, assert
assert.nil! args.state.values
args.state.values += [:a, :b, :c]
assert.equal! args.state.values, [:a, :b, :c]
end
def test_open_entity_subtract_array args, assert
assert.nil! args.state.values
args.state.values -= [:a, :b, :c]
assert.equal! args.state.values, []
end
def test_open_entity_shovel_array args, assert
assert.nil! args.state.values
args.state.values << :a
assert.equal! args.state.values, [:a]
end
def test_open_entity_enumerate args, assert
assert.nil! args.state.values
args.state.values = args.state.values.map_with_index { |i| i }
assert.equal! args.state.values, []
assert.nil! args.state.values_2
args.state.values_2 = args.state.values_2.map { |i| i }
assert.equal! args.state.values_2, []
assert.nil! args.state.values_3
args.state.values_3 = args.state.values_3.flat_map { |i| i }
assert.equal! args.state.values_3, []
end
# hashes
def test_open_entity_indexer args, assert
GTK::Entity.__reset_id__!
assert.nil! args.state.values
args.state.values[:test] = :value
assert.equal! args.state.values.to_s, { entity_id: 1, entity_name: :values, entity_keys_by_ref: {}, test: :value }.to_s
end
# bug
def test_open_entity_nil_bug args, assert
GTK::Entity.__reset_id__!
args.state.foo.a
args.state.foo.b
@hello[:foobar]
assert.nil! args.state.foo.a, "a was not nil."
# the line below fails
# assert.nil! args.state.foo.b, "b was not nil."
end
</code></pre>
<h3 id='----advanced-debugging---unit-tests---object_to_primitive_tests-rb'>Advanced Debugging - Unit Tests - object_to_primitive_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/object_to_primitive_tests.rb
class PlayerSpriteForTest
end
def test_array_to_sprite args, assert
array = [[0, 0, 100, 100, "test.png"]].sprites
puts "No exception was thrown. Sweet!"
end
def test_class_to_sprite args, assert
array = [PlayerSprite.new].sprites
assert.true! array.first.is_a?(PlayerSprite)
puts "No exception was thrown. Sweet!"
end
$gtk.reset 100
$gtk.log_level = :off
</code></pre>
<h3 id='----advanced-debugging---unit-tests---parsing_tests-rb'>Advanced Debugging - Unit Tests - parsing_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/parsing_tests.rb
def test_parse_json args, assert
result = args.gtk.parse_json '{ "name": "John Doe", "aliases": ["JD"] }'
assert.equal! result, { "name"=>"John Doe", "aliases"=>["JD"] }, "Parsing JSON failed."
end
def test_parse_xml args, assert
result = args.gtk.parse_xml <<-S
<Person id="100">
<Name>John Doe</Name>
</Person>
S
expected = {:type=>:element,
:name=>nil,
:children=>[{:type=>:element,
:name=>"Person",
:children=>[{:type=>:element,
:name=>"Name",
:children=>[{:type=>:content,
:data=>"John Doe"}]}],
:attributes=>{"id"=>"100"}}]}
assert.equal! result, expected, "Parsing xml failed."
end
$gtk.reset 100
$gtk.log_level = :off
</code></pre>
<h3 id='----advanced-debugging---unit-tests---pretty_format_tests-rb'>Advanced Debugging - Unit Tests - pretty_format_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/pretty_format_tests.rb
def H opts
opts
end
def A *opts
opts
end
def assert_format args, assert, hash, expected
actual = args.fn.pretty_format hash
assert.are_equal! actual, expected
end
def test_pretty_print args, assert
# =============================
# hash with single value
# =============================
input = (H first_name: "John")
expected = <<-S
{:first_name "John"}
S
(assert_format args, assert, input, expected)
# =============================
# hash with two values
# =============================
input = (H first_name: "John", last_name: "Smith")
expected = <<-S
{:first_name "John"
:last_name "Smith"}
S
(assert_format args, assert, input, expected)
# =============================
# hash with inner hash
# =============================
input = (H first_name: "John",
last_name: "Smith",
middle_initial: "I",
so: (H first_name: "Pocahontas",
last_name: "Tsenacommacah"),
friends: (A (H first_name: "Side", last_name: "Kick"),
(H first_name: "Tim", last_name: "Wizard")))
expected = <<-S
{:first_name "John"
:last_name "Smith"
:middle_initial "I"
:so {:first_name "Pocahontas"
:last_name "Tsenacommacah"}
:friends [{:first_name "Side"
:last_name "Kick"}
{:first_name "Tim"
:last_name "Wizard"}]}
S
(assert_format args, assert, input, expected)
# =============================
# array with one value
# =============================
input = (A 1)
expected = <<-S
[1]
S
(assert_format args, assert, input, expected)
# =============================
# array with multiple values
# =============================
input = (A 1, 2, 3)
expected = <<-S
[1
2
3]
S
(assert_format args, assert, input, expected)
# =============================
# array with multiple values hashes
# =============================
input = (A (H first_name: "Side", last_name: "Kick"),
(H first_name: "Tim", last_name: "Wizard"))
expected = <<-S
[{:first_name "Side"
:last_name "Kick"}
{:first_name "Tim"
:last_name "Wizard"}]
S
(assert_format args, assert, input, expected)
end
def test_nested_nested args, assert
# =============================
# nested array in nested hash
# =============================
input = (H type: :root,
text: "Root",
children: (A (H level: 1,
text: "Level 1",
children: (A (H level: 2,
text: "Level 2",
children: [])))))
expected = <<-S
{:type :root
:text "Root"
:children [{:level 1
:text "Level 1"
:children [{:level 2
:text "Level 2"
:children []}]}]}
S
(assert_format args, assert, input, expected)
end
def test_scene args, assert
script = <<-S
* Scene 1
** Narrator
They say happy endings don't exist.
** Narrator
They say true love is a lie.
S
input = parse_org args, script
puts (args.fn.pretty_format input)
end
</code></pre>
<h3 id='----advanced-debugging---unit-tests---require_tests-rb'>Advanced Debugging - Unit Tests - require_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/require_tests.rb
def write_src path, src
$gtk.write_file path, src
end
write_src 'app/unit_testing_game.rb', <<-S
module UnitTesting
class Game
end
end
S
write_src 'lib/unit_testing_lib.rb', <<-S
module UnitTesting
class Lib
end
end
S
write_src 'app/nested/unit_testing_nested.rb', <<-S
module UnitTesting
class Nested
end
end
S
require 'app/unit_testing_game.rb'
require 'app/nested/unit_testing_nested.rb'
require 'lib/unit_testing_lib.rb'
def test_require args, assert
UnitTesting::Game.new
UnitTesting::Lib.new
UnitTesting::Nested.new
$gtk.exec 'rm ./mygame/app/unit_testing_game.rb'
$gtk.exec 'rm ./mygame/app/nested/unit_testing_nested.rb'
$gtk.exec 'rm ./mygame/lib/unit_testing_lib.rb'
assert.ok!
end
</code></pre>
<h3 id='----advanced-debugging---unit-tests---serialize_deserialize_tests-rb'>Advanced Debugging - Unit Tests - serialize_deserialize_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/serialize_deserialize_tests.rb
def test_serialize args, assert
GTK::Entity.__reset_id__!
args.state.player_one = "test"
result = args.gtk.serialize_state args.state
assert.equal! result, "{:entity_id=>3, :entity_keys_by_ref=>{}, :tick_count=>-1, :player_one=>\"test\"}"
GTK::Entity.__reset_id__!
args.gtk.write_file 'state.txt', ''
result = args.gtk.serialize_state 'state.txt', args.state
assert.equal! result, "{:entity_id=>3, :entity_keys_by_ref=>{}, :tick_count=>-1, :player_one=>\"test\"}"
end
def test_deserialize args, assert
GTK::Entity.__reset_id__!
result = args.gtk.deserialize_state '{:entity_id=>3, :tick_count=>-1, :player_one=>"test"}'
assert.equal! result.player_one, "test"
GTK::Entity.__reset_id__!
args.gtk.write_file 'state.txt', '{:entity_id=>3, :tick_count=>-1, :player_one=>"test"}'
result = args.gtk.deserialize_state 'state.txt'
assert.equal! result.player_one, "test"
end
def test_very_large_serialization args, assert
GTK::Entity.__reset_id__!
size = 3000
size.map_with_index do |i|
args.state.send("k#{i}=".to_sym, i)
end
result = args.gtk.serialize_state args.state
assert.true! (args.gtk.console.log.join.include? "unlikely a string this large will deserialize correctly")
end
def test_strict_entity_serialization args, assert
GTK::Entity.__reset_id__!
args.state.player_one = args.state.new_entity(:player, name: "Ryu")
args.state.player_two = args.state.new_entity_strict(:player_strict, name: "Ken")
serialized_state = args.gtk.serialize_state args.state
assert.equal! serialized_state, '{:entity_id=>1, :entity_keys_by_ref=>{}, :tick_count=>-1, :player_one=>{:entity_id=>1, :entity_name=>:player, :entity_keys_by_ref=>{}, :entity_type=>:player, :created_at=>-1, :global_created_at=>-1, :name=>"Ryu"}, :player_two=>{:entity_id=>3, :entity_name=>:player_strict, :entity_type=>:player_strict, :created_at=>-1, :global_created_at_elapsed=>-1, :entity_strict=>true, :entity_keys_by_ref=>{:entity_type=>:entity_name, :global_created_at_elapsed=>:created_at}, :name=>"Ken"}}'
GTK::Entity.__reset_id__!
deserialize_state = args.gtk.deserialize_state serialized_state
assert.equal! args.state.player_one.name, deserialize_state.player_one.name
assert.true! args.state.player_one.is_a? GTK::OpenEntity
assert.equal! args.state.player_two.name, deserialize_state.player_two.name
assert.true! args.state.player_two.is_a? GTK::StrictEntity
end
def test_strict_entity_serialization_with_nil args, assert
GTK::Entity.__reset_id__!
args.state.player_one = args.state.new_entity(:player, name: "Ryu")
args.state.player_two = args.state.new_entity_strict(:player_strict, name: "Ken", blood_type: nil)
serialized_state = args.gtk.serialize_state args.state
assert.equal! serialized_state, '{:entity_id=>9, :entity_keys_by_ref=>{}, :tick_count=>-1, :player_one=>{:entity_id=>1, :entity_name=>:player, :entity_keys_by_ref=>{}, :entity_type=>:player, :created_at=>-1, :global_created_at=>-1, :name=>"Ryu"}, :player_two=>{:entity_id=>2, :entity_name=>:player_strict, :entity_type=>:player_strict, :created_at=>-1, :global_created_at_elapsed=>-1, :entity_strict=>true, :entity_keys_by_ref=>{:entity_type=>:entity_name, :global_created_at_elapsed=>:created_at}, :name=>"Ken", :blood_type=>nil}}'
GTK::Entity.__reset_id__!
deserialized_state = args.gtk.deserialize_state serialized_state
assert.equal! args.state.player_one.name, deserialized_state.player_one.name
assert.true! args.state.player_one.is_a? GTK::OpenEntity
assert.equal! args.state.player_two.name, deserialized_state.player_two.name
assert.equal! args.state.player_two.blood_type, deserialized_state.player_two.blood_type
assert.equal! deserialized_state.player_two.blood_type, nil
assert.true! args.state.player_two.is_a? GTK::StrictEntity
deserialized_state.player_two.blood_type = :O
assert.equal! deserialized_state.player_two.blood_type, :O
end
def test_multiple_strict_entities args, assert
GTK::Entity.__reset_id__!
args.state.player = args.state.new_entity_strict(:player_one, name: "Ryu")
args.state.enemy = args.state.new_entity_strict(:enemy, name: "Bison", other_property: 'extra mean')
serialized_state = args.gtk.serialize_state args.state
GTK::Entity.__reset_id__!
deserialized_state = args.gtk.deserialize_state serialized_state
assert.equal! deserialized_state.player.name, "Ryu"
assert.equal! deserialized_state.enemy.other_property, "extra mean"
end
def test_by_reference_state args, assert
GTK::Entity.__reset_id__!
args.state.a = { name: "Jane Doe" }
args.state.b = args.state.a
assert.equal! args.state.a.object_id, args.state.b.object_id
serialized_state = args.gtk.serialize_state args.state
GTK::Entity.__reset_id__!
deserialized_state = args.gtk.deserialize_state serialized_state
assert.equal! deserialized_state.a.object_id, deserialized_state.b.object_id
end
def test_by_reference_state_strict_entities args, assert
GTK::Entity.__reset_id__!
args.state.a = { name: "Jane Doe" }
args.state.strict_entity = args.state.new_entity_strict(:couple) do |e|
e.one = args.state.new_entity_strict(:person, name: "Jane")
e.two = e.one
end
assert.equal! args.state.strict_entity.one, args.state.strict_entity.two
serialized_state = args.gtk.serialize_state args.state
GTK::Entity.__reset_id__!
deserialized_state = args.gtk.deserialize_state serialized_state
assert.equal! deserialized_state.strict_entity.one, deserialized_state.strict_entity.two
end
</code></pre>
<h3 id='----advanced-debugging---unit-tests---state_serialization_experimental_tests-rb'>Advanced Debugging - Unit Tests - state_serialization_experimental_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/state_serialization_experimental_tests.rb
MAX_CODE_GEN_LENGTH = 50
# NOTE: This is experimental/advanced stuff.
def needs_partitioning? target
target[:value].to_s.length > MAX_CODE_GEN_LENGTH
end
def partition target
return [] unless needs_partitioning? target
if target[:value].is_a? GTK::OpenEntity
target[:value] = target[:value].hash
end
results = []
idx = 0
left, right = target[:value].partition do
idx += 1
idx.even?
end
left, right = Hash[left], Hash[right]
left = { value: left }
right = { value: right}
[left, right]
end
def add_partition target, path, aggregate, final_result
partitions = partition target
partitions.each do |part|
if needs_partitioning? part
if part[:value].keys.length == 1
first_key = part[:value].keys[0]
new_part = { value: part[:value][first_key] }
path.push first_key
add_partition new_part, path, aggregate, final_result
path.pop
else
add_partition part, path, aggregate, final_result
end
else
final_result << { value: { __path__: [*path] } }
final_result << { value: part[:value] }
end
end
end
def state_to_string state
parts_queue = []
final_queue = []
add_partition({ value: state.hash },
[],
parts_queue,
final_queue)
final_queue.reject {|i| i[:value].keys.length == 0}.map do |i|
i[:value].to_s
end.join("\n#==================================================#\n")
end
def state_from_string string
Kernel.eval("$load_data = {}")
lines = string.split("\n#==================================================#\n")
lines.each do |l|
puts "todo: #{l}"
end
GTK::OpenEntity.parse_from_hash $load_data
end
def test_save_and_load args, assert
args.state.item_1.name = "Jane"
string = state_to_string args.state
state = state_from_string string
assert.equal! args.state.item_1.name, state.item_1.name
end
def test_save_and_load_big args, assert
size = 1000
size.map_with_index do |i|
args.state.send("k#{i}=".to_sym, i)
end
string = state_to_string args.state
state = state_from_string string
size.map_with_index do |i|
assert.equal! args.state.send("k#{i}".to_sym), state.send("k#{i}".to_sym)
assert.equal! args.state.send("k#{i}".to_sym), i
assert.equal! state.send("k#{i}".to_sym), i
end
end
def test_save_and_load_big_nested args, assert
args.state.player_one.friend.nested_hash.k0 = 0
args.state.player_one.friend.nested_hash.k1 = 1
args.state.player_one.friend.nested_hash.k2 = 2
args.state.player_one.friend.nested_hash.k3 = 3
args.state.player_one.friend.nested_hash.k4 = 4
args.state.player_one.friend.nested_hash.k5 = 5
args.state.player_one.friend.nested_hash.k6 = 6
args.state.player_one.friend.nested_hash.k7 = 7
args.state.player_one.friend.nested_hash.k8 = 8
args.state.player_one.friend.nested_hash.k9 = 9
string = state_to_string args.state
state = state_from_string string
end
$gtk.reset 100
$gtk.log_level = :off
</code></pre>
<h3 id='----advanced-debugging---unit-tests---suggest_autocompletion_tests-rb'>Advanced Debugging - Unit Tests - suggest_autocompletion_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/10_advanced_debugging/03_unit_tests/suggest_autocompletion_tests.rb
def default_suggest_autocompletion args
{
index: 4,
text: "args.",
__meta__: {
other_options: [
{
index: Fixnum,
file: "app/main.rb"
}
]
}
}
end
def assert_completion source, *expected
results = suggest_autocompletion text: (source.strip.gsub ":cursor", ""),
index: (source.strip.index ":cursor")
puts results
end
def test_args_completion args, assert
$gtk.write_file_root "autocomplete.txt", ($gtk.suggest_autocompletion text: <<-S, index: 128).join("\n")
require 'app/game.rb'
def tick args
args.gtk.suppress_mailbox = false
$game ||= Game.new
$game.args = args
$game.args.
$game.tick
end
S
puts "contents:"
puts ($gtk.read_file "autocomplete.txt")
end
</code></pre>
<h3 id='----http---retrieve-images---main-rb'>Http - Retrieve Images - main.rb</h3>
<pre><code class="language-ruby"># ./samples/11_http/01_retrieve_images/app/main.rb
def tick args
args.outputs.background_color = [0, 0, 0]
# Show a warning at the start.
args.state.warning_debounce ||= 11 * 60
if args.state.warning_debounce > 0
args.state.warning_debounce -= 1
args.outputs.labels << [640, 600, "This app shows random images from the Internet.", 10, 1, 255, 255, 255]
args.outputs.labels << [640, 500, "Quit in the next few seconds if this is a problem.", 10, 1, 255, 255, 255]
args.outputs.labels << [640, 350, "#{(args.state.warning_debounce / 60.0).to_i}", 10, 1, 255, 255, 255]
return
end
args.state.download_debounce ||= 0 # start immediately, reset to non zero later.
args.state.photos ||= []
# Put a little pause between each download.
if args.state.download.nil?
if args.state.download_debounce > 0
args.state.download_debounce -= 1
else
args.state.download = $gtk.http_get 'https://picsum.photos/200/300.jpg'
end
end
if !args.state.download.nil?
if args.state.download[:complete]
if args.state.download[:http_response_code] == 200
fname = "sprites/#{args.state.photos.length}.jpg"
$gtk.write_file fname, args.state.download[:response_data]
args.state.photos << [ 100 + rand(1080), 500 - rand(480), fname, rand(80) - 40 ]
end
args.state.download = nil
args.state.download_debounce = (rand(3) + 2) * 60
end
end
# draw any downloaded photos...
args.state.photos.each { |i|
args.outputs.primitives << [i[0], i[1], 200, 300, i[2], i[3]].sprite
}
# Draw a download progress bar...
args.outputs.primitives << [0, 0, 1280, 30, 0, 0, 0, 255].solid
if !args.state.download.nil?
br = args.state.download[:response_read]
total = args.state.download[:response_total]
if total != 0
pct = br.to_f / total.to_f
args.outputs.primitives << [0, 0, 1280 * pct, 30, 0, 0, 255, 255].solid
end
end
end
</code></pre>
<h3 id='----http---web-server---main-rb'>Http - Web Server - main.rb</h3>
<pre><code class="language-ruby"># ./samples/11_http/02_web_server/app/main.rb
def tick args
args.state.port ||= 3000
# by default the embedded webserver runs on port 9001 (the port number is over 9000) and is disabled in a production build
# to enable the http server in a production build, you need to manually start
# the server up:
args.gtk.start_server! port: args.state.port, enable_in_prod: true
args.outputs.background_color = [0, 0, 0]
args.outputs.labels << [640, 600, "Point your web browser at http://localhost:#{args.state.port}/", 10, 1, 255, 255, 255]
args.inputs.http_requests.each { |req|
puts("METHOD: #{req.method}");
puts("URI: #{req.uri}");
puts("HEADERS:");
req.headers.each { |k,v| puts(" #{k}: #{v}") }
if (req.uri == '/')
# headers and body can be nil if you don't care about them.
# If you don't set the Content-Type, it will default to
# "text/html; charset=utf-8".
# Don't set Content-Length; we'll ignore it and calculate it for you
args.state.reqnum += 1
req.respond 200, "<html><head><title>hello</title></head><body><h1>This #{req.method} was request number #{args.state.reqnum}!</h1></body></html>\n", { 'X-DRGTK-header' => 'Powered by DragonRuby!' }
else
req.reject
end
}
end
</code></pre>
<h3 id='----c-extensions---basics---main-rb'>C Extensions - Basics - main.rb</h3>
<pre><code class="language-ruby"># ./samples/12_c_extensions/01_basics/app/main.rb
$gtk.ffi_misc.gtk_dlopen("ext")
include FFI::CExt
def tick args
args.outputs.labels << [640, 500, "mouse.x = #{args.mouse.x.to_i}", 5, 1]
args.outputs.labels << [640, 460, "square(mouse.x) = #{square(args.mouse.x.to_i)}", 5, 1]
args.outputs.labels << [640, 420, "mouse.y = #{args.mouse.y.to_i}", 5, 1]
args.outputs.labels << [640, 380, "square(mouse.y) = #{square(args.mouse.y.to_i)}", 5, 1]
end
</code></pre>
<h3 id='----c-extensions---intermediate---main-rb'>C Extensions - Intermediate - main.rb</h3>
<pre><code class="language-ruby"># ./samples/12_c_extensions/02_intermediate/app/main.rb
$gtk.ffi_misc.gtk_dlopen("ext")
include FFI::RE
def split_words(input)
words = []
last = IntPointer.new
re = re_compile("\\w+")
first = re_matchp(re, input, last)
while first != -1
words << input.slice(first, last.value)
input = input.slice(last.value + first, input.length)
first = re_matchp(re, input, last)
end
words
end
def tick args
args.outputs.labels << [640, 500, split_words("hello, dragonriders!").join(' '), 5, 1]
end
</code></pre>
<h3 id='----c-extensions---native-pixel-arrays---main-rb'>C Extensions - Native Pixel Arrays - main.rb</h3>
<pre><code class="language-ruby"># ./samples/12_c_extensions/03_native_pixel_arrays/app/main.rb
$gtk.ffi_misc.gtk_dlopen("ext")
include FFI::CExt
def tick args
args.state.rotation ||= 0
update_scanner_texture # this calls into a C extension!
# New/changed pixel arrays get uploaded to the GPU before we render
# anything. At that point, they can be scaled, rotated, and otherwise
# used like any other sprite.
w = 100
h = 100
x = (1280 - w) / 2
y = (720 - h) / 2
args.outputs.background_color = [64, 0, 128]
args.outputs.primitives << [x, y, w, h, :scanner, args.state.rotation].sprite
args.state.rotation += 1
args.outputs.primitives << args.gtk.current_framerate_primitives
end
</code></pre>
<h3 id='----path-finding-algorithms---breadth-first-search---main-rb'>Path Finding Algorithms - Breadth First Search - main.rb</h3>
<pre><code class="language-ruby"># ./samples/13_path_finding_algorithms/01_breadth_first_search/app/main.rb
# A visual demonstration of a breadth first search
# Inspired by https://www.redblobgames.com/pathfinding/a-star/introduction.html
# An animation that can respond to user input in real time
# A breadth first search expands in all directions one step at a time
# The frontier is a queue of cells to be expanded from
# The visited hash allows quick lookups of cells that have been expanded from
# The walls hash allows quick lookup of whether a cell is a wall
# The breadth first search starts by adding the red star to the frontier array
# and marking it as visited
# Each step a cell is removed from the front of the frontier array (queue)
# Unless the neighbor is a wall or visited, it is added to the frontier array
# The neighbor is then marked as visited
# The frontier is blue
# Visited cells are light brown
# Walls are camo green
# Even when walls are visited, they will maintain their wall color
# The star can be moved by clicking and dragging
# Walls can be added and removed by clicking and dragging
class BreadthFirstSearch
attr_gtk
def initialize(args)
# Variables to edit the size and appearance of the grid
# Freely customizable to user's liking
args.state.grid.width = 30
args.state.grid.height = 15
args.state.grid.cell_size = 40
# Stores which step of the animation is being rendered
# When the user moves the star or messes with the walls,
# the breadth first search is recalculated up to this step
args.state.anim_steps = 0
# At some step the animation will end,
# and further steps won't change anything (the whole grid will be explored)
# This step is roughly the grid's width * height
# When anim_steps equals max_steps no more calculations will occur
# and the slider will be at the end
args.state.max_steps = args.state.grid.width * args.state.grid.height
# Whether the animation should play or not
# If true, every tick moves anim_steps forward one
# Pressing the stepwise animation buttons will pause the animation
args.state.play = true
# The location of the star and walls of the grid
# They can be modified to have a different initial grid
# Walls are stored in a hash for quick look up when doing the search
args.state.star = [0, 0]
args.state.walls = {
[3, 3] => true,
[3, 4] => true,
[3, 5] => true,
[3, 6] => true,
[3, 7] => true,
[3, 8] => true,
[3, 9] => true,
[3, 10] => true,
[3, 11] => true,
[4, 3] => true,
[4, 4] => true,
[4, 5] => true,
[4, 6] => true,
[4, 7] => true,
[4, 8] => true,
[4, 9] => true,
[4, 10] => true,
[4, 11] => true,
[13, 0] => true,
[13, 1] => true,
[13, 2] => true,
[13, 3] => true,
[13, 4] => true,
[13, 5] => true,
[13, 6] => true,
[13, 7] => true,
[13, 8] => true,
[13, 9] => true,
[13, 10] => true,
[14, 0] => true,
[14, 1] => true,
[14, 2] => true,
[14, 3] => true,
[14, 4] => true,
[14, 5] => true,
[14, 6] => true,
[14, 7] => true,
[14, 8] => true,
[14, 9] => true,
[14, 10] => true,
[21, 8] => true,
[21, 9] => true,
[21, 10] => true,
[21, 11] => true,
[21, 12] => true,
[21, 13] => true,
[21, 14] => true,
[22, 8] => true,
[22, 9] => true,
[22, 10] => true,
[22, 11] => true,
[22, 12] => true,
[22, 13] => true,
[22, 14] => true,
[23, 8] => true,
[23, 9] => true,
[24, 8] => true,
[24, 9] => true,
[25, 8] => true,
[25, 9] => true,
}
# Variables that are used by the breadth first search
# Storing cells that the search has visited, prevents unnecessary steps
# Expanding the frontier of the search in order makes the search expand
# from the center outward
args.state.visited = {}
args.state.frontier = []
# What the user is currently editing on the grid
# Possible values are: :none, :slider, :star, :remove_wall, :add_wall
# We store this value, because we want to remember the value even when
# the user's cursor is no longer over what they're interacting with, but
# they are still clicking down on the mouse.
args.state.click_and_drag = :none
# Store the rects of the buttons that control the animation
# They are here for user customization
# Editing these might require recentering the text inside them
# Those values can be found in the render_button methods
args.state.buttons.left = [450, 600, 50, 50]
args.state.buttons.center = [500, 600, 200, 50]
args.state.buttons.right = [700, 600, 50, 50]
# The variables below are related to the slider
# They allow the user to customize them
# They also give a central location for the render and input methods to get
# information from
# x & y are the coordinates of the leftmost part of the slider line
args.state.slider.x = 400
args.state.slider.y = 675
# This is the width of the line
args.state.slider.w = 360
# This is the offset for the circle
# Allows the center of the circle to be on the line,
# as opposed to the upper right corner
args.state.slider.offset = 20
# This is the spacing between each of the notches on the slider
# Notches are places where the circle can rest on the slider line
# There needs to be a notch for each step before the maximum number of steps
args.state.slider.spacing = args.state.slider.w.to_f / args.state.max_steps.to_f
end
# This method is called every frame/tick
# Every tick, the current state of the search is rendered on the screen,
# User input is processed, and
# The next step in the search is calculated
def tick
render
input
# If animation is playing, and max steps have not been reached
# Move the search a step forward
if state.play && state.anim_steps < state.max_steps
# Variable that tells the program what step to recalculate up to
state.anim_steps += 1
calc
end
end
# Draws everything onto the screen
def render
render_buttons
render_slider
render_background
render_visited
render_frontier
render_walls
render_star
end
# The methods below subdivide the task of drawing everything to the screen
# Draws the buttons that control the animation step and state
def render_buttons
render_left_button
render_center_button
render_right_button
end
# Draws the button which steps the search backward
# Shows the user where to click to move the search backward
def render_left_button
# Draws the gray button, and a black border
# The border separates the buttons visually
outputs.solids << [buttons.left, gray]
outputs.borders << [buttons.left, black]
# Renders an explanatory label in the center of the button
# Explains to the user what the button does
# If the button size is changed, the label might need to be edited as well
# to keep the label in the center of the button
label_x = buttons.left.x + 20
label_y = buttons.left.y + 35
outputs.labels << [label_x, label_y, "<"]
end
def render_center_button
# Draws the gray button, and a black border
# The border separates the buttons visually
outputs.solids << [buttons.center, gray]
outputs.borders << [buttons.center, black]
# Renders an explanatory label in the center of the button
# Explains to the user what the button does
# If the button size is changed, the label might need to be edited as well
# to keep the label in the center of the button
label_x = buttons.center.x + 37
label_y = buttons.center.y + 35
label_text = state.play ? "Pause Animation" : "Play Animation"
outputs.labels << [label_x, label_y, label_text]
end
def render_right_button
# Draws the gray button, and a black border
# The border separates the buttons visually
outputs.solids << [buttons.right, gray]
outputs.borders << [buttons.right, black]
# Renders an explanatory label in the center of the button
# Explains to the user what the button does
label_x = buttons.right.x + 20
label_y = buttons.right.y + 35
outputs.labels << [label_x, label_y, ">"]
end
# Draws the slider so the user can move it and see the progress of the search
def render_slider
# Using primitives hides the line under the white circle of the slider
# Draws the line
outputs.primitives << [slider.x, slider.y, slider.x + slider.w, slider.y].line
# The circle needs to be offset so that the center of the circle
# overlaps the line instead of the upper right corner of the circle
# The circle's x value is also moved based on the current seach step
circle_x = (slider.x - slider.offset) + (state.anim_steps * slider.spacing)
circle_y = (slider.y - slider.offset)
circle_rect = [circle_x, circle_y, 37, 37]
outputs.primitives << [circle_rect, 'circle-white.png'].sprite
end
# Draws what the grid looks like with nothing on it
def render_background
render_unvisited
render_grid_lines
end
# Draws a rectangle the size of the entire grid to represent unvisited cells
def render_unvisited
outputs.solids << [scale_up([0, 0, grid.width, grid.height]), unvisited_color]
end
# Draws grid lines to show the division of the grid into cells
def render_grid_lines
for x in 0..grid.width
outputs.lines << vertical_line(x)
end
for y in 0..grid.height
outputs.lines << horizontal_line(y)
end
end
# Easy way to draw vertical lines given an index
def vertical_line column
scale_up([column, 0, column, grid.height])
end
# Easy way to draw horizontal lines given an index
def horizontal_line row
scale_up([0, row, grid.width, row])
end
# Draws the area that is going to be searched from
# The frontier is the most outward parts of the search
def render_frontier
outputs.solids << state.frontier.map do |cell|
[scale_up([cell.x, cell.y]), frontier_color]
end
end
# Draws the walls
def render_walls
outputs.solids << state.walls.map do |wall|
[scale_up([wall.x, wall.y]), wall_color]
end
end
# Renders cells that have been searched in the appropriate color
def render_visited
outputs.solids << state.visited.map do |cell|
[scale_up([cell.x, cell.y]), visited_color]
end
end
# Renders the star
def render_star
outputs.sprites << [scale_up(state.star), 'star.png']
end
# In code, the cells are represented as 1x1 rectangles
# When drawn, the cells are larger than 1x1 rectangles
# This method is used to scale up cells, and lines
# Objects are scaled up according to the grid.cell_size variable
# This allows for easy customization of the visual scale of the grid
def scale_up(cell)
# Prevents the original value of cell from being edited
cell = cell.clone
# If cell is just an x and y coordinate
if cell.size == 2
# Add a width and height of 1
cell << 1
cell << 1
end
# Scale all the values up
cell.map! { |value| value * grid.cell_size }
# Returns the scaled up cell
cell
end
# This method processes user input every tick
# This method allows the user to use the buttons, slider, and edit the grid
# There are 2 types of input:
# Button Input
# Click and Drag Input
#
# Button Input is used for the backward step and forward step buttons
# Input is detected by mouse up within the bounds of the rect
#
# Click and Drag Input is used for moving the star, adding walls,
# removing walls, and the slider
#
# When the mouse is down on the star, the click_and_drag variable is set to :star
# While click_and_drag equals :star, the cursor's position is used to calculate the
# appropriate drag behavior
#
# When the mouse goes up click_and_drag is set to :none
#
# A variable has to be used because the star has to continue being edited even
# when the cursor is no longer over the star
#
# Similar things occur for the other Click and Drag inputs
def input
# Checks whether any of the buttons are being clicked
input_buttons
# The detection and processing of click and drag inputs are separate
# The program has to remember that the user is dragging an object
# even when the mouse is no longer over that object
detect_click_and_drag
process_click_and_drag
end
# Detects and Process input for each button
def input_buttons
input_left_button
input_center_button
input_next_step_button
end
# Checks if the previous step button is clicked
# If it is, it pauses the animation and moves the search one step backward
def input_left_button
if left_button_clicked?
state.play = false
state.anim_steps -= 1
recalculate
end
end
# Controls the play/pause button
# Inverses whether the animation is playing or not when clicked
def input_center_button
if center_button_clicked? or inputs.keyboard.key_down.space
state.play = !state.play
end
end
# Checks if the next step button is clicked
# If it is, it pauses the animation and moves the search one step forward
def input_next_step_button
if right_button_clicked?
state.play = false
state.anim_steps += 1
calc
end
end
# Determines what the user is editing and stores the value
# Storing the value allows the user to continue the same edit as long as the
# mouse left click is held
def detect_click_and_drag
if inputs.mouse.up
state.click_and_drag = :none
elsif star_clicked?
state.click_and_drag = :star
elsif wall_clicked?
state.click_and_drag = :remove_wall
elsif grid_clicked?
state.click_and_drag = :add_wall
elsif slider_clicked?
state.click_and_drag = :slider
end
end
# Processes click and drag based on what the user is currently dragging
def process_click_and_drag
if state.click_and_drag == :star
input_star
elsif state.click_and_drag == :remove_wall
input_remove_wall
elsif state.click_and_drag == :add_wall
input_add_wall
elsif state.click_and_drag == :slider
input_slider
end
end
# Moves the star to the grid closest to the mouse
# Only recalculates the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def input_star
old_star = state.star.clone
state.star = cell_closest_to_mouse
unless old_star == state.star
recalculate
end
end
# Removes walls that are under the cursor
def input_remove_wall
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if mouse_inside_grid?
if state.walls.has_key?(cell_closest_to_mouse)
state.walls.delete(cell_closest_to_mouse)
recalculate
end
end
end
# Adds walls at cells under the cursor
def input_add_wall
if mouse_inside_grid?
unless state.walls.has_key?(cell_closest_to_mouse)
state.walls[cell_closest_to_mouse] = true
recalculate
end
end
end
# This method is called when the user is editing the slider
# It pauses the animation and moves the white circle to the closest integer point
# on the slider
# Changes the step of the search to be animated
def input_slider
state.play = false
mouse_x = inputs.mouse.point.x
# Bounds the mouse_x to the closest x value on the slider line
mouse_x = slider.x if mouse_x < slider.x
mouse_x = slider.x + slider.w if mouse_x > slider.x + slider.w
# Sets the current search step to the one represented by the mouse x value
# The slider's circle moves due to the render_slider method using anim_steps
state.anim_steps = ((mouse_x - slider.x) / slider.spacing).to_i
recalculate
end
# Whenever the user edits the grid,
# The search has to be recalculated upto the current step
# with the current grid as the initial state of the grid
def recalculate
# Resets the search
state.frontier = []
state.visited = {}
# Moves the animation forward one step at a time
state.anim_steps.times { calc }
end
# This method moves the search forward one step
# When the animation is playing it is called every tick
# And called whenever the current step of the animation needs to be recalculated
# Moves the search forward one step
# Parameter called_from_tick is true if it is called from the tick method
# It is false when the search is being recalculated after user editing the grid
def calc
# The setup to the search
# Runs once when the there is no frontier or visited cells
if state.frontier.empty? && state.visited.empty?
state.frontier << state.star
state.visited[state.star] = true
end
# A step in the search
unless state.frontier.empty?
# Takes the next frontier cell
new_frontier = state.frontier.shift
# For each of its neighbors
adjacent_neighbors(new_frontier).each do |neighbor|
# That have not been visited and are not walls
unless state.visited.has_key?(neighbor) || state.walls.has_key?(neighbor)
# Add them to the frontier and mark them as visited
state.frontier << neighbor
state.visited[neighbor] = true
end
end
end
end
# Returns a list of adjacent cells
# Used to determine what the next cells to be added to the frontier are
def adjacent_neighbors(cell)
neighbors = []
neighbors << [cell.x, cell.y + 1] unless cell.y == grid.height - 1
neighbors << [cell.x + 1, cell.y] unless cell.x == grid.width - 1
neighbors << [cell.x, cell.y - 1] unless cell.y == 0
neighbors << [cell.x - 1, cell.y] unless cell.x == 0
neighbors
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse helps with this
def cell_closest_to_mouse
# Closest cell to the mouse
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Bound x and y to the grid
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
# These methods detect when the buttons are clicked
def left_button_clicked?
inputs.mouse.up && inputs.mouse.point.inside_rect?(buttons.left)
end
def center_button_clicked?
inputs.mouse.up && inputs.mouse.point.inside_rect?(buttons.center)
end
def right_button_clicked?
inputs.mouse.up && inputs.mouse.point.inside_rect?(buttons.right)
end
# Signal that the user is going to be moving the slider
# Is the mouse down on the circle of the slider?
def slider_clicked?
circle_x = (slider.x - slider.offset) + (state.anim_steps * slider.spacing)
circle_y = (slider.y - slider.offset)
circle_rect = [circle_x, circle_y, 37, 37]
inputs.mouse.down && inputs.mouse.point.inside_rect?(circle_rect)
end
# Signal that the user is going to be moving the star
def star_clicked?
inputs.mouse.down && inputs.mouse.point.inside_rect?(scale_up(state.star))
end
# Signal that the user is going to be removing walls
def wall_clicked?
inputs.mouse.down && mouse_inside_a_wall?
end
# Signal that the user is going to be adding walls
def grid_clicked?
inputs.mouse.down && mouse_inside_grid?
end
# Returns whether the mouse is inside of a wall
# Part of the condition that checks whether the user is removing a wall
def mouse_inside_a_wall?
state.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(scale_up([wall.x, wall.y]))
end
false
end
# Returns whether the mouse is inside of a grid
# Part of the condition that checks whether the user is adding a wall
def mouse_inside_grid?
inputs.mouse.point.inside_rect?(scale_up([0, 0, grid.width, grid.height]))
end
# These methods provide handy aliases to colors
# Light brown
def unvisited_color
[221, 212, 213]
end
# Black
def grid_line_color
[255, 255, 255]
end
# Dark Brown
def visited_color
[204, 191, 179]
end
# Blue
def frontier_color
[103, 136, 204]
end
# Camo Green
def wall_color
[134, 134, 120]
end
# Button Background
def gray
[190, 190, 190]
end
# Button Outline
def black
[0, 0, 0]
end
# These methods make the code more concise
def grid
state.grid
end
def buttons
state.buttons
end
def slider
state.slider
end
end
# Method that is called by DragonRuby periodically
# Used for updating animations and calculations
def tick args
# Pressing r will reset the application
if args.inputs.keyboard.key_down.r
args.gtk.reset
reset
return
end
# Every tick, new args are passed, and the Breadth First Search tick is called
$breadth_first_search ||= BreadthFirstSearch.new(args)
$breadth_first_search.args = args
$breadth_first_search.tick
end
def reset
$breadth_first_search = nil
end
</code></pre>
<h3 id='----path-finding-algorithms---detailed-breadth-first-search---main-rb'>Path Finding Algorithms - Detailed Breadth First Search - main.rb</h3>
<pre><code class="language-ruby"># ./samples/13_path_finding_algorithms/02_detailed_breadth_first_search/app/main.rb
# A visual demonstration of a breadth first search
# Inspired by https://www.redblobgames.com/pathfinding/a-star/introduction.html
# An animation that can respond to user input in real time
# A breadth first search expands in all directions one step at a time
# The frontier is a queue of cells to be expanded from
# The visited hash allows quick lookups of cells that have been expanded from
# The walls hash allows quick lookup of whether a cell is a wall
# The breadth first search starts by adding the red star to the frontier array
# and marking it as visited
# Each step a cell is removed from the front of the frontier array (queue)
# Unless the neighbor is a wall or visited, it is added to the frontier array
# The neighbor is then marked as visited
# The frontier is blue
# Visited cells are light brown
# Walls are camo green
# Even when walls are visited, they will maintain their wall color
# This search numbers the order in which new cells are explored
# The next cell from where the search will continue is highlighted yellow
# And the cells that will be considered for expansion are in semi-transparent green
# The star can be moved by clicking and dragging
# Walls can be added and removed by clicking and dragging
class DetailedBreadthFirstSearch
attr_gtk
def initialize(args)
# Variables to edit the size and appearance of the grid
# Freely customizable to user's liking
args.state.grid.width = 9
args.state.grid.height = 4
args.state.grid.cell_size = 90
# Stores which step of the animation is being rendered
# When the user moves the star or messes with the walls,
# the breadth first search is recalculated up to this step
args.state.anim_steps = 0
# At some step the animation will end,
# and further steps won't change anything (the whole grid will be explored)
# This step is roughly the grid's width * height
# When anim_steps equals max_steps no more calculations will occur
# and the slider will be at the end
args.state.max_steps = args.state.grid.width * args.state.grid.height
# The location of the star and walls of the grid
# They can be modified to have a different initial grid
# Walls are stored in a hash for quick look up when doing the search
args.state.star = [3, 2]
args.state.walls = {}
# Variables that are used by the breadth first search
# Storing cells that the search has visited, prevents unnecessary steps
# Expanding the frontier of the search in order makes the search expand
# from the center outward
args.state.visited = {}
args.state.frontier = []
args.state.cell_numbers = []
# What the user is currently editing on the grid
# Possible values are: :none, :slider, :star, :remove_wall, :add_wall
# We store this value, because we want to remember the value even when
# the user's cursor is no longer over what they're interacting with, but
# they are still clicking down on the mouse.
args.state.click_and_drag = :none
# The x, y, w, h values for the buttons
# Allow easy movement of the buttons location
# A centralized location to get values to detect input and draw the buttons
# Editing these values might mean needing to edit the label offsets
# which can be found in the appropriate render button methods
args.state.buttons.left = [450, 600, 160, 50]
args.state.buttons.right = [610, 600, 160, 50]
# The variables below are related to the slider
# They allow the user to customize them
# They also give a central location for the render and input methods to get
# information from
# x & y are the coordinates of the leftmost part of the slider line
args.state.slider.x = 400
args.state.slider.y = 675
# This is the width of the line
args.state.slider.w = 360
# This is the offset for the circle
# Allows the center of the circle to be on the line,
# as opposed to the upper right corner
args.state.slider.offset = 20
# This is the spacing between each of the notches on the slider
# Notches are places where the circle can rest on the slider line
# There needs to be a notch for each step before the maximum number of steps
args.state.slider.spacing = args.state.slider.w.to_f / args.state.max_steps.to_f
end
# This method is called every frame/tick
# Every tick, the current state of the search is rendered on the screen,
# User input is processed, and
def tick
render
input
end
# This method is called from tick and renders everything every tick
def render
render_buttons
render_slider
render_background
render_visited
render_frontier
render_walls
render_star
render_highlights
render_cell_numbers
end
# The methods below subdivide the task of drawing everything to the screen
# Draws the buttons that move the search backward or forward
# These buttons are rendered so the user knows where to click to move the search
def render_buttons
render_left_button
render_right_button
end
# Renders the button which steps the search backward
# Shows the user where to click to move the search backward
def render_left_button
# Draws the gray button, and a black border
# The border separates the buttons visually
outputs.solids << [buttons.left, gray]
outputs.borders << [buttons.left, black]
# Renders an explanatory label in the center of the button
# Explains to the user what the button does
label_x = buttons.left.x + 05
label_y = buttons.left.y + 35
outputs.labels << [label_x, label_y, "< Step backward"]
end
# Renders the button which steps the search forward
# Shows the user where to click to move the search forward
def render_right_button
# Draws the gray button, and a black border
# The border separates the buttons visually
outputs.solids << [buttons.right, gray]
outputs.borders << [buttons.right, black]
# Renders an explanatory label in the center of the button
# Explains to the user what the button does
label_x = buttons.right.x + 10
label_y = buttons.right.y + 35
outputs.labels << [label_x, label_y, "Step forward >"]
end
# Draws the slider so the user can move it and see the progress of the search
def render_slider
# Using primitives hides the line under the white circle of the slider
# Draws the line
outputs.primitives << [slider.x, slider.y, slider.x + slider.w, slider.y].line
# The circle needs to be offset so that the center of the circle
# overlaps the line instead of the upper right corner of the circle
# The circle's x value is also moved based on the current seach step
circle_x = (slider.x - slider.offset) + (state.anim_steps * slider.spacing)
circle_y = (slider.y - slider.offset)
circle_rect = [circle_x, circle_y, 37, 37]
outputs.primitives << [circle_rect, 'circle-white.png'].sprite
end
# Draws what the grid looks like with nothing on it
# Which is a bunch of unvisited cells
# Drawn first so other things can draw on top of it
def render_background
render_unvisited
# The grid lines make the cells appear separate
render_grid_lines
end
# Draws a rectangle the size of the entire grid to represent unvisited cells
# Unvisited cells are the default cell
def render_unvisited
background = [0, 0, grid.width, grid.height]
outputs.solids << [scale_up(background), unvisited_color]
end
# Draws grid lines to show the division of the grid into cells
def render_grid_lines
for x in 0..grid.width
outputs.lines << [scale_up(vertical_line(x)), grid_line_color]
end
for y in 0..grid.height
outputs.lines << [scale_up(horizontal_line(y)), grid_line_color]
end
end
# Easy way to get a vertical line given an index
def vertical_line column
[column, 0, column, grid.height]
end
# Easy way to get a horizontal line given an index
def horizontal_line row
[0, row, grid.width, row]
end
# Draws the area that is going to be searched from
# The frontier is the most outward parts of the search
def render_frontier
state.frontier.each do |cell|
outputs.solids << [scale_up(cell), frontier_color]
end
end
# Draws the walls
def render_walls
state.walls.each_key do |wall|
outputs.solids << [scale_up(wall), wall_color]
end
end
# Renders cells that have been searched in the appropriate color
def render_visited
state.visited.each_key do |cell|
outputs.solids << [scale_up(cell), visited_color]
end
end
# Renders the star
def render_star
outputs.sprites << [scale_up(state.star), 'star.png']
end
# Cells have a number rendered in them based on when they were explored
# This is based off of their index in the cell_numbers array
# Cells are added to this array the same time they are added to the frontier array
def render_cell_numbers
state.cell_numbers.each_with_index do |cell, index|
# Math that approx centers the number in the cell
label_x = (cell.x * grid.cell_size) + grid.cell_size / 2 - 5
label_y = (cell.y * grid.cell_size) + (grid.cell_size / 2) + 5
outputs.labels << [label_x, label_y, (index + 1).to_s]
end
end
# The next frontier to be expanded is highlighted yellow
# Its adjacent non-wall neighbors have their border highlighted green
# This is to show the user how the search expands
def render_highlights
return if state.frontier.empty?
# Highlight the next frontier to be expanded yellow
next_frontier = state.frontier[0]
outputs.solids << [scale_up(next_frontier), highlighter_yellow]
# Neighbors have a semi-transparent green layer over them
# Unless the neighbor is a wall
adjacent_neighbors(next_frontier).each do |neighbor|
unless state.walls.has_key?(neighbor)
outputs.solids << [scale_up(neighbor), highlighter_green, 70]
end
end
end
# Cell Size is used when rendering to allow the grid to be scaled up or down
# Cells in the frontier array and visited hash and walls hash are stored as x & y
# Scaling up cells and lines when rendering allows omitting of width and height
def scale_up(cell)
# Prevents the original value of cell from being edited
cell = cell.clone
# If cell is just an x and y coordinate
if cell.size == 2
# Add a width and height of 1
cell << 1
cell << 1
end
# Scale all the values up
cell.map! { |value| value * grid.cell_size }
# Returns the scaled up cell
cell
end
# This method processes user input every tick
# This method allows the user to use the buttons, slider, and edit the grid
# There are 2 types of input:
# Button Input
# Click and Drag Input
#
# Button Input is used for the backward step and forward step buttons
# Input is detected by mouse up within the bounds of the rect
#
# Click and Drag Input is used for moving the star, adding walls,
# removing walls, and the slider
#
# When the mouse is down on the star, the click_and_drag variable is set to :star
# While click_and_drag equals :star, the cursor's position is used to calculate the
# appropriate drag behavior
#
# When the mouse goes up click_and_drag is set to :none
#
# A variable has to be used because the star has to continue being edited even
# when the cursor is no longer over the star
#
# Similar things occur for the other Click and Drag inputs
def input
# Processes inputs for the buttons
input_buttons
# Detects which if any click and drag input is occurring
detect_click_and_drag
# Does the appropriate click and drag input based on the click_and_drag variable
process_click_and_drag
end
# Detects and Process input for each button
def input_buttons
input_left_button
input_right_button
end
# Checks if the previous step button is clicked
# If it is, it pauses the animation and moves the search one step backward
def input_left_button
if left_button_clicked?
unless state.anim_steps == 0
state.anim_steps -= 1
recalculate
end
end
end
# Checks if the next step button is clicked
# If it is, it pauses the animation and moves the search one step forward
def input_right_button
if right_button_clicked?
unless state.anim_steps == state.max_steps
state.anim_steps += 1
# Although normally recalculate would be called here
# because the right button only moves the search forward
# We can just do that
calc
end
end
end
# Whenever the user edits the grid,
# The search has to be recalculated upto the current step
def recalculate
# Resets the search
state.frontier = []
state.visited = {}
state.cell_numbers = []
# Moves the animation forward one step at a time
state.anim_steps.times { calc }
end
# Determines what the user is clicking and planning on dragging
# Click and drag input is initiated by a click on the appropriate item
# and ended by mouse up
# Storing the value allows the user to continue the same edit as long as the
# mouse left click is held
def detect_click_and_drag
if inputs.mouse.up
state.click_and_drag = :none
elsif star_clicked?
state.click_and_drag = :star
elsif wall_clicked?
state.click_and_drag = :remove_wall
elsif grid_clicked?
state.click_and_drag = :add_wall
elsif slider_clicked?
state.click_and_drag = :slider
end
end
# Processes input based on what the user is currently dragging
def process_click_and_drag
if state.click_and_drag == :slider
input_slider
elsif state.click_and_drag == :star
input_star
elsif state.click_and_drag == :remove_wall
input_remove_wall
elsif state.click_and_drag == :add_wall
input_add_wall
end
end
# This method is called when the user is dragging the slider
# It moves the current animation step to the point represented by the slider
def input_slider
mouse_x = inputs.mouse.point.x
# Bounds the mouse_x to the closest x value on the slider line
mouse_x = slider.x if mouse_x < slider.x
mouse_x = slider.x + slider.w if mouse_x > slider.x + slider.w
# Sets the current search step to the one represented by the mouse x value
# The slider's circle moves due to the render_slider method using anim_steps
state.anim_steps = ((mouse_x - slider.x) / slider.spacing).to_i
recalculate
end
# Moves the star to the grid closest to the mouse
# Only recalculates the search if the star changes position
# Called whenever the user is dragging the star
def input_star
old_star = state.star.clone
state.star = cell_closest_to_mouse
unless old_star == state.star
recalculate
end
end
# Removes walls that are under the cursor
def input_remove_wall
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if mouse_inside_grid?
if state.walls.has_key?(cell_closest_to_mouse)
state.walls.delete(cell_closest_to_mouse)
recalculate
end
end
end
# Adds walls at cells under the cursor
def input_add_wall
# Adds a wall to the hash
# We can use the grid closest to mouse, because the cursor is inside the grid
if mouse_inside_grid?
unless state.walls.has_key?(cell_closest_to_mouse)
state.walls[cell_closest_to_mouse] = true
recalculate
end
end
end
# This method moves the search forward one step
# When the animation is playing it is called every tick
# And called whenever the current step of the animation needs to be recalculated
# Moves the search forward one step
# Parameter called_from_tick is true if it is called from the tick method
# It is false when the search is being recalculated after user editing the grid
def calc
# The setup to the search
# Runs once when the there is no frontier or visited cells
if state.frontier.empty? && state.visited.empty?
state.frontier << state.star
state.visited[state.star] = true
end
# A step in the search
unless state.frontier.empty?
# Takes the next frontier cell
new_frontier = state.frontier.shift
# For each of its neighbors
adjacent_neighbors(new_frontier).each do |neighbor|
# That have not been visited and are not walls
unless state.visited.has_key?(neighbor) || state.walls.has_key?(neighbor)
# Add them to the frontier and mark them as visited
state.frontier << neighbor
state.visited[neighbor] = true
# Also assign them a frontier number
state.cell_numbers << neighbor
end
end
end
end
# Returns a list of adjacent cells
# Used to determine what the next cells to be added to the frontier are
def adjacent_neighbors cell
neighbors = []
neighbors << [cell.x, cell.y + 1] unless cell.y == grid.height - 1
neighbors << [cell.x + 1, cell.y] unless cell.x == grid.width - 1
neighbors << [cell.x, cell.y - 1] unless cell.y == 0
neighbors << [cell.x - 1, cell.y] unless cell.x == 0
neighbors
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the grid closest to the mouse helps with this
def cell_closest_to_mouse
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
[x, y]
end
# These methods detect when the buttons are clicked
def left_button_clicked?
(inputs.mouse.up && inputs.mouse.point.inside_rect?(buttons.left)) || inputs.keyboard.key_up.left
end
def right_button_clicked?
(inputs.mouse.up && inputs.mouse.point.inside_rect?(buttons.right)) || inputs.keyboard.key_up.right
end
# Signal that the user is going to be moving the slider
def slider_clicked?
circle_x = (slider.x - slider.offset) + (state.anim_steps * slider.spacing)
circle_y = (slider.y - slider.offset)
circle_rect = [circle_x, circle_y, 37, 37]
inputs.mouse.down && inputs.mouse.point.inside_rect?(circle_rect)
end
# Signal that the user is going to be moving the star
def star_clicked?
inputs.mouse.down && inputs.mouse.point.inside_rect?(scale_up(state.star))
end
# Signal that the user is going to be removing walls
def wall_clicked?
inputs.mouse.down && mouse_inside_a_wall?
end
# Signal that the user is going to be adding walls
def grid_clicked?
inputs.mouse.down && mouse_inside_grid?
end
# Returns whether the mouse is inside of a wall
# Part of the condition that checks whether the user is removing a wall
def mouse_inside_a_wall?
state.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(scale_up(wall))
end
false
end
# Returns whether the mouse is inside of a grid
# Part of the condition that checks whether the user is adding a wall
def mouse_inside_grid?
inputs.mouse.point.inside_rect?(scale_up([0, 0, grid.width, grid.height]))
end
# These methods provide handy aliases to colors
# Light brown
def unvisited_color
[221, 212, 213]
end
# Black
def grid_line_color
[255, 255, 255]
end
# Dark Brown
def visited_color
[204, 191, 179]
end
# Blue
def frontier_color
[103, 136, 204]
end
# Camo Green
def wall_color
[134, 134, 120]
end
# Next frontier to be expanded
def highlighter_yellow
[214, 231, 125]
end
# The neighbors of the next frontier to be expanded
def highlighter_green
[65, 191, 127]
end
# Button background
def gray
[190, 190, 190]
end
# Button outline
def black
[0, 0, 0]
end
# These methods make the code more concise
def grid
state.grid
end
def buttons
state.buttons
end
def slider
state.slider
end
end
def tick args
# Pressing r resets the program
if args.inputs.keyboard.key_down.r
args.gtk.reset
reset
return
end
$detailed_breadth_first_search ||= DetailedBreadthFirstSearch.new(args)
$detailed_breadth_first_search.args = args
$detailed_breadth_first_search.tick
end
def reset
$detailed_breadth_first_search = nil
end
</code></pre>
<h3 id='----path-finding-algorithms---breadcrumbs---main-rb'>Path Finding Algorithms - Breadcrumbs - main.rb</h3>
<pre><code class="language-ruby"># ./samples/13_path_finding_algorithms/03_breadcrumbs/app/main.rb
class Breadcrumbs
attr_gtk
# This method is called every frame/tick
# Every tick, the current state of the search is rendered on the screen,
# User input is processed, and
# The next step in the search is calculated
def tick
defaults
# If the grid has not been searched
if search.came_from.empty?
calc
# Calc Path
end
render
input
end
def defaults
# Variables to edit the size and appearance of the grid
# Freely customizable to user's liking
grid.width ||= 30
grid.height ||= 15
grid.cell_size ||= 40
grid.rect ||= [0, 0, grid.width, grid.height]
# The location of the star and walls of the grid
# They can be modified to have a different initial grid
# Walls are stored in a hash for quick look up when doing the search
grid.star ||= [2, 8]
grid.target ||= [10, 5]
grid.walls ||= {
[3, 3] => true,
[3, 4] => true,
[3, 5] => true,
[3, 6] => true,
[3, 7] => true,
[3, 8] => true,
[3, 9] => true,
[3, 10] => true,
[3, 11] => true,
[4, 3] => true,
[4, 4] => true,
[4, 5] => true,
[4, 6] => true,
[4, 7] => true,
[4, 8] => true,
[4, 9] => true,
[4, 10] => true,
[4, 11] => true,
[13, 0] => true,
[13, 1] => true,
[13, 2] => true,
[13, 3] => true,
[13, 4] => true,
[13, 5] => true,
[13, 6] => true,
[13, 7] => true,
[13, 8] => true,
[13, 9] => true,
[13, 10] => true,
[14, 0] => true,
[14, 1] => true,
[14, 2] => true,
[14, 3] => true,
[14, 4] => true,
[14, 5] => true,
[14, 6] => true,
[14, 7] => true,
[14, 8] => true,
[14, 9] => true,
[14, 10] => true,
[21, 8] => true,
[21, 9] => true,
[21, 10] => true,
[21, 11] => true,
[21, 12] => true,
[21, 13] => true,
[21, 14] => true,
[22, 8] => true,
[22, 9] => true,
[22, 10] => true,
[22, 11] => true,
[22, 12] => true,
[22, 13] => true,
[22, 14] => true,
[23, 8] => true,
[23, 9] => true,
[24, 8] => true,
[24, 9] => true,
[25, 8] => true,
[25, 9] => true,
}
# Variables that are used by the breadth first search
# Storing cells that the search has visited, prevents unnecessary steps
# Expanding the frontier of the search in order makes the search expand
# from the center outward
# The cells from which the search is to expand
search.frontier ||= []
# A hash of where each cell was expanded from
# The key is a cell, and the value is the cell it came from
search.came_from ||= {}
# Cells that are part of the path from the target to the star
search.path ||= {}
# What the user is currently editing on the grid
# We store this value, because we want to remember the value even when
# the user's cursor is no longer over what they're interacting with, but
# they are still clicking down on the mouse.
state.current_input ||= :none
end
def calc
# Setup the search to start from the star
search.frontier << grid.star
search.came_from[grid.star] = nil
# Until there are no more cells to expand from
until search.frontier.empty?
# Takes the next frontier cell
new_frontier = search.frontier.shift
# For each of its neighbors
adjacent_neighbors(new_frontier).each do |neighbor|
# That have not been visited and are not walls
unless search.came_from.has_key?(neighbor) || grid.walls.has_key?(neighbor)
# Add them to the frontier and mark them as visited in the first grid
# Unless the target has been visited
# Add the neighbor to the frontier and remember which cell it came from
search.frontier << neighbor
search.came_from[neighbor] = new_frontier
end
end
end
end
# Draws everything onto the screen
def render
render_background
# render_heat_map
render_walls
# render_path
# render_labels
render_arrows
render_star
render_target
unless grid.walls.has_key?(grid.target)
render_trail
end
end
def render_trail(current_cell=grid.target)
return if current_cell == grid.star
parent_cell = search.came_from[current_cell]
if current_cell && parent_cell
outputs.lines << [(current_cell.x + 0.5) * grid.cell_size, (current_cell.y + 0.5) * grid.cell_size,
(parent_cell.x + 0.5) * grid.cell_size, (parent_cell.y + 0.5) * grid.cell_size, purple]
end
render_trail(parent_cell)
end
def render_arrows
search.came_from.each do |child, parent|
if parent && child
arrow_cell = [(child.x + parent.x) / 2, (child.y + parent.y) / 2]
if parent.x > child.x # If the parent cell is to the right of the child cell
outputs.sprites << [scale_up(arrow_cell), 'arrow.png', 0] # Point the arrow to the right
elsif parent.x < child.x # If the parent cell is to the right of the child cell
outputs.sprites << [scale_up(arrow_cell), 'arrow.png', 180] # Point the arrow to the right
elsif parent.y > child.y # If the parent cell is to the right of the child cell
outputs.sprites << [scale_up(arrow_cell), 'arrow.png', 90] # Point the arrow to the right
elsif parent.y < child.y # If the parent cell is to the right of the child cell
outputs.sprites << [scale_up(arrow_cell), 'arrow.png', 270] # Point the arrow to the right
end
end
end
end
# The methods below subdivide the task of drawing everything to the screen
# Draws what the grid looks like with nothing on it
def render_background
render_unvisited
render_grid_lines
end
# Draws both grids
def render_unvisited
outputs.solids << [scale_up(grid.rect), unvisited_color]
end
# Draws grid lines to show the division of the grid into cells
def render_grid_lines
for x in 0..grid.width
outputs.lines << vertical_line(x)
end
for y in 0..grid.height
outputs.lines << horizontal_line(y)
end
end
# Easy way to draw vertical lines given an index
def vertical_line column
scale_up([column, 0, column, grid.height])
end
# Easy way to draw horizontal lines given an index
def horizontal_line row
scale_up([0, row, grid.width, row])
end
# Draws the walls on both grids
def render_walls
grid.walls.each_key do |wall|
outputs.solids << [scale_up(wall), wall_color]
end
end
# Renders the star on both grids
def render_star
outputs.sprites << [scale_up(grid.star), 'star.png']
end
# Renders the target on both grids
def render_target
outputs.sprites << [scale_up(grid.target), 'target.png']
end
# Labels the grids
def render_labels
outputs.labels << [200, 625, "Without early exit"]
end
# Renders the path based off of the search.path hash
def render_path
# If the star and target are disconnected there will only be one path
# The path should not render in that case
unless search.path.size == 1
search.path.each_key do | cell |
# Renders path on both grids
outputs.solids << [scale_up(cell), path_color]
end
end
end
# Calculates the path from the target to the star after the search is over
# Relies on the came_from hash
# Fills the search.path hash, which is later rendered on screen
def calc_path
endpoint = grid.target
while endpoint
search.path[endpoint] = true
endpoint = search.came_from[endpoint]
end
end
# In code, the cells are represented as 1x1 rectangles
# When drawn, the cells are larger than 1x1 rectangles
# This method is used to scale up cells, and lines
# Objects are scaled up according to the grid.cell_size variable
# This allows for easy customization of the visual scale of the grid
def scale_up(cell)
# Prevents the original value of cell from being edited
cell = cell.clone
# If cell is just an x and y coordinate
if cell.size == 2
# Add a width and height of 1
cell << 1
cell << 1
end
# Scale all the values up
cell.map! { |value| value * grid.cell_size }
# Returns the scaled up cell
cell
end
# This method processes user input every tick
# Any method with "1" is related to the first grid
# Any method with "2" is related to the second grid
def input
# The program has to remember that the user is dragging an object
# even when the mouse is no longer over that object
# So detecting input and processing input is separate
# detect_input
# process_input
if inputs.mouse.up
state.current_input = :none
elsif star_clicked?
state.current_input = :star
end
if mouse_inside_grid?
unless grid.target == cell_closest_to_mouse
grid.target = cell_closest_to_mouse
end
if state.current_input == :star
unless grid.star == cell_closest_to_mouse
grid.star = cell_closest_to_mouse
end
end
end
end
# Determines what the user is editing and stores the value
# Storing the value allows the user to continue the same edit as long as the
# mouse left click is held
def detect_input
# When the mouse is up, nothing is being edited
if inputs.mouse.up
state.current_input = :none
# When the star in the no second grid is clicked
elsif star_clicked?
state.current_input = :star
# When the target in the no second grid is clicked
elsif target_clicked?
state.current_input = :target
# When a wall in the first grid is clicked
elsif wall_clicked?
state.current_input = :remove_wall
# When the first grid is clicked
elsif grid_clicked?
state.current_input = :add_wall
end
end
# Processes click and drag based on what the user is currently dragging
def process_input
if state.current_input == :star
input_star
elsif state.current_input == :target
input_target
elsif state.current_input == :remove_wall
input_remove_wall
elsif state.current_input == :add_wall
input_add_wall
end
end
# Moves the star to the cell closest to the mouse in the first grid
# Only resets the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def input_star
old_star = grid.star.clone
grid.star = cell_closest_to_mouse
unless old_star == grid.star
reset_search
end
end
# Moves the target to the grid closest to the mouse in the first grid
# Only reset_searchs the search if the target changes position
# Called whenever the user is editing the target (puts mouse down on target)
def input_target
old_target = grid.target.clone
grid.target = cell_closest_to_mouse
unless old_target == grid.target
reset_search
end
end
# Removes walls in the first grid that are under the cursor
def input_remove_wall
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if mouse_inside_grid?
if grid.walls.has_key?(cell_closest_to_mouse)
grid.walls.delete(cell_closest_to_mouse)
reset_search
end
end
end
# Adds a wall in the first grid in the cell the mouse is over
def input_add_wall
if mouse_inside_grid?
unless grid.walls.has_key?(cell_closest_to_mouse)
grid.walls[cell_closest_to_mouse] = true
reset_search
end
end
end
# Whenever the user edits the grid,
# The search has to be reset_searchd upto the current step
# with the current grid as the initial state of the grid
def reset_search
# Reset_Searchs the search
search.frontier = []
search.came_from = {}
search.path = {}
end
# Returns a list of adjacent cells
# Used to determine what the next cells to be added to the frontier are
def adjacent_neighbors(cell)
neighbors = []
# Gets all the valid neighbors into the array
# From southern neighbor, clockwise
neighbors << [cell.x, cell.y - 1] unless cell.y == 0
neighbors << [cell.x - 1, cell.y] unless cell.x == 0
neighbors << [cell.x, cell.y + 1] unless cell.y == grid.height - 1
neighbors << [cell.x + 1, cell.y] unless cell.x == grid.width - 1
# Sorts the neighbors so the rendered path is a zigzag path
# Cells in a diagonal direction are given priority
# Comment this line to see the difference
neighbors = neighbors.sort_by { |neighbor_x, neighbor_y| proximity_to_star(neighbor_x, neighbor_y) }
neighbors
end
# Finds the vertical and horizontal distance of a cell from the star
# and returns the larger value
# This method is used to have a zigzag pattern in the rendered path
# A cell that is [5, 5] from the star,
# is explored before over a cell that is [0, 7] away.
# So, if possible, the search tries to go diagonal (zigzag) first
def proximity_to_star(x, y)
distance_x = (grid.star.x - x).abs
distance_y = (grid.star.y - y).abs
if distance_x > distance_y
return distance_x
else
return distance_y
end
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse helps with this
def cell_closest_to_mouse
# Closest cell to the mouse in the first grid
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Bound x and y to the grid
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
# Signal that the user is going to be moving the star from the first grid
def star_clicked?
inputs.mouse.down && inputs.mouse.point.inside_rect?(scale_up(grid.star))
end
# Signal that the user is going to be moving the target from the first grid
def target_clicked?
inputs.mouse.down && inputs.mouse.point.inside_rect?(scale_up(grid.target))
end
# Signal that the user is going to be adding walls from the first grid
def grid_clicked?
inputs.mouse.down && mouse_inside_grid?
end
# Returns whether the mouse is inside of the first grid
# Part of the condition that checks whether the user is adding a wall
def mouse_inside_grid?
inputs.mouse.point.inside_rect?(scale_up(grid.rect))
end
# These methods provide handy aliases to colors
# Light brown
def unvisited_color
[221, 212, 213]
# [255, 255, 255]
end
# Camo Green
def wall_color
[134, 134, 120]
end
# Pastel White
def path_color
[231, 230, 228]
end
def red
[255, 0, 0]
end
def purple
[149, 64, 191]
end
# Makes code more concise
def grid
state.grid
end
def search
state.search
end
end
# Method that is called by DragonRuby periodically
# Used for updating animations and calculations
def tick args
# Pressing r will reset the application
if args.inputs.keyboard.key_down.r
args.gtk.reset
reset
return
end
# Every tick, new args are passed, and the Breadth First Search tick is called
$breadcrumbs ||= Breadcrumbs.new(args)
$breadcrumbs.args = args
$breadcrumbs.tick
end
def reset
$breadcrumbs = nil
end
# # Representation of how far away visited cells are from the star
# # Replaces the render_visited method
# # Visually demonstrates the effectiveness of early exit for pathfinding
# def render_heat_map
# # THIS CODE NEEDS SOME FIXING DUE TO REFACTORING
# search.came_from.each_key do | cell |
# distance = (grid.star.x - visited_cell.x).abs + (state.star.y - visited_cell.y).abs
# max_distance = grid.width + grid.height
# alpha = 255.to_i * distance.to_i / max_distance.to_i
# outputs.solids << [scale_up(visited_cell), red, alpha]
# # outputs.solids << [early_exit_scale_up(visited_cell), red, alpha]
# end
# end
</code></pre>
<h3 id='----path-finding-algorithms---early-exit---main-rb'>Path Finding Algorithms - Early Exit - main.rb</h3>
<pre><code class="language-ruby"># ./samples/13_path_finding_algorithms/04_early_exit/app/main.rb
# Comparison of a breadth first search with and without early exit
# Inspired by https://www.redblobgames.com/pathfinding/a-star/introduction.html
# Demonstrates the exploration difference caused by early exit
# Also demonstrates how breadth first search is used for path generation
# The left grid is a breadth first search without early exit
# The right grid is a breadth first search with early exit
# The red squares represent how far the search expanded
# The darker the red, the farther the search proceeded
# Comparison of the heat map reveals how much searching can be saved by early exit
# The white path shows path generation via breadth first search
class EarlyExitBreadthFirstSearch
attr_gtk
# This method is called every frame/tick
# Every tick, the current state of the search is rendered on the screen,
# User input is processed, and
# The next step in the search is calculated
def tick
defaults
# If the grid has not been searched
if state.visited.empty?
# Complete the search
state.max_steps.times { step }
# And calculate the path
calc_path
end
render
input
end
def defaults
# Variables to edit the size and appearance of the grid
# Freely customizable to user's liking
grid.width ||= 15
grid.height ||= 15
grid.cell_size ||= 40
grid.rect ||= [0, 0, grid.width, grid.height]
# At some step the animation will end,
# and further steps won't change anything (the whole grid.widthill be explored)
# This step is roughly the grid's width * height
# When anim_steps equals max_steps no more calculations will occur
# and the slider will be at the end
state.max_steps ||= args.state.grid.width * args.state.grid.height
# The location of the star and walls of the grid
# They can be modified to have a different initial grid
# Walls are stored in a hash for quick look up when doing the search
state.star ||= [2, 8]
state.target ||= [10, 5]
state.walls ||= {}
# Variables that are used by the breadth first search
# Storing cells that the search has visited, prevents unnecessary steps
# Expanding the frontier of the search in order makes the search expand
# from the center outward
# Visited cells in the first grid
state.visited ||= {}
# Visited cells in the second grid
state.early_exit_visited ||= {}
# The cells from which the search is to expand
state.frontier ||= []
# A hash of where each cell was expanded from
# The key is a cell, and the value is the cell it came from
state.came_from ||= {}
# Cells that are part of the path from the target to the star
state.path ||= {}
# What the user is currently editing on the grid
# We store this value, because we want to remember the value even when
# the user's cursor is no longer over what they're interacting with, but
# they are still clicking down on the mouse.
state.current_input ||= :none
end
# Draws everything onto the screen
def render
render_background
render_heat_map
render_walls
render_path
render_star
render_target
render_labels
end
# The methods below subdivide the task of drawing everything to the screen
# Draws what the grid looks like with nothing on it
def render_background
render_unvisited
render_grid_lines
end
# Draws both grids
def render_unvisited
outputs.solids << [scale_up(grid.rect), unvisited_color]
outputs.solids << [early_exit_scale_up(grid.rect), unvisited_color]
end
# Draws grid lines to show the division of the grid into cells
def render_grid_lines
for x in 0..grid.width
outputs.lines << vertical_line(x)
outputs.lines << early_exit_vertical_line(x)
end
for y in 0..grid.height
outputs.lines << horizontal_line(y)
outputs.lines << early_exit_horizontal_line(y)
end
end
# Easy way to draw vertical lines given an index
def vertical_line column
scale_up([column, 0, column, grid.height])
end
# Easy way to draw horizontal lines given an index
def horizontal_line row
scale_up([0, row, grid.width, row])
end
# Easy way to draw vertical lines given an index
def early_exit_vertical_line column
scale_up([column + grid.width + 1, 0, column + grid.width + 1, grid.height])
end
# Easy way to draw horizontal lines given an index
def early_exit_horizontal_line row
scale_up([grid.width + 1, row, grid.width + grid.width + 1, row])
end
# Draws the walls on both grids
def render_walls
state.walls.each_key do |wall|
outputs.solids << [scale_up(wall), wall_color]
outputs.solids << [early_exit_scale_up(wall), wall_color]
end
end
# Renders the star on both grids
def render_star
outputs.sprites << [scale_up(state.star), 'star.png']
outputs.sprites << [early_exit_scale_up(state.star), 'star.png']
end
# Renders the target on both grids
def render_target
outputs.sprites << [scale_up(state.target), 'target.png']
outputs.sprites << [early_exit_scale_up(state.target), 'target.png']
end
# Labels the grids
def render_labels
outputs.labels << [200, 625, "Without early exit"]
outputs.labels << [875, 625, "With early exit"]
end
# Renders the path based off of the state.path hash
def render_path
# If the star and target are disconnected there will only be one path
# The path should not render in that case
unless state.path.size == 1
state.path.each_key do | cell |
# Renders path on both grids
outputs.solids << [scale_up(cell), path_color]
outputs.solids << [early_exit_scale_up(cell), path_color]
end
end
end
# Calculates the path from the target to the star after the search is over
# Relies on the came_from hash
# Fills the state.path hash, which is later rendered on screen
def calc_path
endpoint = state.target
while endpoint
state.path[endpoint] = true
endpoint = state.came_from[endpoint]
end
end
# Representation of how far away visited cells are from the star
# Replaces the render_visited method
# Visually demonstrates the effectiveness of early exit for pathfinding
def render_heat_map
state.visited.each_key do | visited_cell |
distance = (state.star.x - visited_cell.x).abs + (state.star.y - visited_cell.y).abs
max_distance = grid.width + grid.height
alpha = 255.to_i * distance.to_i / max_distance.to_i
outputs.solids << [scale_up(visited_cell), red, alpha]
# outputs.solids << [early_exit_scale_up(visited_cell), red, alpha]
end
state.early_exit_visited.each_key do | visited_cell |
distance = (state.star.x - visited_cell.x).abs + (state.star.y - visited_cell.y).abs
max_distance = grid.width + grid.height
alpha = 255.to_i * distance.to_i / max_distance.to_i
outputs.solids << [early_exit_scale_up(visited_cell), red, alpha]
end
end
# Translates the given cell grid.width + 1 to the right and then scales up
# Used to draw cells for the second grid
# This method does not work for lines,
# so separate methods exist for the grid lines
def early_exit_scale_up(cell)
cell_clone = cell.clone
cell_clone.x += grid.width + 1
scale_up(cell_clone)
end
# In code, the cells are represented as 1x1 rectangles
# When drawn, the cells are larger than 1x1 rectangles
# This method is used to scale up cells, and lines
# Objects are scaled up according to the grid.cell_size variable
# This allows for easy customization of the visual scale of the grid
def scale_up(cell)
# Prevents the original value of cell from being edited
cell = cell.clone
# If cell is just an x and y coordinate
if cell.size == 2
# Add a width and height of 1
cell << 1
cell << 1
end
# Scale all the values up
cell.map! { |value| value * grid.cell_size }
# Returns the scaled up cell
cell
end
# This method processes user input every tick
# Any method with "1" is related to the first grid
# Any method with "2" is related to the second grid
def input
# The program has to remember that the user is dragging an object
# even when the mouse is no longer over that object
# So detecting input and processing input is separate
detect_input
process_input
end
# Determines what the user is editing and stores the value
# Storing the value allows the user to continue the same edit as long as the
# mouse left click is held
def detect_input
# When the mouse is up, nothing is being edited
if inputs.mouse.up
state.current_input = :none
# When the star in the no second grid is clicked
elsif star_clicked?
state.current_input = :star
# When the star in the second grid is clicked
elsif star2_clicked?
state.current_input = :star2
# When the target in the no second grid is clicked
elsif target_clicked?
state.current_input = :target
# When the target in the second grid is clicked
elsif target2_clicked?
state.current_input = :target2
# When a wall in the first grid is clicked
elsif wall_clicked?
state.current_input = :remove_wall
# When a wall in the second grid is clicked
elsif wall2_clicked?
state.current_input = :remove_wall2
# When the first grid is clicked
elsif grid_clicked?
state.current_input = :add_wall
# When the second grid is clicked
elsif grid2_clicked?
state.current_input = :add_wall2
end
end
# Processes click and drag based on what the user is currently dragging
def process_input
if state.current_input == :star
input_star
elsif state.current_input == :star2
input_star2
elsif state.current_input == :target
input_target
elsif state.current_input == :target2
input_target2
elsif state.current_input == :remove_wall
input_remove_wall
elsif state.current_input == :remove_wall2
input_remove_wall2
elsif state.current_input == :add_wall
input_add_wall
elsif state.current_input == :add_wall2
input_add_wall2
end
end
# Moves the star to the cell closest to the mouse in the first grid
# Only resets the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def input_star
old_star = state.star.clone
state.star = cell_closest_to_mouse
unless old_star == state.star
reset_search
end
end
# Moves the star to the cell closest to the mouse in the second grid
# Only resets the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def input_star2
old_star = state.star.clone
state.star = cell_closest_to_mouse2
unless old_star == state.star
reset_search
end
end
# Moves the target to the grid closest to the mouse in the first grid
# Only reset_searchs the search if the target changes position
# Called whenever the user is editing the target (puts mouse down on target)
def input_target
old_target = state.target.clone
state.target = cell_closest_to_mouse
unless old_target == state.target
reset_search
end
end
# Moves the target to the cell closest to the mouse in the second grid
# Only reset_searchs the search if the target changes position
# Called whenever the user is editing the target (puts mouse down on target)
def input_target2
old_target = state.target.clone
state.target = cell_closest_to_mouse2
unless old_target == state.target
reset_search
end
end
# Removes walls in the first grid that are under the cursor
def input_remove_wall
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if mouse_inside_grid?
if state.walls.has_key?(cell_closest_to_mouse)
state.walls.delete(cell_closest_to_mouse)
reset_search
end
end
end
# Removes walls in the second grid that are under the cursor
def input_remove_wall2
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if mouse_inside_grid2?
if state.walls.has_key?(cell_closest_to_mouse2)
state.walls.delete(cell_closest_to_mouse2)
reset_search
end
end
end
# Adds a wall in the first grid in the cell the mouse is over
def input_add_wall
if mouse_inside_grid?
unless state.walls.has_key?(cell_closest_to_mouse)
state.walls[cell_closest_to_mouse] = true
reset_search
end
end
end
# Adds a wall in the second grid in the cell the mouse is over
def input_add_wall2
if mouse_inside_grid2?
unless state.walls.has_key?(cell_closest_to_mouse2)
state.walls[cell_closest_to_mouse2] = true
reset_search
end
end
end
# Whenever the user edits the grid,
# The search has to be reset_searchd upto the current step
# with the current grid as the initial state of the grid
def reset_search
# Reset_Searchs the search
state.frontier = []
state.visited = {}
state.early_exit_visited = {}
state.came_from = {}
state.path = {}
end
# Moves the search forward one step
def step
# The setup to the search
# Runs once when there are no visited cells
if state.visited.empty?
state.visited[state.star] = true
state.early_exit_visited[state.star] = true
state.frontier << state.star
state.came_from[state.star] = nil
end
# A step in the search
unless state.frontier.empty?
# Takes the next frontier cell
new_frontier = state.frontier.shift
# For each of its neighbors
adjacent_neighbors(new_frontier).each do |neighbor|
# That have not been visited and are not walls
unless state.visited.has_key?(neighbor) || state.walls.has_key?(neighbor)
# Add them to the frontier and mark them as visited in the first grid
state.visited[neighbor] = true
# Unless the target has been visited
unless state.visited.has_key?(state.target)
# Mark the neighbor as visited in the second grid as well
state.early_exit_visited[neighbor] = true
end
# Add the neighbor to the frontier and remember which cell it came from
state.frontier << neighbor
state.came_from[neighbor] = new_frontier
end
end
end
end
# Returns a list of adjacent cells
# Used to determine what the next cells to be added to the frontier are
def adjacent_neighbors(cell)
neighbors = []
# Gets all the valid neighbors into the array
# From southern neighbor, clockwise
neighbors << [cell.x, cell.y - 1] unless cell.y == 0
neighbors << [cell.x - 1, cell.y] unless cell.x == 0
neighbors << [cell.x, cell.y + 1] unless cell.y == grid.height - 1
neighbors << [cell.x + 1, cell.y] unless cell.x == grid.width - 1
# Sorts the neighbors so the rendered path is a zigzag path
# Cells in a diagonal direction are given priority
# Comment this line to see the difference
neighbors = neighbors.sort_by { |neighbor_x, neighbor_y| proximity_to_star(neighbor_x, neighbor_y) }
neighbors
end
# Finds the vertical and horizontal distance of a cell from the star
# and returns the larger value
# This method is used to have a zigzag pattern in the rendered path
# A cell that is [5, 5] from the star,
# is explored before over a cell that is [0, 7] away.
# So, if possible, the search tries to go diagonal (zigzag) first
def proximity_to_star(x, y)
distance_x = (state.star.x - x).abs
distance_y = (state.star.y - y).abs
if distance_x > distance_y
return distance_x
else
return distance_y
end
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse helps with this
def cell_closest_to_mouse
# Closest cell to the mouse in the first grid
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Bound x and y to the grid
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse in the second grid helps with this
def cell_closest_to_mouse2
# Closest cell grid to the mouse in the second
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Translate the cell to the first grid
x -= grid.width + 1
# Bound x and y to the first grid
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
# Signal that the user is going to be moving the star from the first grid
def star_clicked?
inputs.mouse.down && inputs.mouse.point.inside_rect?(scale_up(state.star))
end
# Signal that the user is going to be moving the star from the second grid
def star2_clicked?
inputs.mouse.down && inputs.mouse.point.inside_rect?(early_exit_scale_up(state.star))
end
# Signal that the user is going to be moving the target from the first grid
def target_clicked?
inputs.mouse.down && inputs.mouse.point.inside_rect?(scale_up(state.target))
end
# Signal that the user is going to be moving the target from the second grid
def target2_clicked?
inputs.mouse.down && inputs.mouse.point.inside_rect?(early_exit_scale_up(state.target))
end
# Signal that the user is going to be removing walls from the first grid
def wall_clicked?
inputs.mouse.down && mouse_inside_wall?
end
# Signal that the user is going to be removing walls from the second grid
def wall2_clicked?
inputs.mouse.down && mouse_inside_wall2?
end
# Signal that the user is going to be adding walls from the first grid
def grid_clicked?
inputs.mouse.down && mouse_inside_grid?
end
# Signal that the user is going to be adding walls from the second grid
def grid2_clicked?
inputs.mouse.down && mouse_inside_grid2?
end
# Returns whether the mouse is inside of a wall in the first grid
# Part of the condition that checks whether the user is removing a wall
def mouse_inside_wall?
state.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(scale_up(wall))
end
false
end
# Returns whether the mouse is inside of a wall in the second grid
# Part of the condition that checks whether the user is removing a wall
def mouse_inside_wall2?
state.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(early_exit_scale_up(wall))
end
false
end
# Returns whether the mouse is inside of the first grid
# Part of the condition that checks whether the user is adding a wall
def mouse_inside_grid?
inputs.mouse.point.inside_rect?(scale_up(grid.rect))
end
# Returns whether the mouse is inside of the second grid
# Part of the condition that checks whether the user is adding a wall
def mouse_inside_grid2?
inputs.mouse.point.inside_rect?(early_exit_scale_up(grid.rect))
end
# These methods provide handy aliases to colors
# Light brown
def unvisited_color
[221, 212, 213]
end
# Camo Green
def wall_color
[134, 134, 120]
end
# Pastel White
def path_color
[231, 230, 228]
end
def red
[255, 0, 0]
end
# Makes code more concise
def grid
state.grid
end
end
# Method that is called by DragonRuby periodically
# Used for updating animations and calculations
def tick args
# Pressing r will reset the application
if args.inputs.keyboard.key_down.r
args.gtk.reset
reset
return
end
# Every tick, new args are passed, and the Breadth First Search tick is called
$early_exit_breadth_first_search ||= EarlyExitBreadthFirstSearch.new(args)
$early_exit_breadth_first_search.args = args
$early_exit_breadth_first_search.tick
end
def reset
$early_exit_breadth_first_search = nil
end
</code></pre>
<h3 id='----path-finding-algorithms---dijkstra---main-rb'>Path Finding Algorithms - Dijkstra - main.rb</h3>
<pre><code class="language-ruby"># ./samples/13_path_finding_algorithms/05_dijkstra/app/main.rb
# Demonstrates how Dijkstra's Algorithm allows movement costs to be considered
# Inspired by https://www.redblobgames.com/pathfinding/a-star/introduction.html
# The first grid is a breadth first search with an early exit.
# It shows a heat map of all the cells that were visited by the search and their relative distance.
# The second grid is an implementation of Dijkstra's algorithm.
# Light green cells have 5 times the movement cost of regular cells.
# The heat map will darken based on movement cost.
# Dark green cells are walls, and the search cannot go through them.
class Movement_Costs
attr_gtk
# This method is called every frame/tick
# Every tick, the current state of the search is rendered on the screen,
# User input is processed, and
# The next step in the search is calculated
def tick
defaults
render
input
calc
end
def defaults
# Variables to edit the size and appearance of the grid
# Freely customizable to user's liking
grid.width ||= 10
grid.height ||= 10
grid.cell_size ||= 60
grid.rect ||= [0, 0, grid.width, grid.height]
# The location of the star and walls of the grid
# They can be modified to have a different initial grid
# Walls are stored in a hash for quick look up when doing the search
state.star ||= [1, 5]
state.target ||= [8, 4]
state.walls ||= {[1, 1] => true, [2, 1] => true, [3, 1] => true, [1, 2] => true, [2, 2] => true, [3, 2] => true}
state.hills ||= {
[4, 1] => true,
[5, 1] => true,
[4, 2] => true,
[5, 2] => true,
[6, 2] => true,
[4, 3] => true,
[5, 3] => true,
[6, 3] => true,
[3, 4] => true,
[4, 4] => true,
[5, 4] => true,
[6, 4] => true,
[7, 4] => true,
[3, 5] => true,
[4, 5] => true,
[5, 5] => true,
[6, 5] => true,
[7, 5] => true,
[4, 6] => true,
[5, 6] => true,
[6, 6] => true,
[7, 6] => true,
[4, 7] => true,
[5, 7] => true,
[6, 7] => true,
[4, 8] => true,
[5, 8] => true,
}
# What the user is currently editing on the grid
# We store this value, because we want to remember the value even when
# the user's cursor is no longer over what they're interacting with, but
# they are still clicking down on the mouse.
state.user_input ||= :none
# Values that are used for the breadth first search
# Keeping track of what cells were visited prevents counting cells multiple times
breadth_first_search.visited ||= {}
# The cells from which the breadth first search will expand
breadth_first_search.frontier ||= []
# Keeps track of which cell all cells were searched from
# Used to recreate the path from the target to the star
breadth_first_search.came_from ||= {}
# Keeps track of the movement cost so far to be at a cell
# Allows the costs of new cells to be quickly calculated
# Also doubles as a way to check if cells have already been visited
dijkstra_search.cost_so_far ||= {}
# The cells from which the Dijkstra search will expand
dijkstra_search.frontier ||= []
# Keeps track of which cell all cells were searched from
# Used to recreate the path from the target to the star
dijkstra_search.came_from ||= {}
end
# Draws everything onto the screen
def render
render_background
render_heat_maps
render_star
render_target
render_hills
render_walls
render_paths
end
# The methods below subdivide the task of drawing everything to the screen
# Draws what the grid looks like with nothing on it
def render_background
render_unvisited
render_grid_lines
render_labels
end
# Draws two rectangles the size of the grid in the default cell color
# Used as part of the background
def render_unvisited
outputs.solids << [scale_up(grid.rect), unvisited_color]
outputs.solids << [move_and_scale_up(grid.rect), unvisited_color]
end
# Draws grid lines to show the division of the grid into cells
def render_grid_lines
for x in 0..grid.width
outputs.lines << vertical_line(x)
outputs.lines << shifted_vertical_line(x)
end
for y in 0..grid.height
outputs.lines << horizontal_line(y)
outputs.lines << shifted_horizontal_line(y)
end
end
# Easy way to draw vertical lines given an index for the first grid
def vertical_line column
scale_up([column, 0, column, grid.height])
end
# Easy way to draw horizontal lines given an index for the second grid
def horizontal_line row
scale_up([0, row, grid.width, row])
end
# Easy way to draw vertical lines given an index for the first grid
def shifted_vertical_line column
scale_up([column + grid.width + 1, 0, column + grid.width + 1, grid.height])
end
# Easy way to draw horizontal lines given an index for the second grid
def shifted_horizontal_line row
scale_up([grid.width + 1, row, grid.width + grid.width + 1, row])
end
# Labels the grids
def render_labels
outputs.labels << [175, 650, "Number of steps", 3]
outputs.labels << [925, 650, "Distance", 3]
end
def render_paths
render_breadth_first_search_path
render_dijkstra_path
end
def render_heat_maps
render_breadth_first_search_heat_map
render_dijkstra_heat_map
end
# Renders the breadth first search on the first grid
def render_breadth_first_search
end
# This heat map shows the cells explored by the breadth first search and how far they are from the star.
def render_breadth_first_search_heat_map
# For each cell explored
breadth_first_search.visited.each_key do | visited_cell |
# Find its distance from the star
distance = (state.star.x - visited_cell.x).abs + (state.star.y - visited_cell.y).abs
max_distance = grid.width + grid.height
# Get it as a percent of the maximum distance and scale to 255 for use as an alpha value
alpha = 255.to_i * distance.to_i / max_distance.to_i
outputs.solids << [scale_up(visited_cell), red, alpha]
end
end
def render_breadth_first_search_path
# If the search found the target
if breadth_first_search.visited.has_key?(state.target)
# Start from the target
endpoint = state.target
# And the cell it came from
next_endpoint = breadth_first_search.came_from[endpoint]
while endpoint and next_endpoint
# Draw a path between these two cells
path = get_path_between(endpoint, next_endpoint)
outputs.solids << [scale_up(path), path_color]
# And get the next pair of cells
endpoint = next_endpoint
next_endpoint = breadth_first_search.came_from[endpoint]
# Continue till there are no more cells
end
end
end
# Renders the Dijkstra search on the second grid
def render_dijkstra
end
def render_dijkstra_heat_map
dijkstra_search.cost_so_far.each do |visited_cell, cost|
max_cost = (grid.width + grid.height) #* 5
alpha = 255.to_i * cost.to_i / max_cost.to_i
outputs.solids << [move_and_scale_up(visited_cell), red, alpha]
end
end
def render_dijkstra_path
# If the search found the target
if dijkstra_search.came_from.has_key?(state.target)
# Get the target and the cell it came from
endpoint = state.target
next_endpoint = dijkstra_search.came_from[endpoint]
while endpoint and next_endpoint
# Draw a path between them
path = get_path_between(endpoint, next_endpoint)
outputs.solids << [move_and_scale_up(path), path_color]
# Shift one cell down the path
endpoint = next_endpoint
next_endpoint = dijkstra_search.came_from[endpoint]
# Repeat till the end of the path
end
end
end
# Renders the star on both grids
def render_star
outputs.sprites << [scale_up(state.star), 'star.png']
outputs.sprites << [move_and_scale_up(state.star), 'star.png']
end
# Renders the target on both grids
def render_target
outputs.sprites << [scale_up(state.target), 'target.png']
outputs.sprites << [move_and_scale_up(state.target), 'target.png']
end
def render_hills
state.hills.each_key do |hill|
outputs.solids << [scale_up(hill), hill_color]
outputs.solids << [move_and_scale_up(hill), hill_color]
end
end
# Draws the walls on both grids
def render_walls
state.walls.each_key do |wall|
outputs.solids << [scale_up(wall), wall_color]
outputs.solids << [move_and_scale_up(wall), wall_color]
end
end
def get_path_between(cell_one, cell_two)
path = nil
if cell_one.x == cell_two.x
if cell_one.y < cell_two.y
path = [cell_one.x + 0.3, cell_one.y + 0.3, 0.4, 1.4]
else
path = [cell_two.x + 0.3, cell_two.y + 0.3, 0.4, 1.4]
end
else
if cell_one.x < cell_two.x
path = [cell_one.x + 0.3, cell_one.y + 0.3, 1.4, 0.4]
else
path = [cell_two.x + 0.3, cell_two.y + 0.3, 1.4, 0.4]
end
end
path
end
# Representation of how far away visited cells are from the star
# Replaces the render_visited method
# Visually demonstrates the effectiveness of early exit for pathfinding
def render_breadth_first_search_heat_map
breadth_first_search.visited.each_key do | visited_cell |
distance = (state.star.x - visited_cell.x).abs + (state.star.y - visited_cell.y).abs
max_distance = grid.width + grid.height
alpha = 255.to_i * distance.to_i / max_distance.to_i
outputs.solids << [scale_up(visited_cell), red, alpha]
end
end
# Translates the given cell grid.width + 1 to the right and then scales up
# Used to draw cells for the second grid
# This method does not work for lines,
# so separate methods exist for the grid lines
def move_and_scale_up(cell)
cell_clone = cell.clone
cell_clone.x += grid.width + 1
scale_up(cell_clone)
end
# In code, the cells are represented as 1x1 rectangles
# When drawn, the cells are larger than 1x1 rectangles
# This method is used to scale up cells, and lines
# Objects are scaled up according to the grid.cell_size variable
# This allows for easy customization of the visual scale of the grid
def scale_up(cell)
# Prevents the original value of cell from being edited
cell = cell.clone
# If cell is just an x and y coordinate
if cell.size == 2
# Add a width and height of 1
cell << 1
cell << 1
end
# Scale all the values up
cell.map! { |value| value * grid.cell_size }
# Returns the scaled up cell
cell
end
# Handles user input every tick so the grid can be edited
# Separate input detection and processing is needed
# For example: Adding walls is started by clicking down on a hill,
# but the mouse doesn't need to remain over hills to add walls
def input
# If the mouse was lifted this tick
if inputs.mouse.up
# Set current input to none
state.user_input = :none
end
# If the mouse was clicked this tick
if inputs.mouse.down
# Determine what the user is editing and edit the state.user_input variable
determine_input
end
# Process user input based on user_input variable and current mouse position
process_input
end
# Determines what the user is editing and stores the value
# This method is called the tick the mouse is clicked
# Storing the value allows the user to continue the same edit as long as the
# mouse left click is held
def determine_input
# If the mouse is over the star in the first grid
if mouse_over_star?
# The user is editing the star from the first grid
state.user_input = :star
# If the mouse is over the star in the second grid
elsif mouse_over_star2?
# The user is editing the star from the second grid
state.user_input = :star2
# If the mouse is over the target in the first grid
elsif mouse_over_target?
# The user is editing the target from the first grid
state.user_input = :target
# If the mouse is over the target in the second grid
elsif mouse_over_target2?
# The user is editing the target from the second grid
state.user_input = :target2
# If the mouse is over a wall in the first grid
elsif mouse_over_wall?
# The user is removing a wall from the first grid
state.user_input = :remove_wall
# If the mouse is over a wall in the second grid
elsif mouse_over_wall2?
# The user is removing a wall from the second grid
state.user_input = :remove_wall2
# If the mouse is over a hill in the first grid
elsif mouse_over_hill?
# The user is adding a wall from the first grid
state.user_input = :add_wall
# If the mouse is over a hill in the second grid
elsif mouse_over_hill2?
# The user is adding a wall from the second grid
state.user_input = :add_wall2
# If the mouse is over the first grid
elsif mouse_over_grid?
# The user is adding a hill from the first grid
state.user_input = :add_hill
# If the mouse is over the second grid
elsif mouse_over_grid2?
# The user is adding a hill from the second grid
state.user_input = :add_hill2
end
end
# Processes click and drag based on what the user is currently dragging
def process_input
if state.user_input == :star
input_star
elsif state.user_input == :star2
input_star2
elsif state.user_input == :target
input_target
elsif state.user_input == :target2
input_target2
elsif state.user_input == :remove_wall
input_remove_wall
elsif state.user_input == :remove_wall2
input_remove_wall2
elsif state.user_input == :add_hill
input_add_hill
elsif state.user_input == :add_hill2
input_add_hill2
elsif state.user_input == :add_wall
input_add_wall
elsif state.user_input == :add_wall2
input_add_wall2
end
end
# Calculates the two searches
def calc
# If the searches have not started
if breadth_first_search.visited.empty?
# Calculate the two searches
calc_breadth_first
calc_dijkstra
end
end
def calc_breadth_first
# Sets up the Breadth First Search
breadth_first_search.visited[state.star] = true
breadth_first_search.frontier << state.star
breadth_first_search.came_from[state.star] = nil
until breadth_first_search.frontier.empty?
return if breadth_first_search.visited.has_key?(state.target)
# A step in the search
# Takes the next frontier cell
new_frontier = breadth_first_search.frontier.shift
# For each of its neighbors
adjacent_neighbors(new_frontier).each do | neighbor |
# That have not been visited and are not walls
unless breadth_first_search.visited.has_key?(neighbor) || state.walls.has_key?(neighbor)
# Add them to the frontier and mark them as visited in the first grid
breadth_first_search.visited[neighbor] = true
breadth_first_search.frontier << neighbor
# Remember which cell the neighbor came from
breadth_first_search.came_from[neighbor] = new_frontier
end
end
end
end
# Calculates the Dijkstra Search from the beginning to the end
def calc_dijkstra
# The initial values for the Dijkstra search
dijkstra_search.frontier << [state.star, 0]
dijkstra_search.came_from[state.star] = nil
dijkstra_search.cost_so_far[state.star] = 0
# Until their are no more cells to be explored
until dijkstra_search.frontier.empty?
# Get the next cell to be explored from
# We get the first element of the array which is the cell. The second element is the priority.
current = dijkstra_search.frontier.shift[0]
# Stop the search if we found the target
return if current == state.target
# For each of the neighbors
adjacent_neighbors(current).each do | neighbor |
# Unless this cell is a wall or has already been explored.
unless dijkstra_search.came_from.has_key?(neighbor) or state.walls.has_key?(neighbor)
# Calculate the movement cost of getting to this cell and memo
new_cost = dijkstra_search.cost_so_far[current] + cost(neighbor)
dijkstra_search.cost_so_far[neighbor] = new_cost
# Add this neighbor to the cells too be explored
dijkstra_search.frontier << [neighbor, new_cost]
dijkstra_search.came_from[neighbor] = current
end
end
# Sort the frontier so exploration occurs that have a low cost so far.
# My implementation of a priority queue
dijkstra_search.frontier = dijkstra_search.frontier.sort_by {|cell, priority| priority}
end
end
def cost(cell)
if state.hills.has_key?(cell)
return 5
else
return 1
end
end
# Moves the star to the cell closest to the mouse in the first grid
# Only resets the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def input_star
old_star = state.star.clone
unless cell_closest_to_mouse == state.target
state.star = cell_closest_to_mouse
end
unless old_star == state.star
reset_search
end
end
# Moves the star to the cell closest to the mouse in the second grid
# Only resets the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def input_star2
old_star = state.star.clone
unless cell_closest_to_mouse2 == state.target
state.star = cell_closest_to_mouse2
end
unless old_star == state.star
reset_search
end
end
# Moves the target to the grid closest to the mouse in the first grid
# Only reset_searchs the search if the target changes position
# Called whenever the user is editing the target (puts mouse down on target)
def input_target
old_target = state.target.clone
unless cell_closest_to_mouse == state.star
state.target = cell_closest_to_mouse
end
unless old_target == state.target
reset_search
end
end
# Moves the target to the cell closest to the mouse in the second grid
# Only reset_searchs the search if the target changes position
# Called whenever the user is editing the target (puts mouse down on target)
def input_target2
old_target = state.target.clone
unless cell_closest_to_mouse2 == state.star
state.target = cell_closest_to_mouse2
end
unless old_target == state.target
reset_search
end
end
# Removes walls in the first grid that are under the cursor
def input_remove_wall
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if mouse_over_grid?
if state.walls.has_key?(cell_closest_to_mouse) or state.hills.has_key?(cell_closest_to_mouse)
state.walls.delete(cell_closest_to_mouse)
state.hills.delete(cell_closest_to_mouse)
reset_search
end
end
end
# Removes walls in the second grid that are under the cursor
def input_remove_wall2
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if mouse_over_grid2?
if state.walls.has_key?(cell_closest_to_mouse2) or state.hills.has_key?(cell_closest_to_mouse2)
state.walls.delete(cell_closest_to_mouse2)
state.hills.delete(cell_closest_to_mouse2)
reset_search
end
end
end
# Adds a hill in the first grid in the cell the mouse is over
def input_add_hill
if mouse_over_grid?
unless state.hills.has_key?(cell_closest_to_mouse)
state.hills[cell_closest_to_mouse] = true
reset_search
end
end
end
# Adds a hill in the second grid in the cell the mouse is over
def input_add_hill2
if mouse_over_grid2?
unless state.hills.has_key?(cell_closest_to_mouse2)
state.hills[cell_closest_to_mouse2] = true
reset_search
end
end
end
# Adds a wall in the first grid in the cell the mouse is over
def input_add_wall
if mouse_over_grid?
unless state.walls.has_key?(cell_closest_to_mouse)
state.hills.delete(cell_closest_to_mouse)
state.walls[cell_closest_to_mouse] = true
reset_search
end
end
end
# Adds a wall in the second grid in the cell the mouse is over
def input_add_wall2
if mouse_over_grid2?
unless state.walls.has_key?(cell_closest_to_mouse2)
state.hills.delete(cell_closest_to_mouse2)
state.walls[cell_closest_to_mouse2] = true
reset_search
end
end
end
# Whenever the user edits the grid,
# The search has to be reset_searchd upto the current step
# with the current grid as the initial state of the grid
def reset_search
breadth_first_search.visited = {}
breadth_first_search.frontier = []
breadth_first_search.came_from = {}
dijkstra_search.frontier = []
dijkstra_search.came_from = {}
dijkstra_search.cost_so_far = {}
end
# Returns a list of adjacent cells
# Used to determine what the next cells to be added to the frontier are
def adjacent_neighbors(cell)
neighbors = []
# Gets all the valid neighbors into the array
# From southern neighbor, clockwise
neighbors << [cell.x , cell.y - 1] unless cell.y == 0
neighbors << [cell.x - 1, cell.y ] unless cell.x == 0
neighbors << [cell.x , cell.y + 1] unless cell.y == grid.height - 1
neighbors << [cell.x + 1, cell.y ] unless cell.x == grid.width - 1
# Sorts the neighbors so the rendered path is a zigzag path
# Cells in a diagonal direction are given priority
# Comment this line to see the difference
neighbors = neighbors.sort_by { |neighbor_x, neighbor_y| proximity_to_star(neighbor_x, neighbor_y) }
neighbors
end
# Finds the vertical and horizontal distance of a cell from the star
# and returns the larger value
# This method is used to have a zigzag pattern in the rendered path
# A cell that is [5, 5] from the star,
# is explored before over a cell that is [0, 7] away.
# So, if possible, the search tries to go diagonal (zigzag) first
def proximity_to_star(x, y)
distance_x = (state.star.x - x).abs
distance_y = (state.star.y - y).abs
if distance_x > distance_y
return distance_x
else
return distance_y
end
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse helps with this
def cell_closest_to_mouse
# Closest cell to the mouse in the first grid
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Bound x and y to the grid
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse in the second grid helps with this
def cell_closest_to_mouse2
# Closest cell grid to the mouse in the second
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Translate the cell to the first grid
x -= grid.width + 1
# Bound x and y to the first grid
x = 0 if x < 0
y = 0 if y < 0
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
# Signal that the user is going to be moving the star from the first grid
def mouse_over_star?
inputs.mouse.point.inside_rect?(scale_up(state.star))
end
# Signal that the user is going to be moving the star from the second grid
def mouse_over_star2?
inputs.mouse.point.inside_rect?(move_and_scale_up(state.star))
end
# Signal that the user is going to be moving the target from the first grid
def mouse_over_target?
inputs.mouse.point.inside_rect?(scale_up(state.target))
end
# Signal that the user is going to be moving the target from the second grid
def mouse_over_target2?
inputs.mouse.point.inside_rect?(move_and_scale_up(state.target))
end
# Signal that the user is going to be removing walls from the first grid
def mouse_over_wall?
state.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(scale_up(wall))
end
false
end
# Signal that the user is going to be removing walls from the second grid
def mouse_over_wall2?
state.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(move_and_scale_up(wall))
end
false
end
# Signal that the user is going to be removing hills from the first grid
def mouse_over_hill?
state.hills.each_key do | hill |
return true if inputs.mouse.point.inside_rect?(scale_up(hill))
end
false
end
# Signal that the user is going to be removing hills from the second grid
def mouse_over_hill2?
state.hills.each_key do | hill |
return true if inputs.mouse.point.inside_rect?(move_and_scale_up(hill))
end
false
end
# Signal that the user is going to be adding walls from the first grid
def mouse_over_grid?
inputs.mouse.point.inside_rect?(scale_up(grid.rect))
end
# Signal that the user is going to be adding walls from the second grid
def mouse_over_grid2?
inputs.mouse.point.inside_rect?(move_and_scale_up(grid.rect))
end
# These methods provide handy aliases to colors
# Light brown
def unvisited_color
[221, 212, 213]
end
# Camo Green
def wall_color
[134, 134, 120]
end
# Pastel White
def path_color
[231, 230, 228]
end
def red
[255, 0, 0]
end
# A Green
def hill_color
[139, 173, 132]
end
# Makes code more concise
def grid
state.grid
end
def breadth_first_search
state.breadth_first_search
end
def dijkstra_search
state.dijkstra_search
end
end
# Method that is called by DragonRuby periodically
# Used for updating animations and calculations
def tick args
# Pressing r will reset the application
if args.inputs.keyboard.key_down.r
args.gtk.reset
reset
return
end
# Every tick, new args are passed, and the Dijkstra tick method is called
$movement_costs ||= Movement_Costs.new(args)
$movement_costs.args = args
$movement_costs.tick
end
def reset
$movement_costs = nil
end
</code></pre>
<h3 id='----path-finding-algorithms---heuristic---main-rb'>Path Finding Algorithms - Heuristic - main.rb</h3>
<pre><code class="language-ruby"># ./samples/13_path_finding_algorithms/06_heuristic/app/main.rb
# This program is inspired by https://www.redblobgames.com/pathfinding/a-star/introduction.html
# This time the heuristic search still explored less of the grid, hence finishing faster.
# However, it did not find the shortest path between the star and the target.
# The only difference between this app and Heuristic is the change of the starting position.
class Heuristic_With_Walls
attr_gtk
def tick
defaults
render
input
# If animation is playing, and max steps have not been reached
# Move the search a step forward
if state.play && state.current_step < state.max_steps
# Variable that tells the program what step to recalculate up to
state.current_step += 1
move_searches_one_step_forward
end
end
def defaults
# Variables to edit the size and appearance of the grid
# Freely customizable to user's liking
grid.width ||= 15
grid.height ||= 15
grid.cell_size ||= 40
grid.rect ||= [0, 0, grid.width, grid.height]
grid.star ||= [0, 2]
grid.target ||= [14, 12]
grid.walls ||= {}
# There are no hills in the Heuristic Search Demo
# What the user is currently editing on the grid
# We store this value, because we want to remember the value even when
# the user's cursor is no longer over what they're interacting with, but
# they are still clicking down on the mouse.
state.user_input ||= :none
# These variables allow the breadth first search to take place
# Came_from is a hash with a key of a cell and a value of the cell that was expanded from to find the key.
# Used to prevent searching cells that have already been found
# and to trace a path from the target back to the starting point.
# Frontier is an array of cells to expand the search from.
# The search is over when there are no more cells to search from.
# Path stores the path from the target to the star, once the target has been found
# It prevents calculating the path every tick.
bfs.came_from ||= {}
bfs.frontier ||= []
bfs.path ||= []
heuristic.came_from ||= {}
heuristic.frontier ||= []
heuristic.path ||= []
# Stores which step of the animation is being rendered
# When the user moves the star or messes with the walls,
# the searches are recalculated up to this step
# Unless the current step has a value
unless state.current_step
# Set the current step to 10
state.current_step = 10
# And calculate the searches up to step 10
recalculate_searches
end
# At some step the animation will end,
# and further steps won't change anything (the whole grid will be explored)
# This step is roughly the grid's width * height
# When anim_steps equals max_steps no more calculations will occur
# and the slider will be at the end
state.max_steps = grid.width * grid.height
# Whether the animation should play or not
# If true, every tick moves anim_steps forward one
# Pressing the stepwise animation buttons will pause the animation
# An if statement instead of the ||= operator is used for assigning a boolean value.
# The || operator does not differentiate between nil and false.
if state.play == nil
state.play = false
end
# Store the rects of the buttons that control the animation
# They are here for user customization
# Editing these might require recentering the text inside them
# Those values can be found in the render_button methods
buttons.left = [470, 600, 50, 50]
buttons.center = [520, 600, 200, 50]
buttons.right = [720, 600, 50, 50]
# The variables below are related to the slider
# They allow the user to customize them
# They also give a central location for the render and input methods to get
# information from
# x & y are the coordinates of the leftmost part of the slider line
slider.x = 440
slider.y = 675
# This is the width of the line
slider.w = 360
# This is the offset for the circle
# Allows the center of the circle to be on the line,
# as opposed to the upper right corner
slider.offset = 20
# This is the spacing between each of the notches on the slider
# Notches are places where the circle can rest on the slider line
# There needs to be a notch for each step before the maximum number of steps
slider.spacing = slider.w.to_f / state.max_steps.to_f
end
# All methods with render draw stuff on the screen
# UI has buttons, the slider, and labels
# The search specific rendering occurs in the respective methods
def render
render_ui
render_bfs
render_heuristic
end
def render_ui
render_buttons
render_slider
render_labels
end
def render_buttons
render_left_button
render_center_button
render_right_button
end
def render_bfs
render_bfs_grid
render_bfs_star
render_bfs_target
render_bfs_visited
render_bfs_walls
render_bfs_frontier
render_bfs_path
end
def render_heuristic
render_heuristic_grid
render_heuristic_star
render_heuristic_target
render_heuristic_visited
render_heuristic_walls
render_heuristic_frontier
render_heuristic_path
end
# This method handles user input every tick
def input
# Check and handle button input
input_buttons
# If the mouse was lifted this tick
if inputs.mouse.up
# Set current input to none
state.user_input = :none
end
# If the mouse was clicked this tick
if inputs.mouse.down
# Determine what the user is editing and appropriately edit the state.user_input variable
determine_input
end
# Process user input based on user_input variable and current mouse position
process_input
end
# Determines what the user is editing
# This method is called when the mouse is clicked down
def determine_input
if mouse_over_slider?
state.user_input = :slider
# If the mouse is over the star in the first grid
elsif bfs_mouse_over_star?
# The user is editing the star from the first grid
state.user_input = :bfs_star
# If the mouse is over the star in the second grid
elsif heuristic_mouse_over_star?
# The user is editing the star from the second grid
state.user_input = :heuristic_star
# If the mouse is over the target in the first grid
elsif bfs_mouse_over_target?
# The user is editing the target from the first grid
state.user_input = :bfs_target
# If the mouse is over the target in the second grid
elsif heuristic_mouse_over_target?
# The user is editing the target from the second grid
state.user_input = :heuristic_target
# If the mouse is over a wall in the first grid
elsif bfs_mouse_over_wall?
# The user is removing a wall from the first grid
state.user_input = :bfs_remove_wall
# If the mouse is over a wall in the second grid
elsif heuristic_mouse_over_wall?
# The user is removing a wall from the second grid
state.user_input = :heuristic_remove_wall
# If the mouse is over the first grid
elsif bfs_mouse_over_grid?
# The user is adding a wall from the first grid
state.user_input = :bfs_add_wall
# If the mouse is over the second grid
elsif heuristic_mouse_over_grid?
# The user is adding a wall from the second grid
state.user_input = :heuristic_add_wall
end
end
# Processes click and drag based on what the user is currently dragging
def process_input
if state.user_input == :slider
process_input_slider
elsif state.user_input == :bfs_star
process_input_bfs_star
elsif state.user_input == :heuristic_star
process_input_heuristic_star
elsif state.user_input == :bfs_target
process_input_bfs_target
elsif state.user_input == :heuristic_target
process_input_heuristic_target
elsif state.user_input == :bfs_remove_wall
process_input_bfs_remove_wall
elsif state.user_input == :heuristic_remove_wall
process_input_heuristic_remove_wall
elsif state.user_input == :bfs_add_wall
process_input_bfs_add_wall
elsif state.user_input == :heuristic_add_wall
process_input_heuristic_add_wall
end
end
def render_slider
# Using primitives hides the line under the white circle of the slider
# Draws the line
outputs.primitives << [slider.x, slider.y, slider.x + slider.w, slider.y].line
# The circle needs to be offset so that the center of the circle
# overlaps the line instead of the upper right corner of the circle
# The circle's x value is also moved based on the current seach step
circle_x = (slider.x - slider.offset) + (state.current_step * slider.spacing)
circle_y = (slider.y - slider.offset)
circle_rect = [circle_x, circle_y, 37, 37]
outputs.primitives << [circle_rect, 'circle-white.png'].sprite
end
def render_labels
outputs.labels << [205, 625, "Breadth First Search"]
outputs.labels << [820, 625, "Heuristic Best-First Search"]
end
def render_left_button
# Draws the button_color button, and a black border
# The border separates the buttons visually
outputs.solids << [buttons.left, button_color]
outputs.borders << [buttons.left]
# Renders an explanatory label in the center of the button
# Explains to the user what the button does
# If the button size is changed, the label might need to be edited as well
# to keep the label in the center of the button
label_x = buttons.left.x + 20
label_y = buttons.left.y + 35
outputs.labels << [label_x, label_y, "<"]
end
def render_center_button
# Draws the button_color button, and a black border
# The border separates the buttons visually
outputs.solids << [buttons.center, button_color]
outputs.borders << [buttons.center]
# Renders an explanatory label in the center of the button
# Explains to the user what the button does
# If the button size is changed, the label might need to be edited as well
# to keep the label in the center of the button
label_x = buttons.center.x + 37
label_y = buttons.center.y + 35
label_text = state.play ? "Pause Animation" : "Play Animation"
outputs.labels << [label_x, label_y, label_text]
end
def render_right_button
# Draws the button_color button, and a black border
# The border separates the buttons visually
outputs.solids << [buttons.right, button_color]
outputs.borders << [buttons.right]
# Renders an explanatory label in the center of the button
# Explains to the user what the button does
label_x = buttons.right.x + 20
label_y = buttons.right.y + 35
outputs.labels << [label_x, label_y, ">"]
end
def render_bfs_grid
# A large rect the size of the grid
outputs.solids << [bfs_scale_up(grid.rect), default_color]
# The vertical grid lines
for x in 0..grid.width
outputs.lines << bfs_vertical_line(x)
end
# The horizontal grid lines
for y in 0..grid.height
outputs.lines << bfs_horizontal_line(y)
end
end
def render_heuristic_grid
# A large rect the size of the grid
outputs.solids << [heuristic_scale_up(grid.rect), default_color]
# The vertical grid lines
for x in 0..grid.width
outputs.lines << heuristic_vertical_line(x)
end
# The horizontal grid lines
for y in 0..grid.height
outputs.lines << heuristic_horizontal_line(y)
end
end
# Returns a vertical line for a column of the first grid
def bfs_vertical_line column
bfs_scale_up([column, 0, column, grid.height])
end
# Returns a horizontal line for a column of the first grid
def bfs_horizontal_line row
bfs_scale_up([0, row, grid.width, row])
end
# Returns a vertical line for a column of the second grid
def heuristic_vertical_line column
bfs_scale_up([column + grid.width + 1, 0, column + grid.width + 1, grid.height])
end
# Returns a horizontal line for a column of the second grid
def heuristic_horizontal_line row
bfs_scale_up([grid.width + 1, row, grid.width + grid.width + 1, row])
end
# Renders the star on the first grid
def render_bfs_star
outputs.sprites << [bfs_scale_up(grid.star), 'star.png']
end
# Renders the star on the second grid
def render_heuristic_star
outputs.sprites << [heuristic_scale_up(grid.star), 'star.png']
end
# Renders the target on the first grid
def render_bfs_target
outputs.sprites << [bfs_scale_up(grid.target), 'target.png']
end
# Renders the target on the second grid
def render_heuristic_target
outputs.sprites << [heuristic_scale_up(grid.target), 'target.png']
end
# Renders the walls on the first grid
def render_bfs_walls
grid.walls.each_key do | wall |
outputs.solids << [bfs_scale_up(wall), wall_color]
end
end
# Renders the walls on the second grid
def render_heuristic_walls
grid.walls.each_key do | wall |
outputs.solids << [heuristic_scale_up(wall), wall_color]
end
end
# Renders the visited cells on the first grid
def render_bfs_visited
bfs.came_from.each_key do | visited_cell |
outputs.solids << [bfs_scale_up(visited_cell), visited_color]
end
end
# Renders the visited cells on the second grid
def render_heuristic_visited
heuristic.came_from.each_key do | visited_cell |
outputs.solids << [heuristic_scale_up(visited_cell), visited_color]
end
end
# Renders the frontier cells on the first grid
def render_bfs_frontier
bfs.frontier.each do | frontier_cell |
outputs.solids << [bfs_scale_up(frontier_cell), frontier_color, 200]
end
end
# Renders the frontier cells on the second grid
def render_heuristic_frontier
heuristic.frontier.each do | frontier_cell |
outputs.solids << [heuristic_scale_up(frontier_cell), frontier_color, 200]
end
end
# Renders the path found by the breadth first search on the first grid
def render_bfs_path
bfs.path.each do | path |
outputs.solids << [bfs_scale_up(path), path_color]
end
end
# Renders the path found by the heuristic search on the second grid
def render_heuristic_path
heuristic.path.each do | path |
outputs.solids << [heuristic_scale_up(path), path_color]
end
end
# Returns the rect for the path between two cells based on their relative positions
def get_path_between(cell_one, cell_two)
path = nil
# If cell one is above cell two
if cell_one.x == cell_two.x and cell_one.y > cell_two.y
# Path starts from the center of cell two and moves upward to the center of cell one
path = [cell_two.x + 0.3, cell_two.y + 0.3, 0.4, 1.4]
# If cell one is below cell two
elsif cell_one.x == cell_two.x and cell_one.y < cell_two.y
# Path starts from the center of cell one and moves upward to the center of cell two
path = [cell_one.x + 0.3, cell_one.y + 0.3, 0.4, 1.4]
# If cell one is to the left of cell two
elsif cell_one.x > cell_two.x and cell_one.y == cell_two.y
# Path starts from the center of cell two and moves rightward to the center of cell one
path = [cell_two.x + 0.3, cell_two.y + 0.3, 1.4, 0.4]
# If cell one is to the right of cell two
elsif cell_one.x < cell_two.x and cell_one.y == cell_two.y
# Path starts from the center of cell one and moves rightward to the center of cell two
path = [cell_one.x + 0.3, cell_one.y + 0.3, 1.4, 0.4]
end
path
end
# In code, the cells are represented as 1x1 rectangles
# When drawn, the cells are larger than 1x1 rectangles
# This method is used to scale up cells, and lines
# Objects are scaled up according to the grid.cell_size variable
# This allows for easy customization of the visual scale of the grid
# This method scales up cells for the first grid
def bfs_scale_up(cell)
# Prevents the original value of cell from being edited
cell = cell.clone
# If cell is just an x and y coordinate
if cell.size == 2
# Add a width and height of 1
cell << 1
cell << 1
end
# Scale all the values up
cell.map! { |value| value * grid.cell_size }
# Returns the scaled up cell
cell
end
# Translates the given cell grid.width + 1 to the right and then scales up
# Used to draw cells for the second grid
# This method does not work for lines,
# so separate methods exist for the grid lines
def heuristic_scale_up(cell)
# Prevents the original value of cell from being edited
cell = cell.clone
# Translates the cell to the second grid equivalent
cell.x += grid.width + 1
# Proceeds as if scaling up for the first grid
bfs_scale_up(cell)
end
# Checks and handles input for the buttons
# Called when the mouse is lifted
def input_buttons
input_left_button
input_center_button
input_right_button
end
# Checks if the previous step button is clicked
# If it is, it pauses the animation and moves the search one step backward
def input_left_button
if left_button_clicked?
state.play = false
state.current_step -= 1
recalculate_searches
end
end
# Controls the play/pause button
# Inverses whether the animation is playing or not when clicked
def input_center_button
if center_button_clicked? || inputs.keyboard.key_down.space
state.play = !state.play
end
end
# Checks if the next step button is clicked
# If it is, it pauses the animation and moves the search one step forward
def input_right_button
if right_button_clicked?
state.play = false
state.current_step += 1
move_searches_one_step_forward
end
end
# These methods detect when the buttons are clicked
def left_button_clicked?
inputs.mouse.point.inside_rect?(buttons.left) && inputs.mouse.up
end
def center_button_clicked?
inputs.mouse.point.inside_rect?(buttons.center) && inputs.mouse.up
end
def right_button_clicked?
inputs.mouse.point.inside_rect?(buttons.right) && inputs.mouse.up
end
# Signal that the user is going to be moving the slider
# Is the mouse over the circle of the slider?
def mouse_over_slider?
circle_x = (slider.x - slider.offset) + (state.current_step * slider.spacing)
circle_y = (slider.y - slider.offset)
circle_rect = [circle_x, circle_y, 37, 37]
inputs.mouse.point.inside_rect?(circle_rect)
end
# Signal that the user is going to be moving the star from the first grid
def bfs_mouse_over_star?
inputs.mouse.point.inside_rect?(bfs_scale_up(grid.star))
end
# Signal that the user is going to be moving the star from the second grid
def heuristic_mouse_over_star?
inputs.mouse.point.inside_rect?(heuristic_scale_up(grid.star))
end
# Signal that the user is going to be moving the target from the first grid
def bfs_mouse_over_target?
inputs.mouse.point.inside_rect?(bfs_scale_up(grid.target))
end
# Signal that the user is going to be moving the target from the second grid
def heuristic_mouse_over_target?
inputs.mouse.point.inside_rect?(heuristic_scale_up(grid.target))
end
# Signal that the user is going to be removing walls from the first grid
def bfs_mouse_over_wall?
grid.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(bfs_scale_up(wall))
end
false
end
# Signal that the user is going to be removing walls from the second grid
def heuristic_mouse_over_wall?
grid.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(heuristic_scale_up(wall))
end
false
end
# Signal that the user is going to be adding walls from the first grid
def bfs_mouse_over_grid?
inputs.mouse.point.inside_rect?(bfs_scale_up(grid.rect))
end
# Signal that the user is going to be adding walls from the second grid
def heuristic_mouse_over_grid?
inputs.mouse.point.inside_rect?(heuristic_scale_up(grid.rect))
end
# This method is called when the user is editing the slider
# It pauses the animation and moves the white circle to the closest integer point
# on the slider
# Changes the step of the search to be animated
def process_input_slider
state.play = false
mouse_x = inputs.mouse.point.x
# Bounds the mouse_x to the closest x value on the slider line
mouse_x = slider.x if mouse_x < slider.x
mouse_x = slider.x + slider.w if mouse_x > slider.x + slider.w
# Sets the current search step to the one represented by the mouse x value
# The slider's circle moves due to the render_slider method using anim_steps
state.current_step = ((mouse_x - slider.x) / slider.spacing).to_i
recalculate_searches
end
# Moves the star to the cell closest to the mouse in the first grid
# Only resets the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def process_input_bfs_star
old_star = grid.star.clone
unless bfs_cell_closest_to_mouse == grid.target
grid.star = bfs_cell_closest_to_mouse
end
unless old_star == grid.star
recalculate_searches
end
end
# Moves the star to the cell closest to the mouse in the second grid
# Only resets the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def process_input_heuristic_star
old_star = grid.star.clone
unless heuristic_cell_closest_to_mouse == grid.target
grid.star = heuristic_cell_closest_to_mouse
end
unless old_star == grid.star
recalculate_searches
end
end
# Moves the target to the grid closest to the mouse in the first grid
# Only recalculate_searchess the search if the target changes position
# Called whenever the user is editing the target (puts mouse down on target)
def process_input_bfs_target
old_target = grid.target.clone
unless bfs_cell_closest_to_mouse == grid.star
grid.target = bfs_cell_closest_to_mouse
end
unless old_target == grid.target
recalculate_searches
end
end
# Moves the target to the cell closest to the mouse in the second grid
# Only recalculate_searchess the search if the target changes position
# Called whenever the user is editing the target (puts mouse down on target)
def process_input_heuristic_target
old_target = grid.target.clone
unless heuristic_cell_closest_to_mouse == grid.star
grid.target = heuristic_cell_closest_to_mouse
end
unless old_target == grid.target
recalculate_searches
end
end
# Removes walls in the first grid that are under the cursor
def process_input_bfs_remove_wall
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if bfs_mouse_over_grid?
if grid.walls.has_key?(bfs_cell_closest_to_mouse)
grid.walls.delete(bfs_cell_closest_to_mouse)
recalculate_searches
end
end
end
# Removes walls in the second grid that are under the cursor
def process_input_heuristic_remove_wall
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if heuristic_mouse_over_grid?
if grid.walls.has_key?(heuristic_cell_closest_to_mouse)
grid.walls.delete(heuristic_cell_closest_to_mouse)
recalculate_searches
end
end
end
# Adds a wall in the first grid in the cell the mouse is over
def process_input_bfs_add_wall
if bfs_mouse_over_grid?
unless grid.walls.has_key?(bfs_cell_closest_to_mouse)
grid.walls[bfs_cell_closest_to_mouse] = true
recalculate_searches
end
end
end
# Adds a wall in the second grid in the cell the mouse is over
def process_input_heuristic_add_wall
if heuristic_mouse_over_grid?
unless grid.walls.has_key?(heuristic_cell_closest_to_mouse)
grid.walls[heuristic_cell_closest_to_mouse] = true
recalculate_searches
end
end
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse helps with this
def bfs_cell_closest_to_mouse
# Closest cell to the mouse in the first grid
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Bound x and y to the grid
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse in the second grid helps with this
def heuristic_cell_closest_to_mouse
# Closest cell grid to the mouse in the second
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Translate the cell to the first grid
x -= grid.width + 1
# Bound x and y to the first grid
x = 0 if x < 0
y = 0 if y < 0
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
def recalculate_searches
# Reset the searches
bfs.came_from = {}
bfs.frontier = []
bfs.path = []
heuristic.came_from = {}
heuristic.frontier = []
heuristic.path = []
# Move the searches forward to the current step
state.current_step.times { move_searches_one_step_forward }
end
def move_searches_one_step_forward
bfs_one_step_forward
heuristic_one_step_forward
end
def bfs_one_step_forward
return if bfs.came_from.has_key?(grid.target)
# Only runs at the beginning of the search as setup.
if bfs.came_from.empty?
bfs.frontier << grid.star
bfs.came_from[grid.star] = nil
end
# A step in the search
unless bfs.frontier.empty?
# Takes the next frontier cell
new_frontier = bfs.frontier.shift
# For each of its neighbors
adjacent_neighbors(new_frontier).each do |neighbor|
# That have not been visited and are not walls
unless bfs.came_from.has_key?(neighbor) || grid.walls.has_key?(neighbor)
# Add them to the frontier and mark them as visited
bfs.frontier << neighbor
bfs.came_from[neighbor] = new_frontier
end
end
end
# Sort the frontier so that cells that are in a zigzag pattern are prioritized over those in an line
# Comment this line and let a path generate to see the difference
bfs.frontier = bfs.frontier.sort_by {| cell | proximity_to_star(cell) }
# If the search found the target
if bfs.came_from.has_key?(grid.target)
# Calculate the path between the target and star
bfs_calc_path
end
end
# Calculates the path between the target and star for the breadth first search
# Only called when the breadth first search finds the target
def bfs_calc_path
# Start from the target
endpoint = grid.target
# And the cell it came from
next_endpoint = bfs.came_from[endpoint]
while endpoint and next_endpoint
# Draw a path between these two cells and store it
path = get_path_between(endpoint, next_endpoint)
bfs.path << path
# And get the next pair of cells
endpoint = next_endpoint
next_endpoint = bfs.came_from[endpoint]
# Continue till there are no more cells
end
end
# Moves the heuristic search forward one step
# Can be called from tick while the animation is playing
# Can also be called when recalculating the searches after the user edited the grid
def heuristic_one_step_forward
# Stop the search if the target has been found
return if heuristic.came_from.has_key?(grid.target)
# If the search has not begun
if heuristic.came_from.empty?
# Setup the search to begin from the star
heuristic.frontier << grid.star
heuristic.came_from[grid.star] = nil
end
# One step in the heuristic search
# Unless there are no more cells to explore from
unless heuristic.frontier.empty?
# Get the next cell to explore from
new_frontier = heuristic.frontier.shift
# For each of its neighbors
adjacent_neighbors(new_frontier).each do |neighbor|
# That have not been visited and are not walls
unless heuristic.came_from.has_key?(neighbor) || grid.walls.has_key?(neighbor)
# Add them to the frontier and mark them as visited
heuristic.frontier << neighbor
heuristic.came_from[neighbor] = new_frontier
end
end
end
# Sort the frontier so that cells that are in a zigzag pattern are prioritized over those in an line
heuristic.frontier = heuristic.frontier.sort_by {| cell | proximity_to_star(cell) }
# Sort the frontier so cells that are close to the target are then prioritized
heuristic.frontier = heuristic.frontier.sort_by {| cell | heuristic_heuristic(cell) }
# If the search found the target
if heuristic.came_from.has_key?(grid.target)
# Calculate the path between the target and star
heuristic_calc_path
end
end
# Returns one-dimensional absolute distance between cell and target
# Returns a number to compare distances between cells and the target
def heuristic_heuristic(cell)
(grid.target.x - cell.x).abs + (grid.target.y - cell.y).abs
end
# Calculates the path between the target and star for the heuristic search
# Only called when the heuristic search finds the target
def heuristic_calc_path
# Start from the target
endpoint = grid.target
# And the cell it came from
next_endpoint = heuristic.came_from[endpoint]
while endpoint and next_endpoint
# Draw a path between these two cells and store it
path = get_path_between(endpoint, next_endpoint)
heuristic.path << path
# And get the next pair of cells
endpoint = next_endpoint
next_endpoint = heuristic.came_from[endpoint]
# Continue till there are no more cells
end
end
# Returns a list of adjacent cells
# Used to determine what the next cells to be added to the frontier are
def adjacent_neighbors(cell)
neighbors = []
# Gets all the valid neighbors into the array
# From southern neighbor, clockwise
neighbors << [cell.x , cell.y - 1] unless cell.y == 0
neighbors << [cell.x - 1, cell.y ] unless cell.x == 0
neighbors << [cell.x , cell.y + 1] unless cell.y == grid.height - 1
neighbors << [cell.x + 1, cell.y ] unless cell.x == grid.width - 1
neighbors
end
# Finds the vertical and horizontal distance of a cell from the star
# and returns the larger value
# This method is used to have a zigzag pattern in the rendered path
# A cell that is [5, 5] from the star,
# is explored before over a cell that is [0, 7] away.
# So, if possible, the search tries to go diagonal (zigzag) first
def proximity_to_star(cell)
distance_x = (grid.star.x - cell.x).abs
distance_y = (grid.star.y - cell.y).abs
if distance_x > distance_y
return distance_x
else
return distance_y
end
end
# Methods that allow code to be more concise. Subdivides args.state, which is where all variables are stored.
def grid
state.grid
end
def buttons
state.buttons
end
def slider
state.slider
end
def bfs
state.bfs
end
def heuristic
state.heuristic
end
# Descriptive aliases for colors
def default_color
[221, 212, 213] # Light Brown
end
def wall_color
[134, 134, 120] # Camo Green
end
def visited_color
[204, 191, 179] # Dark Brown
end
def frontier_color
[103, 136, 204] # Blue
end
def path_color
[231, 230, 228] # Pastel White
end
def button_color
[190, 190, 190] # Gray
end
end
# Method that is called by DragonRuby periodically
# Used for updating animations and calculations
def tick args
# Pressing r will reset the application
if args.inputs.keyboard.key_down.r
args.gtk.reset
reset
return
end
# Every tick, new args are passed, and the Breadth First Search tick is called
$heuristic_with_walls ||= Heuristic_With_Walls.new(args)
$heuristic_with_walls.args = args
$heuristic_with_walls.tick
end
def reset
$heuristic_with_walls = nil
end
</code></pre>
<h3 id='----path-finding-algorithms---heuristic-with-walls---main-rb'>Path Finding Algorithms - Heuristic With Walls - main.rb</h3>
<pre><code class="language-ruby"># ./samples/13_path_finding_algorithms/07_heuristic_with_walls/app/main.rb
# This program is inspired by https://www.redblobgames.com/pathfinding/a-star/introduction.html
# The effectiveness of the Heuristic search algorithm is shown through this demonstration.
# Notice that both searches find the shortest path
# The heuristic search, however, explores less of the grid, and is therefore faster.
# The heuristic search prioritizes searching cells that are closer to the target.
# Make sure to look at the Heuristic with walls program to see some of the downsides of the heuristic algorithm.
class Heuristic
attr_gtk
def tick
defaults
render
input
# If animation is playing, and max steps have not been reached
# Move the search a step forward
if state.play && state.current_step < state.max_steps
# Variable that tells the program what step to recalculate up to
state.current_step += 1
move_searches_one_step_forward
end
end
def defaults
# Variables to edit the size and appearance of the grid
# Freely customizable to user's liking
grid.width ||= 15
grid.height ||= 15
grid.cell_size ||= 40
grid.rect ||= [0, 0, grid.width, grid.height]
grid.star ||= [0, 2]
grid.target ||= [14, 12]
grid.walls ||= {
[2, 2] => true,
[3, 2] => true,
[4, 2] => true,
[5, 2] => true,
[6, 2] => true,
[7, 2] => true,
[8, 2] => true,
[9, 2] => true,
[10, 2] => true,
[11, 2] => true,
[12, 2] => true,
[12, 3] => true,
[12, 4] => true,
[12, 5] => true,
[12, 6] => true,
[12, 7] => true,
[12, 8] => true,
[12, 9] => true,
[12, 10] => true,
[12, 11] => true,
[12, 12] => true,
[2, 12] => true,
[3, 12] => true,
[4, 12] => true,
[5, 12] => true,
[6, 12] => true,
[7, 12] => true,
[8, 12] => true,
[9, 12] => true,
[10, 12] => true,
[11, 12] => true,
[12, 12] => true
}
# There are no hills in the Heuristic Search Demo
# What the user is currently editing on the grid
# We store this value, because we want to remember the value even when
# the user's cursor is no longer over what they're interacting with, but
# they are still clicking down on the mouse.
state.user_input ||= :none
# These variables allow the breadth first search to take place
# Came_from is a hash with a key of a cell and a value of the cell that was expanded from to find the key.
# Used to prevent searching cells that have already been found
# and to trace a path from the target back to the starting point.
# Frontier is an array of cells to expand the search from.
# The search is over when there are no more cells to search from.
# Path stores the path from the target to the star, once the target has been found
# It prevents calculating the path every tick.
bfs.came_from ||= {}
bfs.frontier ||= []
bfs.path ||= []
heuristic.came_from ||= {}
heuristic.frontier ||= []
heuristic.path ||= []
# Stores which step of the animation is being rendered
# When the user moves the star or messes with the walls,
# the searches are recalculated up to this step
# Unless the current step has a value
unless state.current_step
# Set the current step to 10
state.current_step = 10
# And calculate the searches up to step 10
recalculate_searches
end
# At some step the animation will end,
# and further steps won't change anything (the whole grid will be explored)
# This step is roughly the grid's width * height
# When anim_steps equals max_steps no more calculations will occur
# and the slider will be at the end
state.max_steps = grid.width * grid.height
# Whether the animation should play or not
# If true, every tick moves anim_steps forward one
# Pressing the stepwise animation buttons will pause the animation
# An if statement instead of the ||= operator is used for assigning a boolean value.
# The || operator does not differentiate between nil and false.
if state.play == nil
state.play = false
end
# Store the rects of the buttons that control the animation
# They are here for user customization
# Editing these might require recentering the text inside them
# Those values can be found in the render_button methods
buttons.left = [470, 600, 50, 50]
buttons.center = [520, 600, 200, 50]
buttons.right = [720, 600, 50, 50]
# The variables below are related to the slider
# They allow the user to customize them
# They also give a central location for the render and input methods to get
# information from
# x & y are the coordinates of the leftmost part of the slider line
slider.x = 440
slider.y = 675
# This is the width of the line
slider.w = 360
# This is the offset for the circle
# Allows the center of the circle to be on the line,
# as opposed to the upper right corner
slider.offset = 20
# This is the spacing between each of the notches on the slider
# Notches are places where the circle can rest on the slider line
# There needs to be a notch for each step before the maximum number of steps
slider.spacing = slider.w.to_f / state.max_steps.to_f
end
# All methods with render draw stuff on the screen
# UI has buttons, the slider, and labels
# The search specific rendering occurs in the respective methods
def render
render_ui
render_bfs
render_heuristic
end
def render_ui
render_buttons
render_slider
render_labels
end
def render_buttons
render_left_button
render_center_button
render_right_button
end
def render_bfs
render_bfs_grid
render_bfs_star
render_bfs_target
render_bfs_visited
render_bfs_walls
render_bfs_frontier
render_bfs_path
end
def render_heuristic
render_heuristic_grid
render_heuristic_star
render_heuristic_target
render_heuristic_visited
render_heuristic_walls
render_heuristic_frontier
render_heuristic_path
end
# This method handles user input every tick
def input
# Check and handle button input
input_buttons
# If the mouse was lifted this tick
if inputs.mouse.up
# Set current input to none
state.user_input = :none
end
# If the mouse was clicked this tick
if inputs.mouse.down
# Determine what the user is editing and appropriately edit the state.user_input variable
determine_input
end
# Process user input based on user_input variable and current mouse position
process_input
end
# Determines what the user is editing
# This method is called when the mouse is clicked down
def determine_input
if mouse_over_slider?
state.user_input = :slider
# If the mouse is over the star in the first grid
elsif bfs_mouse_over_star?
# The user is editing the star from the first grid
state.user_input = :bfs_star
# If the mouse is over the star in the second grid
elsif heuristic_mouse_over_star?
# The user is editing the star from the second grid
state.user_input = :heuristic_star
# If the mouse is over the target in the first grid
elsif bfs_mouse_over_target?
# The user is editing the target from the first grid
state.user_input = :bfs_target
# If the mouse is over the target in the second grid
elsif heuristic_mouse_over_target?
# The user is editing the target from the second grid
state.user_input = :heuristic_target
# If the mouse is over a wall in the first grid
elsif bfs_mouse_over_wall?
# The user is removing a wall from the first grid
state.user_input = :bfs_remove_wall
# If the mouse is over a wall in the second grid
elsif heuristic_mouse_over_wall?
# The user is removing a wall from the second grid
state.user_input = :heuristic_remove_wall
# If the mouse is over the first grid
elsif bfs_mouse_over_grid?
# The user is adding a wall from the first grid
state.user_input = :bfs_add_wall
# If the mouse is over the second grid
elsif heuristic_mouse_over_grid?
# The user is adding a wall from the second grid
state.user_input = :heuristic_add_wall
end
end
# Processes click and drag based on what the user is currently dragging
def process_input
if state.user_input == :slider
process_input_slider
elsif state.user_input == :bfs_star
process_input_bfs_star
elsif state.user_input == :heuristic_star
process_input_heuristic_star
elsif state.user_input == :bfs_target
process_input_bfs_target
elsif state.user_input == :heuristic_target
process_input_heuristic_target
elsif state.user_input == :bfs_remove_wall
process_input_bfs_remove_wall
elsif state.user_input == :heuristic_remove_wall
process_input_heuristic_remove_wall
elsif state.user_input == :bfs_add_wall
process_input_bfs_add_wall
elsif state.user_input == :heuristic_add_wall
process_input_heuristic_add_wall
end
end
def render_slider
# Using primitives hides the line under the white circle of the slider
# Draws the line
outputs.primitives << [slider.x, slider.y, slider.x + slider.w, slider.y].line
# The circle needs to be offset so that the center of the circle
# overlaps the line instead of the upper right corner of the circle
# The circle's x value is also moved based on the current seach step
circle_x = (slider.x - slider.offset) + (state.current_step * slider.spacing)
circle_y = (slider.y - slider.offset)
circle_rect = [circle_x, circle_y, 37, 37]
outputs.primitives << [circle_rect, 'circle-white.png'].sprite
end
def render_labels
outputs.labels << [205, 625, "Breadth First Search"]
outputs.labels << [820, 625, "Heuristic Best-First Search"]
end
def render_left_button
# Draws the button_color button, and a black border
# The border separates the buttons visually
outputs.solids << [buttons.left, button_color]
outputs.borders << [buttons.left]
# Renders an explanatory label in the center of the button
# Explains to the user what the button does
# If the button size is changed, the label might need to be edited as well
# to keep the label in the center of the button
label_x = buttons.left.x + 20
label_y = buttons.left.y + 35
outputs.labels << [label_x, label_y, "<"]
end
def render_center_button
# Draws the button_color button, and a black border
# The border separates the buttons visually
outputs.solids << [buttons.center, button_color]
outputs.borders << [buttons.center]
# Renders an explanatory label in the center of the button
# Explains to the user what the button does
# If the button size is changed, the label might need to be edited as well
# to keep the label in the center of the button
label_x = buttons.center.x + 37
label_y = buttons.center.y + 35
label_text = state.play ? "Pause Animation" : "Play Animation"
outputs.labels << [label_x, label_y, label_text]
end
def render_right_button
# Draws the button_color button, and a black border
# The border separates the buttons visually
outputs.solids << [buttons.right, button_color]
outputs.borders << [buttons.right]
# Renders an explanatory label in the center of the button
# Explains to the user what the button does
label_x = buttons.right.x + 20
label_y = buttons.right.y + 35
outputs.labels << [label_x, label_y, ">"]
end
def render_bfs_grid
# A large rect the size of the grid
outputs.solids << [bfs_scale_up(grid.rect), default_color]
# The vertical grid lines
for x in 0..grid.width
outputs.lines << bfs_vertical_line(x)
end
# The horizontal grid lines
for y in 0..grid.height
outputs.lines << bfs_horizontal_line(y)
end
end
def render_heuristic_grid
# A large rect the size of the grid
outputs.solids << [heuristic_scale_up(grid.rect), default_color]
# The vertical grid lines
for x in 0..grid.width
outputs.lines << heuristic_vertical_line(x)
end
# The horizontal grid lines
for y in 0..grid.height
outputs.lines << heuristic_horizontal_line(y)
end
end
# Returns a vertical line for a column of the first grid
def bfs_vertical_line column
bfs_scale_up([column, 0, column, grid.height])
end
# Returns a horizontal line for a column of the first grid
def bfs_horizontal_line row
bfs_scale_up([0, row, grid.width, row])
end
# Returns a vertical line for a column of the second grid
def heuristic_vertical_line column
bfs_scale_up([column + grid.width + 1, 0, column + grid.width + 1, grid.height])
end
# Returns a horizontal line for a column of the second grid
def heuristic_horizontal_line row
bfs_scale_up([grid.width + 1, row, grid.width + grid.width + 1, row])
end
# Renders the star on the first grid
def render_bfs_star
outputs.sprites << [bfs_scale_up(grid.star), 'star.png']
end
# Renders the star on the second grid
def render_heuristic_star
outputs.sprites << [heuristic_scale_up(grid.star), 'star.png']
end
# Renders the target on the first grid
def render_bfs_target
outputs.sprites << [bfs_scale_up(grid.target), 'target.png']
end
# Renders the target on the second grid
def render_heuristic_target
outputs.sprites << [heuristic_scale_up(grid.target), 'target.png']
end
# Renders the walls on the first grid
def render_bfs_walls
grid.walls.each_key do | wall |
outputs.solids << [bfs_scale_up(wall), wall_color]
end
end
# Renders the walls on the second grid
def render_heuristic_walls
grid.walls.each_key do | wall |
outputs.solids << [heuristic_scale_up(wall), wall_color]
end
end
# Renders the visited cells on the first grid
def render_bfs_visited
bfs.came_from.each_key do | visited_cell |
outputs.solids << [bfs_scale_up(visited_cell), visited_color]
end
end
# Renders the visited cells on the second grid
def render_heuristic_visited
heuristic.came_from.each_key do | visited_cell |
outputs.solids << [heuristic_scale_up(visited_cell), visited_color]
end
end
# Renders the frontier cells on the first grid
def render_bfs_frontier
bfs.frontier.each do | frontier_cell |
outputs.solids << [bfs_scale_up(frontier_cell), frontier_color, 200]
end
end
# Renders the frontier cells on the second grid
def render_heuristic_frontier
heuristic.frontier.each do | frontier_cell |
outputs.solids << [heuristic_scale_up(frontier_cell), frontier_color, 200]
end
end
# Renders the path found by the breadth first search on the first grid
def render_bfs_path
bfs.path.each do | path |
outputs.solids << [bfs_scale_up(path), path_color]
end
end
# Renders the path found by the heuristic search on the second grid
def render_heuristic_path
heuristic.path.each do | path |
outputs.solids << [heuristic_scale_up(path), path_color]
end
end
# Returns the rect for the path between two cells based on their relative positions
def get_path_between(cell_one, cell_two)
path = []
# If cell one is above cell two
if cell_one.x == cell_two.x and cell_one.y > cell_two.y
# Path starts from the center of cell two and moves upward to the center of cell one
path = [cell_two.x + 0.3, cell_two.y + 0.3, 0.4, 1.4]
# If cell one is below cell two
elsif cell_one.x == cell_two.x and cell_one.y < cell_two.y
# Path starts from the center of cell one and moves upward to the center of cell two
path = [cell_one.x + 0.3, cell_one.y + 0.3, 0.4, 1.4]
# If cell one is to the left of cell two
elsif cell_one.x > cell_two.x and cell_one.y == cell_two.y
# Path starts from the center of cell two and moves rightward to the center of cell one
path = [cell_two.x + 0.3, cell_two.y + 0.3, 1.4, 0.4]
# If cell one is to the right of cell two
elsif cell_one.x < cell_two.x and cell_one.y == cell_two.y
# Path starts from the center of cell one and moves rightward to the center of cell two
path = [cell_one.x + 0.3, cell_one.y + 0.3, 1.4, 0.4]
end
path
end
# In code, the cells are represented as 1x1 rectangles
# When drawn, the cells are larger than 1x1 rectangles
# This method is used to scale up cells, and lines
# Objects are scaled up according to the grid.cell_size variable
# This allows for easy customization of the visual scale of the grid
# This method scales up cells for the first grid
def bfs_scale_up(cell)
# Prevents the original value of cell from being edited
cell = cell.clone
# If cell is just an x and y coordinate
if cell.size == 2
# Add a width and height of 1
cell << 1
cell << 1
end
# Scale all the values up
cell.map! { |value| value * grid.cell_size }
# Returns the scaled up cell
cell
end
# Translates the given cell grid.width + 1 to the right and then scales up
# Used to draw cells for the second grid
# This method does not work for lines,
# so separate methods exist for the grid lines
def heuristic_scale_up(cell)
# Prevents the original value of cell from being edited
cell = cell.clone
# Translates the cell to the second grid equivalent
cell.x += grid.width + 1
# Proceeds as if scaling up for the first grid
bfs_scale_up(cell)
end
# Checks and handles input for the buttons
# Called when the mouse is lifted
def input_buttons
input_left_button
input_center_button
input_right_button
end
# Checks if the previous step button is clicked
# If it is, it pauses the animation and moves the search one step backward
def input_left_button
if left_button_clicked?
state.play = false
state.current_step -= 1
recalculate_searches
end
end
# Controls the play/pause button
# Inverses whether the animation is playing or not when clicked
def input_center_button
if center_button_clicked? || inputs.keyboard.key_down.space
state.play = !state.play
end
end
# Checks if the next step button is clicked
# If it is, it pauses the animation and moves the search one step forward
def input_right_button
if right_button_clicked?
state.play = false
state.current_step += 1
move_searches_one_step_forward
end
end
# These methods detect when the buttons are clicked
def left_button_clicked?
inputs.mouse.point.inside_rect?(buttons.left) && inputs.mouse.up
end
def center_button_clicked?
inputs.mouse.point.inside_rect?(buttons.center) && inputs.mouse.up
end
def right_button_clicked?
inputs.mouse.point.inside_rect?(buttons.right) && inputs.mouse.up
end
# Signal that the user is going to be moving the slider
# Is the mouse over the circle of the slider?
def mouse_over_slider?
circle_x = (slider.x - slider.offset) + (state.current_step * slider.spacing)
circle_y = (slider.y - slider.offset)
circle_rect = [circle_x, circle_y, 37, 37]
inputs.mouse.point.inside_rect?(circle_rect)
end
# Signal that the user is going to be moving the star from the first grid
def bfs_mouse_over_star?
inputs.mouse.point.inside_rect?(bfs_scale_up(grid.star))
end
# Signal that the user is going to be moving the star from the second grid
def heuristic_mouse_over_star?
inputs.mouse.point.inside_rect?(heuristic_scale_up(grid.star))
end
# Signal that the user is going to be moving the target from the first grid
def bfs_mouse_over_target?
inputs.mouse.point.inside_rect?(bfs_scale_up(grid.target))
end
# Signal that the user is going to be moving the target from the second grid
def heuristic_mouse_over_target?
inputs.mouse.point.inside_rect?(heuristic_scale_up(grid.target))
end
# Signal that the user is going to be removing walls from the first grid
def bfs_mouse_over_wall?
grid.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(bfs_scale_up(wall))
end
false
end
# Signal that the user is going to be removing walls from the second grid
def heuristic_mouse_over_wall?
grid.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(heuristic_scale_up(wall))
end
false
end
# Signal that the user is going to be adding walls from the first grid
def bfs_mouse_over_grid?
inputs.mouse.point.inside_rect?(bfs_scale_up(grid.rect))
end
# Signal that the user is going to be adding walls from the second grid
def heuristic_mouse_over_grid?
inputs.mouse.point.inside_rect?(heuristic_scale_up(grid.rect))
end
# This method is called when the user is editing the slider
# It pauses the animation and moves the white circle to the closest integer point
# on the slider
# Changes the step of the search to be animated
def process_input_slider
state.play = false
mouse_x = inputs.mouse.point.x
# Bounds the mouse_x to the closest x value on the slider line
mouse_x = slider.x if mouse_x < slider.x
mouse_x = slider.x + slider.w if mouse_x > slider.x + slider.w
# Sets the current search step to the one represented by the mouse x value
# The slider's circle moves due to the render_slider method using anim_steps
state.current_step = ((mouse_x - slider.x) / slider.spacing).to_i
recalculate_searches
end
# Moves the star to the cell closest to the mouse in the first grid
# Only resets the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def process_input_bfs_star
old_star = grid.star.clone
unless bfs_cell_closest_to_mouse == grid.target
grid.star = bfs_cell_closest_to_mouse
end
unless old_star == grid.star
recalculate_searches
end
end
# Moves the star to the cell closest to the mouse in the second grid
# Only resets the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def process_input_heuristic_star
old_star = grid.star.clone
unless heuristic_cell_closest_to_mouse == grid.target
grid.star = heuristic_cell_closest_to_mouse
end
unless old_star == grid.star
recalculate_searches
end
end
# Moves the target to the grid closest to the mouse in the first grid
# Only recalculate_searchess the search if the target changes position
# Called whenever the user is editing the target (puts mouse down on target)
def process_input_bfs_target
old_target = grid.target.clone
unless bfs_cell_closest_to_mouse == grid.star
grid.target = bfs_cell_closest_to_mouse
end
unless old_target == grid.target
recalculate_searches
end
end
# Moves the target to the cell closest to the mouse in the second grid
# Only recalculate_searchess the search if the target changes position
# Called whenever the user is editing the target (puts mouse down on target)
def process_input_heuristic_target
old_target = grid.target.clone
unless heuristic_cell_closest_to_mouse == grid.star
grid.target = heuristic_cell_closest_to_mouse
end
unless old_target == grid.target
recalculate_searches
end
end
# Removes walls in the first grid that are under the cursor
def process_input_bfs_remove_wall
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if bfs_mouse_over_grid?
if grid.walls.has_key?(bfs_cell_closest_to_mouse)
grid.walls.delete(bfs_cell_closest_to_mouse)
recalculate_searches
end
end
end
# Removes walls in the second grid that are under the cursor
def process_input_heuristic_remove_wall
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if heuristic_mouse_over_grid?
if grid.walls.has_key?(heuristic_cell_closest_to_mouse)
grid.walls.delete(heuristic_cell_closest_to_mouse)
recalculate_searches
end
end
end
# Adds a wall in the first grid in the cell the mouse is over
def process_input_bfs_add_wall
if bfs_mouse_over_grid?
unless grid.walls.has_key?(bfs_cell_closest_to_mouse)
grid.walls[bfs_cell_closest_to_mouse] = true
recalculate_searches
end
end
end
# Adds a wall in the second grid in the cell the mouse is over
def process_input_heuristic_add_wall
if heuristic_mouse_over_grid?
unless grid.walls.has_key?(heuristic_cell_closest_to_mouse)
grid.walls[heuristic_cell_closest_to_mouse] = true
recalculate_searches
end
end
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse helps with this
def bfs_cell_closest_to_mouse
# Closest cell to the mouse in the first grid
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Bound x and y to the grid
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse in the second grid helps with this
def heuristic_cell_closest_to_mouse
# Closest cell grid to the mouse in the second
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Translate the cell to the first grid
x -= grid.width + 1
# Bound x and y to the first grid
x = 0 if x < 0
y = 0 if y < 0
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
def recalculate_searches
# Reset the searches
bfs.came_from = {}
bfs.frontier = []
bfs.path = []
heuristic.came_from = {}
heuristic.frontier = []
heuristic.path = []
# Move the searches forward to the current step
state.current_step.times { move_searches_one_step_forward }
end
def move_searches_one_step_forward
bfs_one_step_forward
heuristic_one_step_forward
end
def bfs_one_step_forward
return if bfs.came_from.has_key?(grid.target)
# Only runs at the beginning of the search as setup.
if bfs.came_from.empty?
bfs.frontier << grid.star
bfs.came_from[grid.star] = nil
end
# A step in the search
unless bfs.frontier.empty?
# Takes the next frontier cell
new_frontier = bfs.frontier.shift
# For each of its neighbors
adjacent_neighbors(new_frontier).each do |neighbor|
# That have not been visited and are not walls
unless bfs.came_from.has_key?(neighbor) || grid.walls.has_key?(neighbor)
# Add them to the frontier and mark them as visited
bfs.frontier << neighbor
bfs.came_from[neighbor] = new_frontier
end
end
end
# Sort the frontier so that cells that are in a zigzag pattern are prioritized over those in an line
# Comment this line and let a path generate to see the difference
bfs.frontier = bfs.frontier.sort_by {| cell | proximity_to_star(cell) }
# If the search found the target
if bfs.came_from.has_key?(grid.target)
# Calculate the path between the target and star
bfs_calc_path
end
end
# Calculates the path between the target and star for the breadth first search
# Only called when the breadth first search finds the target
def bfs_calc_path
# Start from the target
endpoint = grid.target
# And the cell it came from
next_endpoint = bfs.came_from[endpoint]
while endpoint and next_endpoint
# Draw a path between these two cells and store it
path = get_path_between(endpoint, next_endpoint)
bfs.path << path
# And get the next pair of cells
endpoint = next_endpoint
next_endpoint = bfs.came_from[endpoint]
# Continue till there are no more cells
end
end
# Moves the heuristic search forward one step
# Can be called from tick while the animation is playing
# Can also be called when recalculating the searches after the user edited the grid
def heuristic_one_step_forward
# Stop the search if the target has been found
return if heuristic.came_from.has_key?(grid.target)
# If the search has not begun
if heuristic.came_from.empty?
# Setup the search to begin from the star
heuristic.frontier << grid.star
heuristic.came_from[grid.star] = nil
end
# One step in the heuristic search
# Unless there are no more cells to explore from
unless heuristic.frontier.empty?
# Get the next cell to explore from
new_frontier = heuristic.frontier.shift
# For each of its neighbors
adjacent_neighbors(new_frontier).each do |neighbor|
# That have not been visited and are not walls
unless heuristic.came_from.has_key?(neighbor) || grid.walls.has_key?(neighbor)
# Add them to the frontier and mark them as visited
heuristic.frontier << neighbor
heuristic.came_from[neighbor] = new_frontier
end
end
end
# Sort the frontier so that cells that are in a zigzag pattern are prioritized over those in an line
heuristic.frontier = heuristic.frontier.sort_by {| cell | proximity_to_star(cell) }
# Sort the frontier so cells that are close to the target are then prioritized
heuristic.frontier = heuristic.frontier.sort_by {| cell | heuristic_heuristic(cell) }
# If the search found the target
if heuristic.came_from.has_key?(grid.target)
# Calculate the path between the target and star
heuristic_calc_path
end
end
# Returns one-dimensional absolute distance between cell and target
# Returns a number to compare distances between cells and the target
def heuristic_heuristic(cell)
(grid.target.x - cell.x).abs + (grid.target.y - cell.y).abs
end
# Calculates the path between the target and star for the heuristic search
# Only called when the heuristic search finds the target
def heuristic_calc_path
# Start from the target
endpoint = grid.target
# And the cell it came from
next_endpoint = heuristic.came_from[endpoint]
while endpoint and next_endpoint
# Draw a path between these two cells and store it
path = get_path_between(endpoint, next_endpoint)
heuristic.path << path
# And get the next pair of cells
endpoint = next_endpoint
next_endpoint = heuristic.came_from[endpoint]
# Continue till there are no more cells
end
end
# Returns a list of adjacent cells
# Used to determine what the next cells to be added to the frontier are
def adjacent_neighbors(cell)
neighbors = []
# Gets all the valid neighbors into the array
# From southern neighbor, clockwise
neighbors << [cell.x , cell.y - 1] unless cell.y == 0
neighbors << [cell.x - 1, cell.y ] unless cell.x == 0
neighbors << [cell.x , cell.y + 1] unless cell.y == grid.height - 1
neighbors << [cell.x + 1, cell.y ] unless cell.x == grid.width - 1
neighbors
end
# Finds the vertical and horizontal distance of a cell from the star
# and returns the larger value
# This method is used to have a zigzag pattern in the rendered path
# A cell that is [5, 5] from the star,
# is explored before over a cell that is [0, 7] away.
# So, if possible, the search tries to go diagonal (zigzag) first
def proximity_to_star(cell)
distance_x = (grid.star.x - cell.x).abs
distance_y = (grid.star.y - cell.y).abs
if distance_x > distance_y
return distance_x
else
return distance_y
end
end
# Methods that allow code to be more concise. Subdivides args.state, which is where all variables are stored.
def grid
state.grid
end
def buttons
state.buttons
end
def slider
state.slider
end
def bfs
state.bfs
end
def heuristic
state.heuristic
end
# Descriptive aliases for colors
def default_color
[221, 212, 213] # Light Brown
end
def wall_color
[134, 134, 120] # Camo Green
end
def visited_color
[204, 191, 179] # Dark Brown
end
def frontier_color
[103, 136, 204] # Blue
end
def path_color
[231, 230, 228] # Pastel White
end
def button_color
[190, 190, 190] # Gray
end
end
# Method that is called by DragonRuby periodically
# Used for updating animations and calculations
def tick args
# Pressing r will reset the application
if args.inputs.keyboard.key_down.r
args.gtk.reset
reset
return
end
# Every tick, new args are passed, and the Breadth First Search tick is called
$heuristic ||= Heuristic.new(args)
$heuristic.args = args
$heuristic.tick
end
def reset
$heuristic = nil
end
</code></pre>
<h3 id='----path-finding-algorithms---a-star---main-rb'>Path Finding Algorithms - A Star - main.rb</h3>
<pre><code class="language-ruby"># ./samples/13_path_finding_algorithms/08_a_star/app/main.rb
# This program is inspired by https://www.redblobgames.com/pathfinding/a-star/introduction.html
# The A* Search works by incorporating both the distance from the starting point
# and the distance from the target in its heurisitic.
# It tends to find the correct (shortest) path even when the Greedy Best-First Search does not,
# and it explores less of the grid, and is therefore faster, than Dijkstra's Search.
class A_Star_Algorithm
attr_gtk
def tick
defaults
render
input
if dijkstra.came_from.empty?
calc_searches
end
end
def defaults
# Variables to edit the size and appearance of the grid
# Freely customizable to user's liking
grid.width ||= 15
grid.height ||= 15
grid.cell_size ||= 27
grid.rect ||= [0, 0, grid.width, grid.height]
grid.star ||= [0, 2]
grid.target ||= [11, 13]
grid.walls ||= {
[2, 2] => true,
[3, 2] => true,
[4, 2] => true,
[5, 2] => true,
[6, 2] => true,
[7, 2] => true,
[8, 2] => true,
[9, 2] => true,
[10, 2] => true,
[11, 2] => true,
[12, 2] => true,
[12, 3] => true,
[12, 4] => true,
[12, 5] => true,
[12, 6] => true,
[12, 7] => true,
[12, 8] => true,
[12, 9] => true,
[12, 10] => true,
[12, 11] => true,
[12, 12] => true,
[5, 12] => true,
[6, 12] => true,
[7, 12] => true,
[8, 12] => true,
[9, 12] => true,
[10, 12] => true,
[11, 12] => true,
[12, 12] => true
}
# What the user is currently editing on the grid
# We store this value, because we want to remember the value even when
# the user's cursor is no longer over what they're interacting with, but
# they are still clicking down on the mouse.
state.user_input ||= :none
# These variables allow the breadth first search to take place
# Came_from is a hash with a key of a cell and a value of the cell that was expanded from to find the key.
# Used to prevent searching cells that have already been found
# and to trace a path from the target back to the starting point.
# Frontier is an array of cells to expand the search from.
# The search is over when there are no more cells to search from.
# Path stores the path from the target to the star, once the target has been found
# It prevents calculating the path every tick.
dijkstra.came_from ||= {}
dijkstra.cost_so_far ||= {}
dijkstra.frontier ||= []
dijkstra.path ||= []
greedy.came_from ||= {}
greedy.frontier ||= []
greedy.path ||= []
a_star.frontier ||= []
a_star.came_from ||= {}
a_star.path ||= []
end
# All methods with render draw stuff on the screen
# UI has buttons, the slider, and labels
# The search specific rendering occurs in the respective methods
def render
render_labels
render_dijkstra
render_greedy
render_a_star
end
def render_labels
outputs.labels << [150, 450, "Dijkstra's"]
outputs.labels << [550, 450, "Greedy Best-First"]
outputs.labels << [1025, 450, "A* Search"]
end
def render_dijkstra
render_dijkstra_grid
render_dijkstra_star
render_dijkstra_target
render_dijkstra_visited
render_dijkstra_walls
render_dijkstra_path
end
def render_greedy
render_greedy_grid
render_greedy_star
render_greedy_target
render_greedy_visited
render_greedy_walls
render_greedy_path
end
def render_a_star
render_a_star_grid
render_a_star_star
render_a_star_target
render_a_star_visited
render_a_star_walls
render_a_star_path
end
# This method handles user input every tick
def input
# If the mouse was lifted this tick
if inputs.mouse.up
# Set current input to none
state.user_input = :none
end
# If the mouse was clicked this tick
if inputs.mouse.down
# Determine what the user is editing and appropriately edit the state.user_input variable
determine_input
end
# Process user input based on user_input variable and current mouse position
process_input
end
# Determines what the user is editing
# This method is called when the mouse is clicked down
def determine_input
# If the mouse is over the star in the first grid
if dijkstra_mouse_over_star?
# The user is editing the star from the first grid
state.user_input = :dijkstra_star
# If the mouse is over the star in the second grid
elsif greedy_mouse_over_star?
# The user is editing the star from the second grid
state.user_input = :greedy_star
# If the mouse is over the star in the third grid
elsif a_star_mouse_over_star?
# The user is editing the star from the third grid
state.user_input = :a_star_star
# If the mouse is over the target in the first grid
elsif dijkstra_mouse_over_target?
# The user is editing the target from the first grid
state.user_input = :dijkstra_target
# If the mouse is over the target in the second grid
elsif greedy_mouse_over_target?
# The user is editing the target from the second grid
state.user_input = :greedy_target
# If the mouse is over the target in the third grid
elsif a_star_mouse_over_target?
# The user is editing the target from the third grid
state.user_input = :a_star_target
# If the mouse is over a wall in the first grid
elsif dijkstra_mouse_over_wall?
# The user is removing a wall from the first grid
state.user_input = :dijkstra_remove_wall
# If the mouse is over a wall in the second grid
elsif greedy_mouse_over_wall?
# The user is removing a wall from the second grid
state.user_input = :greedy_remove_wall
# If the mouse is over a wall in the third grid
elsif a_star_mouse_over_wall?
# The user is removing a wall from the third grid
state.user_input = :a_star_remove_wall
# If the mouse is over the first grid
elsif dijkstra_mouse_over_grid?
# The user is adding a wall from the first grid
state.user_input = :dijkstra_add_wall
# If the mouse is over the second grid
elsif greedy_mouse_over_grid?
# The user is adding a wall from the second grid
state.user_input = :greedy_add_wall
# If the mouse is over the third grid
elsif a_star_mouse_over_grid?
# The user is adding a wall from the third grid
state.user_input = :a_star_add_wall
end
end
# Processes click and drag based on what the user is currently dragging
def process_input
if state.user_input == :dijkstra_star
process_input_dijkstra_star
elsif state.user_input == :greedy_star
process_input_greedy_star
elsif state.user_input == :a_star_star
process_input_a_star_star
elsif state.user_input == :dijkstra_target
process_input_dijkstra_target
elsif state.user_input == :greedy_target
process_input_greedy_target
elsif state.user_input == :a_star_target
process_input_a_star_target
elsif state.user_input == :dijkstra_remove_wall
process_input_dijkstra_remove_wall
elsif state.user_input == :greedy_remove_wall
process_input_greedy_remove_wall
elsif state.user_input == :a_star_remove_wall
process_input_a_star_remove_wall
elsif state.user_input == :dijkstra_add_wall
process_input_dijkstra_add_wall
elsif state.user_input == :greedy_add_wall
process_input_greedy_add_wall
elsif state.user_input == :a_star_add_wall
process_input_a_star_add_wall
end
end
def render_dijkstra_grid
# A large rect the size of the grid
outputs.solids << [dijkstra_scale_up(grid.rect), default_color]
# The vertical grid lines
for x in 0..grid.width
outputs.lines << dijkstra_vertical_line(x)
end
# The horizontal grid lines
for y in 0..grid.height
outputs.lines << dijkstra_horizontal_line(y)
end
end
def render_greedy_grid
# A large rect the size of the grid
outputs.solids << [greedy_scale_up(grid.rect), default_color]
# The vertical grid lines
for x in 0..grid.width
outputs.lines << greedy_vertical_line(x)
end
# The horizontal grid lines
for y in 0..grid.height
outputs.lines << greedy_horizontal_line(y)
end
end
def render_a_star_grid
# A large rect the size of the grid
outputs.solids << [a_star_scale_up(grid.rect), default_color]
# The vertical grid lines
for x in 0..grid.width
outputs.lines << a_star_vertical_line(x)
end
# The horizontal grid lines
for y in 0..grid.height
outputs.lines << a_star_horizontal_line(y)
end
end
# Returns a vertical line for a column of the first grid
def dijkstra_vertical_line column
dijkstra_scale_up([column, 0, column, grid.height])
end
# Returns a horizontal line for a column of the first grid
def dijkstra_horizontal_line row
dijkstra_scale_up([0, row, grid.width, row])
end
# Returns a vertical line for a column of the second grid
def greedy_vertical_line column
dijkstra_scale_up([column + grid.width + 1, 0, column + grid.width + 1, grid.height])
end
# Returns a horizontal line for a column of the second grid
def greedy_horizontal_line row
dijkstra_scale_up([grid.width + 1, row, grid.width + grid.width + 1, row])
end
# Returns a vertical line for a column of the third grid
def a_star_vertical_line column
dijkstra_scale_up([column + (grid.width * 2) + 2, 0, column + (grid.width * 2) + 2, grid.height])
end
# Returns a horizontal line for a column of the third grid
def a_star_horizontal_line row
dijkstra_scale_up([(grid.width * 2) + 2, row, (grid.width * 2) + grid.width + 2, row])
end
# Renders the star on the first grid
def render_dijkstra_star
outputs.sprites << [dijkstra_scale_up(grid.star), 'star.png']
end
# Renders the star on the second grid
def render_greedy_star
outputs.sprites << [greedy_scale_up(grid.star), 'star.png']
end
# Renders the star on the third grid
def render_a_star_star
outputs.sprites << [a_star_scale_up(grid.star), 'star.png']
end
# Renders the target on the first grid
def render_dijkstra_target
outputs.sprites << [dijkstra_scale_up(grid.target), 'target.png']
end
# Renders the target on the second grid
def render_greedy_target
outputs.sprites << [greedy_scale_up(grid.target), 'target.png']
end
# Renders the target on the third grid
def render_a_star_target
outputs.sprites << [a_star_scale_up(grid.target), 'target.png']
end
# Renders the walls on the first grid
def render_dijkstra_walls
grid.walls.each_key do | wall |
outputs.solids << [dijkstra_scale_up(wall), wall_color]
end
end
# Renders the walls on the second grid
def render_greedy_walls
grid.walls.each_key do | wall |
outputs.solids << [greedy_scale_up(wall), wall_color]
end
end
# Renders the walls on the third grid
def render_a_star_walls
grid.walls.each_key do | wall |
outputs.solids << [a_star_scale_up(wall), wall_color]
end
end
# Renders the visited cells on the first grid
def render_dijkstra_visited
dijkstra.came_from.each_key do | visited_cell |
outputs.solids << [dijkstra_scale_up(visited_cell), visited_color]
end
end
# Renders the visited cells on the second grid
def render_greedy_visited
greedy.came_from.each_key do | visited_cell |
outputs.solids << [greedy_scale_up(visited_cell), visited_color]
end
end
# Renders the visited cells on the third grid
def render_a_star_visited
a_star.came_from.each_key do | visited_cell |
outputs.solids << [a_star_scale_up(visited_cell), visited_color]
end
end
# Renders the path found by the breadth first search on the first grid
def render_dijkstra_path
dijkstra.path.each do | path |
outputs.solids << [dijkstra_scale_up(path), path_color]
end
end
# Renders the path found by the greedy search on the second grid
def render_greedy_path
greedy.path.each do | path |
outputs.solids << [greedy_scale_up(path), path_color]
end
end
# Renders the path found by the a_star search on the third grid
def render_a_star_path
a_star.path.each do | path |
outputs.solids << [a_star_scale_up(path), path_color]
end
end
# Returns the rect for the path between two cells based on their relative positions
def get_path_between(cell_one, cell_two)
path = []
# If cell one is above cell two
if cell_one.x == cell_two.x and cell_one.y > cell_two.y
# Path starts from the center of cell two and moves upward to the center of cell one
path = [cell_two.x + 0.3, cell_two.y + 0.3, 0.4, 1.4]
# If cell one is below cell two
elsif cell_one.x == cell_two.x and cell_one.y < cell_two.y
# Path starts from the center of cell one and moves upward to the center of cell two
path = [cell_one.x + 0.3, cell_one.y + 0.3, 0.4, 1.4]
# If cell one is to the left of cell two
elsif cell_one.x > cell_two.x and cell_one.y == cell_two.y
# Path starts from the center of cell two and moves rightward to the center of cell one
path = [cell_two.x + 0.3, cell_two.y + 0.3, 1.4, 0.4]
# If cell one is to the right of cell two
elsif cell_one.x < cell_two.x and cell_one.y == cell_two.y
# Path starts from the center of cell one and moves rightward to the center of cell two
path = [cell_one.x + 0.3, cell_one.y + 0.3, 1.4, 0.4]
end
path
end
# In code, the cells are represented as 1x1 rectangles
# When drawn, the cells are larger than 1x1 rectangles
# This method is used to scale up cells, and lines
# Objects are scaled up according to the grid.cell_size variable
# This allows for easy customization of the visual scale of the grid
# This method scales up cells for the first grid
def dijkstra_scale_up(cell)
# Prevents the original value of cell from being edited
cell = cell.clone
# If cell is just an x and y coordinate
if cell.size == 2
# Add a width and height of 1
cell << 1
cell << 1
end
# Scale all the values up
cell.map! { |value| value * grid.cell_size }
# Returns the scaled up cell
cell
end
# Translates the given cell grid.width + 1 to the right and then scales up
# Used to draw cells for the second grid
# This method does not work for lines,
# so separate methods exist for the grid lines
def greedy_scale_up(cell)
# Prevents the original value of cell from being edited
cell = cell.clone
# Translates the cell to the second grid equivalent
cell.x += grid.width + 1
# Proceeds as if scaling up for the first grid
dijkstra_scale_up(cell)
end
# Translates the given cell (grid.width + 1) * 2 to the right and then scales up
# Used to draw cells for the third grid
# This method does not work for lines,
# so separate methods exist for the grid lines
def a_star_scale_up(cell)
# Prevents the original value of cell from being edited
cell = cell.clone
# Translates the cell to the second grid equivalent
cell.x += grid.width + 1
# Translates the cell to the third grid equivalent
cell.x += grid.width + 1
# Proceeds as if scaling up for the first grid
dijkstra_scale_up(cell)
end
# Signal that the user is going to be moving the star from the first grid
def dijkstra_mouse_over_star?
inputs.mouse.point.inside_rect?(dijkstra_scale_up(grid.star))
end
# Signal that the user is going to be moving the star from the second grid
def greedy_mouse_over_star?
inputs.mouse.point.inside_rect?(greedy_scale_up(grid.star))
end
# Signal that the user is going to be moving the star from the third grid
def a_star_mouse_over_star?
inputs.mouse.point.inside_rect?(a_star_scale_up(grid.star))
end
# Signal that the user is going to be moving the target from the first grid
def dijkstra_mouse_over_target?
inputs.mouse.point.inside_rect?(dijkstra_scale_up(grid.target))
end
# Signal that the user is going to be moving the target from the second grid
def greedy_mouse_over_target?
inputs.mouse.point.inside_rect?(greedy_scale_up(grid.target))
end
# Signal that the user is going to be moving the target from the third grid
def a_star_mouse_over_target?
inputs.mouse.point.inside_rect?(a_star_scale_up(grid.target))
end
# Signal that the user is going to be removing walls from the first grid
def dijkstra_mouse_over_wall?
grid.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(dijkstra_scale_up(wall))
end
false
end
# Signal that the user is going to be removing walls from the second grid
def greedy_mouse_over_wall?
grid.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(greedy_scale_up(wall))
end
false
end
# Signal that the user is going to be removing walls from the third grid
def a_star_mouse_over_wall?
grid.walls.each_key do | wall |
return true if inputs.mouse.point.inside_rect?(a_star_scale_up(wall))
end
false
end
# Signal that the user is going to be adding walls from the first grid
def dijkstra_mouse_over_grid?
inputs.mouse.point.inside_rect?(dijkstra_scale_up(grid.rect))
end
# Signal that the user is going to be adding walls from the second grid
def greedy_mouse_over_grid?
inputs.mouse.point.inside_rect?(greedy_scale_up(grid.rect))
end
# Signal that the user is going to be adding walls from the third grid
def a_star_mouse_over_grid?
inputs.mouse.point.inside_rect?(a_star_scale_up(grid.rect))
end
# Moves the star to the cell closest to the mouse in the first grid
# Only resets the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def process_input_dijkstra_star
old_star = grid.star.clone
unless dijkstra_cell_closest_to_mouse == grid.target
grid.star = dijkstra_cell_closest_to_mouse
end
unless old_star == grid.star
reset_searches
end
end
# Moves the star to the cell closest to the mouse in the second grid
# Only resets the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def process_input_greedy_star
old_star = grid.star.clone
unless greedy_cell_closest_to_mouse == grid.target
grid.star = greedy_cell_closest_to_mouse
end
unless old_star == grid.star
reset_searches
end
end
# Moves the star to the cell closest to the mouse in the third grid
# Only resets the search if the star changes position
# Called whenever the user is editing the star (puts mouse down on star)
def process_input_a_star_star
old_star = grid.star.clone
unless a_star_cell_closest_to_mouse == grid.target
grid.star = a_star_cell_closest_to_mouse
end
unless old_star == grid.star
reset_searches
end
end
# Moves the target to the grid closest to the mouse in the first grid
# Only reset_searchess the search if the target changes position
# Called whenever the user is editing the target (puts mouse down on target)
def process_input_dijkstra_target
old_target = grid.target.clone
unless dijkstra_cell_closest_to_mouse == grid.star
grid.target = dijkstra_cell_closest_to_mouse
end
unless old_target == grid.target
reset_searches
end
end
# Moves the target to the cell closest to the mouse in the second grid
# Only reset_searchess the search if the target changes position
# Called whenever the user is editing the target (puts mouse down on target)
def process_input_greedy_target
old_target = grid.target.clone
unless greedy_cell_closest_to_mouse == grid.star
grid.target = greedy_cell_closest_to_mouse
end
unless old_target == grid.target
reset_searches
end
end
# Moves the target to the cell closest to the mouse in the third grid
# Only reset_searchess the search if the target changes position
# Called whenever the user is editing the target (puts mouse down on target)
def process_input_a_star_target
old_target = grid.target.clone
unless a_star_cell_closest_to_mouse == grid.star
grid.target = a_star_cell_closest_to_mouse
end
unless old_target == grid.target
reset_searches
end
end
# Removes walls in the first grid that are under the cursor
def process_input_dijkstra_remove_wall
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if dijkstra_mouse_over_grid?
if grid.walls.has_key?(dijkstra_cell_closest_to_mouse)
grid.walls.delete(dijkstra_cell_closest_to_mouse)
reset_searches
end
end
end
# Removes walls in the second grid that are under the cursor
def process_input_greedy_remove_wall
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if greedy_mouse_over_grid?
if grid.walls.has_key?(greedy_cell_closest_to_mouse)
grid.walls.delete(greedy_cell_closest_to_mouse)
reset_searches
end
end
end
# Removes walls in the third grid that are under the cursor
def process_input_a_star_remove_wall
# The mouse needs to be inside the grid, because we only want to remove walls
# the cursor is directly over
# Recalculations should only occur when a wall is actually deleted
if a_star_mouse_over_grid?
if grid.walls.has_key?(a_star_cell_closest_to_mouse)
grid.walls.delete(a_star_cell_closest_to_mouse)
reset_searches
end
end
end
# Adds a wall in the first grid in the cell the mouse is over
def process_input_dijkstra_add_wall
if dijkstra_mouse_over_grid?
unless grid.walls.has_key?(dijkstra_cell_closest_to_mouse)
grid.walls[dijkstra_cell_closest_to_mouse] = true
reset_searches
end
end
end
# Adds a wall in the second grid in the cell the mouse is over
def process_input_greedy_add_wall
if greedy_mouse_over_grid?
unless grid.walls.has_key?(greedy_cell_closest_to_mouse)
grid.walls[greedy_cell_closest_to_mouse] = true
reset_searches
end
end
end
# Adds a wall in the third grid in the cell the mouse is over
def process_input_a_star_add_wall
if a_star_mouse_over_grid?
unless grid.walls.has_key?(a_star_cell_closest_to_mouse)
grid.walls[a_star_cell_closest_to_mouse] = true
reset_searches
end
end
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse helps with this
def dijkstra_cell_closest_to_mouse
# Closest cell to the mouse in the first grid
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Bound x and y to the grid
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse in the second grid helps with this
def greedy_cell_closest_to_mouse
# Closest cell grid to the mouse in the second
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Translate the cell to the first grid
x -= grid.width + 1
# Bound x and y to the first grid
x = 0 if x < 0
y = 0 if y < 0
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
# When the user grabs the star and puts their cursor to the far right
# and moves up and down, the star is supposed to move along the grid as well
# Finding the cell closest to the mouse in the third grid helps with this
def a_star_cell_closest_to_mouse
# Closest cell grid to the mouse in the second
x = (inputs.mouse.point.x / grid.cell_size).to_i
y = (inputs.mouse.point.y / grid.cell_size).to_i
# Translate the cell to the first grid
x -= (grid.width + 1) * 2
# Bound x and y to the first grid
x = 0 if x < 0
y = 0 if y < 0
x = grid.width - 1 if x > grid.width - 1
y = grid.height - 1 if y > grid.height - 1
# Return closest cell
[x, y]
end
def reset_searches
# Reset the searches
dijkstra.came_from = {}
dijkstra.cost_so_far = {}
dijkstra.frontier = []
dijkstra.path = []
greedy.came_from = {}
greedy.frontier = []
greedy.path = []
a_star.came_from = {}
a_star.frontier = []
a_star.path = []
end
def calc_searches
calc_dijkstra
calc_greedy
calc_a_star
# Move the searches forward to the current step
# state.current_step.times { move_searches_one_step_forward }
end
def calc_dijkstra
# Sets up the search to begin from the star
dijkstra.frontier << grid.star
dijkstra.came_from[grid.star] = nil
dijkstra.cost_so_far[grid.star] = 0
# Until the target is found or there are no more cells to explore from
until dijkstra.came_from.has_key?(grid.target) or dijkstra.frontier.empty?
# Take the next frontier cell. The first element is the cell, the second is the priority.
new_frontier = dijkstra.frontier.shift#[0]
# For each of its neighbors
adjacent_neighbors(new_frontier).each do | neighbor |
# That have not been visited and are not walls
unless dijkstra.came_from.has_key?(neighbor) or grid.walls.has_key?(neighbor)
# Add them to the frontier and mark them as visited
dijkstra.frontier << neighbor
dijkstra.came_from[neighbor] = new_frontier
dijkstra.cost_so_far[neighbor] = dijkstra.cost_so_far[new_frontier] + 1
end
end
# Sort the frontier so that cells that are in a zigzag pattern are prioritized over those in an line
# Comment this line and let a path generate to see the difference
dijkstra.frontier = dijkstra.frontier.sort_by {| cell | proximity_to_star(cell) }
dijkstra.frontier = dijkstra.frontier.sort_by {| cell | dijkstra.cost_so_far[cell] }
end
# If the search found the target
if dijkstra.came_from.has_key?(grid.target)
# Calculate the path between the target and star
dijkstra_calc_path
end
end
def calc_greedy
# Sets up the search to begin from the star
greedy.frontier << grid.star
greedy.came_from[grid.star] = nil
# Until the target is found or there are no more cells to explore from
until greedy.came_from.has_key?(grid.target) or greedy.frontier.empty?
# Take the next frontier cell
new_frontier = greedy.frontier.shift
# For each of its neighbors
adjacent_neighbors(new_frontier).each do | neighbor |
# That have not been visited and are not walls
unless greedy.came_from.has_key?(neighbor) or grid.walls.has_key?(neighbor)
# Add them to the frontier and mark them as visited
greedy.frontier << neighbor
greedy.came_from[neighbor] = new_frontier
end
end
# Sort the frontier so that cells that are in a zigzag pattern are prioritized over those in an line
# Comment this line and let a path generate to see the difference
greedy.frontier = greedy.frontier.sort_by {| cell | proximity_to_star(cell) }
# Sort the frontier so cells that are close to the target are then prioritized
greedy.frontier = greedy.frontier.sort_by {| cell | greedy_heuristic(cell) }
end
# If the search found the target
if greedy.came_from.has_key?(grid.target)
# Calculate the path between the target and star
greedy_calc_path
end
end
def calc_a_star
# Setup the search to start from the star
a_star.came_from[grid.star] = nil
a_star.cost_so_far[grid.star] = 0
a_star.frontier << grid.star
# Until there are no more cells to explore from or the search has found the target
until a_star.frontier.empty? or a_star.came_from.has_key?(grid.target)
# Get the next cell to expand from
current_frontier = a_star.frontier.shift
# For each of that cells neighbors
adjacent_neighbors(current_frontier).each do | neighbor |
# That have not been visited and are not walls
unless a_star.came_from.has_key?(neighbor) or grid.walls.has_key?(neighbor)
# Add them to the frontier and mark them as visited
a_star.frontier << neighbor
a_star.came_from[neighbor] = current_frontier
a_star.cost_so_far[neighbor] = a_star.cost_so_far[current_frontier] + 1
end
end
# Sort the frontier so that cells that are in a zigzag pattern are prioritized over those in an line
# Comment this line and let a path generate to see the difference
a_star.frontier = a_star.frontier.sort_by {| cell | proximity_to_star(cell) }
a_star.frontier = a_star.frontier.sort_by {| cell | a_star.cost_so_far[cell] + greedy_heuristic(cell) }
end
# If the search found the target
if a_star.came_from.has_key?(grid.target)
# Calculate the path between the target and star
a_star_calc_path
end
end
# Calculates the path between the target and star for the breadth first search
# Only called when the breadth first search finds the target
def dijkstra_calc_path
# Start from the target
endpoint = grid.target
# And the cell it came from
next_endpoint = dijkstra.came_from[endpoint]
while endpoint and next_endpoint
# Draw a path between these two cells and store it
path = get_path_between(endpoint, next_endpoint)
dijkstra.path << path
# And get the next pair of cells
endpoint = next_endpoint
next_endpoint = dijkstra.came_from[endpoint]
# Continue till there are no more cells
end
end
# Returns one-dimensional absolute distance between cell and target
# Returns a number to compare distances between cells and the target
def greedy_heuristic(cell)
(grid.target.x - cell.x).abs + (grid.target.y - cell.y).abs
end
# Calculates the path between the target and star for the greedy search
# Only called when the greedy search finds the target
def greedy_calc_path
# Start from the target
endpoint = grid.target
# And the cell it came from
next_endpoint = greedy.came_from[endpoint]
while endpoint and next_endpoint
# Draw a path between these two cells and store it
path = get_path_between(endpoint, next_endpoint)
greedy.path << path
# And get the next pair of cells
endpoint = next_endpoint
next_endpoint = greedy.came_from[endpoint]
# Continue till there are no more cells
end
end
# Calculates the path between the target and star for the a_star search
# Only called when the a_star search finds the target
def a_star_calc_path
# Start from the target
endpoint = grid.target
# And the cell it came from
next_endpoint = a_star.came_from[endpoint]
while endpoint and next_endpoint
# Draw a path between these two cells and store it
path = get_path_between(endpoint, next_endpoint)
a_star.path << path
# And get the next pair of cells
endpoint = next_endpoint
next_endpoint = a_star.came_from[endpoint]
# Continue till there are no more cells
end
end
# Returns a list of adjacent cells
# Used to determine what the next cells to be added to the frontier are
def adjacent_neighbors(cell)
neighbors = []
# Gets all the valid neighbors into the array
# From southern neighbor, clockwise
neighbors << [cell.x , cell.y - 1] unless cell.y == 0
neighbors << [cell.x - 1, cell.y ] unless cell.x == 0
neighbors << [cell.x , cell.y + 1] unless cell.y == grid.height - 1
neighbors << [cell.x + 1, cell.y ] unless cell.x == grid.width - 1
neighbors
end
# Finds the vertical and horizontal distance of a cell from the star
# and returns the larger value
# This method is used to have a zigzag pattern in the rendered path
# A cell that is [5, 5] from the star,
# is explored before over a cell that is [0, 7] away.
# So, if possible, the search tries to go diagonal (zigzag) first
def proximity_to_star(cell)
distance_x = (grid.star.x - cell.x).abs
distance_y = (grid.star.y - cell.y).abs
if distance_x > distance_y
return distance_x
else
return distance_y
end
end
# Methods that allow code to be more concise. Subdivides args.state, which is where all variables are stored.
def grid
state.grid
end
def dijkstra
state.dijkstra
end
def greedy
state.greedy
end
def a_star
state.a_star
end
# Descriptive aliases for colors
def default_color
[221, 212, 213] # Light Brown
end
def wall_color
[134, 134, 120] # Camo Green
end
def visited_color
[204, 191, 179] # Dark Brown
end
def path_color
[231, 230, 228] # Pastel White
end
def button_color
[190, 190, 190] # Gray
end
end
# Method that is called by DragonRuby periodically
# Used for updating animations and calculations
def tick args
# Pressing r will reset the application
if args.inputs.keyboard.key_down.r
args.gtk.reset
reset
return
end
# Every tick, new args are passed, and the Breadth First Search tick is called
$a_star_algorithm ||= A_Star_Algorithm.new(args)
$a_star_algorithm.args = args
$a_star_algorithm.tick
end
def reset
$a_star_algorithm = nil
end
</code></pre>
<h3 id='----path-finding-algorithms---tower-defense---main-rb'>Path Finding Algorithms - Tower Defense - main.rb</h3>
<pre><code class="language-ruby"># ./samples/13_path_finding_algorithms/09_tower_defense/app/main.rb
# An example of some major components in a tower defence game
# The pathing of the tanks is determined by A* algorithm -- try editing the walls
# The turrets shoot bullets at the closest tank. The bullets are heat-seeking
def tick args
$gtk.reset if args.inputs.keyboard.key_down.r
defaults args
render args
calc args
end
def defaults args
args.outputs.background_color = wall_color
args.state.grid_size = 5
args.state.tile_size = 50
args.state.grid_start ||= [0, 0]
args.state.grid_goal ||= [4, 4]
# Try editing these walls to see the path change!
args.state.walls ||= {
[0, 4] => true,
[1, 3] => true,
[3, 1] => true,
# [4, 0] => true,
}
args.state.a_star.frontier ||= []
args.state.a_star.came_from ||= {}
args.state.a_star.path ||= []
args.state.tanks ||= []
args.state.tank_spawn_period ||= 60
args.state.tank_sprite_path ||= 'sprites/circle/white.png'
args.state.tank_speed ||= 1
args.state.turret_shoot_period = 10
# Turrets can be entered as [x, y] but are immediately mapped to hashes
# Walls are also added where the turrets are to prevent tanks from pathing over them
args.state.turrets ||= [
[2, 2]
].each { |turret| args.state.walls[turret] = true}.map do |x, y|
{
x: x * args.state.tile_size,
y: y * args.state.tile_size,
w: args.state.tile_size,
h: args.state.tile_size,
path: 'sprites/circle/gray.png',
range: 100
}
end
args.state.bullet_size ||= 25
args.state.bullets ||= []
args.state.bullet_path ||= 'sprites/circle/orange.png'
#
end
def render args
render_grid args
render_a_star args
args.outputs.sprites << args.state.tanks
args.outputs.sprites << args.state.turrets
args.outputs.sprites << args.state.bullets
end
def render_grid args
# Draw a square the size and color of the grid
args.outputs.solids << [
0,
0,
args.state.grid_size * args.state.tile_size,
args.state.grid_size * args.state.tile_size,
grid_color
]
# Draw lines across the grid to show tiles
(args.state.grid_size + 1).times do | value |
render_horizontal_line(args, value)
render_vertical_line(args, value)
end
# Render special tiles
render_tile(args, args.state.grid_start, start_color)
render_tile(args, args.state.grid_goal, goal_color)
args.state.walls.keys.each { |wall| render_tile(args, wall, wall_color) }
end
def render_vertical_line args, x
args.outputs.lines << [
x * args.state.tile_size,
0,
x * args.state.tile_size,
args.state.tile_size * args.state.grid_size,
]
end
def render_horizontal_line args, y
args.outputs.lines << [
0,
y * args.state.tile_size,
args.state.tile_size * args.state.grid_size,
y * args.state.tile_size,
]
end
def render_tile args, tile, color
args.outputs.solids << [
tile.x * args.state.tile_size,
tile.y * args.state.tile_size,
args.state.tile_size,
args.state.tile_size,
color
]
end
def calc args
calc_a_star args
calc_tanks args
calc_turrets args
calc_bullets args
end
def calc_a_star args
# Only does this one time
return unless args.state.a_star.path.empty?
# Start the search from the grid start
args.state.a_star.frontier << args.state.grid_start
args.state.a_star.came_from[args.state.grid_start] = nil
# Until a path to the goal has been found or there are no more tiles to explore
until (args.state.a_star.came_from.has_key?(args.state.grid_goal)|| args.state.a_star.frontier.empty?)
# For the first tile in the frontier
tile_to_expand_from = args.state.a_star.frontier.shift
# Add each of its neighbors to the frontier
neighbors(args, tile_to_expand_from).each do | tile |
args.state.a_star.frontier << tile
args.state.a_star.came_from[tile] = tile_to_expand_from
end
end
# Stop calculating a path if the goal was never reached
return unless args.state.a_star.came_from.has_key? args.state.grid_goal
# Fill path by tracing back from the goal
current_cell = args.state.grid_goal
while current_cell
args.state.a_star.path.unshift current_cell
current_cell = args.state.a_star.came_from[current_cell]
end
puts "The path has been calculated"
puts args.state.a_star.path
end
def calc_tanks args
spawn_tank args
move_tanks args
end
def move_tanks args
# Remove tanks that have reached the end of their path
args.state.tanks.reject! { |tank| tank[:a_star].empty? }
# Tanks have an array that has each tile it has to go to in order from a* path
args.state.tanks.each do | tank |
destination = tank[:a_star][0]
# Move the tank towards the destination
tank[:x] += copy_sign(args.state.tank_speed, ((destination.x * args.state.tile_size) - tank[:x]))
tank[:y] += copy_sign(args.state.tank_speed, ((destination.y * args.state.tile_size) - tank[:y]))
# If the tank has reached its destination
if (destination.x * args.state.tile_size) == tank[:x] and
(destination.y * args.state.tile_size) == tank[:y]
# Set the destination to the next point in the path
tank[:a_star].shift
end
end
end
def calc_turrets args
return unless args.state.tick_count.mod_zero? args.state.turret_shoot_period
args.state.turrets.each do | turret |
# Finds the closest tank
target = nil
shortest_distance = turret[:range] + 1
args.state.tanks.each do | tank |
distance = distance_between(turret[:x], turret[:y], tank[:x], tank[:y])
if distance < shortest_distance
target = tank
shortest_distance = distance
end
end
# If there is a tank in range, fires a bullet
if target
args.state.bullets << {
x: turret[:x],
y: turret[:y],
w: args.state.bullet_size,
h: args.state.bullet_size,
path: args.state.bullet_path,
# Note that this makes it heat-seeking, because target is passed by reference
# Could do target.clone to make the bullet go to where the tank initially was
target: target
}
end
end
end
def calc_bullets args
# Bullets aim for the center of their targets
args.state.bullets.each { |bullet| move bullet, center_of(bullet[:target])}
args.state.bullets.reject! { |b| b.intersect_rect? b[:target] }
end
def center_of object
object = object.clone
object[:x] += 0.5
object[:y] += 0.5
object
end
def render_a_star args
args.state.a_star.path.map do |tile|
# Map each x, y coordinate to the center of the tile and scale up
[(tile.x + 0.5) * args.state.tile_size, (tile.y + 0.5) * args.state.tile_size]
end.inject do | point_a, point_b |
# Render the line between each point
args.outputs.lines << [point_a.x, point_a.y, point_b.x, point_b.y, a_star_color]
point_b
end
end
# Moves object to target at speed
def move object, target, speed = 1
if target.is_a? Hash
object[:x] += copy_sign(speed, target[:x] - object[:x])
object[:y] += copy_sign(speed, target[:y] - object[:y])
else
object[:x] += copy_sign(speed, target.x - object[:x])
object[:y] += copy_sign(speed, target.y - object[:y])
end
end
#
#
def distance_between a_x, a_y, b_x, b_y
(((b_x - a_x) ** 2) + ((b_y - a_y) ** 2)) ** 0.5
end
def copy_sign value, sign
return 0 if sign == 0
return value if sign > 0
-value
end
#
def spawn_tank args
return unless args.state.tick_count.mod_zero? args.state.tank_spawn_period
args.state.tanks << {
x: args.state.grid_start.x,
y: args.state.grid_start.y,
w: args.state.tile_size,
h: args.state.tile_size,
path: args.state.tank_sprite_path,
a_star: args.state.a_star.path.clone
}
end
def neighbors args, tile
[[tile.x, tile.y - 1],
[tile.x, tile.y + 1],
[tile.x + 1, tile.y],
[tile.x - 1, tile.y]].reject do | neighbor |
args.state.a_star.came_from.has_key?(neighbor) or
tile_out_of_bounds?(args, neighbor) or
args.state.walls.has_key? neighbor
end
end
def tile_out_of_bounds? args, tile
tile.x < 0 or tile.y < 0 or tile.x >= args.state.grid_size or tile.y >= args.state.grid_size
end
def grid_color
[133, 226, 144]
end
def start_color
[226, 144, 133]
end
def goal_color
[226, 133, 144]
end
def wall_color
[133, 144, 226]
end
def a_star_color
[0, 0, 255]
end
</code></pre>
<h3 id='----3d---3d-cube---main-rb'>3d - 3d Cube - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_3d/01_3d_cube/app/main.rb
STARTX = 0.0
STARTY = 0.0
ENDY = 20.0
ENDX = 20.0
SPINPOINT = 10
SPINDURATION = 400
POINTSIZE = 8
BOXDEPTH = 40
YAW = 1
DISTANCE = 10
def tick args
args.outputs.background_color = [0, 0, 0]
a = Math.sin(args.state.tick_count / SPINDURATION) * Math.tan(args.state.tick_count / SPINDURATION)
s = Math.sin(a)
c = Math.cos(a)
x = STARTX
y = STARTY
offset_x = (1280 - (ENDX - STARTX)) / 2
offset_y = (360 - (ENDY - STARTY)) / 2
srand(1)
while y < ENDY do
while x < ENDX do
if (y == STARTY ||
y == (ENDY / 0.5) * 2 ||
y == (ENDY / 0.5) * 2 + 0.5 ||
y == ENDY - 0.5 ||
x == STARTX ||
x == ENDX - 0.5)
z = rand(BOXDEPTH)
z *= Math.sin(a / 2)
x -= SPINPOINT
u = (x * c) - (z * s)
v = (x * s) + (z * c)
k = DISTANCE.fdiv(100) + (v / 500 * YAW)
u = u / k
v = y / k
w = POINTSIZE / 10 / k
args.outputs.sprites << { x: offset_x + u - w, y: offset_y + v - w, w: w, h: w, path: 'sprites/square-blue.png'}
x += SPINPOINT
end
x += 0.5
end
y += 0.5
x = STARTX
end
end
$gtk.reset
</code></pre>
<h3 id='----3d---wireframe---main-rb'>3d - Wireframe - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_3d/02_wireframe/app/main.rb
def tick args
args.state.model ||= Object3D.new('data/shuttle.off')
args.state.mtx ||= rotate3D(0, 0, 0)
args.state.inv_mtx ||= rotate3D(0, 0, 0)
delta_mtx = rotate3D(args.inputs.up_down * 0.01, input_roll(args) * 0.01, args.inputs.left_right * 0.01)
args.outputs.lines << args.state.model.edges
args.state.model.fast_3x3_transform! args.state.inv_mtx
args.state.inv_mtx = mtx_mul(delta_mtx.transpose, args.state.inv_mtx)
args.state.mtx = mtx_mul(args.state.mtx, delta_mtx)
args.state.model.fast_3x3_transform! args.state.mtx
args.outputs.background_color = [0, 0, 0]
args.outputs.debug << args.gtk.framerate_diagnostics_primitives
end
def input_roll args
roll = 0
roll += 1 if args.inputs.keyboard.e
roll -= 1 if args.inputs.keyboard.q
roll
end
def rotate3D(theta_x = 0.1, theta_y = 0.1, theta_z = 0.1)
c_x, s_x = Math.cos(theta_x), Math.sin(theta_x)
c_y, s_y = Math.cos(theta_y), Math.sin(theta_y)
c_z, s_z = Math.cos(theta_z), Math.sin(theta_z)
rot_x = [[1, 0, 0], [0, c_x, -s_x], [0, s_x, c_x]]
rot_y = [[c_y, 0, s_y], [0, 1, 0], [-s_y, 0, c_y]]
rot_z = [[c_z, -s_z, 0], [s_z, c_z, 0], [0, 0, 1]]
mtx_mul(mtx_mul(rot_x, rot_y), rot_z)
end
def mtx_mul(a, b)
is = (0...a.length)
js = (0...b[0].length)
ks = (0...b.length)
is.map do |i|
js.map do |j|
ks.map do |k|
a[i][k] * b[k][j]
end.reduce(&:plus)
end
end
end
class Object3D
attr_reader :vert_count, :face_count, :edge_count, :verts, :faces, :edges
def initialize(path)
@vert_count = 0
@face_count = 0
@edge_count = 0
@verts = []
@faces = []
@edges = []
_init_from_file path
end
def _init_from_file path
file_lines = $gtk.read_file(path).split("\n")
.reject { |line| line.start_with?('#') || line.split(' ').length == 0 } # Strip out simple comments and blank lines
.map { |line| line.split('#')[0] } # Strip out end of line comments
.map { |line| line.split(' ') } # Tokenize by splitting on whitespace
raise "OFF file did not start with OFF." if file_lines.shift != ["OFF"] # OFF meshes are supposed to begin with "OFF" as the first line.
raise "<NVertices NFaces NEdges> line malformed" if file_lines[0].length != 3 # The second line needs to have 3 numbers. Raise an error if it doesn't.
@vert_count, @face_count, @edge_count = file_lines.shift&.map(&:to_i) # Update the counts
# Only the vertex and face counts need to be accurate. Raise an error if they are inaccurate.
raise "Incorrect number of vertices and/or faces (Parsed VFE header: #{@vert_count} #{@face_count} #{@edge_count})" if file_lines.length != @vert_count + @face_count
# Grab all the lines describing vertices.
vert_lines = file_lines[0, @vert_count]
# Grab all the lines describing faces.
face_lines = file_lines[@vert_count, @face_count]
# Create all the vertices
@verts = vert_lines.map_with_index { |line, id| Vertex.new(line, id) }
# Create all the faces
@faces = face_lines.map { |line| Face.new(line, @verts) }
# Create all the edges
@edges = @faces.flat_map(&:edges).uniq do |edge|
sorted = edge.sorted
[sorted.point_a, sorted.point_b]
end
end
def fast_3x3_transform! mtx
@verts.each { |vert| vert.fast_3x3_transform! mtx }
end
end
class Face
attr_reader :verts, :edges
def initialize(data, verts)
vert_count = data[0].to_i
vert_ids = data[1, vert_count].map(&:to_i)
@verts = vert_ids.map { |i| verts[i] }
@edges = []
(0...vert_count).each { |i| @edges[i] = Edge.new(verts[vert_ids[i - 1]], verts[vert_ids[i]]) }
@edges.rotate! 1
end
end
class Edge
attr_reader :point_a, :point_b
def initialize(point_a, point_b)
@point_a = point_a
@point_b = point_b
end
def sorted
@point_a.id < @point_b.id ? self : Edge.new(@point_b, @point_a)
end
def draw_override ffi
ffi.draw_line(@point_a.render_x, @point_a.render_y, @point_b.render_x, @point_b.render_y, 255, 0, 0, 128)
ffi.draw_line(@point_a.render_x+1, @point_a.render_y, @point_b.render_x+1, @point_b.render_y, 255, 0, 0, 128)
ffi.draw_line(@point_a.render_x, @point_a.render_y+1, @point_b.render_x, @point_b.render_y+1, 255, 0, 0, 128)
ffi.draw_line(@point_a.render_x+1, @point_a.render_y+1, @point_b.render_x+1, @point_b.render_y+1, 255, 0, 0, 128)
end
def primitive_marker
:line
end
end
class Vertex
attr_accessor :x, :y, :z, :id
def initialize(data, id)
@x = data[0].to_f
@y = data[1].to_f
@z = data[2].to_f
@id = id
end
def fast_3x3_transform! mtx
_x, _y, _z = @x, @y, @z
@x = mtx[0][0] * _x + mtx[0][1] * _y + mtx[0][2] * _z
@y = mtx[1][0] * _x + mtx[1][1] * _y + mtx[1][2] * _z
@z = mtx[2][0] * _x + mtx[2][1] * _y + mtx[2][2] * _z
end
def render_x
@x * (10 / (5 - @y)) * 170 + 640
end
def render_y
@z * (10 / (5 - @y)) * 170 + 360
end
end
</code></pre>
<h3 id='----3d---wireframe---data---what-is-this-txt'>3d - Wireframe - Data - what-is-this.txt</h3>
<pre><code class="language-ruby"># ./samples/99_genre_3d/02_wireframe/data/what-is-this.txt
https://en.wikipedia.org/wiki/OFF_(file_format)
</code></pre>
<h3 id='----arcade---bullet-hell---main-rb'>Arcade - Bullet Hell - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_arcade/bullet_hell/app/main.rb
def tick args
args.state.base_columns ||= 10.times.map { |n| 50 * n + 1280 / 2 - 5 * 50 + 5 }
args.state.base_rows ||= 5.times.map { |n| 50 * n + 720 - 5 * 50 }
args.state.offset_columns = 10.times.map { |n| (n - 4.5) * Math.sin(Kernel.tick_count.to_radians) * 12 }
args.state.offset_rows = 5.map { 0 }
args.state.columns = 10.times.map { |i| args.state.base_columns[i] + args.state.offset_columns[i] }
args.state.rows = 5.times.map { |i| args.state.base_rows[i] + args.state.offset_rows[i] }
args.state.explosions ||= []
args.state.enemies ||= []
args.state.score ||= 0
args.state.wave ||= 0
if args.state.enemies.empty?
args.state.wave += 1
args.state.wave_root = Math.sqrt(args.state.wave)
args.state.enemies = make_enemies
end
args.state.player ||= {x: 620, y: 80, w: 40, h: 40, path: 'sprites/circle-gray.png', angle: 90, cooldown: 0, alive: true}
args.state.enemy_bullets ||= []
args.state.player_bullets ||= []
args.state.lives ||= 3
args.state.missed_shots ||= 0
args.state.fired_shots ||= 0
update_explosions args
update_enemy_positions args
if args.inputs.left && args.state.player[:x] > (300 + 5)
args.state.player[:x] -= 5
end
if args.inputs.right && args.state.player[:x] < (1280 - args.state.player[:w] - 300 - 5)
args.state.player[:x] += 5
end
args.state.enemy_bullets.each do |bullet|
bullet[:x] += bullet[:dx]
bullet[:y] += bullet[:dy]
end
args.state.player_bullets.each do |bullet|
bullet[:x] += bullet[:dx]
bullet[:y] += bullet[:dy]
end
args.state.enemy_bullets = args.state.enemy_bullets.find_all { |bullet| bullet[:y].between?(-16, 736) }
args.state.player_bullets = args.state.player_bullets.find_all do |bullet|
if bullet[:y].between?(-16, 736)
true
else
args.state.missed_shots += 1
false
end
end
args.state.enemies = args.state.enemies.reject do |enemy|
if args.state.player[:alive] && 1500 > (args.state.player[:x] - enemy[:x]) ** 2 + (args.state.player[:y] - enemy[:y]) ** 2
args.state.explosions << {x: enemy[:x] + 4, y: enemy[:y] + 4, w: 32, h: 32, path: 'sprites/explosion-0.png', age: 0}
args.state.explosions << {x: args.state.player[:x] + 4, y: args.state.player[:y] + 4, w: 32, h: 32, path: 'sprites/explosion-0.png', age: 0}
args.state.player[:alive] = false
true
else
false
end
end
args.state.enemy_bullets.each do |bullet|
if args.state.player[:alive] && 400 > (args.state.player[:x] - bullet[:x] + 12) ** 2 + (args.state.player[:y] - bullet[:y] + 12) ** 2
args.state.explosions << {x: args.state.player[:x] + 4, y: args.state.player[:y] + 4, w: 32, h: 32, path: 'sprites/explosion-0.png', age: 0}
args.state.player[:alive] = false
bullet[:despawn] = true
end
end
args.state.enemies = args.state.enemies.reject do |enemy|
args.state.player_bullets.any? do |bullet|
if 400 > (enemy[:x] - bullet[:x] + 12) ** 2 + (enemy[:y] - bullet[:y] + 12) ** 2
args.state.explosions << {x: enemy[:x] + 4, y: enemy[:y] + 4, w: 32, h: 32, path: 'sprites/explosion-0.png', age: 0}
bullet[:despawn] = true
args.state.score += 1000 * args.state.wave
true
else
false
end
end
end
args.state.player_bullets = args.state.player_bullets.reject { |bullet| bullet[:despawn] }
args.state.enemy_bullets = args.state.enemy_bullets.reject { |bullet| bullet[:despawn] }
args.state.player[:cooldown] -= 1
if args.inputs.keyboard.key_held.space && args.state.player[:cooldown] <= 0 && args.state.player[:alive]
args.state.player_bullets << {x: args.state.player[:x] + 12, y: args.state.player[:y] + 28, w: 16, h: 16, path: 'sprites/star.png', dx: 0, dy: 8}.sprite
args.state.fired_shots += 1
args.state.player[:cooldown] = 10 + 20 / args.state.wave
end
args.state.enemies.each do |enemy|
if Math.rand < 0.0005 + 0.0005 * args.state.wave && args.state.player[:alive] && enemy[:move_state] == :normal
args.state.enemy_bullets << {x: enemy[:x] + 12, y: enemy[:y] - 8, w: 16, h: 16, path: 'sprites/star.png', dx: 0, dy: -3 - args.state.wave_root}.sprite
end
end
args.outputs.background_color = [0, 0, 0]
args.outputs.primitives << args.state.enemies.map do |enemy|
[enemy[:x], enemy[:y], 40, 40, enemy[:path], -90].sprite
end
args.outputs.primitives << args.state.player if args.state.player[:alive]
args.outputs.primitives << args.state.explosions
args.outputs.primitives << args.state.player_bullets
args.outputs.primitives << args.state.enemy_bullets
accuracy = args.state.fired_shots.zero? ? 1 : (args.state.fired_shots - args.state.missed_shots) / args.state.fired_shots
args.outputs.primitives << [
[0, 0, 300, 720, 96, 0, 0].solid,
[1280 - 300, 0, 300, 720, 96, 0, 0].solid,
[1280 - 290, 60, "Wave #{args.state.wave}", 255, 255, 255].label,
[1280 - 290, 40, "Accuracy #{(accuracy * 100).floor}%", 255, 255, 255].label,
[1280 - 290, 20, "Score #{(args.state.score * accuracy).floor}", 255, 255, 255].label,
]
args.outputs.primitives << args.state.lives.times.map do |n|
[1280 - 290 + 50 * n, 80, 40, 40, 'sprites/circle-gray.png', 90].sprite
end
#args.outputs.debug << args.gtk.framerate_diagnostics_primitives
if (!args.state.player[:alive]) && args.state.enemy_bullets.empty? && args.state.explosions.empty? && args.state.enemies.all? { |enemy| enemy[:move_state] == :normal }
args.state.player[:alive] = true
args.state.player[:x] = 624
args.state.player[:y] = 80
args.state.lives -= 1
if args.state.lives == -1
args.state.clear!
end
end
end
def make_enemies
enemies = []
enemies += 10.times.map { |n| {x: Math.rand * 1280 * 2 - 640, y: Math.rand * 720 * 2 + 720, row: 0, col: n, path: 'sprites/circle-orange.png', move_state: :retreat} }
enemies += 10.times.map { |n| {x: Math.rand * 1280 * 2 - 640, y: Math.rand * 720 * 2 + 720, row: 1, col: n, path: 'sprites/circle-orange.png', move_state: :retreat} }
enemies += 8.times.map { |n| {x: Math.rand * 1280 * 2 - 640, y: Math.rand * 720 * 2 + 720, row: 2, col: n + 1, path: 'sprites/circle-blue.png', move_state: :retreat} }
enemies += 8.times.map { |n| {x: Math.rand * 1280 * 2 - 640, y: Math.rand * 720 * 2 + 720, row: 3, col: n + 1, path: 'sprites/circle-blue.png', move_state: :retreat} }
enemies += 4.times.map { |n| {x: Math.rand * 1280 * 2 - 640, y: Math.rand * 720 * 2 + 720, row: 4, col: n + 3, path: 'sprites/circle-green.png', move_state: :retreat} }
enemies
end
def update_explosions args
args.state.explosions.each do |explosion|
explosion[:age] += 0.5
explosion[:path] = "sprites/explosion-#{explosion[:age].floor}.png"
end
args.state.explosions = args.state.explosions.reject { |explosion| explosion[:age] >= 7 }
end
def update_enemy_positions args
args.state.enemies.each do |enemy|
if enemy[:move_state] == :normal
enemy[:x] = args.state.columns[enemy[:col]]
enemy[:y] = args.state.rows[enemy[:row]]
enemy[:move_state] = :dive if Math.rand < 0.0002 + 0.00005 * args.state.wave && args.state.player[:alive]
elsif enemy[:move_state] == :dive
enemy[:target_x] ||= args.state.player[:x]
enemy[:target_y] ||= args.state.player[:y]
dx = enemy[:target_x] - enemy[:x]
dy = enemy[:target_y] - enemy[:y]
vel = Math.sqrt(dx * dx + dy * dy)
speed_limit = 2 + args.state.wave_root
if vel > speed_limit
dx /= vel / speed_limit
dy /= vel / speed_limit
end
if vel < 1 || !args.state.player[:alive]
enemy[:move_state] = :retreat
end
enemy[:x] += dx
enemy[:y] += dy
elsif enemy[:move_state] == :retreat
enemy[:target_x] = args.state.columns[enemy[:col]]
enemy[:target_y] = args.state.rows[enemy[:row]]
dx = enemy[:target_x] - enemy[:x]
dy = enemy[:target_y] - enemy[:y]
vel = Math.sqrt(dx * dx + dy * dy)
speed_limit = 2 + args.state.wave_root
if vel > speed_limit
dx /= vel / speed_limit
dy /= vel / speed_limit
elsif vel < 1
enemy[:move_state] = :normal
enemy[:target_x] = nil
enemy[:target_y] = nil
end
enemy[:x] += dx
enemy[:y] += dy
end
end
end
</code></pre>
<h3 id='----arcade---dueling-starships---main-rb'>Arcade - Dueling Starships - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_arcade/dueling_starships/app/main.rb
class DuelingSpaceships
attr_accessor :state, :inputs, :outputs, :grid
def tick
defaults
render
calc
input
end
def defaults
outputs.background_color = [0, 0, 0]
state.ship_blue ||= new_blue_ship
state.ship_red ||= new_red_ship
state.flames ||= []
state.bullets ||= []
state.ship_blue_score ||= 0
state.ship_red_score ||= 0
state.stars ||= 100.map do
[rand.add(2).to_square(grid.w_half.randomize(:sign, :ratio),
grid.h_half.randomize(:sign, :ratio)),
128 + 128.randomize(:ratio), 255, 255]
end
end
def default_ship x, y, angle, sprite_path, bullet_sprite_path, color
state.new_entity(:ship,
{ x: x,
y: y,
dy: 0,
dx: 0,
damage: 0,
dead: false,
angle: angle,
max_alpha: 255,
sprite_path: sprite_path,
bullet_sprite_path: bullet_sprite_path,
color: color })
end
def new_red_ship
default_ship(400, 250.randomize(:sign, :ratio),
180, 'sprites/ship_red.png', 'sprites/red_bullet.png',
[255, 90, 90])
end
def new_blue_ship
default_ship(-400, 250.randomize(:sign, :ratio),
0, 'sprites/ship_blue.png', 'sprites/blue_bullet.png',
[110, 140, 255])
end
def render
render_instructions
render_score
render_universe
render_flames
render_ships
render_bullets
end
def render_ships
update_ship_outputs(state.ship_blue)
update_ship_outputs(state.ship_red)
outputs.sprites << [state.ship_blue.sprite, state.ship_red.sprite]
outputs.labels << [state.ship_blue.label, state.ship_red.label]
end
def render_instructions
return if state.ship_blue.dx > 0 || state.ship_blue.dy > 0 ||
state.ship_red.dx > 0 || state.ship_red.dy > 0 ||
state.flames.length > 0
outputs.labels << [grid.left.shift_right(30),
grid.bottom.shift_up(30),
"Two gamepads needed to play. R1 to accelerate. Left and right on D-PAD to turn ship. Hold A to shoot. Press B to drop mines.",
0, 0, 255, 255, 255]
end
def calc
calc_thrusts
calc_ships
calc_bullets
calc_winner
end
def input
input_accelerate
input_turn
input_bullets_and_mines
end
def render_score
outputs.labels << [grid.left.shift_right(80),
grid.top.shift_down(40),
state.ship_blue_score, 30, 1, state.ship_blue.color]
outputs.labels << [grid.right.shift_left(80),
grid.top.shift_down(40),
state.ship_red_score, 30, 1, state.ship_red.color]
end
def render_universe
return if outputs.static_solids.any?
outputs.static_solids << grid.rect
outputs.static_solids << state.stars
end
def apply_round_finished_alpha entity
return entity unless state.round_finished_debounce
entity.a *= state.round_finished_debounce.percentage_of(2.seconds)
return entity
end
def update_ship_outputs ship, sprite_size = 66
ship.sprite =
apply_round_finished_alpha [sprite_size.to_square(ship.x, ship.y),
ship.sprite_path,
ship.angle,
ship.dead ? 0 : 255 * ship.created_at.ease(2.seconds)].sprite
ship.label =
apply_round_finished_alpha [ship.x,
ship.y + 100,
"." * 5.minus(ship.damage).greater(0), 20, 1, ship.color, 255].label
end
def render_flames sprite_size = 6
outputs.sprites << state.flames.map do |p|
apply_round_finished_alpha [sprite_size.to_square(p.x, p.y),
'sprites/flame.png', 0,
p.max_alpha * p.created_at.ease(p.lifetime, :flip)].sprite
end
end
def render_bullets sprite_size = 10
outputs.sprites << state.bullets.map do |b|
apply_round_finished_alpha [b.sprite_size.to_square(b.x, b.y),
b.owner.bullet_sprite_path,
0, b.max_alpha].sprite
end
end
def wrap_location! location
location.x = grid.left if location.x > grid.right
location.x = grid.right if location.x < grid.left
location.y = grid.top if location.y < grid.bottom
location.y = grid.bottom if location.y > grid.top
location
end
def calc_thrusts
state.flames =
state.flames
.reject(&:old?)
.map do |p|
p.speed *= 0.9
p.y += p.angle.vector_y(p.speed)
p.x += p.angle.vector_x(p.speed)
wrap_location! p
end
end
def all_ships
[state.ship_blue, state.ship_red]
end
def alive_ships
all_ships.reject { |s| s.dead }
end
def calc_bullet bullet
bullet.y += bullet.angle.vector_y(bullet.speed)
bullet.x += bullet.angle.vector_x(bullet.speed)
wrap_location! bullet
explode_bullet! bullet if bullet.old?
return if bullet.exploded
return if state.round_finished
alive_ships.each do |s|
if s != bullet.owner &&
s.sprite.intersect_rect?(bullet.sprite_size.to_square(bullet.x, bullet.y))
explode_bullet! bullet, 10, 5, 30
s.damage += 1
end
end
end
def calc_bullets
state.bullets.each { |b| calc_bullet b }
state.bullets.reject! { |b| b.exploded }
end
def create_explosion! type, entity, flame_count, max_speed, lifetime, max_alpha = 255
flame_count.times do
state.flames << state.new_entity(type,
{ angle: 360.randomize(:ratio),
speed: max_speed.randomize(:ratio),
lifetime: lifetime,
x: entity.x,
y: entity.y,
max_alpha: max_alpha })
end
end
def explode_bullet! bullet, flame_override = 5, max_speed = 5, lifetime = 10
bullet.exploded = true
create_explosion! :bullet_explosion,
bullet,
flame_override,
max_speed,
lifetime,
bullet.max_alpha
end
def calc_ship ship
ship.x += ship.dx
ship.y += ship.dy
wrap_location! ship
end
def calc_ships
all_ships.each { |s| calc_ship s }
return if all_ships.any? { |s| s.dead }
return if state.round_finished
return unless state.ship_blue.sprite.intersect_rect?(state.ship_red.sprite)
state.ship_blue.damage = 5
state.ship_red.damage = 5
end
def create_thruster_flames! ship
state.flames << state.new_entity(:ship_thruster,
{ angle: ship.angle + 180 + 60.randomize(:sign, :ratio),
speed: 5.randomize(:ratio),
max_alpha: 255 * ship.created_at_elapsed.percentage_of(2.seconds),
lifetime: 30,
x: ship.x - ship.angle.vector_x(40) + 5.randomize(:sign, :ratio),
y: ship.y - ship.angle.vector_y(40) + 5.randomize(:sign, :ratio) })
end
def input_accelerate_ship should_move_ship, ship
return if ship.dead
should_move_ship &&= (ship.dx + ship.dy).abs < 5
if should_move_ship
create_thruster_flames! ship
ship.dx += ship.angle.vector_x 0.050
ship.dy += ship.angle.vector_y 0.050
else
ship.dx *= 0.99
ship.dy *= 0.99
end
end
def input_accelerate
input_accelerate_ship inputs.controller_one.key_held.r1 || inputs.keyboard.up, state.ship_blue
input_accelerate_ship inputs.controller_two.key_held.r1, state.ship_red
end
def input_turn_ship direction, ship
ship.angle -= 3 * direction
end
def input_turn
input_turn_ship inputs.controller_one.left_right + inputs.keyboard.left_right, state.ship_blue
input_turn_ship inputs.controller_two.left_right, state.ship_red
end
def input_bullet create_bullet, ship
return unless create_bullet
return if ship.dead
state.bullets << state.new_entity(:ship_bullet,
{ owner: ship,
angle: ship.angle,
max_alpha: 255 * ship.created_at_elapsed.percentage_of(2.seconds),
speed: 5 + ship.dx.mult(ship.angle.vector_x) + ship.dy.mult(ship.angle.vector_y),
lifetime: 120,
sprite_size: 10,
x: ship.x + ship.angle.vector_x * 32,
y: ship.y + ship.angle.vector_y * 32 })
end
def input_mine create_mine, ship
return unless create_mine
return if ship.dead
state.bullets << state.new_entity(:ship_bullet,
{ owner: ship,
angle: 360.randomize(:sign, :ratio),
max_alpha: 255 * ship.created_at_elapsed.percentage_of(2.seconds),
speed: 0.02,
sprite_size: 10,
lifetime: 600,
x: ship.x + ship.angle.vector_x * -50,
y: ship.y + ship.angle.vector_y * -50 })
end
def input_bullets_and_mines
return if state.bullets.length > 100
[
[inputs.controller_one.key_held.a || inputs.keyboard.key_held.space,
inputs.controller_one.key_down.b || inputs.keyboard.key_down.down,
state.ship_blue],
[inputs.controller_two.key_held.a, inputs.controller_two.key_down.b, state.ship_red]
].each do |a_held, b_down, ship|
input_bullet(a_held && state.tick_count.mod_zero?(10).or(a_held == 0), ship)
input_mine(b_down, ship)
end
end
def calc_kill_ships
alive_ships.find_all { |s| s.damage >= 5 }.each do |s|
s.dead = true
create_explosion! :ship_explosion, s, 20, 20, 30, s.max_alpha
end
end
def calc_score
return if state.round_finished
return if alive_ships.length > 1
if alive_ships.first == state.ship_red
state.ship_red_score += 1
elsif alive_ships.first == state.ship_blue
state.ship_blue_score += 1
end
state.round_finished = true
end
def calc_reset_ships
return unless state.round_finished
state.round_finished_debounce ||= 2.seconds
state.round_finished_debounce -= 1
return if state.round_finished_debounce > 0
start_new_round!
end
def start_new_round!
state.ship_blue = new_blue_ship
state.ship_red = new_red_ship
state.round_finished = false
state.round_finished_debounce = nil
state.flames.clear
state.bullets.clear
end
def calc_winner
calc_kill_ships
calc_score
calc_reset_ships
end
end
$dueling_spaceship = DuelingSpaceships.new
def tick args
args.grid.origin_center!
$dueling_spaceship.inputs = args.inputs
$dueling_spaceship.outputs = args.outputs
$dueling_spaceship.state = args.state
$dueling_spaceship.grid = args.grid
$dueling_spaceship.tick
end
</code></pre>
<h3 id='----arcade/flappy-dragon/credits-txt'>arcade/flappy dragon/credits.txt</h3>
<pre><code class="language-ruby"># ./samples/99_genre_arcade/flappy_dragon/CREDITS.txt
code: Amir Rajan, https://twitter.com/amirrajan
graphics and audio: Nick Culbertson, https://twitter.com/MobyPixel
</code></pre>
<h3 id='----arcade/flappy-dragon/main-rb'>arcade/flappy dragon/main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_arcade/flappy_dragon/app/main.rb
class FlappyDragon
attr_accessor :grid, :inputs, :state, :outputs
def tick
defaults
render
calc
process_inputs
end
def defaults
state.flap_power = 11
state.gravity = 0.9
state.ceiling = 600
state.ceiling_flap_power = 6
state.wall_countdown_length = 100
state.wall_gap_size = 100
state.wall_countdown ||= 0
state.hi_score ||= 0
state.score ||= 0
state.walls ||= []
state.x ||= 50
state.y ||= 500
state.dy ||= 0
state.scene ||= :menu
state.scene_at ||= 0
state.difficulty ||= :normal
state.new_difficulty ||= :normal
state.countdown ||= 4.seconds
state.flash_at ||= 0
end
def render
outputs.sounds << "sounds/flappy-song.ogg" if state.tick_count == 1
render_score
render_menu
render_game
end
def render_score
outputs.primitives << [10, 710, "HI SCORE: #{state.hi_score}", large_white_typeset].label
outputs.primitives << [10, 680, "SCORE: #{state.score}", large_white_typeset].label
outputs.primitives << [10, 650, "DIFFICULTY: #{state.difficulty.upcase}", large_white_typeset].label
end
def render_menu
return unless state.scene == :menu
render_overlay
outputs.labels << [640, 700, "Flappy Dragon", 50, 1, 255, 255, 255]
outputs.labels << [640, 500, "Instructions: Press Spacebar to flap. Don't die.", 4, 1, 255, 255, 255]
outputs.labels << [430, 430, "[Tab] Change difficulty", 4, 0, 255, 255, 255]
outputs.labels << [430, 400, "[Enter] Start at New Difficulty ", 4, 0, 255, 255, 255]
outputs.labels << [430, 370, "[Escape] Cancel/Resume ", 4, 0, 255, 255, 255]
outputs.labels << [640, 300, "(mouse, touch, and game controllers work, too!) ", 4, 1, 255, 255, 255]
outputs.labels << [640, 200, "Difficulty: #{state.new_difficulty.capitalize}", 4, 1, 255, 255, 255]
outputs.labels << [10, 100, "Code: @amirrajan", 255, 255, 255]
outputs.labels << [10, 80, "Art: @mobypixel", 255, 255, 255]
outputs.labels << [10, 60, "Music: @mobypixel", 255, 255, 255]
outputs.labels << [10, 40, "Engine: DragonRuby GTK", 255, 255, 255]
end
def render_overlay
outputs.primitives << [grid.rect.scale_rect(1.1, 0, 0), 0, 0, 0, 230].solid
end
def render_game
render_game_over
render_background
render_walls
render_dragon
render_flash
end
def render_game_over
return unless state.scene == :game
outputs.labels << [638, 358, score_text, 20, 1]
outputs.labels << [635, 360, score_text, 20, 1, 255, 255, 255]
outputs.labels << [638, 428, countdown_text, 20, 1]
outputs.labels << [635, 430, countdown_text, 20, 1, 255, 255, 255]
end
def render_background
outputs.sprites << [0, 0, 1280, 720, 'sprites/background.png']
scroll_point_at = state.tick_count
scroll_point_at = state.scene_at if state.scene == :menu
scroll_point_at = state.death_at if state.countdown > 0
scroll_point_at ||= 0
outputs.sprites << scrolling_background(scroll_point_at, 'sprites/parallax_back.png', 0.25)
outputs.sprites << scrolling_background(scroll_point_at, 'sprites/parallax_middle.png', 0.50)
outputs.sprites << scrolling_background(scroll_point_at, 'sprites/parallax_front.png', 1.00, -80)
end
def render_walls
state.walls.each do |w|
w.sprites = [
[w.x, w.bottom_height - 720, 100, 720, 'sprites/wall.png', 180],
[w.x, w.top_y, 100, 720, 'sprites/wallbottom.png', 0]
]
end
outputs.sprites << state.walls.map(&:sprites)
end
def render_dragon
state.show_death = true if state.countdown == 3.seconds
render_debug_hitbox false
if state.show_death == false || !state.death_at
animation_index = state.flapped_at.frame_index 6, 2, false if state.flapped_at
sprite_name = "sprites/dragon_fly#{animation_index.or(0) + 1}.png"
state.dragon_sprite = [state.x, state.y, 100, 80, sprite_name, state.dy * 1.2]
else
sprite_name = "sprites/dragon_die.png"
state.dragon_sprite = [state.x, state.y, 100, 80, sprite_name, state.dy * 1.2]
sprite_changed_elapsed = state.death_at.elapsed_time - 1.seconds
state.dragon_sprite.angle += (sprite_changed_elapsed ** 1.3) * state.death_fall_direction * -1
state.dragon_sprite.x += (sprite_changed_elapsed ** 1.2) * state.death_fall_direction
state.dragon_sprite.y += (sprite_changed_elapsed * 14 - sprite_changed_elapsed ** 1.6)
end
outputs.sprites << state.dragon_sprite
end
def render_debug_hitbox show
return unless show
outputs.borders << [dragon_collision_box.rect, 255, 0, 0] if state.dragon_sprite
outputs.borders << state.walls.flat_map do |w|
w.sprites.map { |s| [s.rect, 255, 0, 0] }
end
end
def render_flash
return unless state.flash_at
outputs.primitives << [grid.rect,
white,
255 * state.flash_at.ease(20, :flip)].solid
state.flash_at = 0 if state.flash_at.elapsed_time > 20
end
def calc
return unless state.scene == :game
reset_game if state.countdown == 1
state.countdown -= 1 and return if state.countdown > 0
calc_walls
calc_flap
calc_game_over
end
def calc_walls
state.walls.each { |w| w.x -= 8 }
walls_count_before_removal = state.walls.length
state.walls.reject! { |w| w.x < -100 }
state.score += 1 if state.walls.count < walls_count_before_removal
state.wall_countdown -= 1 and return if state.wall_countdown > 0
state.walls << state.new_entity(:wall) do |w|
w.x = grid.right
w.opening = grid.top
.randomize(:ratio)
.greater(200)
.lesser(520)
w.bottom_height = w.opening - state.wall_gap_size
w.top_y = w.opening + state.wall_gap_size
end
state.wall_countdown = state.wall_countdown_length
end
def calc_flap
state.y += state.dy
state.dy = state.dy.lesser state.flap_power
state.dy -= state.gravity
return if state.y < state.ceiling
state.y = state.ceiling
state.dy = state.dy.lesser state.ceiling_flap_power
end
def calc_game_over
return unless game_over?
state.death_at = state.tick_count
state.death_from = state.walls.first
state.death_fall_direction = -1
state.death_fall_direction = 1 if state.x > state.death_from.x
outputs.sounds << "sounds/hit-sound.wav"
begin_countdown
end
def process_inputs
process_inputs_menu
process_inputs_game
end
def process_inputs_menu
return unless state.scene == :menu
changediff = inputs.keyboard.key_down.tab || inputs.controller_one.key_down.select
if inputs.mouse.click
p = inputs.mouse.click.point
if (p.y >= 165) && (p.y < 200) && (p.x >= 500) && (p.x < 800)
changediff = true
end
end
if changediff
case state.new_difficulty
when :easy
state.new_difficulty = :normal
when :normal
state.new_difficulty = :hard
when :hard
state.new_difficulty = :flappy
when :flappy
state.new_difficulty = :easy
end
end
if inputs.keyboard.key_down.enter || inputs.controller_one.key_down.start || inputs.controller_one.key_down.a
state.difficulty = state.new_difficulty
change_to_scene :game
reset_game false
state.hi_score = 0
begin_countdown
end
if inputs.keyboard.key_down.escape || (inputs.mouse.click && !changediff) || inputs.controller_one.key_down.b
state.new_difficulty = state.difficulty
change_to_scene :game
end
end
def process_inputs_game
return unless state.scene == :game
clicked_menu = false
if inputs.mouse.click
p = inputs.mouse.click.point
clicked_menu = (p.y >= 620) && (p.x < 275)
end
if clicked_menu || inputs.keyboard.key_down.escape || inputs.keyboard.key_down.enter || inputs.controller_one.key_down.start
change_to_scene :menu
elsif (inputs.mouse.down || inputs.mouse.click || inputs.keyboard.key_down.space || inputs.controller_one.key_down.a) && state.countdown == 0
state.dy = 0
state.dy += state.flap_power
state.flapped_at = state.tick_count
outputs.sounds << "sounds/fly-sound.wav"
end
end
def scrolling_background at, path, rate, y = 0
[
[ 0 - at.*(rate) % 1440, y, 1440, 720, path],
[1440 - at.*(rate) % 1440, y, 1440, 720, path]
]
end
def white
[255, 255, 255]
end
def large_white_typeset
[5, 0, 255, 255, 255]
end
def at_beginning?
state.walls.count == 0
end
def dragon_collision_box
state.dragon_sprite
.scale_rect(1.0 - collision_forgiveness, 0.5, 0.5)
.rect_shift_right(10)
.rect_shift_up(state.dy * 2)
end
def game_over?
return true if state.y <= 0.-(500 * collision_forgiveness) && !at_beginning?
state.walls
.flat_map { |w| w.sprites }
.any? do |s|
s.intersect_rect?(dragon_collision_box)
end
end
def collision_forgiveness
case state.difficulty
when :easy
0.9
when :normal
0.7
when :hard
0.5
when :flappy
0.3
else
0.9
end
end
def countdown_text
state.countdown ||= -1
return "" if state.countdown == 0
return "GO!" if state.countdown.idiv(60) == 0
return "GAME OVER" if state.death_at
return "READY?"
end
def begin_countdown
state.countdown = 4.seconds
end
def score_text
return "" unless state.countdown > 1.seconds
return "" unless state.death_at
return "SCORE: 0 (LOL)" if state.score == 0
return "HI SCORE: #{state.score}" if state.score == state.hi_score
return "SCORE: #{state.score}"
end
def reset_game set_flash = true
state.flash_at = state.tick_count if set_flash
state.walls = []
state.y = 500
state.dy = 0
state.hi_score = state.hi_score.greater(state.score)
state.score = 0
state.wall_countdown = state.wall_countdown_length.fdiv(2)
state.show_death = false
state.death_at = nil
end
def change_to_scene scene
state.scene = scene
state.scene_at = state.tick_count
inputs.keyboard.clear
inputs.controller_one.clear
end
end
$flappy_dragon = FlappyDragon.new
def tick args
$flappy_dragon.grid = args.grid
$flappy_dragon.inputs = args.inputs
$flappy_dragon.state = args.state
$flappy_dragon.outputs = args.outputs
$flappy_dragon.tick
end
</code></pre>
<h3 id='----arcade---pong---main-rb'>Arcade - Pong - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_arcade/pong/app/main.rb
def tick args
defaults args
render args
calc args
input args
end
def defaults args
args.state.ball.debounce ||= 3 * 60
args.state.ball.size ||= 10
args.state.ball.size_half ||= args.state.ball.size / 2
args.state.ball.x ||= 640
args.state.ball.y ||= 360
args.state.ball.dx ||= 5.randomize(:sign)
args.state.ball.dy ||= 5.randomize(:sign)
args.state.left_paddle.y ||= 360
args.state.right_paddle.y ||= 360
args.state.paddle.h ||= 120
args.state.paddle.w ||= 10
args.state.left_paddle.score ||= 0
args.state.right_paddle.score ||= 0
end
def render args
render_center_line args
render_scores args
render_countdown args
render_ball args
render_paddles args
render_instructions args
end
begin :render_methods
def render_center_line args
args.outputs.lines << [640, 0, 640, 720]
end
def render_scores args
args.outputs.labels << [
[320, 650, args.state.left_paddle.score, 10, 1],
[960, 650, args.state.right_paddle.score, 10, 1]
]
end
def render_countdown args
return unless args.state.ball.debounce > 0
args.outputs.labels << [640, 360, "%.2f" % args.state.ball.debounce.fdiv(60), 10, 1]
end
def render_ball args
args.outputs.solids << solid_ball(args)
end
def render_paddles args
args.outputs.solids << solid_left_paddle(args)
args.outputs.solids << solid_right_paddle(args)
end
def render_instructions args
args.outputs.labels << [320, 30, "W and S keys to move left paddle.", 0, 1]
args.outputs.labels << [920, 30, "O and L keys to move right paddle.", 0, 1]
end
end
def calc args
args.state.ball.debounce -= 1 and return if args.state.ball.debounce > 0
calc_move_ball args
calc_collision_with_left_paddle args
calc_collision_with_right_paddle args
calc_collision_with_walls args
end
begin :calc_methods
def calc_move_ball args
args.state.ball.x += args.state.ball.dx
args.state.ball.y += args.state.ball.dy
end
def calc_collision_with_left_paddle args
if solid_left_paddle(args).intersect_rect? solid_ball(args)
args.state.ball.dx *= -1
elsif args.state.ball.x < 0
args.state.right_paddle.score += 1
calc_reset_round args
end
end
def calc_collision_with_right_paddle args
if solid_right_paddle(args).intersect_rect? solid_ball(args)
args.state.ball.dx *= -1
elsif args.state.ball.x > 1280
args.state.left_paddle.score += 1
calc_reset_round args
end
end
def calc_collision_with_walls args
if args.state.ball.y + args.state.ball.size_half > 720
args.state.ball.y = 720 - args.state.ball.size_half
args.state.ball.dy *= -1
elsif args.state.ball.y - args.state.ball.size_half < 0
args.state.ball.y = args.state.ball.size_half
args.state.ball.dy *= -1
end
end
def calc_reset_round args
args.state.ball.x = 640
args.state.ball.y = 360
args.state.ball.dx = 5.randomize(:sign)
args.state.ball.dy = 5.randomize(:sign)
args.state.ball.debounce = 3 * 60
end
end
def input args
input_left_paddle args
input_right_paddle args
end
begin :input_methods
def input_left_paddle args
if args.inputs.controller_one.key_down.down || args.inputs.keyboard.key_down.s
args.state.left_paddle.y -= 40
elsif args.inputs.controller_one.key_down.up || args.inputs.keyboard.key_down.w
args.state.left_paddle.y += 40
end
end
def input_right_paddle args
if args.inputs.controller_two.key_down.down || args.inputs.keyboard.key_down.l
args.state.right_paddle.y -= 40
elsif args.inputs.controller_two.key_down.up || args.inputs.keyboard.key_down.o
args.state.right_paddle.y += 40
end
end
end
begin :assets
def solid_ball args
centered_rect args.state.ball.x, args.state.ball.y, args.state.ball.size, args.state.ball.size
end
def solid_left_paddle args
centered_rect_vertically 0, args.state.left_paddle.y, args.state.paddle.w, args.state.paddle.h
end
def solid_right_paddle args
centered_rect_vertically 1280 - args.state.paddle.w, args.state.right_paddle.y, args.state.paddle.w, args.state.paddle.h
end
def centered_rect x, y, w, h
[x - w / 2, y - h / 2, w, h]
end
def centered_rect_vertically x, y, w, h
[x, y - h / 2, w, h]
end
end
</code></pre>
<h3 id='----arcade---snakemoji---main-rb'>Arcade - Snakemoji - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_arcade/snakemoji/app/main.rb
# coding: utf-8
################################
# So I was working on a snake game while
# learning DragonRuby, and at some point I had a thought
# what if I use "😀" as a function name, surely it wont work right...?
# RIGHT....?
# BUT IT DID, IT WORKED
# it all went downhill from then
# Created by Anton K. (ai Doge)
# https://gist.github.com/scorp200
#############LICENSE############
# Feel free to use this anywhere and however you want
# You can sell this to EA for $1,000,000 if you want, its completely free.
# Just rememeber you are helping this... thing... to spread...
# ALSO! I am not liable for any mental, physical or financial damage caused.
#############LICENSE############
class Array
#Helper function
def move! vector
self.x += vector.x
self.y += vector.y
return self
end
#Helper function to draw snake body
def draw! 🎮, 📺, color
translate 📺.solids, 🎮.⛓, [self.x * 🎮.⚖️ + 🎮.🛶 / 2, self.y * 🎮.⚖️ + 🎮.🛶 / 2, 🎮.⚖️ - 🎮.🛶, 🎮.⚖️ - 🎮.🛶, color]
end
#This is where it all started, I was trying to find good way to multiply a map by a number, * is already used so is **
#I kept trying different combinations of symbols, when suddenly...
def 😀 value
self.map {|d| d * value}
end
end
#Draw stuff with an offset
def translate output_collection, ⛓, what
what.x += ⛓.x
what.y += ⛓.y
output_collection << what
end
BLUE = [33, 150, 243]
RED = [244, 67, 54]
GOLD = [255, 193, 7]
LAST = 0
def tick args
defaults args.state
render args.state, args.outputs
input args.state, args.inputs
update args.state
end
def update 🎮
#Update every 10 frames
if 🎮.tick_count.mod_zero? 10
#Add new snake body piece at head's location
🎮.🐍 << [*🎮.🤖]
#Assign Next Direction to Direction
🎮.🚗 = *🎮.🚦
#Trim the snake a bit if its longer than current size
if 🎮.🐍.length > 🎮.🛒
🎮.🐍 = 🎮.🐍[-🎮.🛒..-1]
end
#Move the head in the Direction
🎮.🤖.move! 🎮.🚗
#If Head is outside the playing field, or inside snake's body restart game
if 🎮.🤖.x < 0 || 🎮.🤖.x >= 🎮.🗺.x || 🎮.🤖.y < 0 || 🎮.🤖.y >= 🎮.🗺.y || 🎮.🚗 != [0, 0] && 🎮.🐍.any? {|s| s == 🎮.🤖}
LAST = 🎮.💰
🎮.as_hash.clear
return
end
#If head lands on food add size and score
if 🎮.🤖 == 🎮.🍎
🎮.🛒 += 1
🎮.💰 += (🎮.🛒 * 0.8).floor.to_i + 5
spawn_🍎 🎮
puts 🎮.🍎
end
end
#Every second remove 1 point
if 🎮.💰 > 0 && 🎮.tick_count.mod_zero?(60)
🎮.💰 -= 1
end
end
def spawn_🍎 🎮
#Food
🎮.🍎 ||= [*🎮.🤖]
#Randomly spawns food inside the playing field, keep doing this if the food keeps landing on the snake's body
while 🎮.🐍.any? {|s| s == 🎮.🍎} || 🎮.🍎 == 🎮.🤖 do
🎮.🍎 = [rand(🎮.🗺.x), rand(🎮.🗺.y)]
end
end
def render 🎮, 📺
#Paint the background black
📺.solids << [0, 0, 1280, 720, 0, 0, 0, 255]
#Draw a border for the playing field
translate 📺.borders, 🎮.⛓, [0, 0, 🎮.🗺.x * 🎮.⚖️, 🎮.🗺.y * 🎮.⚖️, 255, 255, 255]
#Draw the snake's body
🎮.🐍.map do |🐍| 🐍.draw! 🎮, 📺, BLUE end
#Draw the head
🎮.🤖.draw! 🎮, 📺, BLUE
#Draw the food
🎮.🍎.draw! 🎮, 📺, RED
#Draw current score
translate 📺.labels, 🎮.⛓, [5, 715, "Score: #{🎮.💰}", GOLD]
#Draw your last score, if any
translate 📺.labels, 🎮.⛓, [[*🎮.🤖.😀(🎮.⚖️)].move!([0, 🎮.⚖️ * 2]), "Your Last score is #{LAST}", 0, 1, GOLD] unless LAST == 0 || 🎮.🚗 != [0, 0]
#Draw starting message, only if Direction is 0
translate 📺.labels, 🎮.⛓, [🎮.🤖.😀(🎮.⚖️), "Press any Arrow key to start", 0, 1, GOLD] unless 🎮.🚗 != [0, 0]
end
def input 🎮, 🕹
#Left and Right keyboard input, only change if X direction is 0
if 🕹.keyboard.key_held.left && 🎮.🚗.x == 0
🎮.🚦 = [-1, 0]
elsif 🕹.keyboard.key_held.right && 🎮.🚗.x == 0
🎮.🚦 = [1, 0]
end
#Up and Down keyboard input, only change if Y direction is 0
if 🕹.keyboard.key_held.up && 🎮.🚗.y == 0
🎮.🚦 = [0, 1]
elsif 🕹.keyboard.key_held.down && 🎮.🚗.y == 0
🎮.🚦 = [0, -1]
end
end
def defaults 🎮
#Playing field size
🎮.🗺 ||= [20, 20]
#Scale for drawing, screen height / Field height
🎮.⚖️ ||= 720 / 🎮.🗺.y
#Offset, offset all rendering to the center of the screen
🎮.⛓ ||= [(1280 - 720).fdiv(2), 0]
#Padding, make the snake body slightly smaller than the scale
🎮.🛶 ||= (🎮.⚖️ * 0.2).to_i
#Snake Size
🎮.🛒 ||= 3
#Snake head, the only part we are actually controlling
🎮.🤖 ||= [🎮.🗺.x / 2, 🎮.🗺.y / 2]
#Snake body map, follows the head
🎮.🐍 ||= []
#Direction the head moves to
🎮.🚗 ||= [0, 0]
#Next_Direction, during input check only change this variable and then when game updates asign this to Direction
🎮.🚦 ||= [*🎮.🚗]
#Your score
🎮.💰 ||= 0
#Spawns Food randomly
spawn_🍎(🎮) unless 🎮.🍎?
end
</code></pre>
<h3 id='----arcade---solar-system---main-rb'>Arcade - Solar System - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_arcade/solar_system/app/main.rb
# Focused tutorial video: https://s3.amazonaws.com/s3.dragonruby.org/dragonruby-nddnug-workshop.mp4
# Workshop/Presentation which provides motivation for creating a game engine: https://www.youtube.com/watch?v=S3CFce1arC8
def defaults args
args.outputs.background_color = [0, 0, 0]
args.state.x ||= 640
args.state.y ||= 360
args.state.stars ||= 100.map do
[1280 * rand, 720 * rand, rand.fdiv(10), 255 * rand, 255 * rand, 255 * rand]
end
args.state.sun ||= args.state.new_entity(:sun) do |s|
s.s = 100
s.path = 'sprites/sun.png'
end
args.state.planets = [
[:mercury, 65, 5, 88],
[:venus, 100, 10, 225],
[:earth, 120, 10, 365],
[:mars, 140, 8, 687],
[:jupiter, 280, 30, 365 * 11.8],
[:saturn, 350, 20, 365 * 29.5],
[:uranus, 400, 15, 365 * 84],
[:neptune, 440, 15, 365 * 164.8],
[:pluto, 480, 5, 365 * 247.8],
].map do |name, distance, size, year_in_days|
args.state.new_entity(name) do |p|
p.path = "sprites/#{name}.png"
p.distance = distance * 0.7
p.s = size * 0.7
p.year_in_days = year_in_days
end
end
args.state.ship ||= args.state.new_entity(:ship) do |s|
s.x = 1280 * rand
s.y = 720 * rand
s.angle = 0
end
end
def to_sprite args, entity
x = 0
y = 0
if entity.year_in_days
day = args.state.tick_count
day_in_year = day % entity.year_in_days
entity.random_start_day ||= day_in_year * rand
percentage_of_year = day_in_year.fdiv(entity.year_in_days)
angle = 365 * percentage_of_year
x = angle.vector_x(entity.distance)
y = angle.vector_y(entity.distance)
end
[640 + x - entity.s.half, 360 + y - entity.s.half, entity.s, entity.s, entity.path]
end
def render args
args.outputs.solids << [0, 0, 1280, 720]
args.outputs.sprites << args.state.stars.map do |x, y, _, r, g, b|
[x, y, 10, 10, 'sprites/star.png', 0, 100, r, g, b]
end
args.outputs.sprites << to_sprite(args, args.state.sun)
args.outputs.sprites << args.state.planets.map { |p| to_sprite args, p }
args.outputs.sprites << [args.state.ship.x, args.state.ship.y, 20, 20, 'sprites/ship.png', args.state.ship.angle]
end
def calc args
args.state.stars = args.state.stars.map do |x, y, speed, r, g, b|
x += speed
y += speed
x = 0 if x > 1280
y = 0 if y > 720
[x, y, speed, r, g, b]
end
if args.state.tick_count == 0
args.outputs.sounds << 'sounds/bg.ogg'
end
end
def process_inputs args
if args.inputs.keyboard.left || args.inputs.controller_one.key_held.left
args.state.ship.angle += 1
elsif args.inputs.keyboard.right || args.inputs.controller_one.key_held.right
args.state.ship.angle -= 1
end
if args.inputs.keyboard.up || args.inputs.controller_one.key_held.a
args.state.ship.x += args.state.ship.angle.x_vector
args.state.ship.y += args.state.ship.angle.y_vector
end
end
def tick args
defaults args
render args
calc args
process_inputs args
end
def r
$gtk.reset
end
</code></pre>
<h3 id='----arcade---sound-golf---main-rb'>Arcade - Sound Golf - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_arcade/sound_golf/app/main.rb
=begin
APIs Listing that haven't been encountered in previous sample apps:
- sample: Chooses random element from array.
In this sample app, the target note is set by taking a sample from the collection
of available notes.
Reminders:
- args.grid.(left|right|top|bottom): Pixel value for the boundaries of the virtual
720 p screen (Dragon Ruby Game Toolkits's virtual resolution is always 1280x720).
- args.state.new_entity: Used when we want to create a new object, like a sprite or button.
For example, if we want to create a new button, we would declare it as a new entity and
then define its properties.
- String interpolation: Uses #{} syntax; everything between the #{ and the } is evaluated
as Ruby code, and the placeholder is replaced with its corresponding value or result.
- args.outputs.labels: An array. The values generate a label.
The parameters are [X, Y, TEXT, SIZE, ALIGNMENT, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.md.
- find_all: Finds all elements from a collection that meet a certain requirements (and excludes the ones that don't).
- first: Returns the first element of an array.
- inside_rect: Returns true or false depending on if the point is inside the rect.
- to_sym: Returns symbol corresponding to string. Will create a symbol if it does
not already exist.
=end
# This sample app allows users to test their musical skills by matching the piano sound that plays in each
# level to the correct note.
# Runs all the methods necessary for the game to function properly.
def tick args
defaults args
render args
calc args
input_mouse args
tick_instructions args, "Sample app shows how to play sounds. args.outputs.sounds << \"path_to_wav.wav\""
end
# Sets default values and creates empty collections
# Initialization happens in the first frame only
def defaults args
args.state.notes ||= []
args.state.click_feedbacks ||= []
args.state.current_level ||= 1
args.state.times_wrong ||= 0 # when game starts, user hasn't guessed wrong yet
end
# Uses a label to display current level, and shows the score
# Creates a button to play the sample note, and displays the available notes that could be a potential match
def render args
# grid.w_half positions the label in the horizontal center of the screen.
args.outputs.labels << [args.grid.w_half, args.grid.top.shift_down(40), "Hole #{args.state.current_level} of 9", 0, 1, 0, 0, 0]
render_score args # shows score on screen
args.state.play_again_button ||= { x: 560, y: args.grid.h * 3 / 4 - 40, w: 160, h: 60, label: 'again' } # array definition, text/title
args.state.play_note_button ||= { x: 560, y: args.grid.h * 3 / 4 - 40, w: 160, h: 60, label: 'play' }
if args.state.game_over # if game is over, a "play again" button is shown
# Calculations ensure that Play Again label is displayed in center of border
# Remove calculations from y parameters and see what happens to border and label placement
args.outputs.labels << [args.grid.w_half, args.grid.h * 3 / 4, "Play Again", 0, 1, 0, 0, 0] # outputs label
args.outputs.borders << args.state.play_again_button # outputs border
else # otherwise, if game is not over
# Calculations ensure that label appears in center of border
args.outputs.labels << [args.grid.w_half, args.grid.h * 3 / 4, "Play Note ##{args.state.current_level}", 0, 1, 0, 0, 0] # outputs label
args.outputs.borders << args.state.play_note_button # outputs border
end
return if args.state.game_over # return if game is over
args.outputs.labels << [args.grid.w_half, 400, "I think the note is a(n)...", 0, 1, 0, 0, 0] # outputs label
# Shows all of the available notes that can be potential matches.
available_notes.each_with_index do |note, i|
args.state.notes[i] ||= piano_button(args, note, i + 1) # calls piano_button method on each note (creates label and border)
args.outputs.labels << args.state.notes[i].label # outputs note on screen with a label and a border
args.outputs.borders << args.state.notes[i].border
end
# Shows whether or not the user is correct by filling the screen with either red or green
args.outputs.solids << args.state.click_feedbacks.map { |c| c.solid }
end
# Shows the score (number of times the user guesses wrong) onto the screen using labels.
def render_score args
if args.state.times_wrong == 0 # if the user has guessed wrong zero times, the score is par
args.outputs.labels << [args.grid.w_half, args.grid.top.shift_down(80), "Score: PAR", 0, 1, 0, 0, 0]
else # otherwise, number of times the user has guessed wrong is shown
args.outputs.labels << [args.grid.w_half, args.grid.top.shift_down(80), "Score: +#{args.state.times_wrong}", 0, 1, 0, 0, 0] # shows score using string interpolation
end
end
# Sets the target note for the level and performs calculations on click_feedbacks.
def calc args
args.state.target_note ||= available_notes.sample # chooses a note from available_notes collection as target note
args.state.click_feedbacks.each { |c| c.solid[-1] -= 5 } # remove this line and solid color will remain on screen indefinitely
# comment this line out and the solid color will keep flashing on screen instead of being removed from click_feedbacks collection
args.state.click_feedbacks.reject! { |c| c.solid[-1] <= 0 }
end
# Uses input from the user to play the target note, as well as the other notes that could be a potential match.
def input_mouse args
return unless args.inputs.mouse.click # return unless the mouse is clicked
# finds button that was clicked by user
button_clicked = args.outputs.borders.find_all do |b| # go through borders collection to find all borders that meet requirements
args.inputs.mouse.click.point.inside_rect? b # find button border that mouse was clicked inside of
end.find_all { |b| b.is_a? Hash }.first # reject, return first element
return unless button_clicked # return unless button_clicked as a value (a button was clicked)
queue_click_feedback args, # calls queue_click_feedback method on the button that was clicked
button_clicked.x,
button_clicked.y,
button_clicked.w,
button_clicked.h,
150, 100, 200 # sets color of button to shade of purple
if button_clicked[:label] == 'play' # if "play note" button is pressed
args.outputs.sounds << "sounds/#{args.state.target_note}.wav" # sound of target note is output
elsif button_clicked[:label] == 'again' # if "play game again" button is pressed
args.state.target_note = nil # no target note
args.state.current_level = 1 # starts at level 1 again
args.state.times_wrong = 0 # starts off with 0 wrong guesses
args.state.game_over = false # the game is not over (because it has just been restarted)
else # otherwise if neither of those buttons were pressed
args.outputs.sounds << "sounds/#{button_clicked[:label]}.wav" # sound of clicked note is played
if button_clicked[:label] == args.state.target_note # if clicked note is target note
args.state.target_note = nil # target note is emptied
if args.state.current_level < 9 # if game hasn't reached level 9
args.state.current_level += 1 # game goes to next level
else # otherwise, if game has reached level 9
args.state.game_over = true # the game is over
end
queue_click_feedback args, 0, 0, args.grid.w, args.grid.h, 100, 200, 100 # green shown if user guesses correctly
else # otherwise, if clicked note is not target note
args.state.times_wrong += 1 # increments times user guessed wrong
queue_click_feedback args, 0, 0, args.grid.w, args.grid.h, 200, 100, 100 # red shown is user guesses wrong
end
end
end
# Creates a collection of all of the available notes as symbols
def available_notes
[:C3, :D3, :E3, :F3, :G3, :A3, :B3, :C4]
end
# Creates buttons for each note, and sets a label (the note's name) and border for each note's button.
def piano_button args, note, position
args.state.new_entity(:button) do |b| # declares button as new entity
b.label = [460 + 40.mult(position), args.grid.h * 0.4, "#{note}", 0, 1, 0, 0, 0] # label definition
b.border = { x: 460 + 40.mult(position) - 20, y: args.grid.h * 0.4 - 32, w: 40, h: 40, label: note } # border definition, text/title; 20 subtracted so label is in center of border
end
end
# Color of click feedback changes depending on what button was clicked, and whether the guess is right or wrong
# If a button is clicked, the inside of button is purple (see input_mouse method)
# If correct note is clicked, screen turns green
# If incorrect note is clicked, screen turns red (again, see input_mouse method)
def queue_click_feedback args, x, y, w, h, *color
args.state.click_feedbacks << args.state.new_entity(:click_feedback) do |c| # declares feedback as new entity
c.solid = [x, y, w, h, *color, 255] # sets color
end
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----arcade---twinstick---main-rb'>Arcade - Twinstick - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_arcade/twinstick/app/main.rb
def tick args
args.state.player ||= {x: 600, y: 320, w: 80, h: 80, path: 'sprites/circle-white.png', vx: 0, vy: 0, health: 10, cooldown: 0, score: 0}
args.state.enemies ||= []
args.state.player_bullets ||= []
args.state.tick_count ||= -1
args.state.tick_count += 1
spawn_enemies args
kill_enemies args
move_enemies args
move_bullets args
move_player args
fire_player args
args.state.player[:r] = args.state.player[:g] = args.state.player[:b] = (args.state.player[:health] * 25.5).clamp(0, 255)
label_color = args.state.player[:health] <= 5 ? 255 : 0
args.outputs.labels << [
{
x: args.state.player.x + 40, y: args.state.player.y + 60, alignment_enum: 1, text: "#{args.state.player[:health]} HP",
r: label_color, g: label_color, b: label_color
}, {
x: args.state.player.x + 40, y: args.state.player.y + 40, alignment_enum: 1, text: "#{args.state.player[:score]} PTS",
r: label_color, g: label_color, b: label_color, size_enum: 2 - args.state.player[:score].to_s.length,
}
]
args.outputs.sprites << [args.state.player, args.state.enemies, args.state.player_bullets]
args.state.clear! if args.state.player[:health] < 0 # Reset the game if the player's health drops below zero
end
def spawn_enemies args
# Spawn enemies more frequently as the player's score increases.
if rand < (100+args.state.player[:score])/(10000 + args.state.player[:score]) || args.state.tick_count.zero?
theta = rand * Math::PI * 2
args.state.enemies << {
x: 600 + Math.cos(theta) * 800, y: 320 + Math.sin(theta) * 800, w: 80, h: 80, path: 'sprites/circle-white.png',
r: (256 * rand).floor, g: (256 * rand).floor, b: (256 * rand).floor
}
end
end
def kill_enemies args
args.state.enemies.reject! do |enemy|
# Check if enemy and player are within 80 pixels of each other (i.e. overlapping)
if 6400 > (enemy.x - args.state.player.x) ** 2 + (enemy.y - args.state.player.y) ** 2
# Enemy is touching player. Kill enemy, and reduce player HP by 1.
args.state.player[:health] -= 1
else
args.state.player_bullets.any? do |bullet|
# Check if enemy and bullet are within 50 pixels of each other (i.e. overlapping)
if 2500 > (enemy.x - bullet.x + 30) ** 2 + (enemy.y - bullet.y + 30) ** 2
# Increase player health by one for each enemy killed by a bullet after the first enemy, up to a maximum of 10 HP
args.state.player[:health] += 1 if args.state.player[:health] < 10 && bullet[:kills] > 0
# Keep track of how many enemies have been killed by this particular bullet
bullet[:kills] += 1
# Earn more points by killing multiple enemies with one shot.
args.state.player[:score] += bullet[:kills]
end
end
end
end
end
def move_enemies args
args.state.enemies.each do |enemy|
# Get the angle from the enemy to the player
theta = Math.atan2(enemy.y - args.state.player.y, enemy.x - args.state.player.x)
# Convert the angle to a vector pointing at the player
dx, dy = theta.to_degrees.vector 5
# Move the enemy towards thr player
enemy.x -= dx
enemy.y -= dy
end
end
def move_bullets args
args.state.player_bullets.each do |bullet|
# Move the bullets according to the bullet's velocity
bullet.x += bullet[:vx]
bullet.y += bullet[:vy]
end
args.state.player_bullets.reject! do |bullet|
# Despawn bullets that are outside the screen area
bullet.x < -20 || bullet.y < -20 || bullet.x > 1300 || bullet.y > 740
end
end
def move_player args
# Get the currently held direction.
dx, dy = move_directional_vector args
# Take the weighted average of the old velocities and the desired velocities.
# Since move_directional_vector returns values between -1 and 1,
# and we want to limit the speed to 7.5, we multiply dx and dy by 7.5*0.1 to get 0.75
args.state.player[:vx] = args.state.player[:vx] * 0.9 + dx * 0.75
args.state.player[:vy] = args.state.player[:vy] * 0.9 + dy * 0.75
# Move the player
args.state.player.x += args.state.player[:vx]
args.state.player.y += args.state.player[:vy]
# If the player is about to go out of bounds, put them back in bounds.
args.state.player.x = args.state.player.x.clamp(0, 1201)
args.state.player.y = args.state.player.y.clamp(0, 640)
end
def fire_player args
# Reduce the firing cooldown each tick
args.state.player[:cooldown] -= 1
# If the player is allowed to fire
if args.state.player[:cooldown] <= 0
dx, dy = shoot_directional_vector args # Get the bullet velocity
return if dx == 0 && dy == 0 # If the velocity is zero, the player doesn't want to fire. Therefore, we just return early.
# Add a new bullet to the list of player bullets.
args.state.player_bullets << {
x: args.state.player.x + 30 + 40 * dx,
y: args.state.player.y + 30 + 40 * dy,
w: 20, h: 20,
path: 'sprites/circle-white.png',
r: 0, g: 0, b: 0,
vx: 10 * dx + args.state.player[:vx] / 7.5, vy: 10 * dy + args.state.player[:vy] / 7.5, # Factor in a bit of the player's velocity
kills: 0
}
args.state.player[:cooldown] = 30 # Reset the cooldown
end
end
# Custom function for getting a directional vector just for movement using WASD
def move_directional_vector args
dx = 0
dx += 1 if args.inputs.keyboard.d
dx -= 1 if args.inputs.keyboard.a
dy = 0
dy += 1 if args.inputs.keyboard.w
dy -= 1 if args.inputs.keyboard.s
if dx != 0 && dy != 0
dx *= 0.7071
dy *= 0.7071
end
[dx, dy]
end
# Custom function for getting a directional vector just for shooting using the arrow keys
def shoot_directional_vector args
dx = 0
dx += 1 if args.inputs.keyboard.key_down.right || args.inputs.keyboard.key_held.right
dx -= 1 if args.inputs.keyboard.key_down.left || args.inputs.keyboard.key_held.left
dy = 0
dy += 1 if args.inputs.keyboard.key_down.up || args.inputs.keyboard.key_held.up
dy -= 1 if args.inputs.keyboard.key_down.down || args.inputs.keyboard.key_held.down
if dx != 0 && dy != 0
dx *= 0.7071
dy *= 0.7071
end
[dx, dy]
end
</code></pre>
<h3 id='----crafting---craft-game-starting-point---main-rb'>Crafting - Craft Game Starting Point - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_crafting/craft_game_starting_point/app/main.rb
# ==================================================
# A NOTE TO JAM CRAFT PARTICIPANTS:
# The comments and code in here are just as small piece of DragonRuby's capabilities.
# Be sure to check out the rest of the sample apps. Start with README.txt and go from there!
# ==================================================
# def tick args is the entry point into your game. This function is called at
# a fixed update time of 60hz (60 fps).
def tick args
# The defaults function intitializes the game.
defaults args
# After the game is initialized, render it.
render args
# After rendering the player should be able to respond to input.
input args
# After responding to input, the game performs any additional calculations.
calc args
end
def defaults args
# hide the mouse cursor for this game, we are going to render our own cursor
if args.state.tick_count == 0
args.gtk.hide_cursor
end
args.state.click_ripples ||= []
# everything is on a 1280x720 virtual canvas, so you can
# hardcode locations
# define the borders for where the inventory is located
# args.state is a data structure that accepts any arbitrary parameters
# so you can create an object graph without having to create any classes.
# Bottom left is 0, 0. Top right is 1280, 720.
# The inventory area is at the top of the screen
# the number 80 is the size of all the sprites, so that is what is being
# used to decide the with and height
args.state.sprite_size = 80
args.state.inventory_border.w = args.state.sprite_size * 10
args.state.inventory_border.h = args.state.sprite_size * 3
args.state.inventory_border.x = 10
args.state.inventory_border.y = 710 - args.state.inventory_border.h
# define the borders for where the crafting area is located
# the crafting area is below the inventory area
# the number 80 is the size of all the sprites, so that is what is being
# used to decide the with and height
args.state.craft_border.x = 10
args.state.craft_border.y = 220
args.state.craft_border.w = args.state.sprite_size * 3
args.state.craft_border.h = args.state.sprite_size * 3
# define the area where results are located
# the crafting result is to the right of the craft area
args.state.result_border.x = 10 + args.state.sprite_size * 3 + args.state.sprite_size
args.state.result_border.y = 220 + args.state.sprite_size
args.state.result_border.w = args.state.sprite_size
args.state.result_border.h = args.state.sprite_size
# initialize items for the first time if they are nil
# you start with 15 wood, 1 chest, and 5 plank
# Ruby has built in syntax for dictionaries (they look a lot like json objects).
# Ruby also has a special type called a Symbol denoted with a : followed by a word.
# Symbols are nice because they remove the need for magic strings.
if !args.state.items
args.state.items = [
{
id: :wood, # :wood is a Symbol, this is better than using "wood" for the id
quantity: 15,
path: 'sprites/wood.png',
location: :inventory,
ordinal_x: 0, ordinal_y: 0
},
{
id: :chest,
quantity: 1,
path: 'sprites/chest.png',
location: :inventory,
ordinal_x: 1, ordinal_y: 0
},
{
id: :plank,
quantity: 5,
path: 'sprites/plank.png',
location: :inventory,
ordinal_x: 2, ordinal_y: 0
},
]
# after initializing the oridinal positions, derive the pixel
# locations assuming that the width and height are 80
args.state.items.each { |item| set_inventory_position args, item }
end
# define all the oridinal positions of the inventory slots
if !args.state.inventory_area
args.state.inventory_area = [
{ ordinal_x: 0, ordinal_y: 0 },
{ ordinal_x: 1, ordinal_y: 0 },
{ ordinal_x: 2, ordinal_y: 0 },
{ ordinal_x: 3, ordinal_y: 0 },
{ ordinal_x: 4, ordinal_y: 0 },
{ ordinal_x: 5, ordinal_y: 0 },
{ ordinal_x: 6, ordinal_y: 0 },
{ ordinal_x: 7, ordinal_y: 0 },
{ ordinal_x: 8, ordinal_y: 0 },
{ ordinal_x: 9, ordinal_y: 0 },
{ ordinal_x: 0, ordinal_y: 1 },
{ ordinal_x: 1, ordinal_y: 1 },
{ ordinal_x: 2, ordinal_y: 1 },
{ ordinal_x: 3, ordinal_y: 1 },
{ ordinal_x: 4, ordinal_y: 1 },
{ ordinal_x: 5, ordinal_y: 1 },
{ ordinal_x: 6, ordinal_y: 1 },
{ ordinal_x: 7, ordinal_y: 1 },
{ ordinal_x: 8, ordinal_y: 1 },
{ ordinal_x: 9, ordinal_y: 1 },
{ ordinal_x: 0, ordinal_y: 2 },
{ ordinal_x: 1, ordinal_y: 2 },
{ ordinal_x: 2, ordinal_y: 2 },
{ ordinal_x: 3, ordinal_y: 2 },
{ ordinal_x: 4, ordinal_y: 2 },
{ ordinal_x: 5, ordinal_y: 2 },
{ ordinal_x: 6, ordinal_y: 2 },
{ ordinal_x: 7, ordinal_y: 2 },
{ ordinal_x: 8, ordinal_y: 2 },
{ ordinal_x: 9, ordinal_y: 2 },
]
# after initializing the oridinal positions, derive the pixel
# locations assuming that the width and height are 80
args.state.inventory_area.each { |i| set_inventory_position args, i }
# if you want to see the result you can use the Ruby function called "puts".
# Uncomment this line to see the value.
# puts args.state.inventory_area
# You can see all things written via puts in DragonRuby's Console, or under logs/log.txt.
# To bring up DragonRuby's Console, press the ~ key within the game.
end
# define all the oridinal positions of the craft slots
if !args.state.craft_area
args.state.craft_area = [
{ ordinal_x: 0, ordinal_y: 0 },
{ ordinal_x: 0, ordinal_y: 1 },
{ ordinal_x: 0, ordinal_y: 2 },
{ ordinal_x: 1, ordinal_y: 0 },
{ ordinal_x: 1, ordinal_y: 1 },
{ ordinal_x: 1, ordinal_y: 2 },
{ ordinal_x: 2, ordinal_y: 0 },
{ ordinal_x: 2, ordinal_y: 1 },
{ ordinal_x: 2, ordinal_y: 2 },
]
# after initializing the oridinal positions, derive the pixel
# locations assuming that the width and height are 80
args.state.craft_area.each { |c| set_craft_position args, c }
end
end
def render args
# for the results area, create a sprite that show its boundaries
args.outputs.primitives << { x: args.state.result_border.x,
y: args.state.result_border.y,
w: args.state.result_border.w,
h: args.state.result_border.h,
path: 'sprites/border-black.png' }
# for each inventory spot, create a sprite
# args.outputs.primitives is how DragonRuby performs a render.
# Adding a single hash or multiple hashes to this array will tell
# DragonRuby to render those primitives on that frame.
# The .map function on Array is used instead of any kind of looping.
# .map returns a new object for every object within an Array.
args.outputs.primitives << args.state.inventory_area.map do |a|
{ x: a.x, y: a.y, w: a.w, h: a.h, path: 'sprites/border-black.png' }
end
# for each craft spot, create a sprite
args.outputs.primitives << args.state.craft_area.map do |a|
{ x: a.x, y: a.y, w: a.w, h: a.h, path: 'sprites/border-black.png' }
end
# after the borders have been rendered, render the
# items within those slots (and allow for highlighting)
# if an item isn't currently being held
allow_inventory_highlighting = !args.state.held_item
# go through each item and render them
# use Array's find_all method to remove any items that are currently being held
args.state.items.find_all { |item| item[:location] != :held }.map do |item|
# if an item is currently being held, don't render it in it's spot within the
# inventory or craft area (this is handled via the find_all method).
# the item_prefab returns a hash containing all the visual components of an item.
# the main sprite, the black background, the quantity text, and a hover indication
# if the mouse is currently hovering over the item.
args.outputs.primitives << item_prefab(args, item, allow_inventory_highlighting, args.inputs.mouse)
end
# The last thing we want to render is the item currently being held.
args.outputs.primitives << item_prefab(args, args.state.held_item, allow_inventory_highlighting, args.inputs.mouse)
args.outputs.primitives << args.state.click_ripples
# render a mouse cursor since we have the OS cursor hidden
args.outputs.primitives << { x: args.inputs.mouse.x - 5, y: args.inputs.mouse.y - 5, w: 10, h: 10, path: 'sprites/circle-gray.png', a: 128 }
end
# Alrighty! This is where all the fun happens
def input args
# if the mouse is clicked and not item is currently being held
# args.state.held_item is nil when the game starts.
# If the player clicks, the property args.inputs.mouse.click will
# be a non nil value, we don't want to process any of the code here
# if the mouse hasn't been clicked
return if !args.inputs.mouse.click
# if a click occurred, add a ripple to the ripple queue
args.state.click_ripples << { x: args.inputs.mouse.x - 5, y: args.inputs.mouse.y - 5, w: 10, h: 10, path: 'sprites/circle-gray.png', a: 128 }
# if the mouse has been clicked, and no item is currently held...
if !args.state.held_item
# see if any of the items intersect the pointer using the inside_rect? method
# the find method will either return the first object that returns true
# for the match clause, or it'll return nil if nothing matches the match clause
found = args.state.items.find do |item|
# for each item in args.state.items, run the following boolean check
args.inputs.mouse.click.point.inside_rect?(item)
end
# if an item intersects the mouse pointer, then set the item's location to :held and
# set args.state.held_item to the item for later reference
if found
args.state.held_item = found
found[:location] = :held
end
# if the mouse is clicked and an item is currently beign held....
elsif args.state.held_item
# determine if a slot within the craft area was clicked
craft_area = args.state.craft_area.find { |a| args.inputs.mouse.click.point.inside_rect? a }
# also determine if a slot within the inventory area was clicked
inventory_area = args.state.inventory_area.find { |a| args.inputs.mouse.click.point.inside_rect? a }
# if the click was within a craft area
if craft_area
# check to see if an item is already there and ignore the click if an item is found
# item_at_craft_slot is a helper method that returns an item or nil for a given oridinal
# position
item_already_there = item_at_craft_slot args, craft_area[:ordinal_x], craft_area[:ordinal_y]
# if an item *doesn't* exist in the craft area
if !item_already_there
# if the quantity they are currently holding is greater than 1
if args.state.held_item[:quantity] > 1
# remove one item (creating a seperate item of the same type), and place it
# at the oridinal position and location of the craft area
# the .merge method on Hash creates a new Hash, but updates any values
# passed as arguments to merge
new_item = args.state.held_item.merge(quantity: 1,
location: :craft,
ordinal_x: craft_area[:ordinal_x],
ordinal_y: craft_area[:ordinal_y])
# after the item is crated, place it into the args.state.items collection
args.state.items << new_item
# then subtract one from the held item
args.state.held_item[:quantity] -= 1
# if the craft area is available and there is only one item being held
elsif args.state.held_item[:quantity] == 1
# instead of creating any new items just set the location of the held item
# to the oridinal position of the craft area, and then nil out the
# held item state so that a new item can be picked up
args.state.held_item[:location] = :craft
args.state.held_item[:ordinal_x] = craft_area[:ordinal_x]
args.state.held_item[:ordinal_y] = craft_area[:ordinal_y]
args.state.held_item = nil
end
end
# if the selected area is an inventory area (as opposed to within the craft area)
elsif inventory_area
# check to see if there is already an item in that inventory slot
# the item_at_inventory_slot helper method returns an item or nil
item_already_there = item_at_inventory_slot args, inventory_area[:ordinal_x], inventory_area[:ordinal_y]
# if there is already an item there, and the item types/id match
if item_already_there && item_already_there[:id] == args.state.held_item[:id]
# then merge the item quantities
held_quantity = args.state.held_item[:quantity]
item_already_there[:quantity] += held_quantity
# remove the item being held from the items collection (since it's quantity is now 0)
args.state.items.reject! { |i| i[:location] == :held }
# nil out the held_item so a new item can be picked up
args.state.held_item = nil
# if there currently isn't an item there, then put the held item in the slot
elsif !item_already_there
args.state.held_item[:location] = :inventory
args.state.held_item[:ordinal_x] = inventory_area[:ordinal_x]
args.state.held_item[:ordinal_y] = inventory_area[:ordinal_y]
# nil out the held_item so a new item can be picked up
args.state.held_item = nil
end
end
end
end
# the calc method is executed after input
def calc args
# make sure that the real position of the inventory
# items are updated every frame to ensure that they
# are placed correctly given their location and oridinal positions
# instead of using .map, here we use .each (since we are not returning a new item and just updating the items in place)
args.state.items.each do |item|
# based on the location of the item, invoke the correct pixel conversion method
if item[:location] == :inventory
set_inventory_position args, item
elsif item[:location] == :craft
set_craft_position args, item
elsif item[:location] == :held
# if the item is held, center the item around the mouse pointer
args.state.held_item.x = args.inputs.mouse.x - args.state.held_item.w.half
args.state.held_item.y = args.inputs.mouse.y - args.state.held_item.h.half
end
end
# for each hash/sprite in the click ripples queue,
# expand its size by 20 percent and decrease its alpha
# by 10.
args.state.click_ripples.each do |ripple|
delta_w = ripple.w * 1.2 - ripple.w
delta_h = ripple.h * 1.2 - ripple.h
ripple.x -= delta_w.half
ripple.y -= delta_h.half
ripple.w += delta_w
ripple.h += delta_h
ripple.a -= 10
end
# remove any items from the collection where the alpha value is less than equal to
# zero using the reject! method (reject with an exclamation point at the end changes the
# array value in place, while reject without the exclamation point returns a new array).
args.state.click_ripples.reject! { |ripple| ripple.a <= 0 }
end
# helper function for finding an item at a craft slot
def item_at_craft_slot args, ordinal_x, ordinal_y
args.state.items.find { |i| i[:location] == :craft && i[:ordinal_x] == ordinal_x && i[:ordinal_y] == ordinal_y }
end
# helper function for finding an item at an inventory slot
def item_at_inventory_slot args, ordinal_x, ordinal_y
args.state.items.find { |i| i[:location] == :inventory && i[:ordinal_x] == ordinal_x && i[:ordinal_y] == ordinal_y }
end
# helper function that creates a visual representation of an item
def item_prefab args, item, should_highlight, mouse
return nil unless item
overlay = nil
x = item.x
y = item.y
w = item.w
h = item.h
if should_highlight && mouse.point.inside_rect?(item)
overlay = { x: x, y: y, w: w, h: h, path: "sprites/square-blue.png", a: 130, }
end
[
# sprites are hashes with a path property, this is the main sprite
{ x: x, y: y, w: args.state.sprite_size, h: args.state.sprite_size, path: item[:path], },
# this represents the black area in the bottom right corner of the main sprite so that the
# quantity is visible
{ x: x + 55, y: y, w: 25, h: 25, path: "sprites/square-black.png", }, # sprites are hashes with a path property
# labels are hashes with a text property
{ x: x + 56, y: y + 22, text: "#{item[:quantity]}", r: 255, g: 255, b: 255, },
# this is the mouse overlay, if the overlay isn't applicable, then this value will be nil (nil values will not be rendered)
overlay
]
end
# helper function for deriving the position of an item within inventory
def set_inventory_position args, item
item.x = args.state.inventory_border.x + item[:ordinal_x] * 80
item.y = (args.state.inventory_border.y + args.state.inventory_border.h - 80) - item[:ordinal_y] * 80
item.w = 80
item.h = 80
end
# helper function for deriving the position of an item within the craft area
def set_craft_position args, item
item.x = args.state.craft_border.x + item[:ordinal_x] * 80
item.y = (args.state.craft_border.y + args.state.inventory_border.h - 80) - item[:ordinal_y] * 80
item.w = 80
item.h = 80
end
# Any lines outside of a function will be executed when the file is reloaded.
# So every time you save main.rb, the game will be reset.
# Comment out the line below if you don't want this to happen.
$gtk.reset
</code></pre>
<h3 id='----crafting---farming-game-starting-point---main-rb'>Crafting - Farming Game Starting Point - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_crafting/farming_game_starting_point/app/main.rb
def tick args
args.state.tile_size = 80
args.state.player_speed = 4
args.state.player ||= tile(args, 7, 3, 0, 128, 180)
generate_map args
#press j to plant a green onion
if args.inputs.keyboard.j
#change this part you can change what you want to plant
args.state.walls << tile(args, ((args.state.player.x+80)/args.state.tile_size), ((args.state.player.y)/args.state.tile_size), 255, 255, 255)
args.state.plants << tile(args, ((args.state.player.x+80)/args.state.tile_size), ((args.state.player.y+80)/args.state.tile_size), 0, 160, 0)
end
# Adds walls, background, and player to args.outputs.solids so they appear on screen
args.outputs.solids << [0,0,1280,720, 237,189,101]
args.outputs.sprites << [0, 0, 1280, 720, 'sprites/background.png']
args.outputs.solids << args.state.walls
args.outputs.solids << args.state.player
args.outputs.solids << args.state.plants
args.outputs.labels << [320, 640, "press J to plant", 3, 1, 255, 0, 0, 200]
move_player args, -1, 0 if args.inputs.keyboard.left # x position decreases by 1 if left key is pressed
move_player args, 1, 0 if args.inputs.keyboard.right # x position increases by 1 if right key is pressed
move_player args, 0, 1 if args.inputs.keyboard.up # y position increases by 1 if up is pressed
move_player args, 0, -1 if args.inputs.keyboard.down # y position decreases by 1 if down is pressed
end
# Sets position, size, and color of the tile
def tile args, x, y, *color
[x * args.state.tile_size, # sets definition for array using method parameters
y * args.state.tile_size, # multiplying by tile_size sets x and y to correct position using pixel values
args.state.tile_size,
args.state.tile_size,
*color]
end
# Creates map by adding tiles to the wall, as well as a goal (that the player needs to reach)
def generate_map args
return if args.state.area
# Creates the area of the map. There are 9 rows running horizontally across the screen
# and 16 columns running vertically on the screen. Any spot with a "1" is not
# open for the player to move into (and is green), and any spot with a "0" is available
# for the player to move in.
args.state.area = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
].reverse # reverses the order of the area collection
# By reversing the order, the way that the area appears above is how it appears
# on the screen in the game. If we did not reverse, the map would appear inverted.
#The wall starts off with no tiles.
args.state.walls = []
args.state.plants = []
# If v is 1, a green tile is added to args.state.walls.
# If v is 2, a black tile is created as the goal.
args.state.area.map_2d do |y, x, v|
if v == 1
args.state.walls << tile(args, x, y, 255, 160, 156) # green tile
end
end
end
# Allows the player to move their box around the screen
def move_player args, *vector
box = args.state.player.shift_rect(vector) # box is able to move at an angle
# If the player's box hits a wall, it is not able to move further in that direction
return if args.state.walls
.any_intersect_rect?(box)
# Player's box is able to move at angles (not just the four general directions) fast
args.state.player =
args.state.player
.shift_rect(vector.x * args.state.player_speed, # if we don't multiply by speed, then
vector.y * args.state.player_speed) # the box will move extremely slow
end
</code></pre>
<h3 id='----crafting---farming-game-starting-point---repl-rb'>Crafting - Farming Game Starting Point - repl.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_crafting/farming_game_starting_point/app/repl.rb
# ===============================================================
# Welcome to repl.rb
# ===============================================================
# You can experiement with code within this file. Code in this
# file is only executed when you save (and only excecuted ONCE).
# ===============================================================
# ===============================================================
# REMOVE the "x" from the word "xrepl" and save the file to RUN
# the code in between the do/end block delimiters.
# ===============================================================
# ===============================================================
# ADD the "x" to the word "repl" (make it xrepl) and save the
# file to IGNORE the code in between the do/end block delimiters.
# ===============================================================
# Remove the x from xrepl to run the code. Add the x back to ignore to code.
xrepl do
puts "The result of 1 + 2 is: #{1 + 2}"
end
# ====================================================================================
# Ruby Crash Course:
# Strings, Numeric, Booleans, Conditionals, Looping, Enumerables, Arrays
# ====================================================================================
# ====================================================================================
# Strings
# ====================================================================================
# Remove the x from xrepl to run the code. Add the x back to ignore to code.
xrepl do
message = "Hello World"
puts "The value of message is: " + message
puts "Any value can be interpolated within a string using \#{}."
puts "Interpolated message: #{message}."
puts 'This #{message} is not interpolated because the string uses single quotes.'
end
# ====================================================================================
# Numerics
# ====================================================================================
# Remove the x from xrepl to run the code. Add the x back to ignore to code.
xrepl do
a = 10
puts "The value of a is: #{a}"
puts "a + 1 is: #{a + 1}"
puts "a / 3 is: #{a / 3}"
end
# Remove the x from xrepl to run the code. Add the x back to ignore to code.
xrepl do
b = 10.12
puts "The value of b is: #{b}"
puts "b + 1 is: #{b + 1}"
puts "b as an integer is: #{b.to_i}"
puts ''
end
# ====================================================================================
# Booleans
# ====================================================================================
# Remove the x from xrepl to run the code. Add the x back to ignore to code.
xrepl do
c = 30
puts "The value of c is #{c}."
if c
puts "This if statement ran because c is truthy."
end
end
# Remove the x from xrepl to run the code. Add the x back to ignore to code.
xrepl do
d = false
puts "The value of d is #{d}."
if !d
puts "This if statement ran because d is falsey, using the not operator (!) makes d evaluate to true."
end
e = nil
puts "Nil is also considered falsey. The value of e is: #{e}."
if !e
puts "This if statement ran because e is nil (a falsey value)."
end
end
# ====================================================================================
# Conditionals
# ====================================================================================
# Remove the x from xrepl to run the code. Add the x back to ignore to code.
xrepl do
i_am_true = true
i_am_nil = nil
i_am_false = false
i_am_hi = "hi"
puts "======== if statement"
i_am_one = 1
if i_am_one
puts "This was printed because i_am_one is truthy."
end
puts "======== if/else statement"
if i_am_false
puts "This will NOT get printed because i_am_false is false."
else
puts "This was printed because i_am_false is false."
end
puts "======== if/elsif/else statement"
if i_am_false
puts "This will NOT get printed because i_am_false is false."
elsif i_am_true
puts "This was printed because i_am_true is true."
else
puts "This will NOT get printed i_am_true was true."
end
puts "======== case statement "
i_am_one = 1
case i_am_one
when 10
puts "case equaled: 10"
when 9
puts "case equaled: 9"
when 5
puts "case equaled: 5"
when 1
puts "case equaled: 1"
else
puts "Value wasn't cased."
end
puts "======== different types of comparisons"
if 4 == 4
puts "equal (4 == 4)"
end
if 4 != 3
puts "not equal (4 != 3)"
end
if 3 < 4
puts "less than (3 < 4)"
end
if 4 > 3
puts "greater than (4 > 3)"
end
if ((4 > 3) || (3 < 4) || false)
puts "or statement ((4 > 3) || (3 < 4) || false)"
end
if ((4 > 3) && (3 < 4))
puts "and statement ((4 > 3) && (3 < 4))"
end
end
# ====================================================================================
# Looping
# ====================================================================================
# Remove the x from xrepl to run the code. Add the x back to ignore to code.
xrepl do
puts "======== times block"
3.times do |i|
puts i
end
puts "======== range block exclusive"
(0...3).each do |i|
puts i
end
puts "======== range block inclusive"
(0..3).each do |i|
puts i
end
end
# ====================================================================================
# Enumerables
# ====================================================================================
# Remove the x from xrepl to run the code. Add the x back to ignore to code.
xrepl do
puts "======== array each"
colors = ["red", "blue", "yellow"]
colors.each do |color|
puts color
end
puts '======== array each_with_index'
colors = ["red", "blue", "yellow"]
colors.each_with_index do |color, i|
puts "#{color} at index #{i}"
end
end
# Remove the x from xrepl to run the code. Add the x back to ignore to code.
xrepl do
puts "======== single parameter function"
def add_one_to n
n + 5
end
puts add_one_to(3)
puts "======== function with default value"
def function_with_default_value v = 10
v * 10
end
puts "passing three: #{function_with_default_value(3)}"
puts "passing nil: #{function_with_default_value}"
puts "======== Or Equal (||=) operator for nil values"
def function_with_nil_default_with_local a = nil
result = a
result ||= "or equal operator was exected and set a default value"
end
puts "passing 'hi': #{function_with_nil_default_with_local 'hi'}"
puts "passing nil: #{function_with_nil_default_with_local}"
end
# ====================================================================================
# Arrays
# ====================================================================================
# Remove the x from xrepl to run the code. Add the x back to ignore to code.
xrepl do
puts "======== Create an array with the numbers 1 to 10."
one_to_ten = (1..10).to_a
puts one_to_ten
puts "======== Create a new array that only contains even numbers from the previous array."
one_to_ten = (1..10).to_a
evens = one_to_ten.find_all do |number|
number % 2 == 0
end
puts evens
puts "======== Create a new array that rejects odd numbers."
one_to_ten = (1..10).to_a
also_even = one_to_ten.reject do |number|
number % 2 != 0
end
puts also_even
puts "======== Create an array that doubles every number."
one_to_ten = (1..10).to_a
doubled = one_to_ten.map do |number|
number * 2
end
puts doubled
puts "======== Create an array that selects only odd numbers and then multiply those by 10."
one_to_ten = (1..10).to_a
odd_doubled = one_to_ten.find_all do |number|
number % 2 != 0
end.map do |odd_number|
odd_number * 10
end
puts odd_doubled
puts "======== All combination of numbers 1 to 10."
one_to_ten = (1..10).to_a
all_combinations = one_to_ten.product(one_to_ten)
puts all_combinations
puts "======== All uniq combinations of numbers. For example: [1, 2] is the same as [2, 1]."
one_to_ten = (1..10).to_a
uniq_combinations =
one_to_ten.product(one_to_ten)
.map do |unsorted_number|
unsorted_number.sort
end.uniq
puts uniq_combinations
end
# ====================================================================================
# Advanced Arrays
# ====================================================================================
# Remove the x from xrepl to run the code. Add the x back to ignore to code.
xrepl do
puts "======== All unique Pythagorean Triples between 1 and 40 sorted by area of the triangle."
one_to_hundred = (1..40).to_a
triples =
one_to_hundred.product(one_to_hundred).map do |width, height|
[width, height, Math.sqrt(width ** 2 + height ** 2)]
end.find_all do |_, _, hypotenuse|
hypotenuse.to_i == hypotenuse
end.map do |triangle|
triangle.map(&:to_i)
end.uniq do |triangle|
triangle.sort
end.map do |width, height, hypotenuse|
[width, height, hypotenuse, (width * height) / 2]
end.sort_by do |_, _, _, area|
area
end
triples.each do |width, height, hypotenuse, area|
puts "(#{width}, #{height}, #{hypotenuse}) = #{area}"
end
end
</code></pre>
<h3 id='----crafting---farming-game-starting-point---tests-rb'>Crafting - Farming Game Starting Point - tests.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_crafting/farming_game_starting_point/app/tests.rb
# For advanced users:
# You can put some quick verification tests here, any method
# that starts with the `test_` will be run when you save this file.
# Here is an example test and game
# To run the test: ./dragonruby mygame --eval app/tests.rb --no-tick
class MySuperHappyFunGame
attr_gtk
def tick
outputs.solids << [100, 100, 300, 300]
end
end
def test_universe args, assert
game = MySuperHappyFunGame.new
game.args = args
game.tick
assert.true! args.outputs.solids.length == 1, "failure: a solid was not added after tick"
assert.false! 1 == 2, "failure: some how, 1 equals 2, the world is ending"
puts "test_universe completed successfully"
end
puts "running tests"
$gtk.reset 100
$gtk.log_level = :off
$gtk.tests.start
</code></pre>
<h3 id='----dev-tools---add-buttons-to-console---main-rb'>Dev Tools - Add Buttons To Console - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_dev_tools/add_buttons_to_console/app/main.rb
# You can customize the buttons that show up in the Console.
class GTK::Console::Menu
# STEP 1: Override the custom_buttons function.
def custom_buttons
[
(button id: :yay,
# row for button
row: 3,
# column for button
col: 10,
# text
text: "I AM CUSTOM",
# when clicked call the custom_button_clicked function
method: :custom_button_clicked),
(button id: :yay,
# row for button
row: 3,
# column for button
col: 9,
# text
text: "CUSTOM ALSO",
# when clicked call the custom_button_also_clicked function
method: :custom_button_also_clicked)
]
end
# STEP 2: Define the function that should be called.
def custom_button_clicked
log "* INFO: I AM CUSTOM was clicked!"
end
def custom_button_also_clicked
log "* INFO: Custom Button Clicked at #{Kernel.global_tick_count}!"
all_buttons_as_string = $gtk.console.menu.buttons.map do |b|
<<-S.strip
** id: #{b[:id]}
:PROPERTIES:
:id: :#{b[:id]}
:method: :#{b[:method]}
:text: #{b[:text]}
:END:
S
end.join("\n")
log <<-S
* INFO: Here are all the buttons:
#{all_buttons_as_string}
S
end
end
def tick args
args.outputs.labels << [args.grid.center.x, args.grid.center.y,
"Open the DragonRuby Console to see the custom menu items.",
0, 1]
end
</code></pre>
<h3 id='----dev-tools---animation-creator-starting-point---main-rb'>Dev Tools - Animation Creator Starting Point - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_dev_tools/animation_creator_starting_point/app/main.rb
class OneBitLowrezPaint
attr_gtk
def tick
outputs.background_color = [0, 0, 0]
defaults
render_instructions
render_canvas
render_buttons_frame_selection
render_animation_frame_thumbnails
render_animation
input_mouse_click
input_keyboard
calc_auto_export
calc_buttons_frame_selection
calc_animation_frames
process_queue_create_sprite
process_queue_reset_sprite
process_queue_update_rt_animation_frame
end
def defaults
state.animation_frames_per_second = 12
queues.create_sprite ||= []
queues.reset_sprite ||= []
queues.update_rt_animation_frame ||= []
if !state.animation_frames
state.animation_frames ||= []
add_animation_frame_to_end
end
state.last_mouse_down ||= 0
state.last_mouse_up ||= 0
state.buttons_frame_selection.left = 10
state.buttons_frame_selection.top = grid.top - 10
state.buttons_frame_selection.size = 20
defaults_canvas_sprite
state.edit_mode ||= :drawing
end
def defaults_canvas_sprite
rt_canvas.size = 16
rt_canvas.zoom = 30
rt_canvas.width = rt_canvas.size * rt_canvas.zoom
rt_canvas.height = rt_canvas.size * rt_canvas.zoom
rt_canvas.sprite = { x: 0,
y: 0,
w: rt_canvas.width,
h: rt_canvas.height,
path: :rt_canvas }.center_inside_rect(x: 0, y: 0, w: 640, h: 720)
return unless state.tick_count == 1
outputs[:rt_canvas].width = rt_canvas.width
outputs[:rt_canvas].height = rt_canvas.height
outputs[:rt_canvas].sprites << (rt_canvas.size + 1).map_with_index do |x|
(rt_canvas.size + 1).map_with_index do |y|
path = 'sprites/square-white.png'
path = 'sprites/square-blue.png' if x == 7 || x == 8
{ x: x * rt_canvas.zoom,
y: y * rt_canvas.zoom,
w: rt_canvas.zoom,
h: rt_canvas.zoom,
path: path,
a: 50 }
end
end
end
def render_instructions
instructions = [
"* Hotkeys:",
"- d: hold to erase, release to draw.",
"- a: add frame.",
"- c: copy frame.",
"- v: paste frame.",
"- x: delete frame.",
"- b: go to previous frame.",
"- f: go to next frame.",
"- w: save to ./canvas directory.",
"- l: load from ./canvas."
]
instructions.each.with_index do |l, i|
outputs.labels << { x: 840, y: 500 - (i * 20), text: "#{l}",
r: 180, g: 180, b: 180, size_enum: 0 }
end
end
def render_canvas
return if state.tick_count.zero?
outputs.sprites << rt_canvas.sprite
end
def render_buttons_frame_selection
args.outputs.primitives << state.buttons_frame_selection.items.map_with_index do |b, i|
label = { x: b.x + state.buttons_frame_selection.size.half,
y: b.y,
text: "#{i + 1}", r: 180, g: 180, b: 180,
size_enum: -4, alignment_enum: 1 }.label!
selection_border = b.merge(r: 40, g: 40, b: 40).border!
if i == state.animation_frames_selected_index
selection_border = b.merge(r: 40, g: 230, b: 200).border!
end
[selection_border, label]
end
end
def render_animation_frame_thumbnails
return if state.tick_count.zero?
outputs[:current_animation_frame].width = rt_canvas.size
outputs[:current_animation_frame].height = rt_canvas.size
outputs[:current_animation_frame].solids << selected_animation_frame[:pixels].map_with_index do |f, i|
{ x: f.x,
y: f.y,
w: 1,
h: 1, r: 255, g: 255, b: 255 }
end
outputs.sprites << rt_canvas.sprite.merge(path: :current_animation_frame)
state.animation_frames.map_with_index do |animation_frame, animation_frame_index|
outputs.sprites << state.buttons_frame_selection[:items][animation_frame_index][:inner_rect]
.merge(path: animation_frame[:rt_name])
end
end
def render_animation
sprite_index = 0.frame_index count: state.animation_frames.length,
hold_for: 60 / state.animation_frames_per_second,
repeat: true
args.outputs.sprites << { x: 700 - 8,
y: 120,
w: 16,
h: 16,
path: (sprite_path sprite_index) }
args.outputs.sprites << { x: 700 - 16,
y: 230,
w: 32,
h: 32,
path: (sprite_path sprite_index) }
args.outputs.sprites << { x: 700 - 32,
y: 360,
w: 64,
h: 64,
path: (sprite_path sprite_index) }
args.outputs.sprites << { x: 700 - 64,
y: 520,
w: 128,
h: 128,
path: (sprite_path sprite_index) }
end
def input_mouse_click
if inputs.mouse.up
state.last_mouse_up = state.tick_count
elsif inputs.mouse.moved && user_is_editing?
edit_current_animation_frame inputs.mouse.point
end
return unless inputs.mouse.click
clicked_frame_button = state.buttons_frame_selection.items.find do |b|
inputs.mouse.point.inside_rect? b
end
if (clicked_frame_button)
state.animation_frames_selected_index = clicked_frame_button[:index]
end
if (inputs.mouse.point.inside_rect? rt_canvas.sprite)
state.last_mouse_down = state.tick_count
edit_current_animation_frame inputs.mouse.point
end
end
def input_keyboard
# w to save
if inputs.keyboard.key_down.w
t = Time.now
state.save_description = "Time: #{t} (#{t.to_i})"
gtk.serialize_state 'canvas/state.txt', state
gtk.serialize_state "tmp/canvas_backups/#{t.to_i}/state.txt", state
animation_frames.each_with_index do |animation_frame, i|
queues.update_rt_animation_frame << { index: i,
at: state.tick_count + i,
queue_sprite_creation: true }
queues.create_sprite << { index: i,
at: state.tick_count + animation_frames.length + i,
path_override: "tmp/canvas_backups/#{t.to_i}/sprite-#{i}.png" }
end
gtk.notify! "Canvas saved."
end
# l to load
if inputs.keyboard.key_down.l
args.state = gtk.deserialize_state 'canvas/state.txt'
animation_frames.each_with_index do |a, i|
queues.update_rt_animation_frame << { index: i,
at: state.tick_count + i,
queue_sprite_creation: true }
end
gtk.notify! "Canvas loaded."
end
# d to go into delete mode, release to paint
if inputs.keyboard.key_held.d
state.edit_mode = :erasing
gtk.notify! "Erasing." if inputs.keyboard.key_held.d == (state.tick_count - 1)
elsif inputs.keyboard.key_up.d
state.edit_mode = :drawing
gtk.notify! "Drawing."
end
# a to add a frame to the end
if inputs.keyboard.key_down.a
queues.create_sprite << { index: state.animation_frames_selected_index,
at: state.tick_count }
queues.create_sprite << { index: state.animation_frames_selected_index + 1,
at: state.tick_count }
add_animation_frame_to_end
gtk.notify! "Frame added to end."
end
# c or t to copy
if (inputs.keyboard.key_down.c || inputs.keyboard.key_down.t)
state.clipboard = [selected_animation_frame[:pixels]].flatten
gtk.notify! "Current frame copied."
end
# v or q to paste
if (inputs.keyboard.key_down.v || inputs.keyboard.key_down.q) && state.clipboard
selected_animation_frame[:pixels] = [state.clipboard].flatten
queues.update_rt_animation_frame << { index: state.animation_frames_selected_index,
at: state.tick_count,
queue_sprite_creation: true }
gtk.notify! "Pasted."
end
# f to go forward/next frame
if (inputs.keyboard.key_down.f)
if (state.animation_frames_selected_index == (state.animation_frames.length - 1))
state.animation_frames_selected_index = 0
else
state.animation_frames_selected_index += 1
end
gtk.notify! "Next frame."
end
# b to go back/previous frame
if (inputs.keyboard.key_down.b)
if (state.animation_frames_selected_index == 0)
state.animation_frames_selected_index = state.animation_frames.length - 1
else
state.animation_frames_selected_index -= 1
end
gtk.notify! "Previous frame."
end
# x to delete frame
if (inputs.keyboard.key_down.x) && animation_frames.length > 1
state.clipboard = selected_animation_frame[:pixels]
state.animation_frames = animation_frames.find_all { |v| v[:index] != state.animation_frames_selected_index }
if state.animation_frames_selected_index >= state.animation_frames.length
state.animation_frames_selected_index = state.animation_frames.length - 1
end
gtk.notify! "Frame deleted."
end
end
def calc_auto_export
return if user_is_editing?
return if state.last_mouse_up.elapsed_time != 30
# auto export current animation frame if there is no editing for 30 ticks
queues.create_sprite << { index: state.animation_frames_selected_index,
at: state.tick_count }
end
def calc_buttons_frame_selection
state.buttons_frame_selection.items = animation_frames.length.map_with_index do |i|
{ x: state.buttons_frame_selection.left + i * state.buttons_frame_selection.size,
y: state.buttons_frame_selection.top - state.buttons_frame_selection.size,
inner_rect: {
x: (state.buttons_frame_selection.left + 2) + i * state.buttons_frame_selection.size,
y: (state.buttons_frame_selection.top - state.buttons_frame_selection.size + 2),
w: 16,
h: 16,
},
w: state.buttons_frame_selection.size,
h: state.buttons_frame_selection.size,
index: i }
end
end
def calc_animation_frames
animation_frames.each_with_index do |animation_frame, i|
animation_frame[:index] = i
animation_frame[:rt_name] = "animation_frame_#{i}"
end
end
def process_queue_create_sprite
sprites_to_create = queues.create_sprite
.find_all { |h| h[:at].elapsed? }
queues.create_sprite = queues.create_sprite - sprites_to_create
sprites_to_create.each do |h|
export_animation_frame h[:index], h[:path_override]
end
end
def process_queue_reset_sprite
sprites_to_reset = queues.reset_sprite
.find_all { |h| h[:at].elapsed? }
queues.reset_sprite -= sprites_to_reset
sprites_to_reset.each { |h| gtk.reset_sprite (sprite_path h[:index]) }
end
def process_queue_update_rt_animation_frame
animation_frames_to_update = queues.update_rt_animation_frame
.find_all { |h| h[:at].elapsed? }
queues.update_rt_animation_frame -= animation_frames_to_update
animation_frames_to_update.each do |h|
update_animation_frame_render_target animation_frames[h[:index]]
if h[:queue_sprite_creation]
queues.create_sprite << { index: h[:index],
at: state.tick_count + 1 }
end
end
end
def update_animation_frame_render_target animation_frame
return if !animation_frame
outputs[animation_frame[:rt_name]].width = state.rt_canvas.size
outputs[animation_frame[:rt_name]].height = state.rt_canvas.size
outputs[animation_frame[:rt_name]].solids << animation_frame[:pixels].map do |f|
{ x: f.x,
y: f.y,
w: 1,
h: 1, r: 255, g: 255, b: 255 }
end
end
def animation_frames
state.animation_frames
end
def add_animation_frame_to_end
animation_frames << {
index: animation_frames.length,
pixels: [],
rt_name: "animation_frame_#{animation_frames.length}"
}
state.animation_frames_selected_index = (animation_frames.length - 1)
queues.update_rt_animation_frame << { index: state.animation_frames_selected_index,
at: state.tick_count,
queue_sprite_creation: true }
end
def sprite_path i
"canvas/sprite-#{i}.png"
end
def export_animation_frame i, path_override = nil
return if !state.animation_frames[i]
outputs.screenshots << state.buttons_frame_selection
.items[i][:inner_rect]
.merge(path: path_override || (sprite_path i))
outputs.screenshots << state.buttons_frame_selection
.items[i][:inner_rect]
.merge(path: "tmp/sprite_backups/#{Time.now.to_i}-sprite-#{i}.png")
queues.reset_sprite << { index: i, at: state.tick_count }
end
def selected_animation_frame
state.animation_frames[state.animation_frames_selected_index]
end
def edit_current_animation_frame point
draw_area_point = (to_draw_area point)
if state.edit_mode == :drawing && (!selected_animation_frame[:pixels].include? draw_area_point)
selected_animation_frame[:pixels] << draw_area_point
queues.update_rt_animation_frame << { index: state.animation_frames_selected_index,
at: state.tick_count,
queue_sprite_creation: !user_is_editing? }
elsif state.edit_mode == :erasing && (selected_animation_frame[:pixels].include? draw_area_point)
selected_animation_frame[:pixels] = selected_animation_frame[:pixels].reject { |p| p == draw_area_point }
queues.update_rt_animation_frame << { index: state.animation_frames_selected_index,
at: state.tick_count,
queue_sprite_creation: !user_is_editing? }
end
end
def user_is_editing?
state.last_mouse_down > state.last_mouse_up
end
def to_draw_area point
x, y = point
x -= rt_canvas.sprite.x
y -= rt_canvas.sprite.y
{ x: x.idiv(rt_canvas.zoom),
y: y.idiv(rt_canvas.zoom) }
end
def rt_canvas
state.rt_canvas ||= state.new_entity(:rt_canvas)
end
def queues
state.queues ||= state.new_entity(:queues)
end
end
$game = OneBitLowrezPaint.new
def tick args
$game.args = args
$game.tick
end
# $gtk.reset
</code></pre>
<h3 id='----dev-tools---tile-editor-starting-point---main-rb'>Dev Tools - Tile Editor Starting Point - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_dev_tools/tile_editor_starting_point/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- to_s: Returns a string representation of an object.
For example, if we had
500.to_s
the string "500" would be returned.
Similar to to_i, which returns an integer representation of an object.
- Ceil: Returns an integer number greater than or equal to the original
with no decimal.
Reminders:
- ARRAY#inside_rect?: Returns true or false depending on if the point is inside a rect.
- args.outputs.labels: An array. The values generate a label.
The parameters are [X, Y, TEXT, SIZE, ALIGNMENT, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.md.
- args.outputs.sprites: An array. The values generate a sprite.
The parameters are [X, Y, WIDTH, HEIGHT, IMAGE PATH]
For more information about sprites, go to mygame/documentation/05-sprites.md.
- args.outputs.solids: An array. The values generate a solid.
The parameters are [X, Y, WIDTH, HEIGHT, RED, GREEN, BLUE]
For more information about solids, go to mygame/documentation/03-solids-and-borders.md.
- args.outputs.lines: An array. The values generate a line.
The parameters are [X1, Y1, X2, Y2, RED, GREEN, BLUE]
For more information about lines, go to mygame/documentation/04-lines.md.
- args.state.new_entity: Used when we want to create a new object, like a sprite or button.
In this sample app, new_entity is used to create a new button that clears the grid.
(Remember, you can use state to define ANY property and it will be retained across frames.)
=end
# This sample app shows an empty grid that the user can paint in. There are different image tiles that
# the user can use to fill the grid, and the "Clear" button can be pressed to clear the grid boxes.
class TileEditor
attr_accessor :inputs, :state, :outputs, :grid, :args
# Runs all the methods necessary for the game to function properly.
def tick
defaults
render
check_click
draw_buttons
end
# Sets default values
# Initialization only happens in the first frame
# NOTE: The values of some of these variables may seem confusingly large at first.
# The gridSize is 1600 but it seems a lot smaller on the screen, for example.
# But keep in mind that by using the "W", "A", "S", and "D" keys, you can
# move the grid's view in all four directions for more grid spaces.
def defaults
state.tileCords ||= []
state.tileQuantity ||= 6
state.tileSize ||= 50
state.tileSelected ||= 1
state.tempX ||= 50
state.tempY ||= 500
state.speed ||= 4
state.centerX ||= 4000
state.centerY ||= 4000
state.originalCenter ||= [state.centerX, state.centerY]
state.gridSize ||= 1600
state.lineQuantity ||= 50
state.increment ||= state.gridSize / state.lineQuantity
state.gridX ||= []
state.gridY ||= []
state.filled_squares ||= []
state.grid_border ||= [390, 140, 500, 500]
get_grid unless state.tempX == 0 # calls get_grid in the first frame only
determineTileCords unless state.tempX == 0 # calls determineTileCords in first frame
state.tempX = 0 # sets tempX to 0; the two methods aren't called again
end
# Calculates the placement of lines or separators in the grid
def get_grid
curr_x = state.centerX - (state.gridSize / 2) # starts at left of grid
deltaX = state.gridSize / state.lineQuantity # finds distance to place vertical lines evenly through width of grid
(state.lineQuantity + 2).times do
state.gridX << curr_x # adds curr_x to gridX collection
curr_x += deltaX # increment curr_x by the distance between vertical lines
end
curr_y = state.centerY - (state.gridSize / 2) # starts at bottom of grid
deltaY = state.gridSize / state.lineQuantity # finds distance to place horizontal lines evenly through height of grid
(state.lineQuantity + 2).times do
state.gridY << curr_y # adds curr_y to gridY collection
curr_y += deltaY # increments curr_y to distance between horizontal lines
end
end
# Determines coordinate positions of patterned tiles (on the left side of the grid)
def determineTileCords
state.tempCounter ||= 1 # initializes tempCounter to 1
state.tileQuantity.times do # there are 6 different kinds of tiles
state.tileCords += [[state.tempX, state.tempY, state.tempCounter]] # adds tile definition to collection
state.tempX += 75 # increments tempX to put horizontal space between the patterned tiles
state.tempCounter += 1 # increments tempCounter
if state.tempX > 200 # if tempX exceeds 200 pixels
state.tempX = 50 # a new row of patterned tiles begins
state.tempY -= 75 # the new row is 75 pixels lower than the previous row
end
end
end
# Outputs objects (grid, tiles, etc) onto the screen
def render
outputs.sprites << state.tileCords.map do # outputs tileCords collection using images in sprites folder
|x, y, order|
[x, y, state.tileSize, state.tileSize, 'sprites/image' + order.to_s + ".png"]
end
outputs.solids << [0, 0, 1280, 720, 255, 255, 255] # outputs white background
add_grid # outputs grid
print_title # outputs title and current tile pattern
end
# Creates a grid by outputting vertical and horizontal grid lines onto the screen.
# Outputs sprites for the filled_squares collection onto the screen.
def add_grid
# Outputs the grid's border.
outputs.borders << state.grid_border
temp = 0
# Before looking at the code that outputs the vertical and horizontal lines in the
# grid, take note of the fact that:
# grid_border[1] refers to the border's bottom line (running horizontally),
# grid_border[2] refers to the border's top line (running (horizontally),
# grid_border[0] refers to the border's left line (running vertically),
# and grid_border[3] refers to the border's right line (running vertically).
# [2]
# ----------
# | |
# [0] | | [3]
# | |
# ----------
# [1]
# Calculates the positions and outputs the x grid lines in the color gray.
state.gridX.map do # perform an action on all elements of the gridX collection
|x|
temp += 1 # increment temp
# if x's value is greater than (or equal to) the x value of the border's left side
# and less than (or equal to) the x value of the border's right side
if x >= state.centerX - (state.grid_border[2] / 2) && x <= state.centerX + (state.grid_border[2] / 2)
delta = state.centerX - 640
# vertical lines have the same starting and ending x positions
# starting y and ending y positions lead from the bottom of the border to the top of the border
outputs.lines << [x - delta, state.grid_border[1], x - delta, state.grid_border[1] + state.grid_border[2], 150, 150, 150] # sets definition of vertical line and outputs it
end
end
temp = 0
# Calculates the positions and outputs the y grid lines in the color gray.
state.gridY.map do # perform an action on all elements of the gridY collection
|y|
temp += 1 # increment temp
# if y's value is greater than (or equal to) the y value of the border's bottom side
# and less than (or equal to) the y value of the border's top side
if y >= state.centerY - (state.grid_border[3] / 2) && y <= state.centerY + (state.grid_border[3] / 2)
delta = state.centerY - 393
# horizontal lines have the same starting and ending y positions
# starting x and ending x positions lead from the left side of the border to the right side of the border
outputs.lines << [state.grid_border[0], y - delta, state.grid_border[0] + state.grid_border[3], y - delta, 150, 150, 150] # sets definition of horizontal line and outputs it
end
end
# Sets values and outputs sprites for the filled_squares collection.
state.filled_squares.map do # perform an action on every element of the filled_squares collection
|x, y, w, h, sprite|
# if x's value is greater than (or equal to) the x value of 17 pixels to the left of the border's left side
# and less than (or equal to) the x value of the border's right side
# and y's value is greater than (or equal to) the y value of the border's bottom side
# and less than (or equal to) the y value of 25 pixels above the border's top side
# NOTE: The allowance of 17 pixels and 25 pixels is due to the fact that a grid box may be slightly cut off or
# not entirely visible in the grid's view (until it is moved using "W", "A", "S", "D")
if x >= state.centerX - (state.grid_border[2] / 2) - 17 && x <= state.centerX + (state.grid_border[2] / 2) &&
y >= state.centerY - (state.grid_border[3] / 2) && y <= state.centerY + (state.grid_border[3] / 2) + 25
# calculations done to place sprites in grid spaces that are meant to filled in
# mess around with the x and y values and see how the sprite placement changes
outputs.sprites << [x - state.centerX + 630, y - state.centerY + 360, w, h, sprite]
end
end
# outputs a white solid along the left side of the grid (change the color and you'll be able to see it against the white background)
# state.increment subtracted in x parameter because solid's position is denoted by bottom left corner
# state.increment subtracted in y parameter to avoid covering the title label
outputs.primitives << [state.grid_border[0] - state.increment,
state.grid_border[1] - state.increment, state.increment, state.grid_border[3] + (state.increment * 2),
255, 255, 255].solid
# outputs a white solid along the right side of the grid
# state.increment subtracted from y parameter to avoid covering title label
outputs.primitives << [state.grid_border[0] + state.grid_border[2],
state.grid_border[1] - state.increment, state.increment, state.grid_border[3] + (state.increment * 2),
255, 255, 255].solid
# outputs a white solid along the bottom of the grid
# state.increment subtracted from y parameter to avoid covering last row of grid boxes
outputs.primitives << [state.grid_border[0] - state.increment, state.grid_border[1] - state.increment,
state.grid_border[2] + (2 * state.increment), state.increment, 255, 255, 255].solid
# outputs a white solid along the top of the grid
outputs.primitives << [state.grid_border[0] - state.increment, state.grid_border[1] + state.grid_border[3],
state.grid_border[2] + (2 * state.increment), state.increment, 255, 255, 255].solid
end
# Outputs title and current tile pattern
def print_title
outputs.labels << [640, 700, 'Mouse to Place Tile, WASD to Move Around', 7, 1] # title label
outputs.lines << horizontal_separator(660, 0, 1280) # outputs horizontal separator
outputs.labels << [1050, 500, 'Current:', 3, 1] # outputs Current label
outputs.sprites << [1110, 474, state.tileSize / 2, state.tileSize / 2, 'sprites/image' + state.tileSelected.to_s + ".png"] # outputs sprite of current tile pattern using images in sprites folder; output is half the size of a tile
end
# Sets the starting position, ending position, and color for the horizontal separator.
def horizontal_separator y, x, x2
[x, y, x2, y, 150, 150, 150] # definition of separator; horizontal line means same starting/ending y
end
# Checks if the mouse is being clicked or dragged
def check_click
if inputs.keyboard.key_down.r # if the "r" key is pressed down
$dragon.reset
end
if inputs.mouse.down #is mouse up or down?
state.mouse_held = true
if inputs.mouse.position.x < state.grid_border[0] # if mouse's x position is inside the grid's borders
state.tileCords.map do # perform action on all elements of tileCords collection
|x, y, order|
# if mouse's x position is greater than (or equal to) the starting x position of a tile
# and the mouse's x position is also less than (or equal to) the ending x position of that tile,
# and the mouse's y position is greater than (or equal to) the starting y position of that tile,
# and the mouse's y position is also less than (or equal to) the ending y position of that tile,
# (BASICALLY, IF THE MOUSE'S POSITION IS WITHIN THE STARTING AND ENDING POSITIONS OF A TILE)
if inputs.mouse.position.x >= x && inputs.mouse.position.x <= x + state.tileSize &&
inputs.mouse.position.y >= y && inputs.mouse.position.y <= y + state.tileSize
state.tileSelected = order # that tile is selected
end
end
end
elsif inputs.mouse.up # otherwise, if the mouse is in the "up" state
state.mouse_held = false # mouse is not held down or dragged
state.mouse_dragging = false
end
if state.mouse_held && # mouse needs to be down
!inputs.mouse.click && # must not be first click
((inputs.mouse.previous_click.point.x - inputs.mouse.position.x).abs > 15 ||
(inputs.mouse.previous_click.point.y - inputs.mouse.position.y).abs > 15) # Need to move 15 pixels before "drag"
state.mouse_dragging = true
end
# if mouse is clicked inside grid's border, search_lines method is called with click input type
if ((inputs.mouse.click) && (inputs.mouse.click.point.inside_rect? state.grid_border))
search_lines(inputs.mouse.click.point, :click)
# if mouse is dragged inside grid's border, search_lines method is called with drag input type
elsif ((state.mouse_dragging) && (inputs.mouse.position.inside_rect? state.grid_border))
search_lines(inputs.mouse.position, :drag)
end
# Changes grid's position on screen by moving it up, down, left, or right.
# centerX is incremented by speed if the "d" key is pressed and if that sum is less than
# the original left side of the center plus half the grid, minus half the top border of grid.
# MOVES GRID RIGHT (increasing x)
state.centerX += state.speed if inputs.keyboard.key_held.d &&
(state.centerX + state.speed) < state.originalCenter[0] + (state.gridSize / 2) - (state.grid_border[2] / 2)
# centerX is decremented by speed if the "a" key is pressed and if that difference is greater than
# the original left side of the center minus half the grid, plus half the top border of grid.
# MOVES GRID LEFT (decreasing x)
state.centerX -= state.speed if inputs.keyboard.key_held.a &&
(state.centerX - state.speed) > state.originalCenter[0] - (state.gridSize / 2) + (state.grid_border[2] / 2)
# centerY is incremented by speed if the "w" key is pressed and if that sum is less than
# the original bottom of the center plus half the grid, minus half the right border of grid.
# MOVES GRID UP (increasing y)
state.centerY += state.speed if inputs.keyboard.key_held.w &&
(state.centerY + state.speed) < state.originalCenter[1] + (state.gridSize / 2) - (state.grid_border[3] / 2)
# centerY is decremented by speed if the "s" key is pressed and if the difference is greater than
# the original bottom of the center minus half the grid, plus half the right border of grid.
# MOVES GRID DOWN (decreasing y)
state.centerY -= state.speed if inputs.keyboard.key_held.s &&
(state.centerY - state.speed) > state.originalCenter[1] - (state.gridSize / 2) + (state.grid_border[3] / 2)
end
# Performs calculations on the gridX and gridY collections, and sets values.
# Sets the definition of a grid box, including the image that it is filled with.
def search_lines (point, input_type)
point.x += state.centerX - 630 # increments x and y
point.y += state.centerY - 360
findX = 0
findY = 0
increment = state.gridSize / state.lineQuantity # divides grid by number of separators
state.gridX.map do # perform an action on every element of collection
|x|
# findX increments x by 10 if point.x is less than that sum and findX is currently 0
findX = x + 10 if point.x < (x + 10) && findX == 0
end
state.gridY.map do
|y|
# findY is set to y if point.y is less than that value and findY is currently 0
findY = y if point.y < (y) && findY == 0
end
# position of a box is denoted by bottom left corner, which is why the increment is being subtracted
grid_box = [findX - (increment.ceil), findY - (increment.ceil), increment.ceil, increment.ceil,
"sprites/image" + state.tileSelected.to_s + ".png"] # sets sprite definition
if input_type == :click # if user clicks their mouse
if state.filled_squares.include? grid_box # if grid box is already filled in
state.filled_squares.delete grid_box # box is cleared and removed from filled_squares
else
state.filled_squares << grid_box # otherwise, box is filled in and added to filled_squares
end
elsif input_type == :drag # if user drags mouse
unless state.filled_squares.include? grid_box # unless grid box dragged over is already filled in
state.filled_squares << grid_box # box is filled in and added to filled_squares
end
end
end
# Creates a "Clear" button using labels and borders.
def draw_buttons
x, y, w, h = 390, 50, 240, 50
state.clear_button ||= state.new_entity(:button_with_fade)
# x and y positions are set to display "Clear" label in center of the button
# Try changing first two parameters to simply x, y and see what happens to the text placement
state.clear_button.label ||= [x + w.half, y + h.half + 10, "Clear", 0, 1]
state.clear_button.border ||= [x, y, w, h] # definition of button's border
# If the mouse is clicked inside the borders of the clear button
if inputs.mouse.click && inputs.mouse.click.point.inside_rect?(state.clear_button.border)
state.clear_button.clicked_at = inputs.mouse.click.created_at # value is frame of mouse click
state.filled_squares.clear # filled squares collection is emptied (squares are cleared)
inputs.mouse.previous_click = nil # no previous click
end
outputs.labels << state.clear_button.label # outputs clear button
outputs.borders << state.clear_button.border
# When the clear button is clicked, the color of the button changes
# and the transparency changes, as well. If you change the time from
# 0.25.seconds to 1.25.seconds or more, the change will last longer.
if state.clear_button.clicked_at
outputs.solids << [x, y, w, h, 0, 180, 80, 255 * state.clear_button.clicked_at.ease(0.25.seconds, :flip)]
end
end
end
$tile_editor = TileEditor.new
def tick args
$tile_editor.inputs = args.inputs
$tile_editor.grid = args.grid
$tile_editor.args = args
$tile_editor.outputs = args.outputs
$tile_editor.state = args.state
$tile_editor.tick
tick_instructions args, "Roll your own tile editor. CLICK to select a sprite. CLICK in grid to place sprite. WASD to move around."
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----dungeon-crawl---classics-jam---main-rb'>Dungeon Crawl - Classics Jam - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_dungeon_crawl/classics_jam/app/main.rb
class Game
attr_gtk
def tick
defaults
render
input
calc
end
def defaults
player.x ||= 640
player.y ||= 360
player.w ||= 16
player.h ||= 16
player.attacked_at ||= -1
player.angle ||= 0
player.future_player ||= future_player_position 0, 0
player.projectiles ||= []
player.damage ||= 0
state.level ||= create_level level_one_template
end
def render
outputs.sprites << level.walls.map do |w|
w.merge(path: 'sprites/square/gray.png')
end
outputs.sprites << level.spawn_locations.map do |s|
s.merge(path: 'sprites/square/blue.png')
end
outputs.sprites << player.projectiles.map do |p|
p.merge(path: 'sprites/square/blue.png')
end
outputs.sprites << level.enemies.map do |e|
e.merge(path: 'sprites/square/red.png')
end
outputs.sprites << player.merge(path: 'sprites/circle/green.png', angle: player.angle)
outputs.labels << { x: 30, y: 30.from_top, text: "damage: #{player.damage || 0}" }
end
def input
player.angle = inputs.directional_angle || player.angle
if inputs.controller_one.key_down.a || inputs.keyboard.key_down.space
player.attacked_at = state.tick_count
end
end
def calc
calc_player
calc_projectiles
calc_enemies
calc_spawn_locations
end
def calc_player
if player.attacked_at == state.tick_count
player.projectiles << { at: state.tick_count,
x: player.x,
y: player.y,
angle: player.angle,
w: 4,
h: 4 }.center_inside_rect(player)
end
if player.attacked_at.elapsed_time > 5
future_player = future_player_position inputs.left_right * 2, inputs.up_down * 2
future_player_collision = future_collision player, future_player, level.walls
player.x = future_player_collision.x if !future_player_collision.dx_collision
player.y = future_player_collision.y if !future_player_collision.dy_collision
end
end
def calc_projectile_collisions entities
entities.each do |e|
e.damage ||= 0
player.projectiles.each do |p|
if !p.collided && (p.intersect_rect? e)
p.collided = true
e.damage += 1
end
end
end
end
def calc_projectiles
player.projectiles.map! do |p|
dx, dy = p.angle.vector 10
p.merge(x: p.x + dx, y: p.y + dy)
end
calc_projectile_collisions level.walls + level.enemies + level.spawn_locations
player.projectiles.reject! { |p| p.at.elapsed_time > 10000 }
player.projectiles.reject! { |p| p.collided }
level.enemies.reject! { |e| e.damage > e.hp }
level.spawn_locations.reject! { |s| s.damage > s.hp }
end
def calc_enemies
level.enemies.map! do |e|
dx = 0
dx = 1 if e.x < player.x
dx = -1 if e.x > player.x
dy = 0
dy = 1 if e.y < player.y
dy = -1 if e.y > player.y
future_e = future_entity_position dx, dy, e
future_e_collision = future_collision e, future_e, level.enemies + level.walls
e.next_x = e.x
e.next_y = e.y
e.next_x = future_e_collision.x if !future_e_collision.dx_collision
e.next_y = future_e_collision.y if !future_e_collision.dy_collision
e
end
level.enemies.map! do |e|
e.x = e.next_x
e.y = e.next_y
e
end
level.enemies.each do |e|
player.damage += 1 if e.intersect_rect? player
end
end
def calc_spawn_locations
level.spawn_locations.map! do |s|
s.merge(countdown: s.countdown - 1)
end
level.spawn_locations
.find_all { |s| s.countdown.neg? }
.each do |s|
s.countdown = s.rate
s.merge(countdown: s.rate)
new_enemy = create_enemy s
if !(level.enemies.find { |e| e.intersect_rect? new_enemy })
level.enemies << new_enemy
end
end
end
def create_enemy spawn_location
to_cell(spawn_location.ordinal_x, spawn_location.ordinal_y).merge hp: 2
end
def create_level level_template
{
walls: level_template.walls.map { |w| to_cell(w.ordinal_x, w.ordinal_y).merge(w) },
enemies: [],
spawn_locations: level_template.spawn_locations.map { |s| to_cell(s.ordinal_x, s.ordinal_y).merge(s) }
}
end
def level_one_template
{
walls: [{ ordinal_x: 25, ordinal_y: 20},
{ ordinal_x: 25, ordinal_y: 21},
{ ordinal_x: 25, ordinal_y: 22},
{ ordinal_x: 25, ordinal_y: 23}],
spawn_locations: [{ ordinal_x: 10, ordinal_y: 10, rate: 120, countdown: 0, hp: 5 }]
}
end
def player
state.player ||= {}
end
def level
state.level ||= {}
end
def future_collision entity, future_entity, others
dx_collision = others.find { |o| o != entity && (o.intersect_rect? future_entity.dx) }
dy_collision = others.find { |o| o != entity && (o.intersect_rect? future_entity.dy) }
{
dx_collision: dx_collision,
x: future_entity.dx.x,
dy_collision: dy_collision,
y: future_entity.dy.y
}
end
def future_entity_position dx, dy, entity
{
dx: entity.merge(x: entity.x + dx),
dy: entity.merge(y: entity.y + dy),
both: entity.merge(x: entity.x + dx, y: entity.y + dy)
}
end
def future_player_position dx, dy
future_entity_position dx, dy, player
end
def to_cell ordinal_x, ordinal_y
{ x: ordinal_x * 16, y: ordinal_y * 16, w: 16, h: 16 }
end
end
def tick args
$game ||= Game.new
$game.args = args
$game.tick
end
$gtk.reset
$game = nil
</code></pre>
<h3 id='----fighting---special-move-inputs---main-rb'>Fighting - Special Move Inputs - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_fighting/01_special_move_inputs/app/main.rb
def tick args
#tick_instructions args, "Use LEFT and RIGHT arrow keys to move and SPACE to jump."
defaults args
render args
input args
calc args
end
# sets default values and creates empty collections
# initialization only happens in the first frame
def defaults args
fiddle args
args.state.tick_count = args.state.tick_count
args.state.bridge_top = 128
args.state.player.x ||= 0 # initializes player's properties
args.state.player.y ||= args.state.bridge_top
args.state.player.w ||= 64
args.state.player.h ||= 64
args.state.player.dy ||= 0
args.state.player.dx ||= 0
args.state.player.r ||= 0
args.state.game_over_at ||= 0
args.state.animation_time ||=0
args.state.timeleft ||=0
args.state.timeright ||=0
args.state.lastpush ||=0
args.state.inputlist ||= ["j","k","l"]
end
# sets enemy, player, hammer values
def fiddle args
args.state.gravity = -0.5
args.state.player_jump_power = 10 # sets player values
args.state.player_jump_power_duration = 5
args.state.player_max_run_speed = 20
args.state.player_speed_slowdown_rate = 0.9
args.state.player_acceleration = 0.9
end
# outputs objects onto the screen
def render args
if (args.state.player.dx < 0.01) && (args.state.player.dx > -0.01)
args.state.player.dx = 0
end
#move list
(args.layout.rect_group row: 0, col_from_right: 8, drow: 0.3,
merge: { vertical_alignment_enum: 0, size_enum: -2 },
group: [
{ text: "move: WASD" },
{ text: "jump: Space" },
{ text: "attack forwards: J (while on ground" },
{ text: "attack upwards: K (while on groud)" },
{ text: "attack backwards: J (while on ground and holding A)" },
{ text: "attack downwards: K (while in air)" },
{ text: "dash attack: J, K in quick succession." },
{ text: "shield: hold J, K at the same time." },
{ text: "dash backwards: A, A in quick succession." },
]).into args.outputs.labels
# registered moves
args.outputs.labels << { x: 0.to_layout_col,
y: 0.to_layout_row,
text: "input history",
size_enum: -2,
vertical_alignment_enum: 0 }
(args.state.inputlist.take(5)).map do |s|
{ text: s, size_enum: -2, vertical_alignment_enum: 0 }
end.yield_self do |group|
(args.layout.rect_group row: 0.3, col: 0, drow: 0.3, group: group).into args.outputs.labels
end
#sprites
player = [args.state.player.x, args.state.player.y,
args.state.player.w, args.state.player.h,
"sprites/square/white.png",
args.state.player.r]
playershield = [args.state.player.x - 20, args.state.player.y - 10,
args.state.player.w + 20, args.state.player.h + 20,
"sprites/square/blue.png",
args.state.player.r,
0]
playerjab = [args.state.player.x + 32, args.state.player.y,
args.state.player.w, args.state.player.h,
"sprites/isometric/indigo.png",
args.state.player.r,
0]
playerupper = [args.state.player.x, args.state.player.y + 32,
args.state.player.w, args.state.player.h,
"sprites/isometric/indigo.png",
args.state.player.r+90,
0]
if ((args.state.tick_count - args.state.lastpush) <= 15)
if (args.state.inputlist[0] == "<<")
player = [args.state.player.x, args.state.player.y,
args.state.player.w, args.state.player.h,
"sprites/square/yellow.png", args.state.player.r]
end
if (args.state.inputlist[0] == "shield")
player = [args.state.player.x, args.state.player.y,
args.state.player.w, args.state.player.h,
"sprites/square/indigo.png", args.state.player.r]
playershield = [args.state.player.x - 10, args.state.player.y - 10,
args.state.player.w + 20, args.state.player.h + 20,
"sprites/square/blue.png", args.state.player.r, 50]
end
if (args.state.inputlist[0] == "back-attack")
playerjab = [args.state.player.x - 20, args.state.player.y,
args.state.player.w - 10, args.state.player.h,
"sprites/isometric/indigo.png", args.state.player.r, 255]
end
if (args.state.inputlist[0] == "forward-attack")
playerjab = [args.state.player.x + 32, args.state.player.y,
args.state.player.w, args.state.player.h,
"sprites/isometric/indigo.png", args.state.player.r, 255]
end
if (args.state.inputlist[0] == "up-attack")
playerupper = [args.state.player.x, args.state.player.y + 32,
args.state.player.w, args.state.player.h,
"sprites/isometric/indigo.png", args.state.player.r + 90, 255]
end
if (args.state.inputlist[0] == "dair")
playerupper = [args.state.player.x, args.state.player.y - 32,
args.state.player.w, args.state.player.h,
"sprites/isometric/indigo.png", args.state.player.r + 90, 255]
end
if (args.state.inputlist[0] == "dash-attack")
playerupper = [args.state.player.x, args.state.player.y + 32,
args.state.player.w, args.state.player.h,
"sprites/isometric/violet.png", args.state.player.r + 90, 255]
playerjab = [args.state.player.x + 32, args.state.player.y,
args.state.player.w, args.state.player.h,
"sprites/isometric/violet.png", args.state.player.r, 255]
end
end
args.outputs.sprites << playerjab
args.outputs.sprites << playerupper
args.outputs.sprites << player
args.outputs.sprites << playershield
args.outputs.solids << 20.map_with_index do |i| # uses 20 squares to form bridge
[i * 64, args.state.bridge_top - 64, 64, 64]
end
end
# Performs calculations to move objects on the screen
def calc args
# Since velocity is the change in position, the change in x increases by dx. Same with y and dy.
args.state.player.x += args.state.player.dx
args.state.player.y += args.state.player.dy
# Since acceleration is the change in velocity, the change in y (dy) increases every frame
args.state.player.dy += args.state.gravity
# player's y position is either current y position or y position of top of
# bridge, whichever has a greater value
# ensures that the player never goes below the bridge
args.state.player.y = args.state.player.y.greater(args.state.bridge_top)
# player's x position is either the current x position or 0, whichever has a greater value
# ensures that the player doesn't go too far left (out of the screen's scope)
args.state.player.x = args.state.player.x.greater(0)
# player is not falling if it is located on the top of the bridge
args.state.player.falling = false if args.state.player.y == args.state.bridge_top
#args.state.player.rect = [args.state.player.x, args.state.player.y, args.state.player.h, args.state.player.w] # sets definition for player
end
# Resets the player by changing its properties back to the values they had at initialization
def reset_player args
args.state.player.x = 0
args.state.player.y = args.state.bridge_top
args.state.player.dy = 0
args.state.player.dx = 0
args.state.enemy.hammers.clear # empties hammer collection
args.state.enemy.hammer_queue.clear # empties hammer_queue
args.state.game_over_at = args.state.tick_count # game_over_at set to current frame (or passage of time)
end
# Processes input from the user to move the player
def input args
if args.state.inputlist.length > 5
args.state.inputlist.pop
end
should_process_special_move = (args.inputs.keyboard.key_down.j) ||
(args.inputs.keyboard.key_down.k) ||
(args.inputs.keyboard.key_down.a) ||
(args.inputs.keyboard.key_down.d) ||
(args.inputs.controller_one.key_down.y) ||
(args.inputs.controller_one.key_down.x) ||
(args.inputs.controller_one.key_down.left) ||
(args.inputs.controller_one.key_down.right)
if (should_process_special_move)
if (args.inputs.keyboard.key_down.j && args.inputs.keyboard.key_down.k) ||
(args.inputs.controller_one.key_down.x && args.inputs.controller_one.key_down.y)
args.state.inputlist.unshift("shield")
elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y) &&
(args.state.inputlist[0] == "forward-attack") && ((args.state.tick_count - args.state.lastpush) <= 15)
args.state.inputlist.unshift("dash-attack")
args.state.player.dx = 20
elsif (args.inputs.keyboard.key_down.j && args.inputs.keyboard.a) ||
(args.inputs.controller_one.key_down.x && args.inputs.controller_one.key_down.left)
args.state.inputlist.unshift("back-attack")
elsif ( args.inputs.controller_one.key_down.x || args.inputs.keyboard.key_down.j)
args.state.inputlist.unshift("forward-attack")
elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y) &&
(args.state.player.y > 128)
args.state.inputlist.unshift("dair")
elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y)
args.state.inputlist.unshift("up-attack")
elsif (args.inputs.controller_one.key_down.left || args.inputs.keyboard.key_down.a) &&
(args.state.inputlist[0] == "<") &&
((args.state.tick_count - args.state.lastpush) <= 10)
args.state.inputlist.unshift("<<")
args.state.player.dx = -15
elsif (args.inputs.controller_one.key_down.left || args.inputs.keyboard.key_down.a)
args.state.inputlist.unshift("<")
args.state.timeleft = args.state.tick_count
elsif (args.inputs.controller_one.key_down.right || args.inputs.keyboard.key_down.d)
args.state.inputlist.unshift(">")
end
args.state.lastpush = args.state.tick_count
end
if args.inputs.keyboard.space || args.inputs.controller_one.r2 # if the user presses the space bar
args.state.player.jumped_at ||= args.state.tick_count # jumped_at is set to current frame
# if the time that has passed since the jump is less than the player's jump duration and
# the player is not falling
if args.state.player.jumped_at.elapsed_time < args.state.player_jump_power_duration && !args.state.player.falling
args.state.player.dy = args.state.player_jump_power # change in y is set to power of player's jump
end
end
# if the space bar is in the "up" state (or not being pressed down)
if args.inputs.keyboard.key_up.space || args.inputs.controller_one.key_up.r2
args.state.player.jumped_at = nil # jumped_at is empty
args.state.player.falling = true # the player is falling
end
if args.inputs.left # if left key is pressed
if args.state.player.dx < -5
args.state.player.dx = args.state.player.dx
else
args.state.player.dx = -5
end
elsif args.inputs.right # if right key is pressed
if args.state.player.dx > 5
args.state.player.dx = args.state.player.dx
else
args.state.player.dx = 5
end
else
args.state.player.dx *= args.state.player_speed_slowdown_rate # dx is scaled down
end
if ((args.state.player.dx).abs > 5) #&& ((args.state.tick_count - args.state.lastpush) <= 10)
args.state.player.dx *= 0.95
end
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.space ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----lowrez---nokia-3310---main-rb'>Lowrez - Nokia 3310 - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_lowrez/nokia_3310/app/main.rb
require 'app/nokia.rb'
def tick args
# =======================================================================
# ==== HELLO WORLD ======================================================
# =======================================================================
# Steps to get started:
# 1. ~def tick args~ is the entry point for your game.
# 2. There are quite a few code samples below, remove the "##"
# before each line and save the file to see the changes.
# 3. 0, 0 is in bottom left and 83, 47 is in top right corner.
# 4. Be sure to come to the discord channel if you need
# more help: [[http://discord.dragonruby.org]].
# Commenting and uncommenting code:
# - Add a "#" infront of lines to comment out code
# - Remove the "#" infront of lines to comment out code
# Invoke the hello_world subroutine/method
hello_world args # <---- add a "#" to the beginning of the line to stop running this subroutine/method.
# =======================================================================
# ==== HOW TO RENDER A LABEL ============================================
# =======================================================================
# Uncomment the line below to invoke the how_to_render_a_label subroutine/method.
# Note: The method is defined in this file with the signature ~def how_to_render_a_label args~
# Scroll down to the method to see the details.
# Remove the "#" at the beginning of the line below
# how_to_render_a_label args # <---- remove the "#" at the beginning of this line to run the method
# =======================================================================
# ==== HOW TO RENDER A FILLED SQUARE (SOLID) ============================
# =======================================================================
# Remove the "#" at the beginning of the line below
# how_to_render_solids args
# =======================================================================
# ==== HOW TO RENDER AN UNFILLED SQUARE (BORDER) ========================
# =======================================================================
# Remove the "#" at the beginning of the line below
# how_to_render_borders args
# =======================================================================
# ==== HOW TO RENDER A LINE =============================================
# =======================================================================
# Remove the "#" at the beginning of the line below
# how_to_render_lines args
# =======================================================================
# == HOW TO RENDER A SPRITE =============================================
# =======================================================================
# Remove the "#" at the beginning of the line below
# how_to_render_sprites args
# =======================================================================
# ==== HOW TO MOVE A SPRITE BASED OFF OF USER INPUT =====================
# =======================================================================
# Remove the "#" at the beginning of the line below
# how_to_move_a_sprite args
# =======================================================================
# ==== HOW TO ANIMATE A SPRITE (SEPERATE PNGS) ==========================
# =======================================================================
# Remove the "#" at the beginning of the line below
# how_to_animate_a_sprite args
# =======================================================================
# ==== HOW TO ANIMATE A SPRITE (SPRITE SHEET) ===========================
# =======================================================================
# Remove the "#" at the beginning of the line below
# how_to_animate_a_sprite_sheet args
# =======================================================================
# ==== HOW TO DETERMINE COLLISION =============================================
# =======================================================================
# Remove the "#" at the beginning of the line below
# how_to_determine_collision args
# =======================================================================
# ==== HOW TO CREATE BUTTONS ==================================================
# =======================================================================
# Remove the "#" at the beginning of the line below
# how_to_create_buttons args
# ==== The line below renders a debug grid, mouse information, and current tick
# render_debug args
end
# =======================================================================
# ==== HELLO WORLD ======================================================
# =======================================================================
def hello_world args
args.nokia.solids << { x: 0, y: 64, w: 10, h: 10, r: 255 }
args.nokia.labels << {
x: 42,
y: 46,
text: "nokia 3310 jam 3",
size_enum: NOKIA_FONT_SM,
alignment_enum: 1,
r: 0,
g: 0,
b: 0,
a: 255,
font: NOKIA_FONT_PATH
}
args.nokia.sprites << {
x: 42 - 10,
y: 26 - 10,
w: 20,
h: 20,
path: 'sprites/monochrome-ship.png',
a: 255,
angle: args.state.tick_count % 360
}
end
# =======================================================================
# ==== HOW TO RENDER A LABEL ============================================
# =======================================================================
def how_to_render_a_label args
# NOTE: Text is aligned from the TOP LEFT corner
# Render an EXTRA LARGE/XL label (remove the "#" in front of each line below)
args.nokia.labels << { x: 0, y: 46, text: "Hello World",
size_enum: NOKIA_FONT_XL,
r: 0, g: 0, b: 0, a: 255,
font: NOKIA_FONT_PATH }
# Render a LARGE/LG label (remove the "#" in front of each line below)
args.nokia.labels << { x: 0, y: 29, text: "Hello World",
size_enum: NOKIA_FONT_LG,
r: 0, g: 0, b: 0, a: 255,
font: NOKIA_FONT_PATH }
# Render a MEDIUM/MD label (remove the "#" in front of each line below)
args.nokia.labels << { x: 0, y: 16, text: "Hello World",
size_enum: NOKIA_FONT_MD,
r: 0, g: 0, b: 0, a: 255,
font: NOKIA_FONT_PATH }
# Render a SMALL/SM label (remove the "#" in front of each line below)
args.nokia.labels << { x: 0, y: 7, text: "Hello World",
size_enum: NOKIA_FONT_SM,
r: 0, g: 0, b: 0, a: 255,
font: NOKIA_FONT_PATH }
# You are provided args.nokia.default_label which returns a Hash that you
# can ~merge~ properties with
# Example 1
args.nokia.labels << args.nokia
.default_label
.merge(text: "Default")
# Example 2
args.nokia.labels << args.nokia
.default_label
.merge(x: 31,
text: "Default")
end
# =============================================================================
# ==== HOW TO RENDER FILLED SQUARES (SOLIDS) ==================================
# =============================================================================
def how_to_render_solids args
# Render a square at 0, 0 with a width and height of 1
args.nokia.solids << { x: 0, y: 0, w: 1, h: 1 }
# Render a square at 1, 1 with a width and height of 2
args.nokia.solids << { x: 1, y: 1, w: 2, h: 2 }
# Render a square at 3, 3 with a width and height of 3
args.nokia.solids << { x: 3, y: 3, w: 3, h: 3 }
# Render a square at 6, 6 with a width and height of 4
args.nokia.solids << { x: 6, y: 6, w: 4, h: 4 }
end
# =============================================================================
# ==== HOW TO RENDER UNFILLED SQUARES (BORDERS) ===============================
# =============================================================================
def how_to_render_borders args
# Render a square at 0, 0 with a width and height of 3
args.nokia.borders << { x: 0, y: 0, w: 3, h: 3, a: 255 }
# Render a square at 3, 3 with a width and height of 3
args.nokia.borders << { x: 3, y: 3, w: 4, h: 4, a: 255 }
# Render a square at 5, 5 with a width and height of 4
args.nokia.borders << { x: 7, y: 7, w: 5, h: 5, a: 255 }
end
# =============================================================================
# ==== HOW TO RENDER A LINE ===================================================
# =============================================================================
def how_to_render_lines args
# Render a horizontal line at the bottom
args.nokia.lines << { x: 0, y: 0, x2: 83, y2: 0 }
# Render a vertical line at the left
args.nokia.lines << { x: 0, y: 0, x2: 0, y2: 47 }
# Render a diagonal line starting from the bottom left and going to the top right
args.nokia.lines << { x: 0, y: 0, x2: 83, y2: 47 }
end
# =============================================================================
# == HOW TO RENDER A SPRITE ===================================================
# =============================================================================
def how_to_render_sprites args
# Loop 10 times and create 10 sprites in 10 positions
# Render a sprite at the bottom left with a width and height of 5 and a path of 'sprites/monochrome-ship.png'
10.times do |i|
args.nokia.sprites << {
x: i * 8.4,
y: i * 4.8,
w: 5,
h: 5,
path: 'sprites/monochrome-ship.png'
}
end
# Given an array of positions create sprites
positions = [
{ x: 20, y: 32 },
{ x: 45, y: 15 },
{ x: 72, y: 23 },
]
positions.each do |position|
# use Ruby's ~Hash#merge~ function to create a sprite
args.nokia.sprites << position.merge(path: 'sprites/monochrome-ship.png',
w: 5,
h: 5)
end
end
# =============================================================================
# ==== HOW TO ANIMATE A SPRITE (SEPERATE PNGS) ==========================
# =============================================================================
def how_to_animate_a_sprite args
# STEP 1: Define when you want the animation to start. The animation in this case will start in 3 seconds
start_animation_on_tick = 180
# STEP 2: Get the frame_index given the start tick.
sprite_index = start_animation_on_tick.frame_index count: 7, # how many sprites?
hold_for: 8, # how long to hold each sprite?
repeat: true # should it repeat?
# STEP 3: frame_index will return nil if the frame hasn't arrived yet
if sprite_index
# if the sprite_index is populated, use it to determine the sprite path and render it
sprite_path = "sprites/explosion-#{sprite_index}.png"
args.nokia.sprites << { x: 42 - 16,
y: 47 - 32,
w: 32,
h: 32,
path: sprite_path }
else
# if the sprite_index is nil, render a countdown instead
countdown_in_seconds = ((start_animation_on_tick - args.state.tick_count) / 60).round(1)
args.nokia.labels << args.nokia
.default_label
.merge(x: 0,
y: 18,
text: "Count Down: #{countdown_in_seconds.to_sf}",
alignment_enum: 0)
end
# render the current tick and the resolved sprite index
args.nokia.labels << args.nokia
.default_label
.merge(x: 0,
y: 11,
text: "Tick: #{args.state.tick_count}")
args.nokia.labels << args.nokia
.default_label
.merge(x: 0,
y: 5,
text: "sprite_index: #{sprite_index}")
end
# =============================================================================
# ==== HOW TO ANIMATE A SPRITE (SPRITE SHEET) =================================
# =============================================================================
def how_to_animate_a_sprite_sheet args
# STEP 1: Define when you want the animation to start. The animation in this case will start in 3 seconds
start_animation_on_tick = 180
# STEP 2: Get the frame_index given the start tick.
sprite_index = start_animation_on_tick.frame_index count: 7, # how many sprites?
hold_for: 8, # how long to hold each sprite?
repeat: true # should it repeat?
# STEP 3: frame_index will return nil if the frame hasn't arrived yet
if sprite_index
# if the sprite_index is populated, use it to determine the source rectangle and render it
args.nokia.sprites << {
x: 42 - 16,
y: 47 - 32,
w: 32,
h: 32,
path: "sprites/explosion-sheet.png",
source_x: 32 * sprite_index,
source_y: 0,
source_w: 32,
source_h: 32
}
else
# if the sprite_index is nil, render a countdown instead
countdown_in_seconds = ((start_animation_on_tick - args.state.tick_count) / 60).round(1)
args.nokia.labels << args.nokia
.default_label
.merge(x: 0,
y: 18,
text: "Count Down: #{countdown_in_seconds.to_sf}",
alignment_enum: 0)
end
# render the current tick and the resolved sprite index
args.nokia.labels << args.nokia
.default_label
.merge(x: 0,
y: 11,
text: "tick: #{args.state.tick_count}")
args.nokia.labels << args.nokia
.default_label
.merge(x: 0,
y: 5,
text: "sprite_index: #{sprite_index}")
end
# =============================================================================
# ==== HOW TO STORE STATE, ACCEPT INPUT, AND RENDER SPRITE BASED OFF OF STATE =
# =============================================================================
def how_to_move_a_sprite args
args.nokia.labels << args.nokia
.default_label
.merge(x: 42,
y: 46, text: "Use Arrow Keys",
alignment_enum: 1)
args.nokia.labels << args.nokia
.default_label
.merge(x: 42,
y: 41, text: "Or WASD",
alignment_enum: 1)
args.nokia.labels << args.nokia
.default_label
.merge(x: 42,
y: 36, text: "Or Click",
alignment_enum: 1)
# set the initial values for x and y using ||= ("or equal operator")
args.state.ship.x ||= 0
args.state.ship.y ||= 0
# if a mouse click occurs, update the ship's x and y to be the location of the click
if args.nokia.mouse_click
args.state.ship.x = args.nokia.mouse_click.x
args.state.ship.y = args.nokia.mouse_click.y
end
# if a or left arrow is pressed/held, decrement the ships x position
if args.nokia.keyboard.left
args.state.ship.x -= 1
end
# if d or right arrow is pressed/held, increment the ships x position
if args.nokia.keyboard.right
args.state.ship.x += 1
end
# if s or down arrow is pressed/held, decrement the ships y position
if args.nokia.keyboard.down
args.state.ship.y -= 1
end
# if w or up arrow is pressed/held, increment the ships y position
if args.nokia.keyboard.up
args.state.ship.y += 1
end
# render the sprite to the screen using the position stored in args.state.ship
args.nokia.sprites << {
x: args.state.ship.x,
y: args.state.ship.y,
w: 5,
h: 5,
path: 'sprites/monochrome-ship.png',
# parameters beyond this point are optional
angle: 0, # Note: rotation angle is denoted in degrees NOT radians
r: 255,
g: 255,
b: 255,
a: 255
}
end
# =======================================================================
# ==== HOW TO DETERMINE COLLISION =======================================
# =======================================================================
def how_to_determine_collision args
# Render the instructions
args.nokia.labels << args.nokia
.default_label
.merge(x: 42,
y: 46, text: "Click Anywhere",
alignment_enum: 1)
# if a mouse click occurs:
# - set ship_one if it isn't set
# - set ship_two if it isn't set
# - otherwise reset ship one and ship two
if args.nokia.mouse_click
# is ship_one set?
if !args.state.ship_one
args.state.ship_one = { x: args.nokia.mouse_click.x - 5,
y: args.nokia.mouse_click.y - 5,
w: 10,
h: 10 }
# is ship_one set?
elsif !args.state.ship_two
args.state.ship_two = { x: args.nokia.mouse_click.x - 5,
y: args.nokia.mouse_click.y - 5,
w: 10,
h: 10 }
# should we reset?
else
args.state.ship_one = nil
args.state.ship_two = nil
end
end
# render ship one if it's set
if args.state.ship_one
# use Ruby's .merge method which is available on ~Hash~ to set the sprite and alpha
# render ship one
args.nokia.sprites << args.state.ship_one.merge(path: 'sprites/monochrome-ship.png')
end
if args.state.ship_two
# use Ruby's .merge method which is available on ~Hash~ to set the sprite and alpha
# render ship two
args.nokia.sprites << args.state.ship_two.merge(path: 'sprites/monochrome-ship.png')
end
# if both ship one and ship two are set, then determine collision
if args.state.ship_one && args.state.ship_two
# collision is determined using the intersect_rect? method
if args.state.ship_one.intersect_rect? args.state.ship_two
# if collision occurred, render the words collision!
args.nokia.labels << args.nokia
.default_label
.merge(x: 42,
y: 5,
text: "Collision!",
alignment_enum: 1)
else
# if collision occurred, render the words no collision.
args.nokia.labels << args.nokia
.default_label
.merge(x: 42,
y: 5,
text: "No Collision.",
alignment_enum: 1)
end
else
# if both ship one and ship two aren't set, then render --
args.nokia.labels << args.nokia
.default_label
.merge(x: 42,
y: 6,
text: "--",
alignment_enum: 1)
end
end
# =============================================================================
# ==== HOW TO CREATE BUTTONS ==================================================
# =============================================================================
def how_to_create_buttons args
# Define a button style
args.state.button_style = { w: 82, h: 10, }
# Render instructions
args.state.button_message ||= "Press a Button!"
args.nokia.labels << args.nokia
.default_label
.merge(x: 42,
y: 82,
text: args.state.button_message,
alignment_enum: 1)
# Creates button one using a border and a label
args.state.button_one_border = args.state.button_style.merge( x: 1, y: 32)
args.nokia.borders << args.state.button_one_border
args.nokia.labels << args.nokia
.default_label
.merge(x: args.state.button_one_border.x + 2,
y: args.state.button_one_border.y + NOKIA_FONT_SM_HEIGHT + 2,
text: "Button One")
# Creates button two using a border and a label
args.state.button_two_border = args.state.button_style.merge( x: 1, y: 20)
args.nokia.borders << args.state.button_two_border
args.nokia.labels << args.nokia
.default_label
.merge(x: args.state.button_two_border.x + 2,
y: args.state.button_two_border.y + NOKIA_FONT_SM_HEIGHT + 2,
text: "Button Two")
# Initialize the state variable that tracks which button was clicked to "" (empty stringI
args.state.last_button_clicked ||= "--"
# If a click occurs, check to see if either button one, or button two was clicked
# using the inside_rect? method of the mouse
# set args.state.last_button_clicked accordingly
if args.nokia.mouse_click
if args.nokia.mouse_click.inside_rect? args.state.button_one_border
args.state.last_button_clicked = "One Clicked!"
elsif args.nokia.mouse_click.inside_rect? args.state.button_two_border
args.state.last_button_clicked = "Two Clicked!"
else
args.state.last_button_clicked = "--"
end
end
# Render the current value of args.state.last_button_clicked
args.nokia.labels << args.nokia
.default_label
.merge(x: 42,
y: 5,
text: args.state.last_button_clicked,
alignment_enum: 1)
end
def render_debug args
if !args.state.grid_rendered
(NOKIA_HEIGHT + 1).map_with_index do |i|
args.outputs.static_debug << {
x: NOKIA_X_OFFSET,
y: NOKIA_Y_OFFSET + (i * NOKIA_ZOOM),
x2: NOKIA_X_OFFSET + NOKIA_ZOOMED_WIDTH,
y2: NOKIA_Y_OFFSET + (i * NOKIA_ZOOM),
r: 128,
g: 128,
b: 128,
a: 80
}.line
end
(NOKIA_WIDTH + 1).map_with_index do |i|
args.outputs.static_debug << {
x: NOKIA_X_OFFSET + (i * NOKIA_ZOOM),
y: NOKIA_Y_OFFSET,
x2: NOKIA_X_OFFSET + (i * NOKIA_ZOOM),
y2: NOKIA_Y_OFFSET + NOKIA_ZOOMED_HEIGHT,
r: 128,
g: 128,
b: 128,
a: 80
}.line
end
end
args.state.grid_rendered = true
args.state.last_click ||= 0
args.state.last_up ||= 0
args.state.last_click = args.state.tick_count if args.nokia.mouse_down # you can also use args.nokia.click
args.state.last_up = args.state.tick_count if args.nokia.mouse_up
args.state.label_style = { size_enum: -1.5 }
args.state.watch_list = [
"args.state.tick_count is: #{args.state.tick_count}",
"args.nokia.mouse_position is: #{args.nokia.mouse_position.x}, #{args.nokia.mouse_position.y}",
"args.nokia.mouse_down tick: #{args.state.last_click || "never"}",
"args.nokia.mouse_up tick: #{args.state.last_up || "false"}",
]
args.outputs.debug << args.state
.watch_list
.map_with_index do |text, i|
{
x: 5,
y: 720 - (i * 18),
text: text,
size_enum: -1.5,
r: 255, g: 255, b: 255
}.label!
end
args.outputs.debug << {
x: 640,
y: 25,
text: "INFO: dev mode is currently enabled. Comment out the invocation of ~render_debug~ within the ~tick~ method to hide the debug layer.",
size_enum: -0.5,
alignment_enum: 1,
r: 255, g: 255, b: 255
}.label!
end
def snake_demo args
end
$gtk.reset
</code></pre>
<h3 id='----lowrez---nokia-3310---nokia-rb'>Lowrez - Nokia 3310 - nokia.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_lowrez/nokia_3310/app/nokia.rb
# Emulation of a 64x64 canvas. Don't change this file unless you know what you're doing :-)
# Head over to main.rb and study the code there.
NOKIA_WIDTH = 84
NOKIA_HEIGHT = 48
NOKIA_ZOOM = 12
NOKIA_ZOOMED_WIDTH = NOKIA_WIDTH * NOKIA_ZOOM
NOKIA_ZOOMED_HEIGHT = NOKIA_HEIGHT * NOKIA_ZOOM
NOKIA_X_OFFSET = (1280 - NOKIA_ZOOMED_WIDTH).half
NOKIA_Y_OFFSET = ( 720 - NOKIA_ZOOMED_HEIGHT).half
NOKIA_FONT_XL = -1
NOKIA_FONT_XL_HEIGHT = 20
NOKIA_FONT_LG = -3.5
NOKIA_FONT_LG_HEIGHT = 15
NOKIA_FONT_MD = -6
NOKIA_FONT_MD_HEIGHT = 10
NOKIA_FONT_SM = -8.5
NOKIA_FONT_SM_HEIGHT = 5
NOKIA_FONT_PATH = 'fonts/lowrez.ttf'
class NokiaOutputs
attr_accessor :width, :height
def initialize args
@args = args
end
def outputs_nokia
return @args.outputs if @args.state.tick_count <= 0
return @args.outputs[:nokia]
end
def solids
outputs_nokia.solids
end
def borders
outputs_nokia.borders
end
def sprites
outputs_nokia.sprites
end
def labels
outputs_nokia.labels
end
def default_label
{
x: 0,
y: 63,
text: "",
size_enum: NOKIA_FONT_SM,
alignment_enum: 0,
r: 0,
g: 0,
b: 0,
a: 255,
font: NOKIA_FONT_PATH
}
end
def lines
outputs_nokia.lines
end
def primitives
outputs_nokia.primitives
end
def click
return nil unless @args.inputs.mouse.click
mouse
end
def mouse_click
click
end
def mouse_down
@args.inputs.mouse.down
end
def mouse_up
@args.inputs.mouse.up
end
def mouse
[
((@args.inputs.mouse.x - NOKIA_X_OFFSET).idiv(NOKIA_ZOOM)),
((@args.inputs.mouse.y - NOKIA_Y_OFFSET).idiv(NOKIA_ZOOM))
]
end
def mouse_position
mouse
end
def keyboard
@args.inputs.keyboard
end
end
class GTK::Args
def init_nokia
return if @nokia
@nokia = NokiaOutputs.new self
end
def nokia
@nokia
end
end
module GTK
class Runtime
alias_method :__original_tick_core__, :tick_core unless Runtime.instance_methods.include?(:__original_tick_core__)
def tick_core
@args.init_nokia
__original_tick_core__
return if @args.state.tick_count <= 0
@args.render_target(:nokia)
.labels
.each do |l|
l.y += 1
if (l.a || 255) > 128
l.r = 67
l.g = 82
l.b = 61
l.a = 255
else
l.a = 0
end
end
@args.render_target(:nokia)
.sprites
.each do |s|
if (s.a || 255) > 128
s.a = 255
else
s.a = 0
end
end
@args.render_target(:nokia)
.solids
.each do |s|
if (s.a || 255) > 128
s.r = 67
s.g = 82
s.b = 61
s.a = 255
else
s.a = 0
end
end
@args.render_target(:nokia)
.borders
.each do |s|
if (s.a || 255) > 128
s.r = 67
s.g = 82
s.b = 61
s.a = 255
else
s.a = 0
end
end
@args.render_target(:nokia)
.lines
.each do |l|
l.y += 1
l.y2 += 1
l.y2 += 1 if l.y1 != l.y2
l.x2 += 1 if l.x1 != l.x2
if (l.a || 255) > 128
l.r = 67
l.g = 82
l.b = 61
l.a = 255
else
l.a = 0
end
end
@args.outputs.borders << {
x: NOKIA_X_OFFSET - 1,
y: NOKIA_Y_OFFSET - 1,
w: NOKIA_ZOOMED_WIDTH + 2,
h: NOKIA_ZOOMED_HEIGHT + 2,
r: 128, g: 128, b: 128
}
@args.outputs.background_color = [199, 240, 216]
@args.outputs.solids << [0, 0, NOKIA_X_OFFSET, 720]
@args.outputs.solids << [0, 0, 1280, NOKIA_Y_OFFSET]
@args.outputs.solids << [NOKIA_X_OFFSET + NOKIA_ZOOMED_WIDTH, 0, NOKIA_X_OFFSET, 720]
@args.outputs.solids << [0, NOKIA_Y_OFFSET.from_top, 1280, NOKIA_Y_OFFSET]
@args.outputs
.sprites << { x: NOKIA_X_OFFSET,
y: NOKIA_Y_OFFSET,
w: NOKIA_ZOOMED_WIDTH,
h: NOKIA_ZOOMED_HEIGHT,
source_x: 0,
source_y: 0,
source_w: NOKIA_WIDTH,
source_h: NOKIA_HEIGHT,
path: :nokia }
if [email protected]_rendered
(NOKIA_HEIGHT + 1).map_with_index do |i|
@args.outputs.static_lines << {
x: NOKIA_X_OFFSET,
y: NOKIA_Y_OFFSET + (i * NOKIA_ZOOM),
x2: NOKIA_X_OFFSET + NOKIA_ZOOMED_WIDTH,
y2: NOKIA_Y_OFFSET + (i * NOKIA_ZOOM),
r: 199,
g: 240,
b: 216,
a: 100
}.line!
end
(NOKIA_WIDTH + 1).map_with_index do |i|
@args.outputs.static_lines << {
x: NOKIA_X_OFFSET + (i * NOKIA_ZOOM),
y: NOKIA_Y_OFFSET,
x2: NOKIA_X_OFFSET + (i * NOKIA_ZOOM),
y2: NOKIA_Y_OFFSET + NOKIA_ZOOMED_HEIGHT,
r: 199,
g: 240,
b: 216,
a: 100
}.line!
end
@args.state.overlay_rendered = true
end
end
end
end
</code></pre>
<h3 id='----lowrez---resolution-64x64---lowrez-rb'>Lowrez - Resolution 64x64 - lowrez.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_lowrez/resolution_64x64/app/lowrez.rb
# Emulation of a 64x64 canvas. Don't change this file unless you know what you're doing :-)
# Head over to main.rb and study the code there.
LOWREZ_SIZE = 64
LOWREZ_ZOOM = 10
LOWREZ_ZOOMED_SIZE = LOWREZ_SIZE * LOWREZ_ZOOM
LOWREZ_X_OFFSET = (1280 - LOWREZ_ZOOMED_SIZE).half
LOWREZ_Y_OFFSET = ( 720 - LOWREZ_ZOOMED_SIZE).half
LOWREZ_FONT_XL = -1
LOWREZ_FONT_XL_HEIGHT = 20
LOWREZ_FONT_LG = -3.5
LOWREZ_FONT_LG_HEIGHT = 15
LOWREZ_FONT_MD = -6
LOWREZ_FONT_MD_HEIGHT = 10
LOWREZ_FONT_SM = -8.5
LOWREZ_FONT_SM_HEIGHT = 5
LOWREZ_FONT_PATH = 'fonts/lowrez.ttf'
class LowrezOutputs
attr_accessor :width, :height
def initialize args
@args = args
@background_color ||= [0, 0, 0]
@args.outputs.background_color = @background_color
end
def background_color
@background_color ||= [0, 0, 0]
end
def background_color= opts
@background_color = opts
@args.outputs.background_color = @background_color
outputs_lowrez.solids << [0, 0, LOWREZ_SIZE, LOWREZ_SIZE, @background_color]
end
def outputs_lowrez
return @args.outputs if @args.state.tick_count <= 0
return @args.outputs[:lowrez]
end
def solids
outputs_lowrez.solids
end
def borders
outputs_lowrez.borders
end
def sprites
outputs_lowrez.sprites
end
def labels
outputs_lowrez.labels
end
def default_label
{
x: 0,
y: 63,
text: "",
size_enum: LOWREZ_FONT_SM,
alignment_enum: 0,
r: 0,
g: 0,
b: 0,
a: 255,
font: LOWREZ_FONT_PATH
}
end
def lines
outputs_lowrez.lines
end
def primitives
outputs_lowrez.primitives
end
def click
return nil unless @args.inputs.mouse.click
mouse
end
def mouse_click
click
end
def mouse_down
@args.inputs.mouse.down
end
def mouse_up
@args.inputs.mouse.up
end
def mouse
[
((@args.inputs.mouse.x - LOWREZ_X_OFFSET).idiv(LOWREZ_ZOOM)),
((@args.inputs.mouse.y - LOWREZ_Y_OFFSET).idiv(LOWREZ_ZOOM))
]
end
def mouse_position
mouse
end
def keyboard
@args.inputs.keyboard
end
end
class GTK::Args
def init_lowrez
return if @lowrez
@lowrez = LowrezOutputs.new self
end
def lowrez
@lowrez
end
end
module GTK
class Runtime
alias_method :__original_tick_core__, :tick_core unless Runtime.instance_methods.include?(:__original_tick_core__)
def tick_core
@args.init_lowrez
__original_tick_core__
return if @args.state.tick_count <= 0
@args.render_target(:lowrez)
.labels
.each do |l|
l.y += 1
end
@args.render_target(:lowrez)
.lines
.each do |l|
l.y += 1
l.y2 += 1
l.y2 += 1 if l.y1 != l.y2
l.x2 += 1 if l.x1 != l.x2
end
@args.outputs
.sprites << { x: 320,
y: 40,
w: 640,
h: 640,
source_x: 0,
source_y: 0,
source_w: 64,
source_h: 64,
path: :lowrez }
end
end
end
</code></pre>
<h3 id='----lowrez---resolution-64x64---main-rb'>Lowrez - Resolution 64x64 - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_lowrez/resolution_64x64/app/main.rb
require 'app/lowrez.rb'
def tick args
# How to set the background color
args.lowrez.background_color = [255, 255, 255]
# ==== HELLO WORLD ======================================================
# Steps to get started:
# 1. ~def tick args~ is the entry point for your game.
# 2. There are quite a few code samples below, remove the "##"
# before each line and save the file to see the changes.
# 3. 0, 0 is in bottom left and 63, 63 is in top right corner.
# 4. Be sure to come to the discord channel if you need
# more help: [[http://discord.dragonruby.org]].
# Commenting and uncommenting code:
# - Add a "#" infront of lines to comment out code
# - Remove the "#" infront of lines to comment out code
# Invoke the hello_world subroutine/method
hello_world args # <---- add a "#" to the beginning of the line to stop running this subroutine/method.
# =======================================================================
# ==== HOW TO RENDER A LABEL ============================================
# Uncomment the line below to invoke the how_to_render_a_label subroutine/method.
# Note: The method is defined in this file with the signature ~def how_to_render_a_label args~
# Scroll down to the method to see the details.
# Remove the "#" at the beginning of the line below
# how_to_render_a_label args # <---- remove the "#" at the begging of this line to run the method
# =======================================================================
# ==== HOW TO RENDER A FILLED SQUARE (SOLID) ============================
# Remove the "#" at the beginning of the line below
# how_to_render_solids args
# =======================================================================
# ==== HOW TO RENDER AN UNFILLED SQUARE (BORDER) ========================
# Remove the "#" at the beginning of the line below
# how_to_render_borders args
# =======================================================================
# ==== HOW TO RENDER A LINE =============================================
# Remove the "#" at the beginning of the line below
# how_to_render_lines args
# =======================================================================
# == HOW TO RENDER A SPRITE =============================================
# Remove the "#" at the beginning of the line below
# how_to_render_sprites args
# =======================================================================
# ==== HOW TO MOVE A SPRITE BASED OFF OF USER INPUT =====================
# Remove the "#" at the beginning of the line below
# how_to_move_a_sprite args
# =======================================================================
# ==== HOW TO ANIMATE A SPRITE (SEPERATE PNGS) ==========================
# Remove the "#" at the beginning of the line below
# how_to_animate_a_sprite args
# =======================================================================
# ==== HOW TO ANIMATE A SPRITE (SPRITE SHEET) ===========================
# Remove the "#" at the beginning of the line below
# how_to_animate_a_sprite_sheet args
# =======================================================================
# ==== HOW TO DETERMINE COLLISION =============================================
# Remove the "#" at the beginning of the line below
# how_to_determine_collision args
# =======================================================================
# ==== HOW TO CREATE BUTTONS ==================================================
# Remove the "#" at the beginning of the line below
# how_to_create_buttons args
# =======================================================================
# ==== The line below renders a debug grid, mouse information, and current tick
render_debug args
end
def hello_world args
args.lowrez.solids << { x: 0, y: 64, w: 10, h: 10, r: 255 }
args.lowrez.labels << {
x: 32,
y: 63,
text: "lowrezjam 2020",
size_enum: LOWREZ_FONT_SM,
alignment_enum: 1,
r: 0,
g: 0,
b: 0,
a: 255,
font: LOWREZ_FONT_PATH
}
args.lowrez.sprites << {
x: 32 - 10,
y: 32 - 10,
w: 20,
h: 20,
path: 'sprites/lowrez-ship-blue.png',
a: args.state.tick_count % 255,
angle: args.state.tick_count % 360
}
end
# =======================================================================
# ==== HOW TO RENDER A LABEL ============================================
# =======================================================================
def how_to_render_a_label args
# NOTE: Text is aligned from the TOP LEFT corner
# Render an EXTRA LARGE/XL label (remove the "#" in front of each line below)
args.lowrez.labels << { x: 0, y: 57, text: "Hello World",
size_enum: LOWREZ_FONT_XL,
r: 0, g: 0, b: 0, a: 255,
font: LOWREZ_FONT_PATH }
# Render a LARGE/LG label (remove the "#" in front of each line below)
args.lowrez.labels << { x: 0, y: 36, text: "Hello World",
size_enum: LOWREZ_FONT_LG,
r: 0, g: 0, b: 0, a: 255,
font: LOWREZ_FONT_PATH }
# Render a MEDIUM/MD label (remove the "#" in front of each line below)
args.lowrez.labels << { x: 0, y: 20, text: "Hello World",
size_enum: LOWREZ_FONT_MD,
r: 0, g: 0, b: 0, a: 255,
font: LOWREZ_FONT_PATH }
# Render a SMALL/SM label (remove the "#" in front of each line below)
args.lowrez.labels << { x: 0, y: 9, text: "Hello World",
size_enum: LOWREZ_FONT_SM,
r: 0, g: 0, b: 0, a: 255,
font: LOWREZ_FONT_PATH }
# You are provided args.lowrez.default_label which returns a Hash that you
# can ~merge~ properties with
# Example 1
args.lowrez.labels << args.lowrez
.default_label
.merge(text: "Default")
# Example 2
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 31,
text: "Default",
r: 128,
g: 128,
b: 128)
end
## # =============================================================================
## # ==== HOW TO RENDER FILLED SQUARES (SOLIDS) ==================================
## # =============================================================================
def how_to_render_solids args
# Render a red square at 0, 0 with a width and height of 1
args.lowrez.solids << { x: 0, y: 0, w: 1, h: 1, r: 255, g: 0, b: 0, a: 255 }
# Render a red square at 1, 1 with a width and height of 2
args.lowrez.solids << { x: 1, y: 1, w: 2, h: 2, r: 255, g: 0, b: 0, a: 255 }
# Render a red square at 3, 3 with a width and height of 3
args.lowrez.solids << { x: 3, y: 3, w: 3, h: 3, r: 255, g: 0, b: 0 }
# Render a red square at 6, 6 with a width and height of 4
args.lowrez.solids << { x: 6, y: 6, w: 4, h: 4, r: 255, g: 0, b: 0 }
end
## # =============================================================================
## # ==== HOW TO RENDER UNFILLED SQUARES (BORDERS) ===============================
## # =============================================================================
def how_to_render_borders args
# Render a red square at 0, 0 with a width and height of 3
args.lowrez.borders << { x: 0, y: 0, w: 3, h: 3, r: 255, g: 0, b: 0, a: 255 }
# Render a red square at 3, 3 with a width and height of 3
args.lowrez.borders << { x: 3, y: 3, w: 4, h: 4, r: 255, g: 0, b: 0, a: 255 }
# Render a red square at 5, 5 with a width and height of 4
args.lowrez.borders << { x: 7, y: 7, w: 5, h: 5, r: 255, g: 0, b: 0, a: 255 }
end
## # =============================================================================
## # ==== HOW TO RENDER A LINE ===================================================
## # =============================================================================
def how_to_render_lines args
# Render a horizontal line at the bottom
args.lowrez.lines << { x: 0, y: 0, x2: 63, y2: 0, r: 255 }
# Render a vertical line at the left
args.lowrez.lines << { x: 0, y: 0, x2: 0, y2: 63, r: 255 }
# Render a diagonal line starting from the bottom left and going to the top right
args.lowrez.lines << { x: 0, y: 0, x2: 63, y2: 63, r: 255 }
end
## # =============================================================================
## # == HOW TO RENDER A SPRITE ===================================================
## # =============================================================================
def how_to_render_sprites args
# Loop 10 times and create 10 sprites in 10 positions
# Render a sprite at the bottom left with a width and height of 5 and a path of 'sprites/lowrez-ship-blue.png'
10.times do |i|
args.lowrez.sprites << {
x: i * 5,
y: i * 5,
w: 5,
h: 5,
path: 'sprites/lowrez-ship-blue.png'
}
end
# Given an array of positions create sprites
positions = [
{ x: 10, y: 42 },
{ x: 15, y: 45 },
{ x: 22, y: 33 },
]
positions.each do |position|
# use Ruby's ~Hash#merge~ function to create a sprite
args.lowrez.sprites << position.merge(path: 'sprites/lowrez-ship-red.png',
w: 5,
h: 5)
end
end
## # =============================================================================
## # ==== HOW TO ANIMATE A SPRITE (SEPERATE PNGS) ==========================
## # =============================================================================
def how_to_animate_a_sprite args
# STEP 1: Define when you want the animation to start. The animation in this case will start in 3 seconds
start_animation_on_tick = 180
# STEP 2: Get the frame_index given the start tick.
sprite_index = start_animation_on_tick.frame_index count: 7, # how many sprites?
hold_for: 4, # how long to hold each sprite?
repeat: true # should it repeat?
# STEP 3: frame_index will return nil if the frame hasn't arrived yet
if sprite_index
# if the sprite_index is populated, use it to determine the sprite path and render it
sprite_path = "sprites/explosion-#{sprite_index}.png"
args.lowrez.sprites << { x: 0, y: 0, w: 64, h: 64, path: sprite_path }
else
# if the sprite_index is nil, render a countdown instead
countdown_in_seconds = ((start_animation_on_tick - args.state.tick_count) / 60).round(1)
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 32,
y: 32,
text: "Count Down: #{countdown_in_seconds}",
alignment_enum: 1)
end
# render the current tick and the resolved sprite index
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 0,
y: 11,
text: "Tick: #{args.state.tick_count}")
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 0,
y: 5,
text: "sprite_index: #{sprite_index}")
end
## # =============================================================================
## # ==== HOW TO ANIMATE A SPRITE (SPRITE SHEET) =================================
## # =============================================================================
def how_to_animate_a_sprite_sheet args
# STEP 1: Define when you want the animation to start. The animation in this case will start in 3 seconds
start_animation_on_tick = 180
# STEP 2: Get the frame_index given the start tick.
sprite_index = start_animation_on_tick.frame_index count: 7, # how many sprites?
hold_for: 4, # how long to hold each sprite?
repeat: true # should it repeat?
# STEP 3: frame_index will return nil if the frame hasn't arrived yet
if sprite_index
# if the sprite_index is populated, use it to determine the source rectangle and render it
args.lowrez.sprites << {
x: 0,
y: 0,
w: 64,
h: 64,
path: "sprites/explosion-sheet.png",
source_x: 32 * sprite_index,
source_y: 0,
source_w: 32,
source_h: 32
}
else
# if the sprite_index is nil, render a countdown instead
countdown_in_seconds = ((start_animation_on_tick - args.state.tick_count) / 60).round(1)
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 32,
y: 32,
text: "Count Down: #{countdown_in_seconds}",
alignment_enum: 1)
end
# render the current tick and the resolved sprite index
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 0,
y: 11,
text: "tick: #{args.state.tick_count}")
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 0,
y: 5,
text: "sprite_index: #{sprite_index}")
end
## # =============================================================================
## # ==== HOW TO STORE STATE, ACCEPT INPUT, AND RENDER SPRITE BASED OFF OF STATE =
## # =============================================================================
def how_to_move_a_sprite args
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 32,
y: 62, text: "Use Arrow Keys",
alignment_enum: 1)
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 32,
y: 56, text: "Use WASD",
alignment_enum: 1)
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 32,
y: 50, text: "Or Click",
alignment_enum: 1)
# set the initial values for x and y using ||= ("or equal operator")
args.state.ship.x ||= 0
args.state.ship.y ||= 0
# if a mouse click occurs, update the ship's x and y to be the location of the click
if args.lowrez.mouse_click
args.state.ship.x = args.lowrez.mouse_click.x
args.state.ship.y = args.lowrez.mouse_click.y
end
# if a or left arrow is pressed/held, decrement the ships x position
if args.lowrez.keyboard.left
args.state.ship.x -= 1
end
# if d or right arrow is pressed/held, increment the ships x position
if args.lowrez.keyboard.right
args.state.ship.x += 1
end
# if s or down arrow is pressed/held, decrement the ships y position
if args.lowrez.keyboard.down
args.state.ship.y -= 1
end
# if w or up arrow is pressed/held, increment the ships y position
if args.lowrez.keyboard.up
args.state.ship.y += 1
end
# render the sprite to the screen using the position stored in args.state.ship
args.lowrez.sprites << {
x: args.state.ship.x,
y: args.state.ship.y,
w: 5,
h: 5,
path: 'sprites/lowrez-ship-blue.png',
# parameters beyond this point are optional
angle: 0, # Note: rotation angle is denoted in degrees NOT radians
r: 255,
g: 255,
b: 255,
a: 255
}
end
# =======================================================================
# ==== HOW TO DETERMINE COLLISION =======================================
# =======================================================================
def how_to_determine_collision args
# Render the instructions
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 32,
y: 62, text: "Click Anywhere",
alignment_enum: 1)
# if a mouse click occurs:
# - set ship_one if it isn't set
# - set ship_two if it isn't set
# - otherwise reset ship one and ship two
if args.lowrez.mouse_click
# is ship_one set?
if !args.state.ship_one
args.state.ship_one = { x: args.lowrez.mouse_click.x - 10,
y: args.lowrez.mouse_click.y - 10,
w: 20,
h: 20 }
# is ship_one set?
elsif !args.state.ship_two
args.state.ship_two = { x: args.lowrez.mouse_click.x - 10,
y: args.lowrez.mouse_click.y - 10,
w: 20,
h: 20 }
# should we reset?
else
args.state.ship_one = nil
args.state.ship_two = nil
end
end
# render ship one if it's set
if args.state.ship_one
# use Ruby's .merge method which is available on ~Hash~ to set the sprite and alpha
# render ship one
args.lowrez.sprites << args.state.ship_one.merge(path: 'sprites/lowrez-ship-blue.png', a: 100)
end
if args.state.ship_two
# use Ruby's .merge method which is available on ~Hash~ to set the sprite and alpha
# render ship two
args.lowrez.sprites << args.state.ship_two.merge(path: 'sprites/lowrez-ship-red.png', a: 100)
end
# if both ship one and ship two are set, then determine collision
if args.state.ship_one && args.state.ship_two
# collision is determined using the intersect_rect? method
if args.state.ship_one.intersect_rect? args.state.ship_two
# if collision occurred, render the words collision!
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 31,
y: 5,
text: "Collision!",
alignment_enum: 1)
else
# if collision occurred, render the words no collision.
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 31,
y: 5,
text: "No Collision.",
alignment_enum: 1)
end
else
# if both ship one and ship two aren't set, then render --
args.lowrez.labels << args.lowrez
.default_label
.merge(x: 31,
y: 6,
text: "--",
alignment_enum: 1)
end
end
## # =============================================================================
## # ==== HOW TO CREATE BUTTONS ==================================================
## # =============================================================================
def how_to_create_buttons args
# Define a button style
args.state.button_style = { w: 62, h: 10, r: 80, g: 80, b: 80 }
args.state.label_style = { r: 80, g: 80, b: 80 }
# Render instructions
args.state.button_message ||= "Press a Button!"
args.lowrez.labels << args.lowrez
.default_label
.merge(args.state.label_style)
.merge(x: 32,
y: 62,
text: args.state.button_message,
alignment_enum: 1)
# Creates button one using a border and a label
args.state.button_one_border = args.state.button_style.merge( x: 1, y: 32)
args.lowrez.borders << args.state.button_one_border
args.lowrez.labels << args.lowrez
.default_label
.merge(args.state.label_style)
.merge(x: args.state.button_one_border.x + 2,
y: args.state.button_one_border.y + LOWREZ_FONT_SM_HEIGHT + 2,
text: "Button One")
# Creates button two using a border and a label
args.state.button_two_border = args.state.button_style.merge( x: 1, y: 20)
args.lowrez.borders << args.state.button_two_border
args.lowrez.labels << args.lowrez
.default_label
.merge(args.state.label_style)
.merge(x: args.state.button_two_border.x + 2,
y: args.state.button_two_border.y + LOWREZ_FONT_SM_HEIGHT + 2,
text: "Button Two")
# Initialize the state variable that tracks which button was clicked to "" (empty stringI
args.state.last_button_clicked ||= "--"
# If a click occurs, check to see if either button one, or button two was clicked
# using the inside_rect? method of the mouse
# set args.state.last_button_clicked accordingly
if args.lowrez.mouse_click
if args.lowrez.mouse_click.inside_rect? args.state.button_one_border
args.state.last_button_clicked = "One Clicked!"
elsif args.lowrez.mouse_click.inside_rect? args.state.button_two_border
args.state.last_button_clicked = "Two Clicked!"
else
args.state.last_button_clicked = "--"
end
end
# Render the current value of args.state.last_button_clicked
args.lowrez.labels << args.lowrez
.default_label
.merge(args.state.label_style)
.merge(x: 32,
y: 5,
text: args.state.last_button_clicked,
alignment_enum: 1)
end
def render_debug args
if !args.state.grid_rendered
65.map_with_index do |i|
args.outputs.static_debug << {
x: LOWREZ_X_OFFSET,
y: LOWREZ_Y_OFFSET + (i * 10),
x2: LOWREZ_X_OFFSET + LOWREZ_ZOOMED_SIZE,
y2: LOWREZ_Y_OFFSET + (i * 10),
r: 128,
g: 128,
b: 128,
a: 80
}.line!
args.outputs.static_debug << {
x: LOWREZ_X_OFFSET + (i * 10),
y: LOWREZ_Y_OFFSET,
x2: LOWREZ_X_OFFSET + (i * 10),
y2: LOWREZ_Y_OFFSET + LOWREZ_ZOOMED_SIZE,
r: 128,
g: 128,
b: 128,
a: 80
}.line!
end
end
args.state.grid_rendered = true
args.state.last_click ||= 0
args.state.last_up ||= 0
args.state.last_click = args.state.tick_count if args.lowrez.mouse_down # you can also use args.lowrez.click
args.state.last_up = args.state.tick_count if args.lowrez.mouse_up
args.state.label_style = { size_enum: -1.5 }
args.state.watch_list = [
"args.state.tick_count is: #{args.state.tick_count}",
"args.lowrez.mouse_position is: #{args.lowrez.mouse_position.x}, #{args.lowrez.mouse_position.y}",
"args.lowrez.mouse_down tick: #{args.state.last_click || "never"}",
"args.lowrez.mouse_up tick: #{args.state.last_up || "false"}",
]
args.outputs.debug << args.state
.watch_list
.map_with_index do |text, i|
{
x: 5,
y: 720 - (i * 20),
text: text,
size_enum: -1.5
}.label!
end
args.outputs.debug << {
x: 640,
y: 25,
text: "INFO: dev mode is currently enabled. Comment out the invocation of ~render_debug~ within the ~tick~ method to hide the debug layer.",
size_enum: -0.5,
alignment_enum: 1
}.label!
end
$gtk.reset
</code></pre>
<h3 id='----platformer---clepto-frog---main-rb'>Platformer - Clepto Frog - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_platformer/clepto_frog/app/main.rb
MAP_FILE_PATH = 'app/map.txt'
require 'app/map.rb'
class CleptoFrog
attr_gtk
def render_ending
state.game_over_at ||= state.tick_count
outputs.labels << [640, 700, "Clepto Frog", 4, 1]
if state.tick_count >= (state.game_over_at + 120)
outputs.labels << [640, 620, "\"I... I.... don't believe it.\" - New Guy",
4, 1, 0, 0, 0, 255 * (state.game_over_at + 120).ease(60)]
end
if state.tick_count >= (state.game_over_at + 240)
outputs.labels << [640, 580, "\"He actually stole all the mugs?\" - New Guy",
4, 1, 0, 0, 0, 255 * (state.game_over_at + 240).ease(60)]
end
if state.tick_count >= (state.game_over_at + 360)
outputs.labels << [640, 540, "\"Kind of feel bad STARTING HIM WITH NOTHING again.\" - New Guy",
4, 1, 0, 0, 0, 255 * (state.game_over_at + 360).ease(60)]
end
outputs.sprites << [640 - 50, 360 - 50, 100, 100,
"sprites/square-green.png"]
outputs.labels << [640, 300, "Current Time: #{"%.2f" % state.stuff_time}", 4, 1]
outputs.labels << [640, 270, "Best Time: #{"%.2f" % state.stuff_best_time}", 4, 1]
if state.tick_count >= (state.game_over_at + 550)
restart_game
end
end
def restart_game
state.world = nil
state.x = nil
state.y = nil
state.dx = nil
state.dy = nil
state.stuff_score = 0
state.stuff_time = 0
state.intro_tick_count = nil
defaults
state.game_start_at = state.tick_count
state.scene = :game
state.game_over_at = nil
end
def render_intro
outputs.labels << [640, 700, "Clepto Frog", 4, 1]
if state.tick_count >= 120
outputs.labels << [640, 620, "\"Uh... your office has a pet frog?\" - New Guy",
4, 1, 0, 0, 0, 255 * 120.ease(60)]
end
if state.tick_count >= 240
outputs.labels << [640, 580, "\"Yep! His name is Clepto.\" - Jim",
4, 1, 0, 0, 0, 255 * 240.ease(60)]
end
if state.tick_count >= 360
outputs.labels << [640, 540, "\"Uh...\" - New Guy",
4, 1, 0, 0, 0, 255 * 360.ease(60)]
end
if state.tick_count >= 480
outputs.labels << [640, 500, "\"He steals mugs while we're away...\" - Jim",
4, 1, 0, 0, 0, 255 * 480.ease(60)]
end
if state.tick_count >= 600
outputs.labels << [640, 460, "\"It's not a big deal, we take them back in the morning.\" - Jim",
4, 1, 0, 0, 0, 255 * 600.ease(60)]
end
outputs.sprites << [640 - 50, 360 - 50, 100, 100,
"sprites/square-green.png"]
if state.tick_count == 800
state.scene = :game
state.game_start_at = state.tick_count
end
end
def tick
defaults
if state.scene == :intro && state.tick_count <= 800
render_intro
elsif state.scene == :ending
render_ending
else
render
end
calc
process_inputs
end
def defaults
state.scene ||= :intro
state.stuff_score ||= 0
state.stuff_time ||= 0
state.stuff_best_time ||= nil
state.camera_x ||= 0
state.camera_y ||= 0
state.target_camera_scale ||= 1
state.camera_scale ||= 1
state.tongue_length ||= 100
state.dev_action ||= :collision_mode
state.action ||= :aiming
state.tongue_angle ||= 90
state.tile_size = 64
state.gravity = -0.1
state.air = -0.01
state.player_width = 60
state.player_height = 60
state.collision_tolerance = 0.0
state.previous_tile_size ||= state.tile_size
state.x ||= 2400
state.y ||= 200
state.dy ||= 0
state.dx ||= 0
attempt_load_world_from_file
state.world_lookup ||= { }
state.world_collision_rects ||= []
state.mode ||= :creating
state.select_menu ||= [0, 720, 1280, 720]
state.sprite_quantity ||= 20
state.sprite_coords ||= []
state.banner_coords ||= [640, 680 + 720]
state.sprite_selected ||= 1
state.map_saved_at ||= 0
state.intro_tick_count ||= state.tick_count
if state.sprite_coords == []
count = 1
temp_x = 165
temp_y = 500 + 720
state.sprite_quantity.times do
state.sprite_coords += [[temp_x, temp_y, count]]
temp_x += 100
count += 1
if temp_x > 1280 - (165 + 50)
temp_x = 165
temp_y -= 75
end
end
end
end
def start_of_tongue x = nil, y = nil
x ||= state.x
y ||= state.y
[
x + state.player_width.half,
y + state.player_height.half
]
end
def stage_definition
outputs.sprites << [vx(0), vy(0), vw(10000), vw(5875), 'sprites/level-map.png']
end
def render
stage_definition
start_of_tongue_render = [vx(start_of_tongue.x), vy(start_of_tongue.y)]
end_of_tongue_render = [vx(end_of_tongue.x), vy(end_of_tongue.y)]
if state.anchor_point
anchor_point_render = [vx(state.anchor_point.x), vy(state.anchor_point.y)]
outputs.sprites << { x: start_of_tongue_render.x,
y: start_of_tongue_render.y,
w: vw(2),
h: args.geometry.distance(start_of_tongue_render, anchor_point_render),
path: 'sprites/square-pink.png',
angle_anchor_y: 0,
angle: state.tongue_angle - 90 }
else
outputs.sprites << { x: vx(start_of_tongue.x),
y: vy(start_of_tongue.y),
w: vw(2),
h: vh(state.tongue_length),
path: 'sprites/square-pink.png',
angle_anchor_y: 0,
angle: state.tongue_angle - 90 }
end
outputs.sprites << state.objects.map { |o| [vx(o.x), vy(o.y), vw(o.w), vh(o.h), o.path] }
if state.god_mode
# SHOW HIDE COLLISIONS
outputs.sprites << state.world.map do |x, y, w, h|
x = vx(x)
y = vy(y)
if x > -80 && x < 1280 && y > -80 && y < 720
{
x: x,
y: y,
w: vw(w || state.tile_size),
h: vh(h || state.tile_size),
path: 'sprites/square-gray.png',
a: 128
}
end
end
end
render_player
outputs.sprites << [vx(2315), vy(45), vw(569), vh(402), 'sprites/square-blue.png', 0, 40]
# Label in top left of the screen
outputs.primitives << [20, 640, 180, 70, 255, 255, 255, 128].solid
outputs.primitives << [30, 700, "Stuff: #{state.stuff_score} of #{$mugs.count}", 1].label
outputs.primitives << [30, 670, "Time: #{"%.2f" % state.stuff_time}", 1].label
if state.god_mode
if state.map_saved_at > 0 && state.map_saved_at.elapsed_time < 120
outputs.primitives << [920, 670, 'Map has been exported!', 1, 0, 50, 100, 50].label
end
# Creates sprite following mouse to help indicate which sprite you have selected
outputs.primitives << [inputs.mouse.position.x, inputs.mouse.position.y,
state.tile_size, state.tile_size, 'sprites/square-indigo.png', 0, 100].sprite
end
render_mini_map
outputs.primitives << [0, 0, 1280, 720, 255, 255, 255, 255 * state.game_start_at.ease(60, :flip)].solid
end
def render_mini_map
x, y = 1170, 10
outputs.primitives << [x, y, 100, 58, 0, 0, 0, 200].solid
outputs.primitives << [x + args.state.x.fdiv(100) - 1, y + args.state.y.fdiv(100) - 1, 2, 2, 0, 255, 0].solid
t_start = start_of_tongue
t_end = end_of_tongue
outputs.primitives << [
x + t_start.x.fdiv(100), y + t_start.y.fdiv(100),
x + t_end.x.fdiv(100), y + t_end.y.fdiv(100),
255, 255, 255
].line
state.objects.each do |o|
outputs.primitives << [x + o.x.fdiv(100) - 1, y + o.y.fdiv(100) - 1, 2, 2, 200, 200, 0].solid
end
end
def calc_camera percentage_override = nil
percentage = percentage_override || (0.2 * state.camera_scale)
target_scale = state.target_camera_scale
distance_scale = target_scale - state.camera_scale
state.camera_scale += distance_scale * percentage
target_x = state.x * state.target_camera_scale
target_y = state.y * state.target_camera_scale
distance_x = target_x - (state.camera_x + 640)
distance_y = target_y - (state.camera_y + 360)
state.camera_x += distance_x * percentage if distance_x.abs > 1
state.camera_y += distance_y * percentage if distance_y.abs > 1
state.camera_x = 0 if state.camera_x < 0
state.camera_y = 0 if state.camera_y < 0
end
def vx x
(x * state.camera_scale) - state.camera_x
end
def vy y
(y * state.camera_scale) - state.camera_y
end
def vw w
w * state.camera_scale
end
def vh h
h * state.camera_scale
end
def calc
calc_camera
calc_world_lookup
calc_player
calc_on_floor
calc_score
end
def set_camera_scale v = nil
return if v < 0.1
state.target_camera_scale = v
end
def process_inputs_god_mode
return unless state.god_mode
if inputs.keyboard.key_down.equal_sign || (inputs.keyboard.equal_sign && state.tick_count.mod_zero?(10))
set_camera_scale state.camera_scale + 0.1
elsif inputs.keyboard.key_down.hyphen || (inputs.keyboard.hyphen && state.tick_count.mod_zero?(10))
set_camera_scale state.camera_scale - 0.1
elsif inputs.keyboard.eight || inputs.keyboard.zero
set_camera_scale 1
end
if input_up?
state.y += 10
state.dy = 0
elsif input_down?
state.y -= 10
state.dy = 0
end
if input_left?
state.x -= 10
state.dx = 0
elsif input_right?
state.x += 10
state.dx = 0
end
end
def process_inputs
if state.scene == :game
process_inputs_player_movement
process_inputs_god_mode
elsif state.scene == :intro
if args.inputs.keyboard.key_down.enter || args.inputs.keyboard.key_down.space
if Kernel.tick_count < 600
Kernel.tick_count = 600
end
end
end
end
def input_up?
inputs.keyboard.w || inputs.keyboard.up || inputs.keyboard.k
end
def input_up_released?
inputs.keyboard.key_up.w ||
inputs.keyboard.key_up.up ||
inputs.keyboard.key_up.k
end
def input_down?
inputs.keyboard.s || inputs.keyboard.down || inputs.keyboard.j
end
def input_down_released?
inputs.keyboard.key_up.s ||
inputs.keyboard.key_up.down ||
inputs.keyboard.key_up.j
end
def input_left?
inputs.keyboard.a || inputs.keyboard.left || inputs.keyboard.h
end
def input_right?
inputs.keyboard.d || inputs.keyboard.right || inputs.keyboard.l
end
def set_object path, w, h
state.object = path
state.object_w = w
state.object_h = h
end
def collision_mode
state.dev_action = :collision_mode
end
def process_inputs_player_movement
if inputs.keyboard.key_down.g
state.god_mode = !state.god_mode
puts state.god_mode
end
if inputs.keyboard.key_down.u && state.dev_action == :collision_mode
state.world = state.world[0..-2]
state.world_lookup = {}
end
if inputs.keyboard.key_down.space && !state.anchor_point
state.tongue_length = 0
state.action = :shooting
outputs.sounds << 'sounds/shooting.wav'
elsif inputs.keyboard.key_down.space
state.action = :aiming
state.anchor_point = nil
state.tongue_length = 100
end
if state.anchor_point
if input_up?
if state.tongue_length >= 105
state.tongue_length -= 5
state.dy += 0.8
end
elsif input_down?
state.tongue_length += 5
state.dy -= 0.8
end
if input_left? && state.dx > 1
state.dx *= 0.98
elsif input_left? && state.dx < -1
state.dx *= 1.03
elsif input_left? && !state.on_floor
state.dx -= 3
elsif input_right? && state.dx > 1
state.dx *= 1.03
elsif input_right? && state.dx < -1
state.dx *= 0.98
elsif input_right? && !state.on_floor
state.dx += 3
end
else
if input_left?
state.tongue_angle += 1.5
state.tongue_angle = state.tongue_angle
elsif input_right?
state.tongue_angle -= 1.5
state.tongue_angle = state.tongue_angle
end
end
end
def add_floors
# floors
state.world += [
[0, 0, 10000, 40],
[0, 1670, 3250, 60],
[6691, 1653, 3290, 60],
[1521, 3792, 7370, 60],
[0, 5137, 3290, 60]
]
end
def attempt_load_world_from_file
return if state.world
# exported_world = gtk.read_file(MAP_FILE_PATH)
state.world = []
state.objects = []
if $collisions
$collisions.map do |x, y, w, h|
state.world << [x, y, w, h]
end
add_floors
# elsif exported_world
# exported_world.each_line.map do |l|
# tokens = l.strip.split(',')
# x = tokens[0].to_i
# y = tokens[1].to_i
# type = tokens[2].to_i
# if type == 1
# state.world << [x, y, state.tile_size, state.tile_size]
# elsif type == 2
# w, h, path = tokens[3..-1]
# state.objects << [x, y, w.to_i, h.to_i, path]
# end
# end
# add_floors
end
if $mugs
$mugs.map do |x, y, w, h, path|
state.objects << [x, y, w, h, path]
end
end
end
def calc_world_lookup
if state.tile_size != state.previous_tile_size
state.previous_tile_size = state.tile_size
state.world_lookup = {}
end
return if state.world_lookup.keys.length > 0
return unless state.world.length > 0
# Searches through the world and finds the cordinates that exist
state.world_lookup = {}
state.world.each do |x, y, w, h|
state.world_lookup[[x, y, w || state.tile_size, h || state.tile_size]] = true
end
# Assigns collision rects for every sprite drawn
state.world_collision_rects =
state.world_lookup
.keys
.map do |x, y, w, h|
s = state.tile_size
w ||= s
h ||= s
{
args: [x, y, w, h],
left_right: [x, y + 4, w, h - 6],
top: [x + 4, y + 6, w - 8, h - 6],
bottom: [x + 1, y - 1, w - 2, h - 8],
}
end
end
def calc_pendulum
return if !state.anchor_point
target_x = state.anchor_point.x - start_of_tongue.x
target_y = state.anchor_point.y -
state.tongue_length - 5 - 20 - state.player_height
diff_y = state.y - target_y
if target_x > 0
state.dx += 0.6
elsif target_x < 0
state.dx -= 0.6
end
if diff_y > 0
state.dy -= 0.1
elsif diff_y < 0
state.dy += 0.1
end
state.dx *= 0.99
if state.dy.abs < 2
state.dy *= 0.8
else
state.dy *= 0.90
end
if state.tongue_length && state.y
state.dy += state.tongue_angle.vector_y state.tongue_length.fdiv(1000)
end
end
def calc_tongue_angle
return unless state.anchor_point
state.tongue_angle = args.geometry.angle_from state.anchor_point, start_of_tongue
state.tongue_length = args.geometry.distance(start_of_tongue, state.anchor_point)
state.tongue_length = state.tongue_length.greater(100)
end
def player_from_end_of_tongue
p = state.tongue_angle.vector(state.tongue_length)
derived_start = [state.anchor_point.x - p.x, state.anchor_point.y - p.y]
derived_start.x -= state.player_width.half
derived_start.y -= state.player_height.half
derived_start
end
def end_of_tongue
p = state.tongue_angle.vector(state.tongue_length)
[start_of_tongue.x + p.x, start_of_tongue.y + p.y]
end
def calc_shooting
return unless state.action == :shooting
state.tongue_length += 30
potential_anchor = end_of_tongue
if potential_anchor.x <= 0
state.anchor_point = potential_anchor
state.action = :anchored
outputs.sounds << 'sounds/attached.wav'
elsif potential_anchor.x >= 10000
state.anchor_point = potential_anchor
state.action = :anchored
outputs.sounds << 'sounds/attached.wav'
elsif potential_anchor.y <= 0
state.anchor_point = potential_anchor
state.action = :anchored
outputs.sounds << 'sounds/attached.wav'
elsif potential_anchor.y >= 5875
state.anchor_point = potential_anchor
state.action = :anchored
outputs.sounds << 'sounds/attached.wav'
else
anchor_rect = [potential_anchor.x - 5, potential_anchor.y - 5, 10, 10]
collision = state.world_collision_rects.find_all do |v|
[v[:args].x, v[:args].y, v[:args].w, v[:args].h].intersect_rect?(anchor_rect)
end.first
if collision
state.anchor_point = potential_anchor
state.action = :anchored
outputs.sounds << 'sounds/attached.wav'
end
end
end
def calc_player
calc_shooting
if !state.god_mode
state.dy += state.gravity # Since acceleration is the change in velocity, the change in y (dy) increases every frame
state.dx += state.dx * state.air
end
calc_pendulum
calc_box_collision
calc_edge_collision
if !state.god_mode
state.y += state.dy
state.x += state.dx
end
calc_tongue_angle
end
def calc_box_collision
return unless state.world_lookup.keys.length > 0
collision_floor
collision_left
collision_right
collision_ceiling
end
def calc_edge_collision
# Ensures that player doesn't fall below the map
if next_y < 0 && state.dy < 0
state.y = 0
state.dy = state.dy.abs * 0.8
state.collision_on_y = true
# Ensures player doesn't go insanely high
elsif next_y > 5875 - state.tile_size && state.dy > 0
state.y = 5875 - state.tile_size
state.dy = state.dy.abs * 0.8 * -1
state.collision_on_y = true
end
# Ensures that player remains in the horizontal range its supposed to
if state.x >= 10000 - state.tile_size && state.dx > 0
state.x = 10000 - state.tile_size
state.dx = state.dx.abs * 0.8 * -1
state.collision_on_x = true
elsif state.x <= 0 && state.dx < 0
state.x = 0
state.dx = state.dx.abs * 0.8
state.collision_on_x = true
end
end
def next_y
state.y + state.dy
end
def next_x
if state.dx < 0
return (state.x + state.dx) - (state.tile_size - state.player_width)
else
return (state.x + state.dx) + (state.tile_size - state.player_width)
end
end
def collision_floor
return unless state.dy <= 0
player_rect = [state.x, next_y, state.tile_size, state.tile_size]
# Runs through all the sprites on the field and determines if the player hits the bottom of sprite (hence "-0.1" above)
floor_collisions = state.world_collision_rects
.find_all { |r| r[:top].intersect_rect?(player_rect, state.collision_tolerance) }
.first
return unless floor_collisions
state.y = floor_collisions[:top].top
state.dy = state.dy.abs * 0.8
end
def collision_left
return unless state.dx < 0
player_rect = [next_x, state.y, state.tile_size, state.tile_size]
# Runs through all the sprites on the field and determines if the player hits the left side of sprite (hence "-0.1" above)
left_side_collisions = state.world_collision_rects
.find_all { |r| r[:left_right].intersect_rect?(player_rect, state.collision_tolerance) }
.first
return unless left_side_collisions
state.x = left_side_collisions[:left_right].right
state.dx = state.dy.abs * 0.8
state.collision_on_x = true
end
def collision_right
return unless state.dx > 0
player_rect = [next_x, state.y, state.tile_size, state.tile_size]
# Runs through all the sprites on the field and determines if the player hits the right side of sprite (hence "-0.1" above)
right_side_collisions = state.world_collision_rects
.find_all { |r| r[:left_right].intersect_rect?(player_rect, state.collision_tolerance) }
.first
return unless right_side_collisions
state.x = right_side_collisions[:left_right].left - state.tile_size
state.dx = state.dx.abs * 0.8 * -1
state.collision_on_x = true
end
def collision_ceiling
return unless state.dy > 0
player_rect = [state.x, next_y, state.player_width, state.player_height]
# Runs through all the sprites on the field and determines if the player hits the ceiling of sprite (hence "+0.1" above)
ceil_collisions = state.world_collision_rects
.find_all { |r| r[:bottom].intersect_rect?(player_rect, state.collision_tolerance) }
.first
return unless ceil_collisions
state.y = ceil_collisions[:bottom].y - state.tile_size
state.dy = state.dy.abs * 0.8 * -1
state.collision_on_y = true
end
def to_coord point
# Integer divides (idiv) point.x to turn into grid
# Then, you can just multiply each integer by state.tile_size
# later and huzzah. Grid coordinates
[point.x.idiv(state.tile_size), point.y.idiv(state.tile_size)]
end
def export_map
export_string = state.world.map do |x, y|
"#{x},#{y},1"
end
export_string += state.objects.map do |x, y, w, h, path|
"#{x},#{y},2,#{w},#{h},#{path}"
end
gtk.write_file(MAP_FILE_PATH, export_string.join("\n"))
state.map_saved_at = state.tick_count
end
def inputs_export_stage
end
def calc_score
return unless state.scene == :game
player = [state.x, state.y, state.player_width, state.player_height]
collected = state.objects.find_all { |s| s.intersect_rect? player }
state.stuff_score += collected.length
if collected.length > 0
outputs.sounds << 'sounds/collectable.wav'
end
state.objects = state.objects.reject { |s| collected.include? s }
state.stuff_time += 0.01
if state.objects.length == 0
if !state.stuff_best_time || state.stuff_time < state.stuff_best_time
state.stuff_best_time = state.stuff_time
end
state.game_over_at = nil
state.scene = :ending
end
end
def calc_on_floor
if state.action == :anchored
state.on_floor = false
state.on_floor_debounce = 30
else
state.on_floor_debounce ||= 30
if state.dy.round != 0
state.on_floor_debounce = 30
state.on_floor = false
else
state.on_floor_debounce -= 1
end
if state.on_floor_debounce <= 0
state.on_floor_debounce = 0
state.on_floor = true
end
end
end
def render_player
path = "sprites/square-green.png"
angle = 0
# outputs.labels << [vx(state.x), vy(state.y) - 30, "dy: #{state.dy.round}"]
if state.action == :idle
# outputs.labels << [vx(state.x), vy(state.y), "IDLE"]
path = "sprites/square-green.png"
elsif state.action == :aiming && !state.on_floor
# outputs.labels << [vx(state.x), vy(state.y), "AIMING AIR BORN"]
angle = state.tongue_angle - 90
path = "sprites/square-green.png"
elsif state.action == :aiming # ON THE GROUND
# outputs.labels << [vx(state.x), vy(state.y), "AIMING GROUND"]
path = "sprites/square-green.png"
elsif state.action == :shooting && !state.on_floor
# outputs.labels << [vx(state.x), vy(state.y), "SHOOTING AIR BORN"]
path = "sprites/square-green.png"
angle = state.tongue_angle - 90
elsif state.action == :shooting
# outputs.labels << [vx(state.x), vy(state.y), "SHOOTING ON GROUND"]
path = "sprites/square-green.png"
elsif state.action == :anchored
# outputs.labels << [vx(state.x), vy(state.y), "SWINGING"]
angle = state.tongue_angle - 90
path = "sprites/square-green.png"
end
outputs.sprites << [vx(state.x),
vy(state.y),
vw(state.player_width),
vh(state.player_height),
path,
angle]
end
def render_player_old
# Player
if state.action == :aiming
path = 'sprites\frg\idle\frog_idle.png'
if state.dx > 2
#directional right sprite was here but i needa redo it
path = 'sprites\frg\anchor\frog-anchor-0.png'
#directional left sprite was here but i needa redo it
elsif state.dx < -2
path = 'sprites\frg\anchor\frog-anchor-0.png'
end
outputs.sprites << [vx(state.x),
vy(state.y),
vw(state.player_width),
vh(state.player_height),
path,
(state.tongue_angle - 90)]
elsif state.action == :anchored || state.action == :shooting
outputs.sprites << [vx(state.x),
vy(state.y),
vw(state.player_width),
vw(state.player_height),
'sprites/animations_povfrog/frog_bwah_up.png',
(state.tongue_angle - 90)]
end
end
end
$game = CleptoFrog.new
def tick args
if args.state.scene == :game
tick_instructions args, "SPACE to SHOOT and RELEASE tongue. LEFT, RIGHT to SWING and BUILD momentum. MINIMAP in bottom right corner.", 360
end
$game.args = args
$game.tick
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.keyboard.directional_vector || args.inputs.keyboard.key_down.space
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(SPACE to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
</code></pre>
<h3 id='----platformer---clepto-frog---map-rb'>Platformer - Clepto Frog - map.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_platformer/clepto_frog/app/map.rb
$collisions = [
[326, 463, 64, 64],
[274, 462, 64, 64],
[326, 413, 64, 64],
[275, 412, 64, 64],
[124, 651, 64, 64],
[72, 651, 64, 64],
[124, 600, 64, 64],
[69, 599, 64, 64],
[501, 997, 64, 64],
[476, 995, 64, 64],
[3224, 2057, 64, 64],
[3224, 1994, 64, 64],
[3225, 1932, 64, 64],
[3225, 1870, 64, 64],
[3226, 1806, 64, 64],
[3224, 1744, 64, 64],
[3225, 1689, 64, 64],
[3226, 1660, 64, 64],
[3161, 1658, 64, 64],
[3097, 1660, 64, 64],
[3033, 1658, 64, 64],
[2969, 1658, 64, 64],
[2904, 1658, 64, 64],
[2839, 1657, 64, 64],
[2773, 1657, 64, 64],
[2709, 1658, 64, 64],
[2643, 1657, 64, 64],
[2577, 1657, 64, 64],
[2509, 1658, 64, 64],
[2440, 1658, 64, 64],
[2371, 1658, 64, 64],
[2301, 1659, 64, 64],
[2230, 1659, 64, 64],
[2159, 1659, 64, 64],
[2092, 1660, 64, 64],
[2025, 1661, 64, 64],
[1958, 1660, 64, 64],
[1888, 1659, 64, 64],
[1817, 1657, 64, 64],
[1745, 1656, 64, 64],
[1673, 1658, 64, 64],
[1605, 1660, 64, 64],
[1536, 1658, 64, 64],
[1465, 1660, 64, 64],
[1386, 1960, 64, 64],
[1384, 1908, 64, 64],
[1387, 1862, 64, 64],
[1326, 1863, 64, 64],
[1302, 1862, 64, 64],
[1119, 1906, 64, 64],
[1057, 1905, 64, 64],
[994, 1905, 64, 64],
[937, 1904, 64, 64],
[896, 1904, 64, 64],
[1001, 1845, 64, 64],
[1003, 1780, 64, 64],
[1003, 1718, 64, 64],
[692, 1958, 64, 64],
[691, 1900, 64, 64],
[774, 1861, 64, 64],
[712, 1861, 64, 64],
[691, 1863, 64, 64],
[325, 2133, 64, 64],
[275, 2134, 64, 64],
[326, 2082, 64, 64],
[275, 2082, 64, 64],
[124, 2321, 64, 64],
[71, 2320, 64, 64],
[123, 2267, 64, 64],
[71, 2268, 64, 64],
[2354, 1859, 64, 64],
[2292, 1859, 64, 64],
[2231, 1857, 64, 64],
[2198, 1858, 64, 64],
[2353, 1802, 64, 64],
[2296, 1798, 64, 64],
[2233, 1797, 64, 64],
[2200, 1797, 64, 64],
[2352, 1742, 64, 64],
[2288, 1741, 64, 64],
[2230, 1743, 64, 64],
[2196, 1743, 64, 64],
[1736, 460, 64, 64],
[1735, 400, 64, 64],
[1736, 339, 64, 64],
[1736, 275, 64, 64],
[1738, 210, 64, 64],
[1735, 145, 64, 64],
[1735, 87, 64, 64],
[1736, 51, 64, 64],
[539, 289, 64, 64],
[541, 228, 64, 64],
[626, 191, 64, 64],
[572, 192, 64, 64],
[540, 193, 64, 64],
[965, 233, 64, 64],
[904, 234, 64, 64],
[840, 234, 64, 64],
[779, 234, 64, 64],
[745, 236, 64, 64],
[851, 169, 64, 64],
[849, 108, 64, 64],
[852, 50, 64, 64],
[1237, 289, 64, 64],
[1236, 228, 64, 64],
[1238, 197, 64, 64],
[1181, 192, 64, 64],
[1152, 192, 64, 64],
[1443, 605, 64, 64],
[1419, 606, 64, 64],
[1069, 925, 64, 64],
[1068, 902, 64, 64],
[1024, 927, 64, 64],
[1017, 897, 64, 64],
[963, 926, 64, 64],
[958, 898, 64, 64],
[911, 928, 64, 64],
[911, 896, 64, 64],
[2132, 803, 64, 64],
[2081, 803, 64, 64],
[2131, 752, 64, 64],
[2077, 751, 64, 64],
[2615, 649, 64, 64],
[2564, 651, 64, 64],
[2533, 650, 64, 64],
[2027, 156, 64, 64],
[1968, 155, 64, 64],
[1907, 153, 64, 64],
[1873, 155, 64, 64],
[2025, 95, 64, 64],
[1953, 98, 64, 64],
[1894, 100, 64, 64],
[1870, 100, 64, 64],
[2029, 45, 64, 64],
[1971, 48, 64, 64],
[1915, 47, 64, 64],
[1873, 47, 64, 64],
[3956, 288, 64, 64],
[3954, 234, 64, 64],
[4042, 190, 64, 64],
[3990, 190, 64, 64],
[3958, 195, 64, 64],
[3422, 709, 64, 64],
[3425, 686, 64, 64],
[3368, 709, 64, 64],
[3364, 683, 64, 64],
[3312, 711, 64, 64],
[3307, 684, 64, 64],
[3266, 712, 64, 64],
[3269, 681, 64, 64],
[4384, 236, 64, 64],
[4320, 234, 64, 64],
[4257, 235, 64, 64],
[4192, 234, 64, 64],
[4162, 234, 64, 64],
[4269, 171, 64, 64],
[4267, 111, 64, 64],
[4266, 52, 64, 64],
[4580, 458, 64, 64],
[4582, 396, 64, 64],
[4582, 335, 64, 64],
[4581, 275, 64, 64],
[4581, 215, 64, 64],
[4581, 152, 64, 64],
[4582, 89, 64, 64],
[4583, 51, 64, 64],
[4810, 289, 64, 64],
[4810, 227, 64, 64],
[4895, 189, 64, 64],
[4844, 191, 64, 64],
[4809, 191, 64, 64],
[5235, 233, 64, 64],
[5176, 232, 64, 64],
[5118, 230, 64, 64],
[5060, 232, 64, 64],
[5015, 237, 64, 64],
[5123, 171, 64, 64],
[5123, 114, 64, 64],
[5121, 51, 64, 64],
[5523, 461, 64, 64],
[5123, 42, 64, 64],
[5525, 401, 64, 64],
[5525, 340, 64, 64],
[5526, 273, 64, 64],
[5527, 211, 64, 64],
[5525, 150, 64, 64],
[5527, 84, 64, 64],
[5524, 44, 64, 64],
[5861, 288, 64, 64],
[5861, 229, 64, 64],
[5945, 193, 64, 64],
[5904, 193, 64, 64],
[5856, 194, 64, 64],
[6542, 234, 64, 64],
[6478, 235, 64, 64],
[6413, 238, 64, 64],
[6348, 235, 64, 64],
[6285, 236, 64, 64],
[6222, 235, 64, 64],
[6160, 235, 64, 64],
[6097, 236, 64, 64],
[6069, 237, 64, 64],
[6321, 174, 64, 64],
[6318, 111, 64, 64],
[6320, 49, 64, 64],
[6753, 291, 64, 64],
[6752, 227, 64, 64],
[6753, 192, 64, 64],
[6692, 191, 64, 64],
[6668, 193, 64, 64],
[6336, 604, 64, 64],
[6309, 603, 64, 64],
[7264, 461, 64, 64],
[7264, 395, 64, 64],
[7264, 333, 64, 64],
[7264, 270, 64, 64],
[7265, 207, 64, 64],
[7266, 138, 64, 64],
[7264, 78, 64, 64],
[7266, 48, 64, 64],
[7582, 149, 64, 64],
[7524, 147, 64, 64],
[7461, 146, 64, 64],
[7425, 148, 64, 64],
[7580, 86, 64, 64],
[7582, 41, 64, 64],
[7519, 41, 64, 64],
[7460, 40, 64, 64],
[7427, 96, 64, 64],
[7427, 41, 64, 64],
[8060, 288, 64, 64],
[8059, 226, 64, 64],
[8145, 194, 64, 64],
[8081, 194, 64, 64],
[8058, 195, 64, 64],
[8485, 234, 64, 64],
[8422, 235, 64, 64],
[8360, 235, 64, 64],
[8296, 235, 64, 64],
[8266, 237, 64, 64],
[8371, 173, 64, 64],
[8370, 117, 64, 64],
[8372, 59, 64, 64],
[8372, 51, 64, 64],
[9147, 192, 64, 64],
[9063, 287, 64, 64],
[9064, 225, 64, 64],
[9085, 193, 64, 64],
[9063, 194, 64, 64],
[9492, 234, 64, 64],
[9428, 234, 64, 64],
[9365, 235, 64, 64],
[9302, 235, 64, 64],
[9270, 237, 64, 64],
[9374, 172, 64, 64],
[9376, 109, 64, 64],
[9377, 48, 64, 64],
[9545, 1060, 64, 64],
[9482, 1062, 64, 64],
[9423, 1062, 64, 64],
[9387, 1062, 64, 64],
[9541, 999, 64, 64],
[9542, 953, 64, 64],
[9478, 953, 64, 64],
[9388, 999, 64, 64],
[9414, 953, 64, 64],
[9389, 953, 64, 64],
[9294, 1194, 64, 64],
[9245, 1195, 64, 64],
[9297, 1143, 64, 64],
[9245, 1144, 64, 64],
[5575, 1781, 64, 64],
[5574, 1753, 64, 64],
[5522, 1782, 64, 64],
[5518, 1753, 64, 64],
[5472, 1783, 64, 64],
[5471, 1751, 64, 64],
[5419, 1781, 64, 64],
[5421, 1749, 64, 64],
[500, 3207, 64, 64],
[477, 3205, 64, 64],
[1282, 3214, 64, 64],
[1221, 3214, 64, 64],
[1188, 3215, 64, 64],
[1345, 3103, 64, 64],
[1288, 3103, 64, 64],
[1231, 3104, 64, 64],
[1190, 3153, 64, 64],
[1189, 3105, 64, 64],
[2255, 3508, 64, 64],
[2206, 3510, 64, 64],
[2254, 3458, 64, 64],
[2202, 3458, 64, 64],
[2754, 2930, 64, 64],
[2726, 2932, 64, 64],
[3408, 2874, 64, 64],
[3407, 2849, 64, 64],
[3345, 2872, 64, 64],
[3342, 2847, 64, 64],
[3284, 2874, 64, 64],
[3284, 2848, 64, 64],
[3248, 2878, 64, 64],
[3252, 2848, 64, 64],
[3953, 3274, 64, 64],
[3899, 3277, 64, 64],
[3951, 3222, 64, 64],
[3900, 3222, 64, 64],
[4310, 2968, 64, 64],
[4246, 2969, 64, 64],
[4183, 2965, 64, 64],
[4153, 2967, 64, 64],
[4311, 2910, 64, 64],
[4308, 2856, 64, 64],
[4251, 2855, 64, 64],
[4197, 2857, 64, 64],
[5466, 3184, 64, 64],
[5466, 3158, 64, 64],
[5404, 3184, 64, 64],
[5404, 3156, 64, 64],
[5343, 3185, 64, 64],
[5342, 3156, 64, 64],
[5308, 3185, 64, 64],
[5307, 3154, 64, 64],
[6163, 2950, 64, 64],
[6111, 2952, 64, 64],
[6164, 2898, 64, 64],
[6113, 2897, 64, 64],
[7725, 3156, 64, 64],
[7661, 3157, 64, 64],
[7598, 3157, 64, 64],
[7533, 3156, 64, 64],
[7468, 3156, 64, 64],
[7401, 3156, 64, 64],
[7335, 3157, 64, 64],
[7270, 3157, 64, 64],
[7208, 3157, 64, 64],
[7146, 3157, 64, 64],
[7134, 3159, 64, 64],
[6685, 3726, 64, 64],
[6685, 3663, 64, 64],
[6683, 3602, 64, 64],
[6679, 3538, 64, 64],
[6680, 3474, 64, 64],
[6682, 3413, 64, 64],
[6681, 3347, 64, 64],
[6681, 3287, 64, 64],
[6682, 3223, 64, 64],
[6683, 3161, 64, 64],
[6682, 3102, 64, 64],
[6684, 3042, 64, 64],
[6685, 2980, 64, 64],
[6685, 2920, 64, 64],
[6683, 2859, 64, 64],
[6684, 2801, 64, 64],
[6686, 2743, 64, 64],
[6683, 2683, 64, 64],
[6681, 2622, 64, 64],
[6682, 2559, 64, 64],
[6683, 2498, 64, 64],
[6685, 2434, 64, 64],
[6683, 2371, 64, 64],
[6683, 2306, 64, 64],
[6684, 2242, 64, 64],
[6683, 2177, 64, 64],
[6683, 2112, 64, 64],
[6683, 2049, 64, 64],
[6683, 1985, 64, 64],
[6682, 1923, 64, 64],
[6683, 1860, 64, 64],
[6685, 1797, 64, 64],
[6684, 1735, 64, 64],
[6685, 1724, 64, 64],
[7088, 1967, 64, 64],
[7026, 1966, 64, 64],
[6964, 1967, 64, 64],
[6900, 1965, 64, 64],
[6869, 1969, 64, 64],
[6972, 1904, 64, 64],
[6974, 1840, 64, 64],
[6971, 1776, 64, 64],
[6971, 1716, 64, 64],
[7168, 1979, 64, 64],
[7170, 1919, 64, 64],
[7169, 1882, 64, 64],
[7115, 1880, 64, 64],
[7086, 1881, 64, 64],
[7725, 1837, 64, 64],
[7724, 1776, 64, 64],
[7724, 1728, 64, 64],
[7661, 1727, 64, 64],
[7603, 1728, 64, 64],
[7571, 1837, 64, 64],
[7570, 1774, 64, 64],
[7572, 1725, 64, 64],
[7859, 2134, 64, 64],
[7858, 2070, 64, 64],
[7858, 2008, 64, 64],
[7860, 1942, 64, 64],
[7856, 1878, 64, 64],
[7860, 1813, 64, 64],
[7859, 1750, 64, 64],
[7856, 1724, 64, 64],
[8155, 1837, 64, 64],
[8092, 1839, 64, 64],
[8032, 1838, 64, 64],
[7999, 1839, 64, 64],
[8153, 1773, 64, 64],
[8154, 1731, 64, 64],
[8090, 1730, 64, 64],
[8035, 1732, 64, 64],
[8003, 1776, 64, 64],
[8003, 1730, 64, 64],
[8421, 1978, 64, 64],
[8420, 1917, 64, 64],
[8505, 1878, 64, 64],
[8443, 1881, 64, 64],
[8420, 1882, 64, 64],
[8847, 1908, 64, 64],
[8783, 1908, 64, 64],
[8718, 1910, 64, 64],
[8654, 1910, 64, 64],
[8628, 1911, 64, 64],
[8729, 1847, 64, 64],
[8731, 1781, 64, 64],
[8731, 1721, 64, 64],
[9058, 2135, 64, 64],
[9056, 2073, 64, 64],
[9058, 2006, 64, 64],
[9057, 1939, 64, 64],
[9058, 1876, 64, 64],
[9056, 1810, 64, 64],
[9059, 1745, 64, 64],
[9060, 1722, 64, 64],
[9273, 1977, 64, 64],
[9273, 1912, 64, 64],
[9358, 1883, 64, 64],
[9298, 1881, 64, 64],
[9270, 1883, 64, 64],
[9699, 1910, 64, 64],
[9637, 1910, 64, 64],
[9576, 1910, 64, 64],
[9512, 1911, 64, 64],
[9477, 1912, 64, 64],
[9584, 1846, 64, 64],
[9585, 1783, 64, 64],
[9586, 1719, 64, 64],
[8320, 2788, 64, 64],
[8256, 2789, 64, 64],
[8192, 2789, 64, 64],
[8180, 2789, 64, 64],
[8319, 2730, 64, 64],
[8319, 2671, 64, 64],
[8319, 2639, 64, 64],
[8259, 2639, 64, 64],
[8202, 2639, 64, 64],
[8179, 2727, 64, 64],
[8178, 2665, 64, 64],
[8177, 2636, 64, 64],
[9360, 3138, 64, 64],
[9296, 3137, 64, 64],
[9235, 3139, 64, 64],
[9174, 3139, 64, 64],
[9113, 3138, 64, 64],
[9050, 3138, 64, 64],
[8988, 3138, 64, 64],
[8925, 3138, 64, 64],
[8860, 3136, 64, 64],
[8797, 3136, 64, 64],
[8770, 3138, 64, 64],
[8827, 4171, 64, 64],
[8827, 4107, 64, 64],
[8827, 4043, 64, 64],
[8827, 3978, 64, 64],
[8825, 3914, 64, 64],
[8824, 3858, 64, 64],
[9635, 4234, 64, 64],
[9584, 4235, 64, 64],
[9634, 4187, 64, 64],
[9582, 4183, 64, 64],
[9402, 5114, 64, 64],
[9402, 5087, 64, 64],
[9347, 5113, 64, 64],
[9345, 5086, 64, 64],
[9287, 5114, 64, 64],
[9285, 5085, 64, 64],
[9245, 5114, 64, 64],
[9244, 5086, 64, 64],
[9336, 5445, 64, 64],
[9285, 5445, 64, 64],
[9337, 5395, 64, 64],
[9283, 5393, 64, 64],
[8884, 4968, 64, 64],
[8884, 4939, 64, 64],
[8822, 4967, 64, 64],
[8823, 4940, 64, 64],
[8765, 4967, 64, 64],
[8762, 4937, 64, 64],
[8726, 4969, 64, 64],
[8727, 4939, 64, 64],
[7946, 5248, 64, 64],
[7945, 5220, 64, 64],
[7887, 5248, 64, 64],
[7886, 5219, 64, 64],
[7830, 5248, 64, 64],
[7827, 5218, 64, 64],
[7781, 5248, 64, 64],
[7781, 5216, 64, 64],
[6648, 4762, 64, 64],
[6621, 4761, 64, 64],
[5011, 4446, 64, 64],
[4982, 4444, 64, 64],
[4146, 4641, 64, 64],
[4092, 4643, 64, 64],
[4145, 4589, 64, 64],
[4091, 4590, 64, 64],
[4139, 4497, 64, 64],
[4135, 4437, 64, 64],
[4135, 4383, 64, 64],
[4078, 4495, 64, 64],
[4014, 4494, 64, 64],
[3979, 4496, 64, 64],
[4074, 4384, 64, 64],
[4015, 4381, 64, 64],
[3980, 4433, 64, 64],
[3981, 4384, 64, 64],
[3276, 4279, 64, 64],
[3275, 4218, 64, 64],
[3276, 4170, 64, 64],
[3211, 4164, 64, 64],
[3213, 4280, 64, 64],
[3156, 4278, 64, 64],
[3120, 4278, 64, 64],
[3151, 4163, 64, 64],
[3120, 4216, 64, 64],
[3120, 4161, 64, 64],
[1536, 4171, 64, 64],
[1536, 4110, 64, 64],
[1535, 4051, 64, 64],
[1536, 3991, 64, 64],
[1536, 3928, 64, 64],
[1536, 3863, 64, 64],
[1078, 4605, 64, 64],
[1076, 4577, 64, 64],
[1018, 4604, 64, 64],
[1018, 4575, 64, 64],
[957, 4606, 64, 64],
[960, 4575, 64, 64],
[918, 4602, 64, 64],
[918, 4580, 64, 64],
[394, 4164, 64, 64],
[335, 4163, 64, 64],
[274, 4161, 64, 64],
[236, 4163, 64, 64],
[394, 4140, 64, 64],
[329, 4139, 64, 64],
[268, 4139, 64, 64],
[239, 4139, 64, 64],
[4326, 5073, 64, 64],
[4324, 5042, 64, 64],
[4265, 5074, 64, 64],
[4263, 5042, 64, 64],
[4214, 5072, 64, 64],
[4211, 5043, 64, 64],
[4166, 5073, 64, 64],
[4164, 5041, 64, 64],
[4844, 5216, 64, 64],
[4844, 5189, 64, 64],
[4785, 5217, 64, 64],
[4790, 5187, 64, 64],
[4726, 5219, 64, 64],
[4728, 5185, 64, 64],
[4681, 5218, 64, 64],
[4684, 5186, 64, 64],
[4789, 4926, 64, 64],
[4734, 4928, 64, 64],
[4787, 4876, 64, 64],
[4738, 4874, 64, 64],
[4775, 5548, 64, 64],
[4775, 5495, 64, 64],
[4723, 5550, 64, 64],
[4725, 5494, 64, 64],
[1360, 5269, 64, 64],
[1362, 5218, 64, 64],
[1315, 5266, 64, 64],
[1282, 5266, 64, 64],
[1246, 5311, 64, 64],
[1190, 5312, 64, 64],
[1136, 5310, 64, 64],
[1121, 5427, 64, 64],
[1121, 5370, 64, 64],
[1074, 5427, 64, 64],
[1064, 5423, 64, 64],
[1052, 5417, 64, 64],
[1050, 5368, 64, 64],
[1008, 5314, 64, 64],
[997, 5307, 64, 64],
[977, 5299, 64, 64],
[976, 5248, 64, 64],
[825, 5267, 64, 64],
[826, 5213, 64, 64],
[776, 5267, 64, 64],
[768, 5261, 64, 64],
[755, 5256, 64, 64],
[753, 5209, 64, 64],
[1299, 5206, 64, 64],
[1238, 5204, 64, 64],
[1178, 5203, 64, 64],
[1124, 5204, 64, 64],
[1065, 5206, 64, 64],
[1008, 5203, 64, 64],
[977, 5214, 64, 64],
[410, 5313, 64, 64],
[407, 5249, 64, 64],
[411, 5225, 64, 64],
[397, 5217, 64, 64],
[378, 5209, 64, 64],
[358, 5312, 64, 64],
[287, 5427, 64, 64],
[286, 5364, 64, 64],
[300, 5313, 64, 64],
[242, 5427, 64, 64],
[229, 5420, 64, 64],
[217, 5416, 64, 64],
[215, 5364, 64, 64],
[174, 5311, 64, 64],
[165, 5308, 64, 64],
[139, 5300, 64, 64],
[141, 5236, 64, 64],
[141, 5211, 64, 64],
[315, 5208, 64, 64],
[251, 5208, 64, 64],
[211, 5211, 64, 64],
[8050, 4060, 64, 64],
[7992, 4060, 64, 64],
[7929, 4060, 64, 64],
[7866, 4061, 64, 64],
[7828, 4063, 64, 64],
[7934, 4001, 64, 64],
[7935, 3936, 64, 64],
[7935, 3875, 64, 64],
[7622, 4111, 64, 64],
[7623, 4049, 64, 64],
[7707, 4018, 64, 64],
[7663, 4019, 64, 64],
[7623, 4017, 64, 64],
[7193, 4060, 64, 64],
[7131, 4059, 64, 64],
[7070, 4057, 64, 64],
[7008, 4060, 64, 64],
[6977, 4060, 64, 64],
[7080, 3998, 64, 64],
[7081, 3935, 64, 64],
[7080, 3873, 64, 64],
[6855, 4019, 64, 64],
[6790, 4018, 64, 64],
[6770, 4114, 64, 64],
[6770, 4060, 64, 64],
[6768, 4013, 64, 64],
[6345, 4060, 64, 64],
[6284, 4062, 64, 64],
[6222, 4061, 64, 64],
[6166, 4061, 64, 64],
[6124, 4066, 64, 64],
[6226, 3995, 64, 64],
[6226, 3933, 64, 64],
[6228, 3868, 64, 64],
[5916, 4113, 64, 64],
[5918, 4052, 64, 64],
[6001, 4018, 64, 64],
[5941, 4019, 64, 64],
[5918, 4020, 64, 64],
[5501, 4059, 64, 64],
[5439, 4061, 64, 64],
[5376, 4059, 64, 64],
[5312, 4058, 64, 64],
[5285, 4062, 64, 64],
[5388, 3999, 64, 64],
[5385, 3941, 64, 64],
[5384, 3874, 64, 64],
[5075, 4112, 64, 64],
[5074, 4051, 64, 64],
[5158, 4018, 64, 64],
[5095, 4020, 64, 64],
[5073, 4018, 64, 64],
[4549, 3998, 64, 64],
[4393, 3996, 64, 64],
[4547, 3938, 64, 64],
[4547, 3886, 64, 64],
[4488, 3885, 64, 64],
[4427, 3885, 64, 64],
[4395, 3938, 64, 64],
[4395, 3885, 64, 64],
[0, 0, 64, 64],
[0, 1670, 64, 64],
[6691, 1653, 64, 64],
[1521, 3792, 64, 64],
[0, 5137, 64, 64],
[0, 0, 64, 64],
[0, 1670, 64, 64],
[6691, 1653, 64, 64],
[1521, 3792, 64, 64],
[0, 5137, 64, 64],
[1215, 2421, 64, 64],
[1214, 2360, 64, 64],
[1211, 2300, 64, 64],
[1211, 2291, 64, 64],
[1158, 2420, 64, 64],
[1156, 2358, 64, 64],
[1149, 2291, 64, 64],
[1095, 2420, 64, 64],
[1030, 2418, 64, 64],
[966, 2419, 64, 64],
[903, 2419, 64, 64],
[852, 2419, 64, 64],
[1087, 2291, 64, 64],
[1023, 2291, 64, 64],
[960, 2291, 64, 64],
[896, 2292, 64, 64],
[854, 2355, 64, 64],
[854, 2292, 64, 64],
[675, 3017, 64, 64],
[622, 3017, 64, 64],
[676, 2965, 64, 64],
[622, 2965, 64, 64],
[1560, 3212, 64, 64],
[1496, 3212, 64, 64],
[1430, 3211, 64, 64],
[1346, 3214, 64, 64],
[1410, 3213, 64, 64],
[1560, 3147, 64, 64],
[1559, 3105, 64, 64],
[1496, 3105, 64, 64],
[1442, 3105, 64, 64],
[1412, 3106, 64, 64],
[918, 4163, 64, 64],
[854, 4161, 64, 64],
[792, 4160, 64, 64],
[729, 4159, 64, 64],
[666, 4158, 64, 64],
[601, 4158, 64, 64],
[537, 4156, 64, 64],
[918, 4137, 64, 64],
[854, 4137, 64, 64],
[789, 4136, 64, 64],
[726, 4137, 64, 64],
[661, 4137, 64, 64],
[599, 4139, 64, 64],
[538, 4137, 64, 64],
[5378, 4254, 64, 64],
[5440, 4204, 64, 64],
[5405, 4214, 64, 64],
[5350, 4254, 64, 64],
[5439, 4177, 64, 64],
[5413, 4173, 64, 64],
[5399, 4128, 64, 64],
[5352, 4200, 64, 64],
[5352, 4158, 64, 64],
[5392, 4130, 64, 64],
[6216, 4251, 64, 64],
[6190, 4251, 64, 64],
[6279, 4200, 64, 64],
[6262, 4205, 64, 64],
[6233, 4214, 64, 64],
[6280, 4172, 64, 64],
[6256, 4169, 64, 64],
[6239, 4128, 64, 64],
[6231, 4128, 64, 64],
[6191, 4195, 64, 64],
[6190, 4158, 64, 64],
[7072, 4250, 64, 64],
[7046, 4250, 64, 64],
[7133, 4202, 64, 64],
[7107, 4209, 64, 64],
[7086, 4214, 64, 64],
[7133, 4173, 64, 64],
[7108, 4169, 64, 64],
[7092, 4127, 64, 64],
[7084, 4128, 64, 64],
[7047, 4191, 64, 64],
[7047, 4156, 64, 64],
[7926, 4252, 64, 64],
[7900, 4253, 64, 64],
[7987, 4202, 64, 64],
[7965, 4209, 64, 64],
[7942, 4216, 64, 64],
[7989, 4174, 64, 64],
[7970, 4170, 64, 64],
[7949, 4126, 64, 64],
[7901, 4196, 64, 64],
[7900, 4159, 64, 64],
[7941, 4130, 64, 64],
[2847, 379, 64, 64],
[2825, 380, 64, 64],
[2845, 317, 64, 64],
[2829, 316, 64, 64],
[2845, 255, 64, 64],
[2830, 257, 64, 64],
[2845, 202, 64, 64],
[2829, 198, 64, 64],
[2770, 169, 64, 64],
[2708, 170, 64, 64],
[2646, 171, 64, 64],
[2582, 171, 64, 64],
[2518, 171, 64, 64],
[2454, 171, 64, 64],
[2391, 172, 64, 64],
[2332, 379, 64, 64],
[2315, 379, 64, 64],
[2334, 316, 64, 64],
[2315, 317, 64, 64],
[2332, 254, 64, 64],
[2314, 254, 64, 64],
[2335, 192, 64, 64],
[2311, 192, 64, 64],
[2846, 142, 64, 64],
[2784, 140, 64, 64],
[2846, 79, 64, 64],
[2847, 41, 64, 64],
[2783, 80, 64, 64],
[2790, 39, 64, 64],
[2727, 41, 64, 64],
[2665, 43, 64, 64],
[2605, 43, 64, 64],
[2543, 44, 64, 64],
[2480, 45, 64, 64],
[2419, 45, 64, 64],
[2357, 44, 64, 64],
[2313, 129, 64, 64],
[2313, 70, 64, 64],
[2314, 40, 64, 64],
[2517, 2385, 64, 64],
[2452, 2385, 64, 64],
[2390, 2386, 64, 64],
[2328, 2386, 64, 64],
[2264, 2386, 64, 64],
[2200, 2386, 64, 64],
[2137, 2387, 64, 64],
[2071, 2385, 64, 64],
[2016, 2389, 64, 64],
[2517, 2341, 64, 64],
[2518, 2316, 64, 64],
[2456, 2316, 64, 64],
[2393, 2316, 64, 64],
[2328, 2317, 64, 64],
[2264, 2316, 64, 64],
[2207, 2318, 64, 64],
[2144, 2317, 64, 64],
[2081, 2316, 64, 64],
[2015, 2342, 64, 64],
[2016, 2315, 64, 64],
[869, 3709, 64, 64],
[819, 3710, 64, 64],
[869, 3658, 64, 64],
[820, 3658, 64, 64],
[0, 0, 64, 64],
[0, 1670, 64, 64],
[6691, 1653, 64, 64],
[1521, 3792, 64, 64],
[0, 5137, 64, 64],
[3898, 2400, 64, 64],
[3835, 2400, 64, 64],
[3771, 2400, 64, 64],
[3708, 2401, 64, 64],
[3646, 2401, 64, 64],
[3587, 2401, 64, 64],
[3530, 2401, 64, 64],
[3897, 2340, 64, 64],
[3897, 2295, 64, 64],
[3834, 2296, 64, 64],
[3773, 2295, 64, 64],
[3710, 2296, 64, 64],
[3656, 2295, 64, 64],
[3593, 2294, 64, 64],
[3527, 2339, 64, 64],
[3531, 2293, 64, 64],
[4152, 2903, 64, 64],
[4155, 2858, 64, 64],
[3942, 1306, 64, 64],
[3942, 1279, 64, 64],
[3879, 1306, 64, 64],
[3881, 1278, 64, 64],
[3819, 1305, 64, 64],
[3819, 1277, 64, 64],
[3756, 1306, 64, 64],
[3756, 1277, 64, 64],
[3694, 1306, 64, 64],
[3695, 1277, 64, 64],
[3631, 1306, 64, 64],
[3632, 1278, 64, 64],
[3565, 1306, 64, 64],
[3567, 1279, 64, 64],
[4432, 1165, 64, 64],
[4408, 1163, 64, 64],
[5123, 1003, 64, 64],
[5065, 1002, 64, 64],
[5042, 1002, 64, 64],
[6020, 1780, 64, 64],
[6020, 1756, 64, 64],
[5959, 1780, 64, 64],
[5959, 1752, 64, 64],
[5897, 1779, 64, 64],
[5899, 1752, 64, 64],
[5836, 1779, 64, 64],
[5836, 1751, 64, 64],
[5776, 1780, 64, 64],
[5776, 1754, 64, 64],
[5717, 1780, 64, 64],
[5716, 1752, 64, 64],
[5658, 1781, 64, 64],
[5658, 1755, 64, 64],
[5640, 1781, 64, 64],
[5640, 1754, 64, 64],
[5832, 2095, 64, 64],
[5782, 2093, 64, 64],
[5832, 2044, 64, 64],
[5777, 2043, 64, 64],
[4847, 2577, 64, 64],
[4795, 2577, 64, 64],
[4846, 2526, 64, 64],
[4794, 2526, 64, 64],
[8390, 923, 64, 64],
[8363, 922, 64, 64],
[7585, 1084, 64, 64],
[7582, 1058, 64, 64],
[7525, 1084, 64, 64],
[7524, 1056, 64, 64],
[7478, 1085, 64, 64],
[7476, 1055, 64, 64],
[7421, 1086, 64, 64],
[7421, 1052, 64, 64],
[7362, 1085, 64, 64],
[7361, 1053, 64, 64],
[7307, 1087, 64, 64],
[7307, 1054, 64, 64],
[7258, 1086, 64, 64],
[7255, 1058, 64, 64],
[7203, 1083, 64, 64],
[7203, 1055, 64, 64],
[7161, 1085, 64, 64],
[7158, 1057, 64, 64],
[7100, 1083, 64, 64],
[7099, 1058, 64, 64],
[7038, 1082, 64, 64],
[7038, 1058, 64, 64],
[6982, 1083, 64, 64],
[6984, 1057, 64, 64],
[0, 0, 64, 64],
[0, 1670, 64, 64],
[6691, 1653, 64, 64],
[1521, 3792, 64, 64],
[0, 5137, 64, 64],
[0, 0, 64, 64],
[0, 1670, 64, 64],
[6691, 1653, 64, 64],
[1521, 3792, 64, 64],
[0, 5137, 64, 64],
[0, 0, 64, 64],
[0, 1670, 64, 64],
[6691, 1653, 64, 64],
[1521, 3792, 64, 64],
[0, 5137, 64, 64],
[8346, 424, 64, 64],
[8407, 376, 64, 64],
[8375, 386, 64, 64],
[8407, 347, 64, 64],
[8388, 343, 64, 64],
[8320, 423, 64, 64],
[8319, 363, 64, 64],
[8368, 303, 64, 64],
[8359, 303, 64, 64],
[8318, 330, 64, 64],
[9369, 425, 64, 64],
[9340, 425, 64, 64],
[9431, 376, 64, 64],
[9414, 382, 64, 64],
[9387, 391, 64, 64],
[9431, 349, 64, 64],
[9412, 344, 64, 64],
[9392, 305, 64, 64],
[9339, 365, 64, 64],
[9341, 333, 64, 64],
[9384, 301, 64, 64],
[7673, 1896, 64, 64],
[7642, 1834, 64, 64],
[7646, 1901, 64, 64],
[4500, 4054, 64, 64],
[4476, 4055, 64, 64],
[4459, 3997, 64, 64],
[76, 5215, 64, 64],
[39, 5217, 64, 64],
]
$mugs = [
[85, 87, 39, 43, "sprites/square-orange.png"],
[958, 1967, 39, 43, "sprites/square-orange.png"],
[2537, 1734, 39, 43, "sprites/square-orange.png"],
[3755, 2464, 39, 43, "sprites/square-orange.png"],
[1548, 3273, 39, 43, "sprites/square-orange.png"],
[2050, 220, 39, 43, "sprites/square-orange.png"],
[854, 297, 39, 43, "sprites/square-orange.png"],
[343, 526, 39, 43, "sprites/square-orange.png"],
[3454, 772, 39, 43, "sprites/square-orange.png"],
[5041, 298, 39, 43, "sprites/square-orange.png"],
[6089, 300, 39, 43, "sprites/square-orange.png"],
[6518, 295, 39, 43, "sprites/square-orange.png"],
[7661, 47, 39, 43, "sprites/square-orange.png"],
[9392, 1125, 39, 43, "sprites/square-orange.png"],
[7298, 1152, 39, 43, "sprites/square-orange.png"],
[5816, 1843, 39, 43, "sprites/square-orange.png"],
[876, 3772, 39, 43, "sprites/square-orange.png"],
[1029, 4667, 39, 43, "sprites/square-orange.png"],
[823, 5324, 39, 43, "sprites/square-orange.png"],
[3251, 5220, 39, 43, "sprites/square-orange.png"],
[4747, 5282, 39, 43, "sprites/square-orange.png"],
[9325, 5178, 39, 43, "sprites/square-orange.png"],
[9635, 4298, 39, 43, "sprites/square-orange.png"],
[7837, 4127, 39, 43, "sprites/square-orange.png"],
[8651, 1971, 39, 43, "sprites/square-orange.png"],
[6892, 2031, 39, 43, "sprites/square-orange.png"],
[4626, 3882, 39, 43, "sprites/square-orange.png"],
[4024, 4554, 39, 43, "sprites/square-orange.png"],
[3925, 3337, 39, 43, "sprites/square-orange.png"],
[5064, 1064, 39, 43, "sprites/square-orange.png"]
]
</code></pre>
<h3 id='----platformer---gorillas-basic---credits-txt'>Platformer - Gorillas Basic - credits.txt</h3>
<pre><code class="language-ruby"># ./samples/99_genre_platformer/gorillas_basic/CREDITS.txt
code: Amir Rajan, https://twitter.com/amirrajan
graphics: Nick Culbertson, https://twitter.com/MobyPixel
</code></pre>
<h3 id='----platformer---gorillas-basic---main-rb'>Platformer - Gorillas Basic - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_platformer/gorillas_basic/app/main.rb
class YouSoBasicGorillas
attr_accessor :outputs, :grid, :state, :inputs
def tick
defaults
render
calc
process_inputs
end
def defaults
outputs.background_color = [33, 32, 87]
state.building_spacing = 1
state.building_room_spacing = 15
state.building_room_width = 10
state.building_room_height = 15
state.building_heights = [4, 4, 6, 8, 15, 20, 18]
state.building_room_sizes = [5, 4, 6, 7]
state.gravity = 0.25
state.first_strike ||= :player_1
state.buildings ||= []
state.holes ||= []
state.player_1_score ||= 0
state.player_2_score ||= 0
state.wind ||= 0
end
def render
render_stage
render_value_insertion
render_gorillas
render_holes
render_banana
render_game_over
render_score
render_wind
end
def render_score
outputs.primitives << [0, 0, 1280, 31, fancy_white].solid
outputs.primitives << [1, 1, 1279, 29].solid
outputs.labels << [ 10, 25, "Score: #{state.player_1_score}", 0, 0, fancy_white]
outputs.labels << [1270, 25, "Score: #{state.player_2_score}", 0, 2, fancy_white]
end
def render_wind
outputs.primitives << [640, 12, state.wind * 500 + state.wind * 10 * rand, 4, 35, 136, 162].solid
outputs.lines << [640, 30, 640, 0, fancy_white]
end
def render_game_over
return unless state.over
outputs.primitives << [grid.rect, 0, 0, 0, 200].solid
outputs.primitives << [640, 370, "Game Over!!", 5, 1, fancy_white].label
if state.winner == :player_1
outputs.primitives << [640, 340, "Player 1 Wins!!", 5, 1, fancy_white].label
else
outputs.primitives << [640, 340, "Player 2 Wins!!", 5, 1, fancy_white].label
end
end
def render_stage
return unless state.stage_generated
return if state.stage_rendered
outputs.static_solids << [grid.rect, 33, 32, 87]
outputs.static_solids << state.buildings.map(&:solids)
state.stage_rendered = true
end
def render_gorilla gorilla, id
return unless gorilla
if state.banana && state.banana.owner == gorilla
animation_index = state.banana.created_at.frame_index(3, 5, false)
end
if !animation_index
outputs.sprites << [gorilla.solid, "sprites/#{id}-idle.png"]
else
outputs.sprites << [gorilla.solid, "sprites/#{id}-#{animation_index}.png"]
end
end
def render_gorillas
render_gorilla state.player_1, :left
render_gorilla state.player_2, :right
end
def render_value_insertion
return if state.banana
return if state.over
if state.current_turn == :player_1_angle
outputs.labels << [ 10, 710, "Angle: #{state.player_1_angle}_", fancy_white]
elsif state.current_turn == :player_1_velocity
outputs.labels << [ 10, 710, "Angle: #{state.player_1_angle}", fancy_white]
outputs.labels << [ 10, 690, "Velocity: #{state.player_1_velocity}_", fancy_white]
elsif state.current_turn == :player_2_angle
outputs.labels << [1120, 710, "Angle: #{state.player_2_angle}_", fancy_white]
elsif state.current_turn == :player_2_velocity
outputs.labels << [1120, 710, "Angle: #{state.player_2_angle}", fancy_white]
outputs.labels << [1120, 690, "Velocity: #{state.player_2_velocity}_", fancy_white]
end
end
def render_banana
return unless state.banana
rotation = state.tick_count.%(360) * 20
rotation *= -1 if state.banana.dx > 0
outputs.sprites << [state.banana.x, state.banana.y, 15, 15, 'sprites/banana.png', rotation]
end
def render_holes
outputs.sprites << state.holes.map do |s|
animation_index = s.created_at.frame_index(7, 3, false)
if animation_index
[s.sprite, [s.sprite.rect, "sprites/explosion#{animation_index}.png" ]]
else
s.sprite
end
end
end
def calc
calc_generate_stage
calc_current_turn
calc_banana
end
def calc_current_turn
return if state.current_turn
state.current_turn = :player_1_angle
state.current_turn = :player_2_angle if state.first_strike == :player_2
end
def calc_generate_stage
return if state.stage_generated
state.buildings << building_prefab(state.building_spacing + -20, *random_building_size)
8.numbers.inject(state.buildings) do |buildings, i|
buildings <<
building_prefab(state.building_spacing +
state.buildings.last.right,
*random_building_size)
end
building_two = state.buildings[1]
state.player_1 = new_player(building_two.x + building_two.w.fdiv(2),
building_two.h)
building_nine = state.buildings[-3]
state.player_2 = new_player(building_nine.x + building_nine.w.fdiv(2),
building_nine.h)
state.stage_generated = true
state.wind = 1.randomize(:ratio, :sign)
end
def new_player x, y
state.new_entity(:gorilla) do |p|
p.x = x - 25
p.y = y
p.solid = [p.x, p.y, 50, 50]
end
end
def calc_banana
return unless state.banana
state.banana.x += state.banana.dx
state.banana.dx += state.wind.fdiv(50)
state.banana.y += state.banana.dy
state.banana.dy -= state.gravity
banana_collision = [state.banana.x, state.banana.y, 10, 10]
if state.player_1 && banana_collision.intersect_rect?(state.player_1.solid)
state.over = true
if state.banana.owner == state.player_2
state.winner = :player_2
else
state.winner = :player_1
end
state.player_2_score += 1
elsif state.player_2 && banana_collision.intersect_rect?(state.player_2.solid)
state.over = true
if state.banana.owner == state.player_2
state.winner = :player_1
else
state.winner = :player_2
end
state.player_1_score += 1
end
if state.over
place_hole
return
end
return if state.holes.any? do |h|
h.sprite.scale_rect(0.8, 0.5, 0.5).intersect_rect? [state.banana.x, state.banana.y, 10, 10]
end
return unless state.banana.y < 0 || state.buildings.any? do |b|
b.rect.intersect_rect? [state.banana.x, state.banana.y, 1, 1]
end
place_hole
end
def place_hole
return unless state.banana
state.holes << state.new_entity(:banana) do |b|
b.sprite = [state.banana.x - 20, state.banana.y - 20, 40, 40, 'sprites/hole.png']
end
state.banana = nil
end
def process_inputs_main
return if state.banana
return if state.over
if inputs.keyboard.key_down.enter
input_execute_turn
elsif inputs.keyboard.key_down.backspace
state.as_hash[state.current_turn] ||= ""
state.as_hash[state.current_turn] = state.as_hash[state.current_turn][0..-2]
elsif inputs.keyboard.key_down.char
state.as_hash[state.current_turn] ||= ""
state.as_hash[state.current_turn] += inputs.keyboard.key_down.char
end
end
def process_inputs_game_over
return unless state.over
return unless inputs.keyboard.key_down.truthy_keys.any?
state.over = false
outputs.static_solids.clear
state.buildings.clear
state.holes.clear
state.stage_generated = false
state.stage_rendered = false
if state.first_strike == :player_1
state.first_strike = :player_2
else
state.first_strike = :player_1
end
end
def process_inputs
process_inputs_main
process_inputs_game_over
end
def input_execute_turn
return if state.banana
if state.current_turn == :player_1_angle && parse_or_clear!(:player_1_angle)
state.current_turn = :player_1_velocity
elsif state.current_turn == :player_1_velocity && parse_or_clear!(:player_1_velocity)
state.current_turn = :player_2_angle
state.banana =
new_banana(state.player_1,
state.player_1.x + 25,
state.player_1.y + 60,
state.player_1_angle,
state.player_1_velocity)
elsif state.current_turn == :player_2_angle && parse_or_clear!(:player_2_angle)
state.current_turn = :player_2_velocity
elsif state.current_turn == :player_2_velocity && parse_or_clear!(:player_2_velocity)
state.current_turn = :player_1_angle
state.banana =
new_banana(state.player_2,
state.player_2.x + 25,
state.player_2.y + 60,
180 - state.player_2_angle,
state.player_2_velocity)
end
if state.banana
state.player_1_angle = nil
state.player_1_velocity = nil
state.player_2_angle = nil
state.player_2_velocity = nil
end
end
def random_building_size
[state.building_heights.sample, state.building_room_sizes.sample]
end
def int? v
v.to_i.to_s == v.to_s
end
def random_building_color
[[ 99, 0, 107],
[ 35, 64, 124],
[ 35, 136, 162],
].sample
end
def random_window_color
[[ 88, 62, 104],
[253, 224, 187]].sample
end
def windows_for_building starting_x, floors, rooms
floors.-(1).combinations(rooms - 1).map do |floor, room|
[starting_x +
state.building_room_width.*(room) +
state.building_room_spacing.*(room + 1),
state.building_room_height.*(floor) +
state.building_room_spacing.*(floor + 1),
state.building_room_width,
state.building_room_height,
random_window_color]
end
end
def building_prefab starting_x, floors, rooms
state.new_entity(:building) do |b|
b.x = starting_x
b.y = 0
b.w = state.building_room_width.*(rooms) +
state.building_room_spacing.*(rooms + 1)
b.h = state.building_room_height.*(floors) +
state.building_room_spacing.*(floors + 1)
b.right = b.x + b.w
b.rect = [b.x, b.y, b.w, b.h]
b.solids = [[b.x - 1, b.y, b.w + 2, b.h + 1, fancy_white],
[b.x, b.y, b.w, b.h, random_building_color],
windows_for_building(b.x, floors, rooms)]
end
end
def parse_or_clear! game_prop
if int? state.as_hash[game_prop]
state.as_hash[game_prop] = state.as_hash[game_prop].to_i
return true
end
state.as_hash[game_prop] = nil
return false
end
def new_banana owner, x, y, angle, velocity
state.new_entity(:banana) do |b|
b.owner = owner
b.x = x
b.y = y
b.angle = angle % 360
b.velocity = velocity / 5
b.dx = b.angle.vector_x(b.velocity)
b.dy = b.angle.vector_y(b.velocity)
end
end
def fancy_white
[253, 252, 253]
end
end
$you_so_basic_gorillas = YouSoBasicGorillas.new
def tick args
$you_so_basic_gorillas.outputs = args.outputs
$you_so_basic_gorillas.grid = args.grid
$you_so_basic_gorillas.state = args.state
$you_so_basic_gorillas.inputs = args.inputs
$you_so_basic_gorillas.tick
end
</code></pre>
<h3 id='----platformer---gorillas-basic---tests-rb'>Platformer - Gorillas Basic - tests.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_platformer/gorillas_basic/app/tests.rb
$gtk.reset 100
$gtk.supress_framerate_warning = true
$gtk.require 'app/tests/building_generation_tests.rb'
$gtk.tests.start
</code></pre>
<h3 id='----platformer---gorillas-basic---tests---building_generation_tests-rb'>Platformer - Gorillas Basic - Tests - building_generation_tests.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_platformer/gorillas_basic/app/tests/building_generation_tests.rb
def test_solids args, assert
game = YouSoBasicGorillas.new
game.outputs = args.outputs
game.grid = args.grid
game.state = args.state
game.inputs = args.inputs
game.tick
assert.true! args.state.stage_generated, "stage wasn't generated but it should have been"
game.tick
assert.true! args.outputs.static_solids.length > 0, "stage wasn't rendered"
number_of_building_components = (args.state.buildings.map { |b| 2 + b.solids[2].length }.inject do |sum, v| (sum || 0) + v end)
the_only_background = 1
static_solids = args.outputs.static_solids.length
assert.true! static_solids == the_only_background.+(number_of_building_components), "not all parts of the buildings and background were rendered"
end
</code></pre>
<h3 id='----platformer---the-little-probe---main-rb'>Platformer - The Little Probe - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_platformer/the_little_probe/app/main.rb
class FallingCircle
attr_gtk
def tick
fiddle
defaults
render
input
calc
end
def fiddle
state.gravity = -0.02
circle.radius = 15
circle.elasticity = 0.4
camera.follow_speed = 0.4 * 0.4
end
def render
render_stage_editor
render_debug
render_game
end
def defaults
if state.tick_count == 0
outputs.sounds << "sounds/bg.ogg"
end
state.storyline ||= [
{ text: "<- -> to aim, hold space to charge", distance_gate: 0 },
{ text: "the little probe - by @amirrajan, made with DragonRuby Game Toolkit", distance_gate: 0 },
{ text: "mission control, this is sasha. landing on europa successful.", distance_gate: 0 },
{ text: "operation \"find earth 2.0\", initiated at 8-29-2036 14:00.", distance_gate: 0 },
{ text: "jupiter's sure is beautiful...", distance_gate: 4000 },
{ text: "hmm, it seems there's some kind of anomoly in the sky", distance_gate: 7000 },
{ text: "dancing lights, i'll call them whisps.", distance_gate: 8000 },
{ text: "#todo... look i ran out of time -_-", distance_gate: 9000 },
{ text: "there's never enough time", distance_gate: 9000 },
{ text: "the game jam was fun though ^_^", distance_gate: 10000 },
]
load_level force: args.state.tick_count == 0
state.line_mode ||= :terrain
state.sound_index ||= 1
circle.potential_lift ||= 0
circle.angle ||= 90
circle.check_point_at ||= -1000
circle.game_over_at ||= -1000
circle.x ||= -485
circle.y ||= 12226
circle.check_point_x ||= circle.x
circle.check_point_y ||= circle.y
circle.dy ||= 0
circle.dx ||= 0
circle.previous_dy ||= 0
circle.previous_dx ||= 0
circle.angle ||= 0
circle.after_images ||= []
circle.terrains_to_monitor ||= {}
circle.impact_history ||= []
camera.x ||= 0
camera.y ||= 0
camera.target_x ||= 0
camera.target_y ||= 0
state.snaps ||= { }
state.snap_number = 10
args.state.storyline_x ||= -1000
args.state.storyline_y ||= -1000
end
def render_game
outputs.background_color = [0, 0, 0]
outputs.sprites << [-circle.x + 1100,
-circle.y - 100,
2416 * 4,
3574 * 4,
'sprites/jupiter.png']
outputs.sprites << [-circle.x,
-circle.y,
2416 * 4,
3574 * 4,
'sprites/level.png']
outputs.sprites << state.whisp_queue
render_aiming_retical
render_circle
render_notification
end
def render_notification
toast_length = 500
if circle.game_over_at.elapsed_time < toast_length
label_text = "..."
elsif circle.check_point_at.elapsed_time > toast_length
args.state.current_storyline = nil
return
end
if circle.check_point_at &&
circle.check_point_at.elapsed_time == 1 &&
!args.state.current_storyline
if args.state.storyline.length > 0 && args.state.distance_traveled > args.state.storyline[0][:distance_gate]
args.state.current_storyline = args.state.storyline.shift[:text]
args.state.distance_traveled ||= 0
args.state.storyline_x = circle.x
args.state.storyline_y = circle.y
end
return unless args.state.current_storyline
end
label_text = args.state.current_storyline
return unless label_text
x = circle.x + camera.x
y = circle.y + camera.y - 40
w = 900
h = 30
outputs.primitives << [x - w.idiv(2), y - h, w, h, 255, 255, 255, 255].solid
outputs.primitives << [x - w.idiv(2), y - h, w, h, 0, 0, 0, 255].border
outputs.labels << [x, y - 4, label_text, 1, 1, 0, 0, 0, 255]
end
def render_aiming_retical
outputs.sprites << [state.camera.x + circle.x + circle.angle.vector_x(circle.potential_lift * 10) - 5,
state.camera.y + circle.y + circle.angle.vector_y(circle.potential_lift * 10) - 5,
10, 10, 'sprites/circle-orange.png']
outputs.sprites << [state.camera.x + circle.x + circle.angle.vector_x(circle.radius * 3) - 5,
state.camera.y + circle.y + circle.angle.vector_y(circle.radius * 3) - 5,
10, 10, 'sprites/circle-orange.png', 0, 128]
if rand > 0.9
outputs.sprites << [state.camera.x + circle.x + circle.angle.vector_x(circle.radius * 3) - 5,
state.camera.y + circle.y + circle.angle.vector_y(circle.radius * 3) - 5,
10, 10, 'sprites/circle-white.png', 0, 128]
end
end
def render_circle
outputs.sprites << circle.after_images.map do |ai|
ai.merge(x: ai.x + state.camera.x - circle.radius,
y: ai.y + state.camera.y - circle.radius,
w: circle.radius * 2,
h: circle.radius * 2,
path: 'sprites/circle-white.png')
end
outputs.sprites << [(circle.x - circle.radius) + state.camera.x,
(circle.y - circle.radius) + state.camera.y,
circle.radius * 2,
circle.radius * 2,
'sprites/probe.png']
end
def render_debug
return unless state.debug_mode
outputs.labels << [10, 30, state.line_mode, 0, 0, 0, 0, 0]
outputs.labels << [12, 32, state.line_mode, 0, 0, 255, 255, 255]
args.outputs.lines << trajectory(circle).line.to_hash.tap do |h|
h[:x] += state.camera.x
h[:y] += state.camera.y
h[:x2] += state.camera.x
h[:y2] += state.camera.y
end
outputs.primitives << state.terrain.find_all do |t|
circle.x.between?(t.x - 640, t.x2 + 640) || circle.y.between?(t.y - 360, t.y2 + 360)
end.map do |t|
[
t.line.associate(r: 0, g: 255, b: 0) do |h|
h.x += state.camera.x
h.y += state.camera.y
h.x2 += state.camera.x
h.y2 += state.camera.y
if circle.rect.intersect_rect? t[:rect]
h[:r] = 255
h[:g] = 0
end
h
end,
t[:rect].border.associate(r: 255, g: 0, b: 0) do |h|
h.x += state.camera.x
h.y += state.camera.y
h.b = 255 if line_near_rect? circle.rect, t
h
end
]
end
outputs.primitives << state.lava.find_all do |t|
circle.x.between?(t.x - 640, t.x2 + 640) || circle.y.between?(t.y - 360, t.y2 + 360)
end.map do |t|
[
t.line.associate(r: 0, g: 0, b: 255) do |h|
h.x += state.camera.x
h.y += state.camera.y
h.x2 += state.camera.x
h.y2 += state.camera.y
if circle.rect.intersect_rect? t[:rect]
h[:r] = 255
h[:b] = 0
end
h
end,
t[:rect].border.associate(r: 255, g: 0, b: 0) do |h|
h.x += state.camera.x
h.y += state.camera.y
h.b = 255 if line_near_rect? circle.rect, t
h
end
]
end
if state.god_mode
border = circle.rect.merge(x: circle.rect.x + state.camera.x,
y: circle.rect.y + state.camera.y,
g: 255)
else
border = circle.rect.merge(x: circle.rect.x + state.camera.x,
y: circle.rect.y + state.camera.y,
b: 255)
end
outputs.borders << border
overlapping ||= {}
circle.impact_history.each do |h|
label_mod = 300
x = (h[:body][:x].-(150).idiv(label_mod)) * label_mod + camera.x
y = (h[:body][:y].+(150).idiv(label_mod)) * label_mod + camera.y
10.times do
if overlapping[x] && overlapping[x][y]
y -= 52
else
break
end
end
overlapping[x] ||= {}
overlapping[x][y] ||= true
outputs.primitives << [x, y - 25, 300, 50, 0, 0, 0, 128].solid
outputs.labels << [x + 10, y + 24, "dy: %.2f" % h[:body][:new_dy], -2, 0, 255, 255, 255]
outputs.labels << [x + 10, y + 9, "dx: %.2f" % h[:body][:new_dx], -2, 0, 255, 255, 255]
outputs.labels << [x + 10, y - 5, " ?: #{h[:body][:new_reason]}", -2, 0, 255, 255, 255]
outputs.labels << [x + 100, y + 24, "angle: %.2f" % h[:impact][:angle], -2, 0, 255, 255, 255]
outputs.labels << [x + 100, y + 9, "m(l): %.2f" % h[:terrain][:slope], -2, 0, 255, 255, 255]
outputs.labels << [x + 100, y - 5, "m(c): %.2f" % h[:body][:slope], -2, 0, 255, 255, 255]
outputs.labels << [x + 200, y + 24, "ray: #{h[:impact][:ray]}", -2, 0, 255, 255, 255]
outputs.labels << [x + 200, y + 9, "nxt: #{h[:impact][:ray_next]}", -2, 0, 255, 255, 255]
outputs.labels << [x + 200, y - 5, "typ: #{h[:impact][:type]}", -2, 0, 255, 255, 255]
end
if circle.floor
outputs.labels << [circle.x + camera.x + 30, circle.y + camera.y + 100, "point: #{circle.floor_point.slice(:x, :y).values}", -2, 0]
outputs.labels << [circle.x + camera.x + 31, circle.y + camera.y + 101, "point: #{circle.floor_point.slice(:x, :y).values}", -2, 0, 255, 255, 255]
outputs.labels << [circle.x + camera.x + 30, circle.y + camera.y + 85, "circle: #{circle.as_hash.slice(:x, :y).values}", -2, 0]
outputs.labels << [circle.x + camera.x + 31, circle.y + camera.y + 86, "circle: #{circle.as_hash.slice(:x, :y).values}", -2, 0, 255, 255, 255]
outputs.labels << [circle.x + camera.x + 30, circle.y + camera.y + 70, "rel: #{circle.floor_relative_x} #{circle.floor_relative_y}", -2, 0]
outputs.labels << [circle.x + camera.x + 31, circle.y + camera.y + 71, "rel: #{circle.floor_relative_x} #{circle.floor_relative_y}", -2, 0, 255, 255, 255]
end
end
def render_stage_editor
return unless state.god_mode
return unless state.point_one
args.lines << [state.point_one, inputs.mouse.point, 0, 255, 255]
end
def trajectory body
[body.x + body.dx,
body.y + body.dy,
body.x + body.dx * 1000,
body.y + body.dy * 1000,
0, 255, 255]
end
def lengthen_line line, num
line = normalize_line(line)
slope = geometry.line_slope(line, replace_infinity: 10).abs
if slope < 2
[line.x - num, line.y, line.x2 + num, line.y2].line.to_hash
else
[line.x, line.y, line.x2, line.y2].line.to_hash
end
end
def normalize_line line
if line.x > line.x2
x = line.x2
y = line.y2
x2 = line.x
y2 = line.y
else
x = line.x
y = line.y
x2 = line.x2
y2 = line.y2
end
[x, y, x2, y2]
end
def rect_for_line line
if line.x > line.x2
x = line.x2
y = line.y2
x2 = line.x
y2 = line.y
else
x = line.x
y = line.y
x2 = line.x2
y2 = line.y2
end
w = x2 - x
h = y2 - y
if h < 0
y += h
h = h.abs
end
if w < circle.radius
x -= circle.radius
w = circle.radius * 2
end
if h < circle.radius
y -= circle.radius
h = circle.radius * 2
end
{ x: x, y: y, w: w, h: h }
end
def snap_to_grid x, y, snaps
snap_number = 10
x = x.to_i
y = y.to_i
x_floor = x.idiv(snap_number) * snap_number
x_mod = x % snap_number
x_ceil = (x.idiv(snap_number) + 1) * snap_number
y_floor = y.idiv(snap_number) * snap_number
y_mod = y % snap_number
y_ceil = (y.idiv(snap_number) + 1) * snap_number
if snaps[x_floor]
x_result = x_floor
elsif snaps[x_ceil]
x_result = x_ceil
elsif x_mod < snap_number.idiv(2)
x_result = x_floor
else
x_result = x_ceil
end
snaps[x_result] ||= {}
if snaps[x_result][y_floor]
y_result = y_floor
elsif snaps[x_result][y_ceil]
y_result = y_ceil
elsif y_mod < snap_number.idiv(2)
y_result = y_floor
else
y_result = y_ceil
end
snaps[x_result][y_result] = true
return [x_result, y_result]
end
def snap_line line
x, y, x2, y2 = line
end
def string_to_line s
x, y, x2, y2 = s.split(',').map(&:to_f)
if x > x2
x2, x = x, x2
y2, y = y, y2
end
x, y = snap_to_grid x, y, state.snaps
x2, y2 = snap_to_grid x2, y2, state.snaps
[x, y, x2, y2].line.to_hash
end
def load_lines file
data = gtk.read_file(file) || ""
data.each_line
.reject { |l| l.strip.length == 0 }
.map { |l| string_to_line l }
.map { |h| h.merge(rect: rect_for_line(h)) }
end
def load_terrain
load_lines 'data/level.txt'
end
def load_lava
load_lines 'data/level_lava.txt'
end
def load_level force: false
if force
state.snaps = {}
state.terrain = load_terrain
state.lava = load_lava
else
state.terrain ||= load_terrain
state.lava ||= load_lava
end
end
def save_lines lines, file
s = lines.map do |l|
"#{l.x1},#{l.y1},#{l.x2},#{l.y2}"
end.join("\n")
gtk.write_file(file, s)
end
def save_level
save_lines(state.terrain, 'level.txt')
save_lines(state.lava, 'level_lava.txt')
load_level force: true
end
def line_near_rect? rect, terrain
geometry.intersect_rect?(rect, terrain[:rect])
end
def point_within_line? point, line
return false if !point
return false if !line
return true
end
def calc_impacts x, dx, y, dy, radius
results = { }
results[:x] = x
results[:y] = y
results[:dx] = x
results[:dy] = y
results[:point] = { x: x, y: y }
results[:rect] = { x: x - radius, y: y - radius, w: radius * 2, h: radius * 2 }
results[:trajectory] = trajectory(results)
results[:impacts] = terrain.find_all { |t| line_near_rect? results[:rect], t }.map do |t|
{
terrain: t,
point: geometry.line_intersect(results[:trajectory], t),
type: :terrain
}
end.reject { |t| !point_within_line? t[:point], t[:terrain] }
results[:impacts] += lava.find_all { |t| line_near_rect? results[:rect], t }.map do |t|
{
terrain: t,
point: geometry.line_intersect(results[:trajectory], t),
type: :lava
}
end.reject { |t| !point_within_line? t[:point], t[:terrain] }
results
end
def calc_potential_impacts
impact_results = calc_impacts circle.x, circle.dx, circle.y, circle.dy, circle.radius
circle.rect = impact_results[:rect]
circle.trajectory = impact_results[:trajectory]
circle.impacts = impact_results[:impacts]
end
def calc_terrains_to_monitor
circle.impact = nil
circle.impacts.each do |i|
circle.terrains_to_monitor[i[:terrain]] ||= {
ray_start: geometry.ray_test(circle, i[:terrain]),
}
circle.terrains_to_monitor[i[:terrain]][:ray_current] = geometry.ray_test(circle, i[:terrain])
if circle.terrains_to_monitor[i[:terrain]][:ray_start] != circle.terrains_to_monitor[i[:terrain]][:ray_current]
if circle.x.between?(i[:terrain].x, i[:terrain].x2) || circle.y.between?(i[:terrain].y, i[:terrain].y2)
circle.impact = i
circle.ray_current = circle.terrains_to_monitor[i[:terrain]][:ray_current]
end
end
end
end
def impact_result body, impact
infinity_alias = 1000
r = {
body: {},
terrain: {},
impact: {}
}
r[:body][:line] = body.trajectory.dup
r[:body][:slope] = geometry.line_slope(body.trajectory, replace_infinity: infinity_alias)
r[:body][:slope_sign] = r[:body][:slope].sign
r[:body][:x] = body.x
r[:body][:y] = body.y
r[:body][:dy] = body.dy
r[:body][:dx] = body.dx
r[:terrain][:line] = impact[:terrain].dup
r[:terrain][:slope] = geometry.line_slope(impact[:terrain], replace_infinity: infinity_alias)
r[:terrain][:slope_sign] = r[:terrain][:slope].sign
r[:impact][:angle] = geometry.angle_between_lines(body.trajectory, impact[:terrain], replace_infinity: infinity_alias)
r[:impact][:point] = { x: impact[:point].x, y: impact[:point].y }
r[:impact][:same_slope_sign] = r[:body][:slope_sign] == r[:terrain][:slope_sign]
r[:impact][:ray] = body.ray_current
r[:body][:new_on_floor] = body.on_floor
r[:body][:new_floor] = r[:terrain][:line]
if r[:impact][:angle].abs < 90 && r[:terrain][:slope].abs < 3
play_sound
r[:body][:new_dy] = r[:body][:dy] * circle.elasticity * -1
r[:body][:new_dx] = r[:body][:dx] * circle.elasticity
r[:impact][:type] = :horizontal
r[:body][:new_reason] = "-"
elsif r[:impact][:angle].abs < 90 && r[:terrain][:slope].abs > 3
play_sound
r[:body][:new_dy] = r[:body][:dy] * 1.1
r[:body][:new_dx] = r[:body][:dx] * -circle.elasticity
r[:impact][:type] = :vertical
r[:body][:new_reason] = "|"
else
play_sound
r[:body][:new_dx] = r[:body][:dx] * -circle.elasticity
r[:body][:new_dy] = r[:body][:dy] * -circle.elasticity
r[:impact][:type] = :slanted
r[:body][:new_reason] = "/"
end
r[:impact][:energy] = r[:body][:new_dx].abs + r[:body][:new_dy].abs
if r[:impact][:energy] <= 0.3 && r[:terrain][:slope].abs < 4
r[:body][:new_dx] = 0
r[:body][:new_dy] = 0
r[:impact][:energy] = 0
r[:body][:new_on_floor] = true
r[:body][:new_floor] = r[:terrain][:line]
r[:body][:new_reason] = "0"
end
r[:impact][:ray_next] = geometry.ray_test({ x: r[:body][:x] - (r[:body][:dx] * 1.1) + r[:body][:new_dx],
y: r[:body][:y] - (r[:body][:dy] * 1.1) + r[:body][:new_dy] + state.gravity },
r[:terrain][:line])
if r[:impact][:ray_next] == r[:impact][:ray]
r[:body][:new_dx] *= -1
r[:body][:new_dy] *= -1
r[:body][:new_reason] = "clip"
end
r
end
def game_over!
circle.x = circle.check_point_x
circle.y = circle.check_point_y
circle.dx = 0
circle.dy = 0
circle.game_over_at = state.tick_count
end
def not_game_over!
impact_history_entry = impact_result circle, circle.impact
circle.impact_history << impact_history_entry
circle.x -= circle.dx * 1.1
circle.y -= circle.dy * 1.1
circle.dx = impact_history_entry[:body][:new_dx]
circle.dy = impact_history_entry[:body][:new_dy]
circle.on_floor = impact_history_entry[:body][:new_on_floor]
if circle.on_floor
circle.check_point_at = state.tick_count
circle.check_point_x = circle.x
circle.check_point_y = circle.y
end
circle.previous_floor = circle.floor || {}
circle.floor = impact_history_entry[:body][:new_floor] || {}
circle.floor_point = impact_history_entry[:impact][:point]
if circle.floor.slice(:x, :y, :x2, :y2) != circle.previous_floor.slice(:x, :y, :x2, :y2)
new_relative_x = if circle.dx > 0
:right
elsif circle.dx < 0
:left
else
nil
end
new_relative_y = if circle.dy > 0
:above
elsif circle.dy < 0
:below
else
nil
end
circle.floor_relative_x = new_relative_x
circle.floor_relative_y = new_relative_y
end
circle.impact = nil
circle.terrains_to_monitor.clear
end
def calc_physics
if args.state.god_mode
calc_potential_impacts
calc_terrains_to_monitor
return
end
if circle.y < -700
game_over
return
end
return if state.game_over
return if circle.on_floor
circle.previous_dy = circle.dy
circle.previous_dx = circle.dx
circle.x += circle.dx
circle.y += circle.dy
args.state.distance_traveled ||= 0
args.state.distance_traveled += circle.dx.abs + circle.dy.abs
circle.dy += state.gravity
calc_potential_impacts
calc_terrains_to_monitor
return unless circle.impact
if circle.impact && circle.impact[:type] == :lava
game_over!
else
not_game_over!
end
end
def input_god_mode
state.debug_mode = !state.debug_mode if inputs.keyboard.key_down.forward_slash
# toggle god mode
if inputs.keyboard.key_down.g
state.god_mode = !state.god_mode
state.potential_lift = 0
circle.floor = nil
circle.floor_point = nil
circle.floor_relative_x = nil
circle.floor_relative_y = nil
circle.impact = nil
circle.terrains_to_monitor.clear
return
end
return unless state.god_mode
circle.x = circle.x.to_i
circle.y = circle.y.to_i
# move god circle
if inputs.keyboard.left || inputs.keyboard.a
circle.x -= 20
elsif inputs.keyboard.right || inputs.keyboard.d || inputs.keyboard.f
circle.x += 20
end
if inputs.keyboard.up || inputs.keyboard.w
circle.y += 20
elsif inputs.keyboard.down || inputs.keyboard.s
circle.y -= 20
end
# delete terrain
if inputs.keyboard.key_down.x
calc_terrains_to_monitor
state.terrain = state.terrain.reject do |t|
t[:rect].intersect_rect? circle.rect
end
state.lava = state.lava.reject do |t|
t[:rect].intersect_rect? circle.rect
end
calc_potential_impacts
save_level
end
# change terrain type
if inputs.keyboard.key_down.l
if state.line_mode == :terrain
state.line_mode = :lava
else
state.line_mode = :terrain
end
end
if inputs.mouse.click && !state.point_one
state.point_one = inputs.mouse.click.point
elsif inputs.mouse.click && state.point_one
l = [*state.point_one, *inputs.mouse.click.point]
l = [l.x - state.camera.x,
l.y - state.camera.y,
l.x2 - state.camera.x,
l.y2 - state.camera.y].line.to_hash
l[:rect] = rect_for_line l
if state.line_mode == :terrain
state.terrain << l
else
state.lava << l
end
save_level
next_x = inputs.mouse.click.point.x - 640
next_y = inputs.mouse.click.point.y - 360
circle.x += next_x
circle.y += next_y
state.point_one = nil
elsif inputs.keyboard.one
state.point_one = [circle.x + camera.x, circle.y+ camera.y]
end
# cancel chain lines
if inputs.keyboard.key_down.nine || inputs.keyboard.key_down.escape || inputs.keyboard.key_up.six || inputs.keyboard.key_up.one
state.point_one = nil
end
end
def play_sound
return if state.sound_debounce > 0
state.sound_debounce = 5
outputs.sounds << "sounds/03#{"%02d" % state.sound_index}.wav"
state.sound_index += 1
if state.sound_index > 21
state.sound_index = 1
end
end
def input_game
if inputs.keyboard.down || inputs.keyboard.space
circle.potential_lift += 0.03
circle.potential_lift = circle.potential_lift.lesser(10)
elsif inputs.keyboard.key_up.down || inputs.keyboard.key_up.space
play_sound
circle.dy += circle.angle.vector_y circle.potential_lift
circle.dx += circle.angle.vector_x circle.potential_lift
if circle.on_floor
if circle.floor_relative_y == :above
circle.y += circle.potential_lift.abs * 2
elsif circle.floor_relative_y == :below
circle.y -= circle.potential_lift.abs * 2
end
end
circle.on_floor = false
circle.potential_lift = 0
circle.terrains_to_monitor.clear
circle.impact_history.clear
circle.impact = nil
calc_physics
end
# aim probe
if inputs.keyboard.right || inputs.keyboard.a
circle.angle -= 2
elsif inputs.keyboard.left || inputs.keyboard.d
circle.angle += 2
end
end
def input
input_god_mode
input_game
end
def calc_camera
state.camera.target_x = 640 - circle.x
state.camera.target_y = 360 - circle.y
xdiff = state.camera.target_x - state.camera.x
ydiff = state.camera.target_y - state.camera.y
state.camera.x += xdiff * camera.follow_speed
state.camera.y += ydiff * camera.follow_speed
end
def calc
state.sound_debounce ||= 0
state.sound_debounce -= 1
state.sound_debounce = 0 if state.sound_debounce < 0
if state.god_mode
circle.dy *= 0.1
circle.dx *= 0.1
end
calc_camera
state.whisp_queue ||= []
if state.tick_count.mod_zero?(4)
state.whisp_queue << {
x: -300,
y: 1400 * rand,
speed: 2.randomize(:ratio) + 3,
w: 20,
h: 20, path: 'sprites/whisp.png',
a: 0,
created_at: state.tick_count,
angle: 0,
r: 100,
g: 128 + 128 * rand,
b: 128 + 128 * rand
}
end
state.whisp_queue.each do |w|
w.x += w[:speed] * 2
w.x -= circle.dx * 0.3
w.y -= w[:speed]
w.y -= circle.dy * 0.3
w.angle += w[:speed]
w.a = w[:created_at].ease(30) * 255
end
state.whisp_queue = state.whisp_queue.reject { |w| w[:x] > 1280 }
if state.tick_count.mod_zero?(2) && (circle.dx != 0 || circle.dy != 0)
circle.after_images << {
x: circle.x,
y: circle.y,
w: circle.radius,
h: circle.radius,
a: 255,
created_at: state.tick_count
}
end
circle.after_images.each do |ai|
ai.a = ai[:created_at].ease(10, :flip) * 255
end
circle.after_images = circle.after_images.reject { |ai| ai[:created_at].elapsed_time > 10 }
calc_physics
end
def circle
state.circle
end
def camera
state.camera
end
def terrain
state.terrain
end
def lava
state.lava
end
end
# $gtk.reset
def tick args
args.outputs.background_color = [0, 0, 0]
if args.inputs.keyboard.r
args.gtk.reset
return
end
# uncomment the line below to slow down the game so you
# can see each tick as it passes
# args.gtk.slowmo! 30
$game ||= FallingCircle.new
$game.args = args
$game.tick
end
def reset
$game = nil
end
</code></pre>
<h3 id='----platformer---the-little-probe---data---level-txt'>Platformer - The Little Probe - Data - level.txt</h3>
<pre><code class="language-ruby"># ./samples/99_genre_platformer/the_little_probe/data/level.txt
640,8840,1180,8840
-60,10220,0,9960
-60,10220,0,10500
0,10500,0,10780
0,10780,40,10900
500,10920,760,10960
300,10560,820,10600
420,10320,700,10300
820,10600,1500,10600
1500,10600,1940,10600
1940,10600,2380,10580
2380,10580,2800,10620
2240,11080,2480,11020
2000,11120,2240,11080
1760,11180,2000,11120
1620,11180,1760,11180
1500,11220,1620,11180
1180,11280,1340,11220
1040,11240,1180,11280
840,11280,1040,11240
640,11280,840,11280
500,11220,640,11280
420,11140,500,11220
240,11100,420,11140
100,11120,240,11100
0,11180,100,11120
-160,11220,0,11180
-260,11240,-160,11220
1340,11220,1500,11220
960,13300,1280,13060
1280,13060,1540,12860
1540,12860,1820,12700
1820,12700,2080,12520
2080,12520,2240,12400
2240,12400,2240,12240
2240,12240,2400,12080
2400,12080,2560,11920
2560,11920,2640,11740
2640,11740,2740,11580
2740,11580,2800,11400
2800,11400,2800,11240
2740,11140,2800,11240
2700,11040,2740,11140
2700,11040,2740,10960
2740,10960,2740,10920
2700,10900,2740,10920
2380,10900,2700,10900
2040,10920,2380,10900
1720,10940,2040,10920
1380,11000,1720,10940
1180,10980,1380,11000
900,10980,1180,10980
760,10960,900,10980
240,10960,500,10920
40,10900,240,10960
0,9700,0,9960
-60,9500,0,9700
-60,9420,-60,9500
-60,9420,-60,9340
-60,9340,-60,9280
-60,9120,-60,9280
-60,8940,-60,9120
-60,8940,-60,8780
-60,8780,0,8700
0,8700,40,8680
40,8680,240,8700
240,8700,360,8780
360,8780,640,8840
1420,8400,1540,8480
1540,8480,1680,8500
1680,8500,1940,8460
1180,8840,1280,8880
1280,8880,1340,8860
1340,8860,1720,8860
1720,8860,1820,8920
1820,8920,1820,9140
1820,9140,1820,9280
1820,9460,1820,9280
1760,9480,1820,9460
1640,9480,1760,9480
1540,9500,1640,9480
1340,9500,1540,9500
1100,9500,1340,9500
1040,9540,1100,9500
960,9540,1040,9540
300,9420,360,9460
240,9440,300,9420
180,9600,240,9440
120,9660,180,9600
100,9820,120,9660
100,9820,120,9860
120,9860,140,9900
140,9900,140,10000
140,10440,180,10540
100,10080,140,10000
100,10080,140,10100
140,10100,140,10440
180,10540,300,10560
2140,9560,2140,9640
2140,9720,2140,9640
1880,9780,2140,9720
1720,9780,1880,9780
1620,9740,1720,9780
1500,9780,1620,9740
1380,9780,1500,9780
1340,9820,1380,9780
1200,9820,1340,9820
1100,9780,1200,9820
900,9780,1100,9780
820,9720,900,9780
540,9720,820,9720
360,9840,540,9720
360,9840,360,9960
360,9960,360,10080
360,10140,360,10080
360,10140,360,10240
360,10240,420,10320
700,10300,820,10280
820,10280,820,10280
820,10280,900,10320
900,10320,1040,10300
1040,10300,1200,10320
1200,10320,1380,10280
1380,10280,1500,10300
1500,10300,1760,10300
2800,10620,2840,10600
2840,10600,2900,10600
2900,10600,3000,10620
3000,10620,3080,10620
3080,10620,3140,10600
3140,10540,3140,10600
3140,10540,3140,10460
3140,10460,3140,10360
3140,10360,3140,10260
3140,10260,3140,10140
3140,10140,3140,10000
3140,10000,3140,9860
3140,9860,3160,9720
3160,9720,3160,9580
3160,9580,3160,9440
3160,9300,3160,9440
3160,9300,3160,9140
3160,9140,3160,8980
3160,8980,3160,8820
3160,8820,3160,8680
3160,8680,3160,8520
1760,10300,1880,10300
660,9500,960,9540
640,9460,660,9500
360,9460,640,9460
-480,10760,-440,10880
-480,11020,-440,10880
-480,11160,-260,11240
-480,11020,-480,11160
-600,11420,-380,11320
-380,11320,-200,11340
-200,11340,0,11340
0,11340,180,11340
960,13420,960,13300
960,13420,960,13520
960,13520,1000,13560
1000,13560,1040,13540
1040,13540,1200,13440
1200,13440,1380,13380
1380,13380,1620,13300
1620,13300,1820,13220
1820,13220,2000,13200
2000,13200,2240,13200
2240,13200,2440,13160
2440,13160,2640,13040
-480,10760,-440,10620
-440,10620,-360,10560
-380,10460,-360,10560
-380,10460,-360,10300
-380,10140,-360,10300
-380,10140,-380,10040
-380,9880,-380,10040
-380,9720,-380,9880
-380,9720,-380,9540
-380,9360,-380,9540
-380,9180,-380,9360
-380,9180,-380,9000
-380,8840,-380,9000
-380,8840,-380,8760
-380,8760,-380,8620
-380,8620,-380,8520
-380,8520,-360,8400
-360,8400,-100,8400
-100,8400,-60,8420
-60,8420,240,8440
240,8440,240,8380
240,8380,500,8440
500,8440,760,8460
760,8460,1000,8400
1000,8400,1180,8420
1180,8420,1420,8400
1940,8460,2140,8420
2140,8420,2200,8520
2200,8680,2200,8520
2140,8840,2200,8680
2140,8840,2140,9020
2140,9100,2140,9020
2140,9200,2140,9100
2140,9200,2200,9320
2200,9320,2200,9440
2140,9560,2200,9440
1880,10300,2200,10280
2200,10280,2480,10260
2480,10260,2700,10240
2700,10240,2840,10180
2840,10180,2900,10060
2900,9860,2900,10060
2900,9640,2900,9860
2900,9640,2900,9500
2900,9460,2900,9500
2740,9460,2900,9460
2700,9460,2740,9460
2700,9360,2700,9460
2700,9320,2700,9360
2600,9320,2700,9320
2600,9260,2600,9320
2600,9200,2600,9260
2480,9120,2600,9200
2440,9080,2480,9120
2380,9080,2440,9080
2320,9060,2380,9080
2320,8860,2320,9060
2320,8860,2380,8840
2380,8840,2480,8860
2480,8860,2600,8840
2600,8840,2740,8840
2740,8840,2840,8800
2840,8800,2900,8700
2900,8600,2900,8700
2900,8480,2900,8600
2900,8380,2900,8480
2900,8380,2900,8260
2900,8260,2900,8140
2900,8140,2900,8020
2900,8020,2900,7900
2900,7820,2900,7900
2900,7820,2900,7740
2900,7660,2900,7740
2900,7560,2900,7660
2900,7460,2900,7560
2900,7460,2900,7360
2900,7260,2900,7360
2840,7160,2900,7260
2800,7080,2840,7160
2700,7100,2800,7080
2560,7120,2700,7100
2400,7100,2560,7120
2320,7100,2400,7100
2140,7100,2320,7100
2040,7080,2140,7100
1940,7080,2040,7080
1820,7140,1940,7080
1680,7140,1820,7140
1540,7140,1680,7140
1420,7220,1540,7140
1280,7220,1380,7220
1140,7200,1280,7220
1000,7220,1140,7200
760,7280,900,7320
540,7220,760,7280
300,7180,540,7220
180,7120,180,7160
40,7140,180,7120
-60,7160,40,7140
-200,7120,-60,7160
180,7160,300,7180
-260,7060,-200,7120
-260,6980,-260,7060
-260,6880,-260,6980
-260,6880,-260,6820
-260,6820,-200,6760
-200,6760,-100,6740
-100,6740,-60,6740
-60,6740,40,6740
40,6740,300,6800
300,6800,420,6760
420,6760,500,6740
500,6740,540,6760
540,6760,540,6760
540,6760,640,6780
640,6660,640,6780
580,6580,640,6660
580,6440,580,6580
580,6440,640,6320
640,6320,640,6180
580,6080,640,6180
580,6080,640,5960
640,5960,640,5840
640,5840,640,5700
640,5700,660,5560
660,5560,660,5440
660,5440,660,5300
660,5140,660,5300
660,5140,660,5000
660,5000,660,4880
660,4880,820,4860
820,4860,1000,4840
1000,4840,1100,4860
1100,4860,1280,4860
1280,4860,1420,4840
1420,4840,1580,4860
1580,4860,1720,4820
1720,4820,1880,4860
1880,4860,2000,4840
2000,4840,2140,4840
2140,4840,2320,4860
2320,4860,2440,4880
2440,4880,2600,4880
2600,4880,2800,4880
2800,4880,2900,4880
2900,4880,2900,4820
2900,4740,2900,4820
2800,4700,2900,4740
2520,4680,2800,4700
2240,4660,2520,4680
1940,4620,2240,4660
1820,4580,1940,4620
1820,4500,1820,4580
1820,4500,1880,4420
1880,4420,2000,4420
2000,4420,2200,4420
2200,4420,2400,4440
2400,4440,2600,4440
2600,4440,2840,4440
2840,4440,2900,4400
2740,4260,2900,4280
2600,4240,2740,4260
2480,4280,2600,4240
2320,4240,2480,4280
2140,4220,2320,4240
1940,4220,2140,4220
1880,4160,1940,4220
1880,4160,1880,4080
1880,4080,2040,4040
2040,4040,2240,4060
2240,4060,2400,4040
2400,4040,2600,4060
2600,4060,2740,4020
2740,4020,2840,3940
2840,3780,2840,3940
2740,3660,2840,3780
2700,3680,2740,3660
2520,3700,2700,3680
2380,3700,2520,3700
2200,3720,2380,3700
2040,3720,2200,3720
1880,3700,2040,3720
1820,3680,1880,3700
1760,3600,1820,3680
1760,3600,1820,3480
1820,3480,1880,3440
1880,3440,1960,3460
1960,3460,2140,3460
2140,3460,2380,3460
2380,3460,2640,3440
2640,3440,2900,3380
2840,3280,2900,3380
2840,3280,2900,3200
2900,3200,2900,3140
2840,3020,2900,3140
2800,2960,2840,3020
2700,3000,2800,2960
2600,2980,2700,3000
2380,3000,2600,2980
2140,3000,2380,3000
1880,3000,2140,3000
1720,3040,1880,3000
1640,2960,1720,3040
1500,2940,1640,2960
1340,3000,1500,2940
1240,3000,1340,3000
1140,3020,1240,3000
1040,3000,1140,3020
960,2960,1040,3000
900,2960,960,2960
840,2840,900,2960
700,2820,840,2840
540,2820,700,2820
420,2820,540,2820
180,2800,420,2820
60,2780,180,2800
-60,2800,60,2780
-160,2760,-60,2800
-260,2740,-160,2760
-300,2640,-260,2740
-360,2560,-300,2640
-380,2460,-360,2560
-380,2460,-300,2380
-300,2300,-300,2380
-300,2300,-300,2220
-300,2100,-300,2220
-300,2100,-300,2040
-300,2040,-160,2040
-160,2040,-60,2040
-60,2040,60,2040
60,2040,180,2040
180,2040,360,2040
360,2040,540,2040
540,2040,700,2080
660,2160,700,2080
660,2160,700,2260
660,2380,700,2260
500,2340,660,2380
360,2340,500,2340
240,2340,360,2340
40,2320,240,2340
-60,2320,40,2320
-100,2380,-60,2320
-100,2380,-100,2460
-100,2460,-100,2540
-100,2540,0,2560
0,2560,140,2600
140,2600,300,2600
300,2600,460,2600
460,2600,640,2600
640,2600,760,2580
760,2580,820,2560
820,2560,820,2500
820,2500,820,2400
820,2400,840,2320
840,2320,840,2240
820,2120,840,2240
820,2020,820,2120
820,1900,820,2020
760,1840,820,1900
640,1840,760,1840
500,1840,640,1840
300,1860,420,1880
180,1840,300,1860
420,1880,500,1840
0,1840,180,1840
-60,1860,0,1840
-160,1840,-60,1860
-200,1800,-160,1840
-260,1760,-200,1800
-260,1680,-260,1760
-260,1620,-260,1680
-260,1540,-260,1620
-260,1540,-260,1460
-300,1420,-260,1460
-300,1420,-300,1340
-300,1340,-260,1260
-260,1260,-260,1160
-260,1060,-260,1160
-260,1060,-260,960
-260,880,-260,960
-260,880,-260,780
-260,780,-260,680
-300,580,-260,680
-300,580,-300,480
-300,480,-260,400
-300,320,-260,400
-300,320,-300,240
-300,240,-200,220
-200,220,-200,160
-200,160,-100,140
-100,140,0,120
0,120,60,120
60,120,180,120
180,120,300,120
300,120,420,140
420,140,580,180
580,180,760,180
760,180,900,180
960,180,1100,180
1100,180,1340,200
1340,200,1580,200
1580,200,1720,180
1720,180,2000,140
2000,140,2240,140
2240,140,2480,140
2520,140,2800,160
2800,160,3000,160
3000,160,3140,160
3140,260,3140,160
3140,260,3140,380
3080,500,3140,380
3080,620,3080,500
3080,620,3080,740
3080,740,3080,840
3080,960,3080,840
3080,1080,3080,960
3080,1080,3080,1200
3080,1200,3080,1340
3080,1340,3080,1460
3080,1580,3080,1460
3080,1700,3080,1580
3080,1700,3080,1760
3080,1760,3200,1760
3200,1760,3320,1760
3320,1760,3520,1760
3520,1760,3680,1740
3680,1740,3780,1700
3780,1700,3840,1620
3840,1620,3840,1520
3840,1520,3840,1420
3840,1320,3840,1420
3840,1120,3840,1320
3840,1120,3840,940
3840,940,3840,760
3780,600,3840,760
3780,600,3780,440
3780,320,3780,440
3780,320,3780,160
3780,60,3780,160
3780,60,4020,60
4020,60,4260,40
4260,40,4500,40
4500,40,4740,40
4740,40,4840,20
4840,20,4880,80
4880,80,5080,40
5080,40,5280,20
5280,20,5500,0
5500,0,5720,0
5720,0,5940,60
5940,60,6240,60
6240,60,6540,20
6540,20,6840,20
6840,20,7040,0
7040,0,7140,0
7140,0,7400,20
7400,20,7680,0
7680,0,7940,0
7940,0,8200,-20
8200,-20,8360,20
8360,20,8560,-40
8560,-40,8760,0
8760,0,8880,40
8880,120,8880,40
8840,220,8840,120
8620,240,8840,220
8420,260,8620,240
8200,280,8420,260
7940,280,8200,280
7760,240,7940,280
7560,220,7760,240
7360,280,7560,220
7140,260,7360,280
6940,240,7140,260
6720,220,6940,240
6480,220,6720,220
6360,300,6480,220
6240,300,6360,300
6200,500,6240,300
6200,500,6360,540
6360,540,6540,520
6540,520,6720,480
6720,480,6880,460
6880,460,7080,500
7080,500,7320,500
7320,500,7680,500
7680,620,7680,500
7520,640,7680,620
7360,640,7520,640
7200,640,7360,640
7040,660,7200,640
6880,720,7040,660
6720,700,6880,720
6540,700,6720,700
6420,760,6540,700
6280,740,6420,760
6240,760,6280,740
6200,920,6240,760
6200,920,6360,960
6360,960,6540,960
6540,960,6720,960
6720,960,6760,980
6760,980,6880,940
6880,940,7080,940
7080,940,7280,940
7280,940,7520,920
7520,920,7760,900
7760,900,7980,860
7980,860,8100,880
8100,880,8280,900
8280,900,8500,820
8500,820,8700,820
8700,820,8760,840
8760,960,8760,840
8700,1040,8760,960
8560,1060,8700,1040
8460,1080,8560,1060
8360,1040,8460,1080
8280,1080,8360,1040
8160,1120,8280,1080
8040,1120,8160,1120
7940,1100,8040,1120
7800,1120,7940,1100
7680,1120,7800,1120
7520,1100,7680,1120
7360,1100,7520,1100
7200,1120,7360,1100
7040,1180,7200,1120
6880,1160,7040,1180
6720,1160,6880,1160
6540,1160,6720,1160
6360,1160,6540,1160
6200,1160,6360,1160
6040,1220,6200,1160
6040,1220,6040,1400
6040,1400,6200,1440
6200,1440,6320,1440
6320,1440,6440,1440
6600,1440,6760,1440
6760,1440,6940,1420
6440,1440,6600,1440
6940,1420,7280,1400
7280,1400,7560,1400
7560,1400,7760,1400
7760,1400,7940,1360
7940,1360,8100,1380
8100,1380,8280,1340
8280,1340,8460,1320
8660,1300,8760,1360
8460,1320,8660,1300
8760,1360,8800,1500
8800,1660,8800,1500
8800,1660,8800,1820
8700,1840,8800,1820
8620,1860,8700,1840
8560,1800,8620,1860
8560,1800,8620,1680
8500,1640,8620,1680
8420,1680,8500,1640
8280,1680,8420,1680
8160,1680,8280,1680
7900,1680,8160,1680
7680,1680,7900,1680
7400,1660,7680,1680
7140,1680,7400,1660
6880,1640,7140,1680
6040,1820,6320,1780
5900,1840,6040,1820
6640,1700,6880,1640
6320,1780,6640,1700
5840,2040,5900,1840
5840,2040,5840,2220
5840,2220,5840,2320
5840,2460,5840,2320
5840,2560,5840,2460
5840,2560,5960,2620
5960,2620,6200,2620
6200,2620,6380,2600
6380,2600,6600,2580
6600,2580,6800,2600
6800,2600,7040,2580
7040,2580,7280,2580
7280,2580,7480,2560
7760,2540,7980,2520
7980,2520,8160,2500
7480,2560,7760,2540
8160,2500,8160,2420
8160,2420,8160,2320
8160,2180,8160,2320
7980,2160,8160,2180
7800,2180,7980,2160
7600,2200,7800,2180
7400,2200,7600,2200
6960,2200,7200,2200
7200,2200,7400,2200
6720,2200,6960,2200
6540,2180,6720,2200
6320,2200,6540,2180
6240,2160,6320,2200
6240,2160,6240,2040
6240,2040,6240,1940
6240,1940,6440,1940
6440,1940,6720,1940
6720,1940,6940,1920
7520,1920,7760,1920
6940,1920,7280,1920
7280,1920,7520,1920
7760,1920,8100,1900
8100,1900,8420,1900
8420,1900,8460,1940
8460,2120,8460,1940
8460,2280,8460,2120
8460,2280,8560,2420
8560,2420,8660,2380
8660,2380,8800,2340
8800,2340,8840,2400
8840,2520,8840,2400
8800,2620,8840,2520
8800,2740,8800,2620
8800,2860,8800,2740
8800,2940,8800,2860
8760,2980,8800,2940
8660,2980,8760,2980
8620,2960,8660,2980
8560,2880,8620,2960
8560,2880,8560,2780
8500,2740,8560,2780
8420,2760,8500,2740
8420,2840,8420,2760
8420,2840,8420,2940
8420,3040,8420,2940
8420,3160,8420,3040
8420,3280,8420,3380
8420,3280,8420,3160
8420,3380,8620,3460
8620,3460,8760,3460
8760,3460,8840,3400
8840,3400,8960,3400
8960,3400,9000,3500
9000,3700,9000,3500
9000,3900,9000,3700
9000,4080,9000,3900
9000,4280,9000,4080
9000,4500,9000,4280
9000,4620,9000,4500
9000,4780,9000,4620
9000,4780,9000,4960
9000,5120,9000,4960
9000,5120,9000,5300
8960,5460,9000,5300
8920,5620,8960,5460
8920,5620,8920,5800
8920,5800,8920,5960
8920,5960,8920,6120
8920,6120,8960,6300
8960,6300,8960,6480
8960,6660,8960,6480
8960,6860,8960,6660
8960,7040,8960,6860
8920,7420,8920,7220
8920,7420,8960,7620
8960,7620,8960,7800
8960,7800,8960,8000
8960,8000,8960,8180
8960,8180,8960,8380
8960,8580,8960,8380
8920,8800,8960,8580
8880,9000,8920,8800
8840,9180,8880,9000
8800,9220,8840,9180
8800,9220,8840,9340
8760,9380,8840,9340
8560,9340,8760,9380
8360,9360,8560,9340
8160,9360,8360,9360
8040,9340,8160,9360
7860,9360,8040,9340
7680,9360,7860,9360
7520,9360,7680,9360
7420,9260,7520,9360
7400,9080,7420,9260
7400,9080,7420,8860
7420,8860,7440,8720
7440,8720,7480,8660
7480,8660,7520,8540
7520,8540,7600,8460
7600,8460,7800,8480
7800,8480,8040,8480
8040,8480,8280,8480
8280,8480,8500,8460
8500,8460,8620,8440
8620,8440,8660,8340
8660,8340,8660,8220
8660,8220,8700,8080
8700,8080,8700,7920
8700,7920,8700,7760
8700,7760,8700,7620
8700,7480,8700,7620
8700,7480,8700,7320
8700,7160,8700,7320
8920,7220,8960,7040
8660,7040,8700,7160
8660,7040,8700,6880
8660,6700,8700,6880
8660,6700,8700,6580
8700,6460,8700,6580
8700,6460,8700,6320
8700,6160,8700,6320
8700,6160,8760,6020
8760,6020,8760,5860
8760,5860,8760,5700
8760,5700,8760,5540
8760,5540,8760,5360
8760,5360,8760,5180
8760,5000,8760,5180
8700,4820,8760,5000
8560,4740,8700,4820
8420,4700,8560,4740
8280,4700,8420,4700
8100,4700,8280,4700
7980,4700,8100,4700
7820,4740,7980,4700
7800,4920,7820,4740
7800,4920,7900,4960
7900,4960,8060,4980
8060,4980,8220,5000
8220,5000,8420,5040
8420,5040,8460,5120
8460,5180,8460,5120
8360,5200,8460,5180
8360,5280,8360,5200
8160,5300,8360,5280
8040,5260,8160,5300
7860,5220,8040,5260
7720,5160,7860,5220
7640,5120,7720,5160
7480,5120,7640,5120
7240,5120,7480,5120
7000,5120,7240,5120
6800,5160,7000,5120
6640,5220,6800,5160
6600,5360,6640,5220
6600,5460,6600,5360
6480,5520,6600,5460
6240,5540,6480,5520
5980,5540,6240,5540
5740,5540,5980,5540
5500,5520,5740,5540
5400,5520,5500,5520
5280,5540,5400,5520
5080,5540,5280,5540
4940,5540,5080,5540
4760,5540,4940,5540
4600,5540,4760,5540
4440,5560,4600,5540
4040,5580,4120,5520
4260,5540,4440,5560
4120,5520,4260,5540
4020,5720,4040,5580
4020,5840,4020,5720
4020,5840,4080,5940
4080,5940,4120,6040
4120,6040,4200,6080
4200,6080,4340,6080
4340,6080,4500,6060
4500,6060,4700,6060
4700,6060,4880,6060
4880,6060,5080,6060
5080,6060,5280,6080
5280,6080,5440,6100
5440,6100,5660,6100
5660,6100,5900,6080
5900,6080,6120,6080
6120,6080,6360,6080
6360,6080,6480,6100
6480,6100,6540,6060
6540,6060,6720,6060
6720,6060,6940,6060
6940,6060,7140,6060
7400,6060,7600,6060
7140,6060,7400,6060
7600,6060,7800,6060
7800,6060,7860,6080
7860,6080,8060,6080
8060,6080,8220,6080
8220,6080,8320,6140
8320,6140,8360,6300
8320,6460,8360,6300
8320,6620,8320,6460
8320,6800,8320,6620
8320,6960,8320,6800
8320,6960,8360,7120
8320,7280,8360,7120
8320,7440,8320,7280
8320,7600,8320,7440
8100,7580,8220,7600
8220,7600,8320,7600
7900,7560,8100,7580
7680,7560,7900,7560
7480,7580,7680,7560
7280,7580,7480,7580
7080,7580,7280,7580
7000,7600,7080,7580
6880,7600,7000,7600
6800,7580,6880,7600
6640,7580,6800,7580
6540,7580,6640,7580
6380,7600,6540,7580
6280,7620,6380,7600
6240,7700,6280,7620
6240,7700,6240,7800
6240,7840,6240,7800
6080,7840,6240,7840
5960,7820,6080,7840
5660,7840,5800,7840
5500,7800,5660,7840
5440,7700,5500,7800
5800,7840,5960,7820
5440,7540,5440,7700
5440,7440,5440,7540
5440,7320,5440,7440
5400,7320,5440,7320
5340,7400,5400,7320
5340,7400,5340,7500
5340,7600,5340,7500
5340,7600,5340,7720
5340,7720,5340,7860
5340,7860,5340,7960
5340,7960,5440,8020
5440,8020,5560,8020
5560,8020,5720,8040
5720,8040,5900,8060
5900,8060,6080,8060
6080,8060,6240,8060
6720,8040,6840,8060
6240,8060,6480,8040
6480,8040,6720,8040
6840,8060,6940,8060
6940,8060,7080,8120
7080,8120,7140,8180
7140,8460,7140,8320
7140,8620,7140,8460
7140,8620,7140,8740
7140,8860,7140,8740
7140,8960,7140,8860
7140,8960,7200,9080
7140,9200,7200,9080
7140,9200,7200,9320
7200,9320,7200,9460
7200,9760,7200,9900
7200,9620,7200,9460
7200,9620,7200,9760
7200,9900,7200,10060
7200,10220,7200,10060
7200,10360,7200,10220
7140,10400,7200,10360
6880,10400,7140,10400
6640,10360,6880,10400
6420,10360,6640,10360
6160,10380,6420,10360
5940,10340,6160,10380
5720,10320,5940,10340
5500,10340,5720,10320
5280,10300,5500,10340
5080,10300,5280,10300
4840,10280,5080,10300
4700,10280,4840,10280
4540,10280,4700,10280
4360,10280,4540,10280
4200,10300,4360,10280
4040,10380,4200,10300
4020,10500,4040,10380
3980,10640,4020,10500
3980,10640,3980,10760
3980,10760,4020,10920
4020,10920,4080,11000
4080,11000,4340,11020
4340,11020,4600,11060
4600,11060,4840,11040
4840,11040,4880,10960
4880,10740,4880,10960
4880,10740,4880,10600
4880,10600,5080,10560
5080,10560,5340,10620
5340,10620,5660,10620
5660,10620,6040,10600
6040,10600,6120,10620
6120,10620,6240,10720
6240,10720,6420,10740
6420,10740,6640,10760
6640,10760,6880,10780
7140,10780,7400,10780
6880,10780,7140,10780
7400,10780,7680,10780
7680,10780,8100,10760
8100,10760,8460,10740
8460,10740,8700,10760
8800,10840,8800,10980
8700,10760,8800,10840
8760,11200,8800,10980
8760,11200,8760,11380
8760,11380,8800,11560
8760,11680,8800,11560
8760,11760,8760,11680
8760,11760,8760,11920
8760,11920,8800,12080
8800,12200,8800,12080
8700,12240,8800,12200
8560,12220,8700,12240
8360,12220,8560,12220
8160,12240,8360,12220
7720,12220,7980,12220
7980,12220,8160,12240
7400,12200,7720,12220
7200,12180,7400,12200
7000,12160,7200,12180
6800,12160,7000,12160
6280,12140,6380,12180
6120,12180,6280,12140
6540,12180,6800,12160
6380,12180,6540,12180
5900,12200,6120,12180
5620,12180,5900,12200
5340,12120,5620,12180
5140,12100,5340,12120
4980,12120,5140,12100
4840,12120,4980,12120
4700,12200,4840,12120
4700,12380,4700,12200
4740,12480,4940,12520
4700,12380,4740,12480
4940,12520,5160,12560
5160,12560,5340,12600
5340,12600,5400,12600
5400,12600,5500,12600
5500,12600,5620,12600
5620,12600,5720,12560
5720,12560,5800,12440
5800,12440,5900,12380
5900,12380,6120,12420
6120,12420,6380,12440
6380,12440,6600,12460
6720,12460,6840,12520
6840,12520,6960,12520
6600,12460,6720,12460
6960,12520,7040,12500
7040,12500,7140,12440
7200,12440,7360,12500
7360,12500,7600,12560
7600,12560,7860,12600
7860,12600,8060,12500
8100,12500,8200,12340
8200,12340,8360,12360
8360,12360,8560,12400
8560,12400,8660,12420
8660,12420,8840,12400
8840,12400,9000,12360
9000,12360,9000,12360
2900,4400,2900,4280
900,7320,1000,7220
2640,13040,2900,12920
2900,12920,3160,12840
3480,12760,3780,12620
3780,12620,4020,12460
4300,12360,4440,12260
4020,12460,4300,12360
3160,12840,3480,12760
4440,12080,4440,12260
4440,12080,4440,11880
4440,11880,4440,11720
4440,11720,4600,11720
4600,11720,4760,11740
4760,11740,4980,11760
4980,11760,5160,11760
5160,11760,5340,11780
6000,11860,6120,11820
5340,11780,5620,11820
5620,11820,6000,11860
6120,11820,6360,11820
6360,11820,6640,11860
6940,11920,7240,11940
7240,11940,7520,11960
7520,11960,7860,11960
7860,11960,8100,11920
8100,11920,8420,11940
8420,11940,8460,11960
8460,11960,8500,11860
8460,11760,8500,11860
8320,11720,8460,11760
8160,11720,8320,11720
7940,11720,8160,11720
7720,11700,7940,11720
7520,11680,7720,11700
7320,11680,7520,11680
7200,11620,7320,11680
7200,11620,7200,11500
7200,11500,7280,11440
7280,11440,7420,11440
7420,11440,7600,11440
7600,11440,7980,11460
7980,11460,8160,11460
8160,11460,8360,11460
8360,11460,8460,11400
8420,11060,8500,11200
8280,11040,8420,11060
8100,11060,8280,11040
8460,11400,8500,11200
7800,11060,8100,11060
7520,11060,7800,11060
7240,11060,7520,11060
6940,11040,7240,11060
6640,11000,6940,11040
6420,10980,6640,11000
6360,11060,6420,10980
6360,11180,6360,11060
6200,11280,6360,11180
5960,11300,6200,11280
5720,11280,5960,11300
5500,11280,5720,11280
4940,11300,5200,11280
4660,11260,4940,11300
4440,11280,4660,11260
4260,11280,4440,11280
4220,11220,4260,11280
4080,11280,4220,11220
3980,11420,4080,11280
3980,11420,4040,11620
4040,11620,4040,11820
3980,11960,4040,11820
3840,12000,3980,11960
3720,11940,3840,12000
3680,11800,3720,11940
3680,11580,3680,11800
3680,11360,3680,11580
3680,11360,3680,11260
3680,11080,3680,11260
3680,11080,3680,10880
3680,10700,3680,10880
3680,10700,3680,10620
3680,10480,3680,10620
3680,10480,3680,10300
3680,10300,3680,10100
3680,10100,3680,9940
3680,9940,3720,9860
3720,9860,3920,9900
3920,9900,4220,9880
4980,9940,5340,9960
4220,9880,4540,9900
4540,9900,4980,9940
5340,9960,5620,9960
5620,9960,5900,9960
5900,9960,6160,10000
6160,10000,6480,10000
6480,10000,6720,10000
6720,10000,6880,9860
6880,9860,6880,9520
6880,9520,6940,9340
6940,9120,6940,9340
6940,9120,6940,8920
6940,8700,6940,8920
6880,8500,6940,8700
6880,8320,6880,8500
7140,8320,7140,8180
6760,8260,6880,8320
6540,8240,6760,8260
6420,8180,6540,8240
6280,8240,6420,8180
6160,8300,6280,8240
6120,8400,6160,8300
6080,8520,6120,8400
5840,8480,6080,8520
5620,8500,5840,8480
5500,8500,5620,8500
5340,8560,5500,8500
5160,8540,5340,8560
4620,8520,4880,8520
4360,8480,4620,8520
4880,8520,5160,8540
4140,8440,4360,8480
3920,8460,4140,8440
3720,8380,3920,8460
3680,8160,3720,8380
3680,8160,3720,7940
3720,7720,3720,7940
3680,7580,3720,7720
3680,7580,3720,7440
3720,7440,3720,7300
3720,7160,3720,7300
3720,7160,3720,7020
3720,7020,3780,6900
3780,6900,4080,6940
4080,6940,4340,6980
4340,6980,4600,6980
4600,6980,4880,6980
4880,6980,5160,6980
5160,6980,5400,7000
5400,7000,5560,7020
5560,7020,5660,7080
5660,7080,5660,7280
5660,7280,5660,7440
5660,7440,5740,7520
5740,7520,5740,7600
5740,7600,5900,7600
5900,7600,6040,7540
6040,7540,6040,7320
6040,7320,6120,7200
6120,7200,6120,7040
6120,7040,6240,7000
6240,7000,6480,7060
6480,7060,6800,7060
6800,7060,7080,7080
7080,7080,7320,7100
7940,7100,7980,6920
7860,6860,7980,6920
7640,6860,7860,6860
7400,6840,7640,6860
7320,7100,7560,7120
7560,7120,7760,7120
7760,7120,7940,7100
7200,6820,7400,6840
7040,6820,7200,6820
6600,6840,6840,6840
6380,6800,6600,6840
6120,6800,6380,6800
5900,6840,6120,6800
5620,6820,5900,6840
5400,6800,5620,6820
5140,6800,5400,6800
4880,6780,5140,6800
4600,6760,4880,6780
4340,6760,4600,6760
4080,6760,4340,6760
3840,6740,4080,6760
3680,6720,3840,6740
3680,6720,3680,6560
3680,6560,3720,6400
3720,6400,3720,6200
3720,6200,3780,6000
3720,5780,3780,6000
3720,5580,3720,5780
3720,5360,3720,5580
3720,5360,3840,5240
3840,5240,4200,5260
4200,5260,4600,5280
4600,5280,4880,5280
4880,5280,5140,5200
5140,5200,5220,5100
5220,5100,5280,4900
5280,4900,5340,4840
5340,4840,5720,4880
6120,4880,6480,4860
6880,4840,7200,4860
6480,4860,6880,4840
7200,4860,7320,4860
7320,4860,7360,4740
7360,4600,7440,4520
7360,4600,7360,4740
7440,4520,7640,4520
7640,4520,7800,4480
7800,4480,7800,4280
7800,4280,7800,4040
7800,4040,7800,3780
7800,3560,7800,3780
7800,3560,7860,3440
7860,3440,8060,3460
8060,3460,8160,3340
8160,3340,8160,3140
8160,3140,8160,2960
8000,2900,8160,2960
7860,2900,8000,2900
7640,2940,7860,2900
7400,2980,7640,2940
7100,2980,7400,2980
6840,3000,7100,2980
5620,2980,5840,2980
5840,2980,6500,3000
6500,3000,6840,3000
5560,2780,5620,2980
5560,2780,5560,2580
5560,2580,5560,2380
5560,2140,5560,2380
5560,2140,5560,1900
5560,1900,5620,1660
5620,1660,5660,1460
5660,1460,5660,1300
5500,1260,5660,1300
5340,1260,5500,1260
4600,1220,4840,1240
4440,1220,4600,1220
4440,1080,4440,1220
4440,1080,4600,1020
5080,1260,5340,1260
4840,1240,5080,1260
4600,1020,4940,1020
4940,1020,5220,1020
5220,1020,5560,960
5560,960,5660,860
5660,740,5660,860
5280,740,5660,740
4940,780,5280,740
4660,760,4940,780
4500,700,4660,760
4500,520,4500,700
4500,520,4700,460
4700,460,5080,440
5440,420,5740,420
5080,440,5440,420
5740,420,5840,360
5800,280,5840,360
5560,280,5800,280
4980,300,5280,320
4360,320,4660,300
4200,360,4360,320
5280,320,5560,280
4660,300,4980,300
4140,480,4200,360
4140,480,4140,640
4140,640,4200,780
4200,780,4200,980
4200,980,4220,1180
4220,1400,4220,1180
4220,1400,4260,1540
4260,1540,4500,1540
4500,1540,4700,1520
4700,1520,4980,1540
5280,1560,5400,1560
4980,1540,5280,1560
5400,1560,5400,1700
5400,1780,5400,1700
5340,1900,5400,1780
5340,2020,5340,1900
5340,2220,5340,2020
5340,2220,5340,2420
5340,2420,5340,2520
5080,2600,5220,2580
5220,2580,5340,2520
4900,2580,5080,2600
4700,2540,4900,2580
4500,2540,4700,2540
4220,2580,4340,2540
4200,2700,4220,2580
4340,2540,4500,2540
3980,2740,4200,2700
3840,2740,3980,2740
3780,2640,3840,2740
3780,2640,3780,2460
3780,2280,3780,2460
3620,2020,3780,2100
3780,2280,3780,2100
3360,2040,3620,2020
3080,2040,3360,2040
2840,2020,3080,2040
2740,1940,2840,2020
2740,1940,2800,1800
2800,1640,2800,1800
2800,1640,2800,1460
2800,1300,2800,1460
2700,1180,2800,1300
2480,1140,2700,1180
1580,1200,1720,1200
2240,1180,2480,1140
1960,1180,2240,1180
1720,1200,1960,1180
1500,1320,1580,1200
1500,1440,1500,1320
1500,1440,1760,1480
1760,1480,1940,1480
1940,1480,2140,1500
2140,1500,2320,1520
2400,1560,2400,1700
2280,1820,2380,1780
2320,1520,2400,1560
2380,1780,2400,1700
2080,1840,2280,1820
1720,1820,2080,1840
1420,1800,1720,1820
1280,1800,1420,1800
1240,1720,1280,1800
1240,1720,1240,1600
1240,1600,1280,1480
1280,1340,1280,1480
1180,1280,1280,1340
1000,1280,1180,1280
760,1280,1000,1280
360,1240,540,1260
180,1220,360,1240
540,1260,760,1280
180,1080,180,1220
180,1080,180,1000
180,1000,360,940
360,940,540,960
540,960,820,980
1100,980,1200,920
820,980,1100,980
6640,11860,6940,11920
5200,11280,5500,11280
4120,7330,4120,7230
4120,7230,4660,7250
4660,7250,4940,7250
4940,7250,5050,7340
5010,7400,5050,7340
4680,7380,5010,7400
4380,7370,4680,7380
4120,7330,4360,7370
4120,7670,4120,7760
4120,7670,4280,7650
4280,7650,4540,7660
4550,7660,4820,7680
4820,7680,4900,7730
4880,7800,4900,7730
4620,7820,4880,7800
4360,7790,4620,7820
4120,7760,4360,7790
6840,6840,7040,6820
5720,4880,6120,4880
1200,920,1340,810
1340,810,1520,790
1520,790,1770,800
2400,790,2600,750
2600,750,2640,520
2520,470,2640,520
2140,470,2520,470
1760,800,2090,800
2080,800,2400,790
1760,450,2140,470
1420,450,1760,450
1180,440,1420,450
900,480,1180,440
640,450,900,480
360,440,620,450
120,430,360,440
0,520,120,430
-20,780,0,520
-20,780,-20,1020
-20,1020,-20,1150
-20,1150,0,1300
0,1470,60,1530
0,1300,0,1470
60,1530,360,1530
360,1530,660,1520
660,1520,980,1520
980,1520,1040,1520
1040,1520,1070,1560
1070,1770,1070,1560
1070,1770,1100,2010
1070,2230,1100,2010
1070,2240,1180,2340
1180,2340,1580,2340
1580,2340,1940,2350
1940,2350,2440,2350
2440,2350,2560,2380
2560,2380,2600,2540
2810,2640,3140,2680
2600,2540,2810,2640
3140,2680,3230,2780
3230,2780,3260,2970
3230,3220,3260,2970
3200,3470,3230,3220
3200,3480,3210,3760
3210,3760,3210,4040
3200,4040,3230,4310
3210,4530,3230,4310
3210,4530,3230,4730
3230,4960,3230,4730
3230,4960,3260,5190
3170,5330,3260,5190
2920,5330,3170,5330
2660,5360,2920,5330
2420,5330,2660,5360
2200,5280,2400,5330
2020,5280,2200,5280
1840,5260,2020,5280
1660,5280,1840,5260
1500,5300,1660,5280
1360,5270,1500,5300
1200,5290,1340,5270
1070,5400,1200,5290
1040,5630,1070,5400
1000,5900,1040,5630
980,6170,1000,5900
980,6280,980,6170
980,6540,980,6280
980,6540,1040,6720
1040,6720,1360,6730
1360,6730,1760,6710
2110,6720,2420,6730
1760,6710,2110,6720
2420,6730,2640,6720
2640,6720,2970,6720
2970,6720,3160,6700
3160,6700,3240,6710
3240,6710,3260,6890
3260,7020,3260,6890
3230,7180,3260,7020
3230,7350,3230,7180
3210,7510,3230,7350
3210,7510,3210,7690
3210,7870,3210,7690
3210,7870,3210,7980
3200,8120,3210,7980
3200,8330,3200,8120
3160,8520,3200,8330
2460,11100,2480,11020
2200,11180,2460,11100
1260,11350,1600,11320
600,11430,930,11400
180,11340,620,11430
1600,11320,1910,11280
1910,11280,2200,11180
923.0029599285435,11398.99893503157,1264.002959928544,11351.99893503157
</code></pre>
<h3 id='----platformer---the-little-probe---data---level_lava-txt'>Platformer - The Little Probe - Data - level_lava.txt</h3>
<pre><code class="language-ruby"># ./samples/99_genre_platformer/the_little_probe/data/level_lava.txt
100,10740,500,10780
500,10780,960,10760
960,10760,1340,10760
1380,10760,1820,10780
1820,10780,2240,10780
2280,10780,2740,10740
2740,10740,3000,10780
3000,10780,3140,11020
-520,8820,-480,9160
-520,8480,-520,8820
-520,8480,-480,8180
-480,8180,-200,8120
-200,8120,100,8220
100,8220,420,8240
420,8240,760,8260
760,8260,1140,8280
1140,8280,1500,8200
1500,8200,1880,8240
1880,8240,2240,8260
2240,8260,2320,8480
2320,8480,2380,8680
2240,8860,2380,8680
2240,9080,2240,8860
2240,9080,2320,9260
2320,9260,2480,9440
2480,9440,2600,9640
2480,9840,2600,9640
2400,10020,2480,9840
2240,10080,2400,10020
1960,10080,2240,10080
1720,10080,1960,10080
1460,10080,1720,10080
1180,10080,1420,10080
900,10080,1180,10080
640,10080,900,10080
640,10080,640,9900
60,10520,100,10740
40,10240,60,10520
40,10240,40,9960
40,9960,40,9680
40,9680,40,9360
40,9360,60,9080
60,9080,100,8860
100,8860,460,9040
460,9040,760,9220
760,9220,1140,9220
1140,9220,1720,9200
-660,11580,-600,11420
-660,11800,-660,11580
-660,12000,-660,11800
-660,12000,-600,12220
-600,12220,-600,12440
-600,12440,-600,12640
-600,11240,-260,11280
-260,11280,100,11240
9000,12360,9020,12400
9020,12620,9020,12400
9020,12840,9020,12620
9020,13060,9020,12840
9020,13060,9020,13240
9020,13240,9020,13420
9020,13420,9020,13600
9020,13600,9020,13780
8880,13900,9020,13780
8560,13800,8880,13900
8220,13780,8560,13800
7860,13760,8220,13780
7640,13780,7860,13760
7360,13800,7640,13780
7100,13800,7360,13800
6540,13760,6800,13780
6800,13780,7100,13800
6280,13760,6540,13760
5760,13760,6280,13760
5220,13780,5760,13760
4700,13760,5220,13780
4200,13740,4700,13760
3680,13720,4200,13740
3140,13700,3680,13720
2600,13680,3140,13700
2040,13940,2600,13680
1640,13940,2040,13940
1200,13960,1640,13940
840,14000,1200,13960
300,13960,840,14000
-200,13900,300,13960
-600,12840,-600,12640
-600,13140,-600,12840
-600,13140,-600,13420
-600,13700,-600,13420
-600,13700,-600,13820
-600,13820,-200,13900
-600,11240,-560,11000
-560,11000,-480,10840
-520,10660,-480,10840
-520,10660,-520,10480
-520,10480,-520,10300
-520,10260,-480,10080
-480,9880,-440,10060
-520,9680,-480,9880
-520,9680,-480,9400
-480,9400,-480,9160
1820,9880,2140,9800
1540,9880,1820,9880
1200,9920,1500,9880
900,9880,1200,9920
640,9900,840,9880
2380,8760,2800,8760
2800,8760,2840,8660
2840,8660,2840,8420
2840,8160,2840,8420
2800,7900,2840,8160
2800,7900,2800,7720
2800,7540,2800,7720
2800,7540,2800,7360
2700,7220,2800,7360
2400,7220,2700,7220
2080,7240,2400,7220
1760,7320,2080,7240
1380,7360,1720,7320
1040,7400,1340,7360
640,7400,1000,7420
300,7380,640,7400
0,7300,240,7380
-300,7180,-60,7300
-380,6860,-360,7180
-380,6880,-360,6700
-360,6700,-260,6540
-260,6540,0,6520
0,6520,240,6640
240,6640,460,6640
460,6640,500,6480
500,6260,500,6480
460,6060,500,6260
460,5860,460,6060
460,5860,500,5640
500,5640,540,5440
540,5440,580,5220
580,5220,580,5000
580,4960,580,4740
580,4740,960,4700
960,4700,1140,4760
1140,4760,1420,4740
1420,4740,1720,4700
1720,4700,2000,4740
2000,4740,2380,4760
2380,4760,2700,4800
1720,4600,1760,4300
1760,4300,2200,4340
2200,4340,2560,4340
2560,4340,2740,4340
2160,12580,2440,12400
1820,12840,2160,12580
1500,13080,1820,12840
1140,13340,1500,13080
1140,13340,1580,13220
2110,13080,2520,13000
2520,13000,2900,12800
1580,13220,2110,13080
2900,12800,3200,12680
3200,12680,3440,12640
3440,12640,3720,12460
3720,12460,4040,12320
4040,12320,4360,12200
4360,11940,4380,12180
4360,11700,4360,11940
4360,11700,4540,11500
4540,11500,4880,11540
6000,11660,6280,11640
5440,11600,5720,11610
5720,11610,6000,11660
6280,11640,6760,11720
6760,11720,7060,11780
7060,11780,7360,11810
7360,11810,7640,11840
7640,11840,8000,11830
8000,11830,8320,11850
8320,11850,8390,11800
8330,11760,8390,11800
8160,11760,8330,11760
7910,11750,8160,11760
7660,11740,7900,11750
7400,11730,7660,11740
7160,11680,7400,11730
7080,11570,7160,11680
7080,11570,7100,11350
7100,11350,7440,11280
7440,11280,7940,11280
7960,11280,8360,11280
5840,11540,6650,11170
4880,11540,5440,11600
3410,11830,3420,11300
3410,11260,3520,10920
3520,10590,3520,10920
3520,10590,3540,10260
3520,9900,3540,10240
3520,9900,3640,9590
3640,9570,4120,9590
4140,9590,4600,9680
4620,9680,5030,9730
5120,9750,5520,9800
5620,9820,6080,9800
6130,9810,6580,9820
6640,9820,6800,9700
6780,9400,6800,9700
6780,9400,6840,9140
6820,8860,6840,9120
6780,8600,6820,8830
6720,8350,6780,8570
6480,8340,6720,8320
6260,8400,6480,8340
6050,8580,6240,8400
5760,8630,6040,8590
5520,8690,5740,8630
5120,8690,5450,8700
4570,8670,5080,8690
4020,8610,4540,8670
3540,8480,4020,8610
3520,8230,3520,8480
3520,7930,3520,8230
3520,7930,3540,7630
3480,7320,3540,7610
3480,7280,3500,7010
3500,6980,3680,6850
3680,6850,4220,6840
4230,6840,4760,6850
4780,6850,5310,6860
5310,6860,5720,6940
5720,6940,5880,7250
5880,7250,5900,7520
100,11240,440,11300
440,11300,760,11330
1480,11280,1840,11230
2200,11130,2360,11090
1840,11230,2200,11130
</code></pre>
<h3 id='----rpg-narrative---choose-your-own-adventure---decision-rb'>Rpg Narrative - Choose Your Own Adventure - decision.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/choose_your_own_adventure/app/decision.rb
# Hey there! Welcome to Four Decisions. Here is how you
# create your decision tree. Remove =being and =end from the text to
# enable the game (just save the file). Change stuff and see what happens!
def game
{
starting_decision: :stormy_night,
decisions: {
stormy_night: {
description: 'It was a dark and stormy night. (storyline located in decision.rb)',
option_one: {
description: 'Go to sleep.',
decision: :nap
},
option_two: {
description: 'Watch a movie.',
decision: :movie
},
option_three: {
description: 'Go outside.',
decision: :go_outside
},
option_four: {
description: 'Get a snack.',
decision: :get_a_snack
}
},
nap: {
description: 'You took a nap. The end.',
option_one: {
description: 'Start over.',
decision: :stormy_night
}
}
}
}
end
</code></pre>
<h3 id='----rpg-narrative---choose-your-own-adventure---main-rb'>Rpg Narrative - Choose Your Own Adventure - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/choose_your_own_adventure/app/main.rb
=begin
Reminders:
- Hashes: Collection of unique keys and their corresponding values. The values can be found
using their keys.
In this sample app, the decisions needed for the game are stored in a hash. In fact, the
decision.rb file contains hashes inside of other hashes!
Each option is a key in the first hash, but also contains a hash (description and
decision being its keys) as its value.
Go into the decision.rb file and take a look before diving into the code below.
- args.outputs.labels: An array. The values generate a label.
The parameters are [X, Y, TEXT, SIZE, ALIGNMENT, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.md.
- args.keyboard.key_down.KEY: Determines if a key is in the down state or pressed down.
For more information about the keyboard, go to mygame/documentation/06-keyboard.md.
- String interpolation: uses #{} syntax; everything between the #{ and the } is evaluated
as Ruby code, and the placeholder is replaced with its corresponding value or result.
=end
# This sample app provides users with a story and multiple decisions that they can choose to make.
# Users can make a decision using their keyboard, and the story will move forward based on user choices.
# The decisions available to users are stored in the decision.rb file.
# We must have access to it for the game to function properly.
GAME_FILE = 'app/decision.rb' # found in app folder
require GAME_FILE # require used to load another file, import class/method definitions
# Instructions are given using labels to users if they have not yet set up their story in the decision.rb file.
# Otherwise, the game is run.
def tick args
if !args.state.loaded && !respond_to?(:game) # if game is not loaded and not responding to game symbol's method
args.labels << [640, 370, 'Hey there! Welcome to Four Decisions.', 0, 1] # a welcome label is shown
args.labels << [640, 340, 'Go to the file called decision.rb and tell me your story.', 0, 1]
elsif respond_to?(:game) # otherwise, if responds to game
args.state.loaded = true
tick_game args # calls tick_game method, runs game
end
if args.state.tick_count.mod_zero? 60 # update every 60 frames
t = args.gtk.ffi_file.mtime GAME_FILE # mtime returns modification time for named file
if t != args.state.mtime
args.state.mtime = t
require GAME_FILE # require used to load file
args.state.game_definition = nil # game definition and decision are empty
args.state.decision_id = nil
end
end
end
# Runs methods needed for game to function properly
# Creates a rectangular border around the screen
def tick_game args
defaults args
args.borders << args.grid.rect
render_decision args
process_inputs args
end
# Sets default values and uses decision.rb file to define game and decision_id
# variable using the starting decision
def defaults args
args.state.game_definition ||= game
args.state.decision_id ||= args.state.game_definition[:starting_decision]
end
# Outputs the possible decision descriptions the user can choose onto the screen
# as well as what key to press on their keyboard to make their decision
def render_decision args
decision = current_decision args
# text is either the value of decision's description key or warning that no description exists
args.labels << [640, 360, decision[:description] || "No definition found for #{args.state.decision_id}. Please update decision.rb.", 0, 1] # uses string interpolation
# All decisions are stored in a hash
# The descriptions output onto the screen are the values for the description keys of the hash.
if decision[:option_one]
args.labels << [10, 360, decision[:option_one][:description], 0, 0] # option one's description label
args.labels << [10, 335, "(Press 'left' on the keyboard to select this decision)", -5, 0] # label of what key to press to select the decision
end
if decision[:option_two]
args.labels << [1270, 360, decision[:option_two][:description], 0, 2] # option two's description
args.labels << [1270, 335, "(Press 'right' on the keyboard to select this decision)", -5, 2]
end
if decision[:option_three]
args.labels << [640, 45, decision[:option_three][:description], 0, 1] # option three's description
args.labels << [640, 20, "(Press 'down' on the keyboard to select this decision)", -5, 1]
end
if decision[:option_four]
args.labels << [640, 700, decision[:option_four][:description], 0, 1] # option four's description
args.labels << [640, 675, "(Press 'up' on the keyboard to select this decision)", -5, 1]
end
end
# Uses keyboard input from the user to make a decision
# Assigns the decision as the value of the decision_id variable
def process_inputs args
decision = current_decision args # calls current_decision method
if args.keyboard.key_down.left! && decision[:option_one] # if left key pressed and option one exists
args.state.decision_id = decision[:option_one][:decision] # value of option one's decision hash key is set to decision_id
end
if args.keyboard.key_down.right! && decision[:option_two] # if right key pressed and option two exists
args.state.decision_id = decision[:option_two][:decision] # value of option two's decision hash key is set to decision_id
end
if args.keyboard.key_down.down! && decision[:option_three] # if down key pressed and option three exists
args.state.decision_id = decision[:option_three][:decision] # value of option three's decision hash key is set to decision_id
end
if args.keyboard.key_down.up! && decision[:option_four] # if up key pressed and option four exists
args.state.decision_id = decision[:option_four][:decision] # value of option four's decision hash key is set to decision_id
end
end
# Uses decision_id's value to keep track of current decision being made
def current_decision args
args.state.game_definition[:decisions][args.state.decision_id] || {} # either has value or is empty
end
# Resets the game.
$gtk.reset
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---lowrez_simulator-rb'>Rpg Narrative - Return Of Serenity - lowrez_simulator.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/lowrez_simulator.rb
###################################################################################
# YOU CAN PLAY AROUND WITH THE CODE BELOW, BUT USE CAUTION AS THIS IS WHAT EMULATES
# THE 64x64 CANVAS.
###################################################################################
TINY_RESOLUTION = 64
TINY_SCALE = 720.fdiv(TINY_RESOLUTION + 5)
CENTER_OFFSET = 10
EMULATED_FONT_SIZE = 20
EMULATED_FONT_X_ZERO = 0
EMULATED_FONT_Y_ZERO = 46
def tick args
sprites = []
labels = []
borders = []
solids = []
mouse = emulate_lowrez_mouse args
args.state.show_gridlines = false
lowrez_tick args, sprites, labels, borders, solids, mouse
render_gridlines_if_needed args
render_mouse_crosshairs args, mouse
emulate_lowrez_scene args, sprites, labels, borders, solids, mouse
end
def emulate_lowrez_mouse args
args.state.new_entity_strict(:lowrez_mouse) do |m|
m.x = args.mouse.x.idiv(TINY_SCALE) - CENTER_OFFSET.idiv(TINY_SCALE) - 1
m.y = args.mouse.y.idiv(TINY_SCALE)
if args.mouse.click
m.click = [
args.mouse.click.point.x.idiv(TINY_SCALE) - CENTER_OFFSET.idiv(TINY_SCALE) - 1,
args.mouse.click.point.y.idiv(TINY_SCALE)
]
m.down = m.click
else
m.click = nil
m.down = nil
end
if args.mouse.up
m.up = [
args.mouse.up.point.x.idiv(TINY_SCALE) - CENTER_OFFSET.idiv(TINY_SCALE) - 1,
args.mouse.up.point.y.idiv(TINY_SCALE)
]
else
m.up = nil
end
end
end
def render_mouse_crosshairs args, mouse
return unless args.state.show_gridlines
args.labels << [10, 25, "mouse: #{mouse.x} #{mouse.y}", 255, 255, 255]
end
def emulate_lowrez_scene args, sprites, labels, borders, solids, mouse
args.render_target(:lowrez).solids << [0, 0, 1280, 720]
args.render_target(:lowrez).sprites << sprites
args.render_target(:lowrez).borders << borders
args.render_target(:lowrez).solids << solids
args.outputs.primitives << labels.map do |l|
as_label = l.label
l.text.each_char.each_with_index.map do |char, i|
[CENTER_OFFSET + EMULATED_FONT_X_ZERO + (as_label.x * TINY_SCALE) + i * 5 * TINY_SCALE,
EMULATED_FONT_Y_ZERO + (as_label.y * TINY_SCALE), char,
EMULATED_FONT_SIZE, 0, as_label.r, as_label.g, as_label.b, as_label.a, 'fonts/dragonruby-gtk-4x4.ttf'].label
end
end
args.sprites << [CENTER_OFFSET, 0, 1280 * TINY_SCALE, 720 * TINY_SCALE, :lowrez]
end
def render_gridlines_if_needed args
if args.state.show_gridlines && args.static_lines.length == 0
args.static_lines << 65.times.map do |i|
[
[CENTER_OFFSET + i * TINY_SCALE + 1, 0,
CENTER_OFFSET + i * TINY_SCALE + 1, 720, 128, 128, 128],
[CENTER_OFFSET + i * TINY_SCALE, 0,
CENTER_OFFSET + i * TINY_SCALE, 720, 128, 128, 128],
[CENTER_OFFSET, 0 + i * TINY_SCALE,
CENTER_OFFSET + 720, 0 + i * TINY_SCALE, 128, 128, 128],
[CENTER_OFFSET, 1 + i * TINY_SCALE,
CENTER_OFFSET + 720, 1 + i * TINY_SCALE, 128, 128, 128]
]
end
elsif !args.state.show_gridlines
args.static_lines.clear
end
end
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---main-rb'>Rpg Narrative - Return Of Serenity - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/main.rb
require 'app/require.rb'
def defaults args
args.outputs.background_color = [0, 0, 0]
args.state.last_story_line_text ||= ""
args.state.scene_history ||= []
args.state.storyline_history ||= []
args.state.word_delay ||= 8
if args.state.tick_count == 0
args.gtk.stop_music
args.outputs.sounds << 'sounds/static-loop.ogg'
end
if args.state.last_story_line_text
lines = args.state
.last_story_line_text
.gsub("-", "")
.gsub("~", "")
.wrapped_lines(50)
args.outputs.labels << lines.map_with_index { |l, i| [690, 200 - (i * 25), l, 1, 0, 255, 255, 255] }
elsif args.state.storyline_history[-1]
lines = args.state
.storyline_history[-1]
.gsub("-", "")
.gsub("~", "")
.wrapped_lines(50)
args.outputs.labels << lines.map_with_index { |l, i| [690, 200 - (i * 25), l, 1, 0, 255, 255, 255] }
end
return if args.state.current_scene
set_scene(args, day_one_beginning(args))
end
def inputs_move_player args
if args.state.scene_changed_at.elapsed_time > 5
if args.keyboard.down || args.keyboard.s || args.keyboard.j
args.state.player.y -= 0.25
elsif args.keyboard.up || args.keyboard.w || args.keyboard.k
args.state.player.y += 0.25
end
if args.keyboard.left || args.keyboard.a || args.keyboard.h
args.state.player.x -= 0.25
elsif args.keyboard.right || args.keyboard.d || args.keyboard.l
args.state.player.x += 0.25
end
args.state.player.y = 60 if args.state.player.y > 63
args.state.player.y = 0 if args.state.player.y < -3
args.state.player.x = 60 if args.state.player.x > 63
args.state.player.x = 0 if args.state.player.x < -3
end
end
def null_or_empty? ary
return true unless ary
return true if ary.length == 0
return false
end
def calc_storyline_hotspot args
hotspots = args.state.storylines.find_all do |hs|
args.state.player.inside_rect?(hs.shift_rect(-2, 0))
end
if !null_or_empty?(hotspots) && !args.state.inside_storyline_hotspot
_, _, _, _, storyline = hotspots.first
queue_storyline_text(args, storyline)
args.state.inside_storyline_hotspot = true
elsif null_or_empty?(hotspots)
args.state.inside_storyline_hotspot = false
args.state.storyline_queue_empty_at ||= args.state.tick_count
args.state.is_storyline_dialog_active = false
args.state.scene_storyline_queue.clear
end
end
def calc_scenes args
hotspots = args.state.scenes.find_all do |hs|
args.state.player.inside_rect?(hs.shift_rect(-2, 0))
end
if !null_or_empty?(hotspots) && !args.state.inside_scene_hotspot
_, _, _, _, scene_method_or_hash = hotspots.first
if scene_method_or_hash.is_a? Symbol
set_scene(args, send(scene_method_or_hash, args))
args.state.last_hotspot_scene = scene_method_or_hash
args.state.scene_history << scene_method_or_hash
else
set_scene(args, scene_method_or_hash)
end
args.state.inside_scene_hotspot = true
elsif null_or_empty?(hotspots)
args.state.inside_scene_hotspot = false
end
end
def null_or_whitespace? word
return true if !word
return true if word.strip.length == 0
return false
end
def calc_storyline_presentation args
return unless args.state.tick_count > args.state.next_storyline
return unless args.state.scene_storyline_queue
next_storyline = args.state.scene_storyline_queue.shift
if null_or_whitespace? next_storyline
args.state.storyline_queue_empty_at ||= args.state.tick_count
args.state.is_storyline_dialog_active = false
return
end
args.state.storyline_to_show = next_storyline
args.state.is_storyline_dialog_active = true
args.state.storyline_queue_empty_at = nil
if next_storyline.end_with?(".") || next_storyline.end_with?("!") || next_storyline.end_with?("?") || next_storyline.end_with?("\"")
args.state.next_storyline += 60
elsif next_storyline.end_with?(",")
args.state.next_storyline += 50
elsif next_storyline.end_with?(":")
args.state.next_storyline += 60
else
default_word_delay = 13 + args.state.word_delay - 8
if next_storyline.gsub("-", "").gsub("~", "").length <= 4
default_word_delay = 11 + args.state.word_delay - 8
end
number_of_syllabals = next_storyline.length - next_storyline.gsub("-", "").length
args.state.next_storyline += default_word_delay + number_of_syllabals * (args.state.word_delay + 1)
end
end
def inputs_reload_current_scene args
return
if args.inputs.keyboard.key_down.r!
reload_current_scene
end
end
def inputs_dismiss_current_storyline args
if args.inputs.keyboard.key_down.x!
args.state.scene_storyline_queue.clear
end
end
def inputs_restart_game args
if args.inputs.keyboard.exclamation_point
args.gtk.reset_state
end
end
def inputs_change_word_delay args
if args.inputs.keyboard.key_down.plus || args.inputs.keyboard.key_down.equal_sign
args.state.word_delay -= 2
if args.state.word_delay < 0
args.state.word_delay = 0
# queue_storyline_text args, "Text speed at MAXIMUM. Geez, how fast do you read?"
else
# queue_storyline_text args, "Text speed INCREASED."
end
end
if args.inputs.keyboard.key_down.hyphen || args.inputs.keyboard.key_down.underscore
args.state.word_delay += 2
# queue_storyline_text args, "Text speed DECREASED."
end
end
def multiple_lines args, x, y, texts, size = 0, minimum_alpha = nil
texts.each_with_index.map do |t, i|
[x, y - i * (25 + size * 2), t, size, 0, 255, 255, 255, adornments_alpha(args, 255, minimum_alpha)]
end
end
def lowrez_tick args, lowrez_sprites, lowrez_labels, lowrez_borders, lowrez_solids, lowrez_mouse
# args.state.show_gridlines = true
defaults args
render_current_scene args, lowrez_sprites, lowrez_labels, lowrez_solids
render_controller args, lowrez_borders
lowrez_solids << [0, 0, 64, 64, 0, 0, 0]
calc_storyline_presentation args
calc_scenes args
calc_storyline_hotspot args
inputs_move_player args
inputs_print_mouse_rect args, lowrez_mouse
inputs_reload_current_scene args
inputs_dismiss_current_storyline args
inputs_change_word_delay args
inputs_restart_game args
end
def render_controller args, lowrez_borders
args.state.up_button = [85, 40, 15, 15, 255, 255, 255]
args.state.down_button = [85, 20, 15, 15, 255, 255, 255]
args.state.left_button = [65, 20, 15, 15, 255, 255, 255]
args.state.right_button = [105, 20, 15, 15, 255, 255, 255]
lowrez_borders << args.state.up_button
lowrez_borders << args.state.down_button
lowrez_borders << args.state.left_button
lowrez_borders << args.state.right_button
end
def inputs_print_mouse_rect args, lowrez_mouse
if lowrez_mouse.up
args.state.mouse_held = false
elsif lowrez_mouse.click
mouse_rect = [lowrez_mouse.x, lowrez_mouse.y, 1, 1]
if args.state.up_button.intersect_rect? mouse_rect
args.state.player.y += 1
end
if args.state.down_button.intersect_rect? mouse_rect
args.state.player.y -= 1
end
if args.state.left_button.intersect_rect? mouse_rect
args.state.player.x -= 1
end
if args.state.right_button.intersect_rect? mouse_rect
args.state.player.x += 1
end
args.state.mouse_held = true
elsif args.state.mouse_held
mouse_rect = [lowrez_mouse.x, lowrez_mouse.y, 1, 1]
if args.state.up_button.intersect_rect? mouse_rect
args.state.player.y += 0.25
end
if args.state.down_button.intersect_rect? mouse_rect
args.state.player.y -= 0.25
end
if args.state.left_button.intersect_rect? mouse_rect
args.state.player.x -= 0.25
end
if args.state.right_button.intersect_rect? mouse_rect
args.state.player.x += 0.25
end
end
if lowrez_mouse.click
dx = lowrez_mouse.click.x - args.state.previous_mouse_click.x
dy = lowrez_mouse.click.y - args.state.previous_mouse_click.y
x, y, w, h = args.state.previous_mouse_click.x, args.state.previous_mouse_click.y, dx, dy
puts "x #{lowrez_mouse.click.x}, y: #{lowrez_mouse.click.y}"
if args.state.previous_mouse_click
if dx < 0 && dx < 0
x = x + w
w = w.abs
y = y + h
h = h.abs
end
w += 1
h += 1
args.state.previous_mouse_click = nil
else
args.state.previous_mouse_click = lowrez_mouse.click
square_x, square_y = lowrez_mouse.click
end
end
end
def try_centering! word
word ||= ""
just_word = word.gsub("-", "").gsub(",", "").gsub(".", "").gsub("'", "").gsub('""', "\"-\"")
return word if just_word.strip.length == 0
return word if just_word.include? "~"
return "~#{word}" if just_word.length <= 2
if just_word.length.mod_zero? 2
center_index = just_word.length.idiv(2) - 1
else
center_index = (just_word.length - 1).idiv(2)
end
return "#{word[0..center_index - 1]}~#{word[center_index]}#{word[center_index + 1..-1]}"
end
def queue_storyline args, scene
queue_storyline_text args, scene[:storyline]
end
def queue_storyline_text args, text
args.state.last_story_line_text = text
args.state.storyline_history << text if text
words = (text || "").split(" ")
words = words.map { |w| try_centering! w }
args.state.scene_storyline_queue = words
if args.state.scene_storyline_queue.length != 0
args.state.scene_storyline_queue.unshift "~$--"
args.state.storyline_to_show = "~."
else
args.state.storyline_to_show = ""
end
args.state.scene_storyline_queue << ""
args.state.next_storyline = args.state.tick_count
end
def set_scene args, scene
args.state.current_scene = scene
args.state.background = scene[:background] || 'sprites/todo.png'
args.state.scene_fade = scene[:fade] || 0
args.state.scenes = (scene[:scenes] || []).reject { |s| !s }
args.state.scene_render_override = scene[:render_override]
args.state.storylines = (scene[:storylines] || []).reject { |s| !s }
args.state.scene_changed_at = args.state.tick_count
if scene[:player]
args.state.player = scene[:player]
end
args.state.inside_scene_hotspot = false
args.state.inside_storyline_hotspot = false
queue_storyline args, scene
end
def replay_storyline_rect
[26, -1, 7, 4]
end
def labels_for_word word
left_side_of_word = ""
center_letter = ""
right_side_of_word = ""
if word[0] == "~"
left_side_of_word = ""
center_letter = word[1]
right_side_of_word = word[2..-1]
elsif word.length > 0
left_side_of_word, right_side_of_word = word.split("~")
center_letter = right_side_of_word[0]
right_side_of_word = right_side_of_word[1..-1]
end
right_side_of_word = right_side_of_word.gsub("-", "")
{
left: [29 - left_side_of_word.length * 4 - 1 * left_side_of_word.length, 2, left_side_of_word],
center: [29, 2, center_letter, 255, 0, 0],
right: [34, 2, right_side_of_word]
}
end
def render_scenes args, lowrez_sprites
lowrez_sprites << args.state.scenes.flat_map do |hs|
hotspot_square args, hs.x, hs.y, hs.w, hs.h
end
end
def render_storylines args, lowrez_sprites
lowrez_sprites << args.state.storylines.flat_map do |hs|
hotspot_square args, hs.x, hs.y, hs.w, hs.h
end
end
def adornments_alpha args, target_alpha = nil, minimum_alpha = nil
return (minimum_alpha || 80) unless args.state.storyline_queue_empty_at
target_alpha ||= 255
target_alpha * args.state.storyline_queue_empty_at.ease(60)
end
def hotspot_square args, x, y, w, h
if w >= 3 && h >= 3
[
[x + w.idiv(2) + 1, y, w.idiv(2), h, 'sprites/label-background.png', 0, adornments_alpha(args, 50), 23, 23, 23],
[x, y, w.idiv(2), h, 'sprites/label-background.png', 0, adornments_alpha(args, 100), 223, 223, 223],
[x + 1, y + 1, w - 2, h - 2, 'sprites/label-background.png', 0, adornments_alpha(args, 200), 40, 140, 40],
]
else
[
[x, y, w, h, 'sprites/label-background.png', 0, adornments_alpha(args, 200), 0, 140, 0],
]
end
end
def render_storyline_dialog args, lowrez_labels, lowrez_sprites
return unless args.state.is_storyline_dialog_active
return unless args.state.storyline_to_show
labels = labels_for_word args.state.storyline_to_show
if true # high rez version
scale = 8.88
offset = 45
size = 25
args.outputs.labels << [offset + labels[:left].x.-(1) * scale,
labels[:left].y * TINY_SCALE + 55,
labels[:left].text, size, 0, 0, 0, 0, 255,
'fonts/manaspc.ttf']
center_text = labels[:center].text
center_text = "|" if center_text == "$"
args.outputs.labels << [offset + labels[:center].x * scale,
labels[:center].y * TINY_SCALE + 55,
center_text, size, 0, 255, 0, 0, 255,
'fonts/manaspc.ttf']
args.outputs.labels << [offset + labels[:right].x * scale,
labels[:right].y * TINY_SCALE + 55,
labels[:right].text, size, 0, 0, 0, 0, 255,
'fonts/manaspc.ttf']
else
lowrez_labels << labels[:left]
lowrez_labels << labels[:center]
lowrez_labels << labels[:right]
end
args.state.is_storyline_dialog_active = true
render_player args, lowrez_sprites
lowrez_sprites << [0, 0, 64, 8, 'sprites/label-background.png']
end
def render_player args, lowrez_sprites
lowrez_sprites << player_md_down(args, *args.state.player)
end
def render_adornments args, lowrez_sprites
render_scenes args, lowrez_sprites
render_storylines args, lowrez_sprites
return if args.state.is_storyline_dialog_active
lowrez_sprites << player_md_down(args, *args.state.player)
end
def global_alpha_percentage args, max_alpha = 255
return 255 unless args.state.scene_changed_at
return 255 unless args.state.scene_fade
return 255 unless args.state.scene_fade > 0
return max_alpha * args.state.scene_changed_at.ease(args.state.scene_fade)
end
def render_current_scene args, lowrez_sprites, lowrez_labels, lowrez_solids
lowrez_sprites << [0, 0, 64, 64, args.state.background, 0, (global_alpha_percentage args)]
if args.state.scene_render_override
send args.state.scene_render_override, args, lowrez_sprites, lowrez_labels, lowrez_solids
end
storyline_to_show = args.state.storyline_to_show || ""
render_adornments args, lowrez_sprites
render_storyline_dialog args, lowrez_labels, lowrez_sprites
if args.state.background == 'sprites/tribute-game-over.png'
lowrez_sprites << [0, 0, 64, 11, 'sprites/label-background.png', 0, adornments_alpha(args, 200), 0, 0, 0]
lowrez_labels << [9, 6, 'Return of', 255, 255, 255]
lowrez_labels << [9, 1, ' Serenity', 255, 255, 255]
if !args.state.ended
args.gtk.stop_music
args.outputs.sounds << 'sounds/music-loop.ogg'
args.state.ended = true
end
end
end
def player_md_right args, x, y
[x, y, 4, 11, 'sprites/player-right.png', 0, (global_alpha_percentage args)]
end
def player_md_left args, x, y
[x, y, 4, 11, 'sprites/player-left.png', 0, (global_alpha_percentage args)]
end
def player_md_up args, x, y
[x, y, 4, 11, 'sprites/player-up.png', 0, (global_alpha_percentage args)]
end
def player_md_down args, x, y
[x, y, 4, 11, 'sprites/player-down.png', 0, (global_alpha_percentage args)]
end
def player_sm args, x, y
[x, y, 3, 7, 'sprites/player-zoomed-out.png', 0, (global_alpha_percentage args)]
end
def player_xs args, x, y
[x, y, 1, 4, 'sprites/player-zoomed-out.png', 0, (global_alpha_percentage args)]
end
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---require-rb'>Rpg Narrative - Return Of Serenity - require.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/require.rb
require 'app/lowrez_simulator.rb'
require 'app/storyline_day_one.rb'
require 'app/storyline_blinking_light.rb'
require 'app/storyline_serenity_introduction.rb'
require 'app/storyline_speed_of_light.rb'
require 'app/storyline_serenity_alive.rb'
require 'app/storyline_serenity_bio.rb'
require 'app/storyline_anka.rb'
require 'app/storyline_final_message.rb'
require 'app/storyline_final_decision.rb'
require 'app/storyline.rb'
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---storyline-rb'>Rpg Narrative - Return Of Serenity - storyline.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/storyline.rb
def hotspot_top
[4, 61, 56, 3]
end
def hotspot_bottom
[4, 0, 56, 3]
end
def hotspot_top_right
[62, 35, 3, 25]
end
def hotspot_bottom_right
[62, 0, 3, 25]
end
def storyline_history_include? args, text
args.state.storyline_history.any? { |s| s.gsub("-", "").gsub(" ", "").include? text.gsub("-", "").gsub(" ", "") }
end
def blinking_light_side_of_home_render args, lowrez_sprites, lowrez_labels, lowrez_solids
lowrez_sprites << [48, 44, 5, 5, 'sprites/square.png', 0, 50 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
lowrez_sprites << [49, 45, 3, 3, 'sprites/square.png', 0, 100 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
lowrez_sprites << [50, 46, 1, 1, 'sprites/square.png', 0, 255 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
end
def blinking_light_mountain_pass_render args, lowrez_sprites, lowrez_labels, lowrez_solids
lowrez_sprites << [18, 47, 5, 5, 'sprites/square.png', 0, 50 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
lowrez_sprites << [19, 48, 3, 3, 'sprites/square.png', 0, 100 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
lowrez_sprites << [20, 49, 1, 1, 'sprites/square.png', 0, 255 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
end
def blinking_light_path_to_observatory_render args, lowrez_sprites, lowrez_labels, lowrez_solids
lowrez_sprites << [0, 26, 5, 5, 'sprites/square.png', 0, 50 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
lowrez_sprites << [1, 27, 3, 3, 'sprites/square.png', 0, 100 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
lowrez_sprites << [2, 28, 1, 1, 'sprites/square.png', 0, 255 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
end
def blinking_light_observatory_render args, lowrez_sprites, lowrez_labels, lowrez_solids
lowrez_sprites << [23, 59, 5, 5, 'sprites/square.png', 0, 50 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
lowrez_sprites << [24, 60, 3, 3, 'sprites/square.png', 0, 100 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
lowrez_sprites << [25, 61, 1, 1, 'sprites/square.png', 0, 255 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
end
def blinking_light_inside_observatory_render args, lowrez_sprites, lowrez_labels, lowrez_solids
lowrez_sprites << [30, 30, 5, 5, 'sprites/square.png', 0, 50 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
lowrez_sprites << [31, 31, 3, 3, 'sprites/square.png', 0, 100 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
lowrez_sprites << [32, 32, 1, 1, 'sprites/square.png', 0, 255 * (args.state.tick_count % 50).fdiv(50), 0, 255, 0]
end
def decision_graph context_message, context_action, context_result_one, context_result_two, context_result_three = [], context_result_four = []
result_one_scene, result_one_label, result_one_text = context_result_one
result_two_scene, result_two_label, result_two_text = context_result_two
result_three_scene, result_three_label, result_three_text = context_result_three
result_four_scene, result_four_label, result_four_text = context_result_four
top_level_hash = {
background: 'sprites/decision.png',
fade: 60,
player: [20, 36],
storylines: [ ],
scenes: [ ]
}
confirmation_result_one_hash = {
background: 'sprites/decision.png',
scenes: [ ],
storylines: [ ]
}
confirmation_result_two_hash = {
background: 'sprites/decision.png',
scenes: [ ],
storylines: [ ]
}
confirmation_result_three_hash = {
background: 'sprites/decision.png',
scenes: [ ],
storylines: [ ]
}
confirmation_result_four_hash = {
background: 'sprites/decision.png',
scenes: [ ],
storylines: [ ]
}
top_level_hash[:storylines] << [ 5, 35, 4, 4, context_message]
top_level_hash[:storylines] << [20, 35, 4, 4, context_action]
confirmation_result_one_hash[:scenes] << [20, 35, 4, 4, top_level_hash]
confirmation_result_one_hash[:scenes] << [60, 50, 4, 4, result_one_scene]
confirmation_result_one_hash[:storylines] << [40, 50, 4, 4, "#{result_one_label}: \"#{result_one_text}\""]
confirmation_result_one_hash[:scenes] << [40, 40, 4, 4, confirmation_result_four_hash] if result_four_scene
confirmation_result_one_hash[:scenes] << [40, 30, 4, 4, confirmation_result_three_hash] if result_three_scene
confirmation_result_one_hash[:scenes] << [40, 20, 4, 4, confirmation_result_two_hash]
confirmation_result_two_hash[:scenes] << [20, 35, 4, 4, top_level_hash]
confirmation_result_two_hash[:scenes] << [40, 50, 4, 4, confirmation_result_one_hash]
confirmation_result_two_hash[:scenes] << [40, 40, 4, 4, confirmation_result_four_hash] if result_four_scene
confirmation_result_two_hash[:scenes] << [40, 30, 4, 4, confirmation_result_three_hash] if result_three_scene
confirmation_result_two_hash[:scenes] << [60, 20, 4, 4, result_two_scene]
confirmation_result_two_hash[:storylines] << [40, 20, 4, 4, "#{result_two_label}: \"#{result_two_text}\""]
confirmation_result_three_hash[:scenes] << [20, 35, 4, 4, top_level_hash]
confirmation_result_three_hash[:scenes] << [40, 50, 4, 4, confirmation_result_one_hash]
confirmation_result_three_hash[:scenes] << [40, 40, 4, 4, confirmation_result_four_hash]
confirmation_result_three_hash[:scenes] << [60, 30, 4, 4, result_three_scene]
confirmation_result_three_hash[:storylines] << [40, 30, 4, 4, "#{result_three_label}: \"#{result_three_text}\""]
confirmation_result_three_hash[:scenes] << [40, 20, 4, 4, confirmation_result_two_hash]
confirmation_result_four_hash[:scenes] << [20, 35, 4, 4, top_level_hash]
confirmation_result_four_hash[:scenes] << [40, 50, 4, 4, confirmation_result_one_hash]
confirmation_result_four_hash[:scenes] << [60, 40, 4, 4, result_four_scene]
confirmation_result_four_hash[:storylines] << [40, 40, 4, 4, "#{result_four_label}: \"#{result_four_text}\""]
confirmation_result_four_hash[:scenes] << [40, 30, 4, 4, confirmation_result_three_hash]
confirmation_result_four_hash[:scenes] << [40, 20, 4, 4, confirmation_result_two_hash]
top_level_hash[:scenes] << [40, 50, 4, 4, confirmation_result_one_hash]
top_level_hash[:scenes] << [40, 40, 4, 4, confirmation_result_four_hash] if result_four_scene
top_level_hash[:scenes] << [40, 30, 4, 4, confirmation_result_three_hash] if result_three_scene
top_level_hash[:scenes] << [40, 20, 4, 4, confirmation_result_two_hash]
top_level_hash
end
def ship_control_hotspot offset_x, offset_y, a, b, c, d
results = []
results << [ 6 + offset_x, 0 + offset_y, 4, 4, a] if a
results << [ 1 + offset_x, 5 + offset_y, 4, 4, b] if b
results << [ 6 + offset_x, 5 + offset_y, 4, 4, c] if c
results << [ 11 + offset_x, 5 + offset_y, 4, 4, d] if d
results
end
def reload_current_scene
if $gtk.args.state.last_hotspot_scene
set_scene $gtk.args, send($gtk.args.state.last_hotspot_scene, $gtk.args)
tick $gtk.args
elsif respond_to? :set_scene
set_scene $gtk.args, (replied_to_serenity_alive_firmly $gtk.args)
tick $gtk.args
end
$gtk.console.close
end
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---storyline_anka-rb'>Rpg Narrative - Return Of Serenity - storyline_anka.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/storyline_anka.rb
def anka_inside_room args
{
background: 'sprites/inside-home.png',
player: [34, 35],
storylines: [
[34, 34, 4, 4, "Ahhhh!!! Oh god, it was just- a nightmare."],
],
scenes: [
[32, -1, 8, 3, :anka_observatory]
]
}
end
def anka_observatory args
{
background: 'sprites/inside-observatory.png',
fade: 60,
player: [51, 12],
storylines: [
[50, 10, 4, 4, "Breathe, Hiro. Just see what's there... everything--- will- be okay."]
],
scenes: [
[30, 18, 5, 12, :anka_inside_mainframe]
],
render_override: :blinking_light_inside_observatory_render
}
end
def anka_inside_mainframe args
{
player: [32, 4],
background: 'sprites/mainframe.png',
fade: 60,
storylines: [
[22, 45, 17, 4, (anka_last_reply args)],
[45, 45, 4, 4, (anka_current_reply args)],
],
scenes: [
[*hotspot_top_right, :reply_to_anka]
]
}
end
def reply_to_anka args
decision_graph anka_current_reply(args),
"Matthew's-- wife is doing-- well. What's-- even-- better-- is that he's-- a dad, and he didn't-- even-- know it. Should- I- leave- out the part about-- the crew- being-- in hibernation-- for 20-- years? They- should- enter-- statis-- on a high- note... Right?",
[:replied_with_whole_truth, "Whole-- Truth--", anka_reply_whole_truth],
[:replied_with_half_truth, "Half-- Truth--", anka_reply_half_truth]
end
def anka_last_reply args
if args.state.scene_history.include? :replied_to_serenity_alive_firmly
return "Buffer--: #{serenity_alive_firm_reply.quote}"
else
return "Buffer--: #{serenity_alive_sugarcoated_reply.quote}"
end
end
def anka_reply_whole_truth
"Matthew's wife is doing-- very-- well. In fact, she was pregnant. Matthew-- is a dad. He has a son. But, I need- all-- of-- you-- to brace-- yourselves. You've-- been in statis-- for 20 years. A lot has changed. Most of Earth's-- population--- didn't-- survive. Tell- Matthew-- that I'm-- sorry he didn't-- get to see- his- son grow- up."
end
def anka_reply_half_truth
"Matthew's--- wife- is doing-- very-- well. In fact, she was pregnant. Matthew is a dad! It's a boy! Tell- Matthew-- congrats-- for me. Hope-- to see- all of you- soon."
end
def replied_with_whole_truth args
{
background: 'sprites/inside-observatory.png',
fade: 60,
player: [32, 21],
scenes: [[60, 0, 4, 32, :replied_to_anka_back_home]],
storylines: [
[30, 18, 5, 12, "Buffer-- has been set to: #{anka_reply_whole_truth.quote}"],
[30, 10, 5, 4, "I- hope- I- did the right- thing- by laying-- it all- out- there."],
]
}
end
def replied_with_half_truth args
{
background: 'sprites/inside-observatory.png',
fade: 60,
player: [32, 21],
scenes: [[60, 0, 4, 32, :replied_to_anka_back_home]],
storylines: [
[30, 18, 5, 12, "Buffer-- has been set to: #{anka_reply_half_truth.quote}"],
[30, 10, 5, 4, "I- hope- I- did the right- thing- by not giving-- them- the whole- truth."],
]
}
end
def anka_current_reply args
if args.state.scene_history.include? :replied_to_serenity_alive_firmly
return "Hello. This is, Aanka. Sasha-- is still- trying-- to gather-- her wits about-- her, given- the gravity--- of your- last- reply. Thank- you- for being-- honest, and thank- you- for the help- with the ship- diagnostics. I was able-- to retrieve-- all of the navigation--- information---- after-- the battery--- swap. We- are ready-- to head back to Earth. Before-- we go- back- into-- statis, Matthew--- wanted-- to know- how his- wife- is doing. Please- reply-- as soon- as you can. He's-- not going-- to get- into-- the statis-- chamber-- until-- he knows- his wife is okay."
else
return "Hello. This is, Aanka. Thank- you for the help- with the ship's-- diagnostics. I was able-- to retrieve-- all of the navigation--- information--- after-- the battery-- swap. I- know-- that- you didn't-- tell- the whole truth- about-- how far we are from- Earth. Don't-- worry. I understand-- why you did it. We- are ready-- to head back to Earth. Before-- we go- back- into-- statis, Matthew--- wanted-- to know- how his- wife- is doing. Please- reply-- as soon- as you can. He's-- not going-- to get- into-- the statis-- chamber-- until-- he knows- his wife is okay."
end
end
def replied_to_anka_back_home args
if args.state.scene_history.include? :replied_with_whole_truth
return {
fade: 60,
background: 'sprites/inside-home.png',
player: [34, 4],
storylines: [
[34, 4, 4, 4, "I- hope-- this pit in my stomach-- is gone-- by tomorrow---."],
],
scenes: [
[30, 38, 12, 13, :final_message_sad],
]
}
else
return {
fade: 60,
background: 'sprites/inside-home.png',
player: [34, 4],
storylines: [
[34, 4, 4, 4, "I- get the feeling-- I'm going-- to sleep real well tonight--."],
],
scenes: [
[30, 38, 12, 13, :final_message_happy],
]
}
end
end
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---storyline_blinking_light-rb'>Rpg Narrative - Return Of Serenity - storyline_blinking_light.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/storyline_blinking_light.rb
def the_blinking_light args
{
fade: 60,
background: 'sprites/side-of-home.png',
player: [16, 13],
scenes: [
[52, 24, 11, 5, :blinking_light_mountain_pass],
],
render_override: :blinking_light_side_of_home_render
}
end
def blinking_light_mountain_pass args
{
background: 'sprites/mountain-pass-zoomed-out.png',
player: [4, 4],
scenes: [
[18, 47, 5, 5, :blinking_light_path_to_observatory]
],
render_override: :blinking_light_mountain_pass_render
}
end
def blinking_light_path_to_observatory args
{
background: 'sprites/path-to-observatory.png',
player: [60, 4],
scenes: [
[0, 26, 5, 5, :blinking_light_observatory]
],
render_override: :blinking_light_path_to_observatory_render
}
end
def blinking_light_observatory args
{
background: 'sprites/observatory.png',
player: [60, 2],
scenes: [
[28, 39, 4, 10, :blinking_light_inside_observatory]
],
render_override: :blinking_light_observatory_render
}
end
def blinking_light_inside_observatory args
{
background: 'sprites/inside-observatory.png',
player: [60, 2],
storylines: [
[50, 2, 4, 8, "That's weird. I thought- this- mainframe-- was broken--."]
],
scenes: [
[30, 18, 5, 12, :blinking_light_inside_mainframe]
],
render_override: :blinking_light_inside_observatory_render
}
end
def blinking_light_inside_mainframe args
{
background: 'sprites/mainframe.png',
fade: 60,
player: [30, 4],
scenes: [
[62, 32, 4, 32, :reply_to_introduction]
],
storylines: [
[43, 43, 8, 8, "\"Mission-- control--, your- main- comm-- channels-- seem-- to be down. My apologies-- for- using-- this low- level-- exploit--. What's-- going-- on down there? We are ready-- for reentry--.\" Message--- Timestamp---: 4- hours-- 23--- minutes-- ago--."],
[30, 30, 4, 4, "There's-- a low- level-- message-- here... NANI.T.F?"],
[14, 10, 24, 4, "Oh interesting---. This transistor--- needed-- to be activated--- for the- mainframe-- to work."],
[14, 20, 24, 4, "What the heck activated--- this thing- though?"]
]
}
end
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---storyline_day_one-rb'>Rpg Narrative - Return Of Serenity - storyline_day_one.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/storyline_day_one.rb
def day_one_beginning args
{
background: 'sprites/side-of-home.png',
player: [16, 13],
scenes: [
[0, 0, 64, 2, :day_one_infront_of_home],
],
storylines: [
[35, 10, 6, 6, "Man. Hard to believe- that today- is the 20th--- anniversary-- of The Impact."]
]
}
end
def day_one_infront_of_home args
{
background: 'sprites/front-of-home.png',
player: [56, 23],
scenes: [
[43, 34, 10, 16, :day_one_home],
[62, 0, 3, 40, :day_one_beginning],
[0, 4, 3, 20, :day_one_ceremony]
],
storylines: [
[40, 20, 4, 4, "It looks like everyone- is already- at the rememberance-- ceremony."],
]
}
end
def day_one_home args
{
background: 'sprites/inside-home.png',
player: [34, 3],
scenes: [
[28, 0, 12, 2, :day_one_infront_of_home]
],
storylines: [
[
38, 4, 4, 4, "My mansion- in all its glory! Okay yea, it's just a shipping- container-. Apparently-, it's nothing- like the luxuries- of the 2040's. But it's- all we have- in- this day and age. And it'll suffice."
],
[
28, 7, 4, 7,
"Ahhh. My reading- couch. It's so comfortable--."
],
[
38, 21, 4, 4,
"I'm- lucky- to have a computer--. I'm- one of the few people- with- the skills to put this- thing to good use."
],
[
45, 37, 4, 8,
"This corner- of my home- is always- warmer-. It's cause of the ref~lected-- light- from the solar-- panels--, just on the other- side- of this wall. It's hard- to believe- there was o~nce-- an unlimited- amount- of electricity--."
],
[
32, 40, 8, 10,
"This isn't- a good time- to sleep. I- should probably- head to the ceremony-."
],
[
25, 21, 5, 12,
"Fifteen-- years- of computer-- science-- notes, neatly-- organized. Compiler--- Theory--, Linear--- Algebra---, Game-- Development---... Every-- subject-- imaginable--."
]
]
}
end
def day_one_ceremony args
{
background: 'sprites/tribute.png',
player: [57, 21],
scenes: [
[62, 0, 2, 40, :day_one_infront_of_home],
[0, 24, 2, 40, :day_one_infront_of_library]
],
storylines: [
[53, 12, 3, 8, "It's- been twenty- years since The Impact. Twenty- years, since Halley's-- Comet-- set Earth's- blue- sky on fire."],
[45, 12, 3, 8, "The space mission- sent to prevent- Earth's- total- destruction--, was a success. Only- 99.9%------ of the world's- population-- died-- that day. Hey, it's- better-- than 100%---- of humanity-- dying."],
[20, 12, 23, 4, "The monument--- reads:---- Here- stands- the tribute-- to Space- Mission-- Serenity--- and- its- crew. You- have- given-- humanity--- a second-- chance."],
[15, 12, 3, 8, "Rest- in- peace--- Matthew----, Sasha----, Aanka----"],
]
}
end
def day_one_infront_of_library args
{
background: 'sprites/outside-library.png',
player: [57, 21],
scenes: [
[62, 0, 2, 40, :day_one_ceremony],
[49, 39, 6, 9, :day_one_library]
],
storylines: [
[50, 20, 4, 8, "Shipping- containers-- as far- as the eye- can see. It's- rather- beautiful-- if you ask me. Even- though-- this- view- represents-- all- that's-- left- of humanity-."]
]
}
end
def day_one_library args
{
background: 'sprites/library.png',
player: [27, 4],
scenes: [
[0, 0, 64, 2, :end_day_one_infront_of_library]
],
storylines: [
[28, 22, 8, 4, "I grew- up- in this library. I've- read every- book- here. My favorites-- were- of course-- anything- computer-- related."],
[6, 32, 10, 6, "My favorite-- area--- of the library. The Science-- Section."]
]
}
end
def end_day_one_infront_of_library args
{
background: 'sprites/outside-library.png',
player: [51, 33],
scenes: [
[49, 39, 6, 9, :day_one_library],
[62, 0, 2, 40, :end_day_one_monument],
],
storylines: [
[50, 27, 4, 4, "It's getting late. Better get some sleep."]
]
}
end
def end_day_one_monument args
{
background: 'sprites/tribute.png',
player: [2, 36],
scenes: [
[62, 0, 2, 40, :end_day_one_infront_of_home],
],
storylines: [
[50, 27, 4, 4, "It's getting late. Better get some sleep."],
]
}
end
def end_day_one_infront_of_home args
{
background: 'sprites/front-of-home.png',
player: [1, 17],
scenes: [
[43, 34, 10, 16, :end_day_one_home],
],
storylines: [
[20, 10, 4, 4, "It's getting late. Better get some sleep."],
]
}
end
def end_day_one_home args
{
background: 'sprites/inside-home.png',
player: [34, 3],
scenes: [
[32, 40, 8, 10, :end_day_one_dream],
],
storylines: [
[38, 4, 4, 4, "It's getting late. Better get some sleep."],
]
}
end
def end_day_one_dream args
{
background: 'sprites/dream.png',
fade: 60,
player: [4, 4],
scenes: [
[62, 0, 2, 64, :explaining_the_special_power]
],
storylines: [
[10, 10, 4, 4, "Why- does this- moment-- always- haunt- my dreams?"],
[20, 10, 4, 4, "This kid- reads these computer--- science--- books- nonstop-. What's- wrong with him?"],
[30, 10, 4, 4, "There- is nothing-- wrong- with him. This behavior-- should be encouraged---! In fact-, I think- he's- special---. Have- you seen- him use- a computer---? It's-- almost-- as if he can- speak-- to it."]
]
}
end
def explaining_the_special_power args
{
fade: 60,
background: 'sprites/inside-home.png',
player: [32, 30],
scenes: [
[
38, 21, 4, 4, :explaining_the_special_power_inside_computer
],
]
}
end
def explaining_the_special_power_inside_computer args
{
background: 'sprites/pc.png',
fade: 60,
player: [34, 4],
scenes: [
[0, 62, 64, 3, :the_blinking_light]
],
storylines: [
[14, 20, 24, 4, "So... I have a special-- power--. I don't-- need a mouse-, keyboard--, or even-- a monitor--- to control-- a computer--."],
[14, 25, 24, 4, "I only-- pretend-- to use peripherals---, so as not- to freak- anyone--- out."],
[14, 30, 24, 4, "Inside-- this silicon--- Universe---, is the only-- place I- feel- at peace."],
[14, 35, 24, 4, "It's-- the only-- place where I don't-- feel alone."]
]
}
end
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---storyline_final_decision-rb'>Rpg Narrative - Return Of Serenity - storyline_final_decision.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/storyline_final_decision.rb
def final_decision_side_of_home args
{
fade: 120,
background: 'sprites/side-of-home.png',
player: [16, 13],
scenes: [
[52, 24, 11, 5, :final_decision_mountain_pass],
],
render_override: :blinking_light_side_of_home_render,
storylines: [
[28, 13, 8, 4, "Man. Hard to believe- that today- is the 21st--- anniversary-- of The Impact. Serenity--- will- be- home- soon."]
]
}
end
def final_decision_mountain_pass args
{
background: 'sprites/mountain-pass-zoomed-out.png',
player: [4, 4],
scenes: [
[18, 47, 5, 5, :final_decision_path_to_observatory]
],
render_override: :blinking_light_mountain_pass_render
}
end
def final_decision_path_to_observatory args
{
background: 'sprites/path-to-observatory.png',
player: [60, 4],
scenes: [
[0, 26, 5, 5, :final_decision_observatory]
],
render_override: :blinking_light_path_to_observatory_render
}
end
def final_decision_observatory args
{
background: 'sprites/observatory.png',
player: [60, 2],
scenes: [
[28, 39, 4, 10, :final_decision_inside_observatory]
],
render_override: :blinking_light_observatory_render
}
end
def final_decision_inside_observatory args
{
background: 'sprites/inside-observatory.png',
player: [60, 2],
storylines: [],
scenes: [
[30, 18, 5, 12, :final_decision_inside_mainframe]
],
render_override: :blinking_light_inside_observatory_render
}
end
def final_decision_inside_mainframe args
{
player: [32, 4],
background: 'sprites/mainframe.png',
storylines: [],
scenes: [
[*hotspot_top, :final_decision_ship_status],
]
}
end
def final_decision_ship_status args
{
background: 'sprites/serenity.png',
fade: 60,
player: [30, 10],
scenes: [
[*hotspot_top_right, :final_decision]
],
storylines: [
[30, 8, 4, 4, "????"],
*final_decision_ship_status_shared(args)
]
}
end
def final_decision args
decision_graph "Stasis-- Chambers--: UNDERPOWERED, Life- forms-- will be terminated---- unless-- equilibrium----- is reached.",
"I CAN'T DO THIS... But... If-- I-- don't--- bring-- the- chambers--- to- equilibrium-----, they all die...",
[:final_decision_game_over_noone, "Kill--- Everyone---", "DO--- NOTHING?"],
[:final_decision_game_over_matthew, "Kill--- Sasha---", "KILL--- SASHA?"],
[:final_decision_game_over_anka, "Kill--- Aanka---", "KILL--- AANKA?"],
[:final_decision_game_over_sasha, "Kill--- Matthew---", "KILL--- MATTHEW?"]
end
def final_decision_game_over_noone args
{
background: 'sprites/tribute-game-over.png',
player: [53, 14],
fade: 600
}
end
def final_decision_game_over_matthew args
{
background: 'sprites/tribute-game-over.png',
player: [53, 14],
fade: 600
}
end
def final_decision_game_over_anka args
{
background: 'sprites/tribute-game-over.png',
player: [53, 14],
fade: 600
}
end
def final_decision_game_over_sasha args
{
background: 'sprites/tribute-game-over.png',
player: [53, 14],
fade: 600
}
end
def final_decision_ship_status_shared args
[
*ship_control_hotspot(24, 22,
"Stasis-- Chambers--: UNDERPOWERED, Life- forms-- will be terminated---- unless-- equilibrium----- is reached. WHAT?! NO!",
"Matthew's--- Chamber--: UNDER-- THREAT-- OF-- TERMINATION. WHAT?! NO!",
"Aanka's--- Chamber--: UNDER-- THREAT-- OF-- TERMINATION. WHAT?! NO!",
"Sasha's--- Chamber--: UNDER-- THREAT-- OF-- TERMINATION. WHAT?! NO!"),
]
end
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---storyline_final_message-rb'>Rpg Narrative - Return Of Serenity - storyline_final_message.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/storyline_final_message.rb
def final_message_sad args
{
fade: 60,
background: 'sprites/inside-home.png',
player: [34, 35],
storylines: [
[34, 34, 4, 4, "Another-- sleepless-- night..."],
],
scenes: [
[32, -1, 8, 3, :final_message_observatory]
]
}
end
def final_message_happy args
{
fade: 60,
background: 'sprites/inside-home.png',
player: [34, 35],
storylines: [
[34, 34, 4, 4, "Oh man, I slept like rock!"],
],
scenes: [
[32, -1, 8, 3, :final_message_observatory]
]
}
end
def final_message_side_of_home args
{
fade: 60,
background: 'sprites/side-of-home.png',
player: [16, 13],
scenes: [
[52, 24, 11, 5, :final_message_mountain_pass],
],
render_override: :blinking_light_side_of_home_render
}
end
def final_message_mountain_pass args
{
background: 'sprites/mountain-pass-zoomed-out.png',
player: [4, 4],
scenes: [
[18, 47, 5, 5, :final_message_path_to_observatory],
],
storylines: [
[18, 13, 5, 5, "Hnnnnnnnggg. My legs-- are still sore- from yesterday."]
],
render_override: :blinking_light_mountain_pass_render
}
end
def final_message_path_to_observatory args
{
background: 'sprites/path-to-observatory.png',
player: [60, 4],
scenes: [
[0, 26, 5, 5, :final_message_observatory]
],
storylines: [
[22, 20, 10, 10, "This spot--, on the mountain, right here, it's-- perfect. This- is where- I'll-- yeet-- the person-- who is playing-- this- prank- on me."]
],
render_override: :blinking_light_path_to_observatory_render
}
end
def final_message_observatory args
if args.state.scene_history.include? :replied_with_whole_truth
return {
background: 'sprites/inside-observatory.png',
fade: 60,
player: [51, 12],
storylines: [
[50, 10, 4, 4, "Here-- we- go..."]
],
scenes: [
[30, 18, 5, 12, :final_message_inside_mainframe]
],
render_override: :blinking_light_inside_observatory_render
}
else
return {
background: 'sprites/inside-observatory.png',
fade: 60,
player: [51, 12],
storylines: [
[50, 10, 4, 4, "I feel like I'm-- walking-- on sunshine!"]
],
scenes: [
[30, 18, 5, 12, :final_message_inside_mainframe]
],
render_override: :blinking_light_inside_observatory_render
}
end
end
def final_message_inside_mainframe args
{
player: [32, 4],
background: 'sprites/mainframe.png',
fade: 60,
scenes: [[45, 45, 4, 4, :final_message_check_ship_status]]
}
end
def final_message_check_ship_status args
{
background: 'sprites/mainframe.png',
storylines: [
[45, 45, 4, 4, (final_message_current args)],
],
scenes: [
[*hotspot_top, :final_message_ship_status],
]
}
end
def final_message_ship_status args
{
background: 'sprites/serenity.png',
fade: 60,
player: [30, 10],
scenes: [
[30, 50, 4, 4, :final_message_ship_status_reviewed]
],
storylines: [
[30, 8, 4, 4, "Let me make- sure- everything--- looks good. It'll-- give me peace- of mind."],
*final_message_ship_status_shared(args)
]
}
end
def final_message_ship_status_reviewed args
{
background: 'sprites/serenity.png',
fade: 60,
scenes: [
[*hotspot_bottom, :final_message_summary]
],
storylines: [
[0, 62, 62, 3, "Whew. Everyone-- is in their- chambers. The engines-- are roaring-- and Serenity-- is coming-- home."],
]
}
end
def final_message_ship_status_shared args
[
*ship_control_hotspot( 0, 50,
"Stasis-- Chambers--: Online, All chambers-- are powered. Battery--- Allocation---: 3--- of-- 3--.",
"Matthew's--- Chamber--: OCCUPIED----",
"Aanka's--- Chamber--: OCCUPIED----",
"Sasha's--- Chamber--: OCCUPIED----"),
*ship_control_hotspot(12, 35,
"Life- Support--: Not-- Needed---",
"O2--- Production---: OFF---",
"CO2--- Scrubbers---: OFF---",
"H2O--- Production---: OFF---"),
*ship_control_hotspot(24, 20,
"Navigation: Offline---",
"Sensor: OFF---",
"Heads- Up- Display: DAMAGED---",
"Arithmetic--- Unit: DAMAGED----"),
*ship_control_hotspot(36, 35,
"COMM: Underpowered----",
"Text: ON---",
"Audio: SEGFAULT---",
"Video: DAMAGED---"),
*ship_control_hotspot(48, 50,
"Engine: Online, Coordinates--- Set- for Earth. Battery--- Allocation---: 3--- of-- 3---",
"Engine I: ON---",
"Engine II: ON---",
"Engine III: ON---")
]
end
def final_message_last_reply args
if args.state.scene_history.include? :replied_with_whole_truth
return "Buffer--: #{anka_reply_whole_truth.quote}"
else
return "Buffer--: #{anka_reply_half_truth.quote}"
end
end
def final_message_current args
if args.state.scene_history.include? :replied_with_whole_truth
return "Hey... It's-- me Sasha. Aanka-- is trying-- her best to comfort-- Matthew. This- is the first- time- I've-- ever-- seen-- Matthew-- cry. We'll-- probably-- be in stasis-- by the time you get this message--. Thank- you- again-- for all your help. I look forward-- to meeting-- you in person."
else
return "Hey! It's-- me Sasha! LOL! Aanka-- and Matthew-- are dancing-- around-- like- goofballs--! They- are both- so adorable! Only-- this- tiny-- little-- genius-- can make-- a battle-- hardened-- general--- put- on a tiara-- and dance- around-- like a fairy-- princess-- XD------ Anyways, we are heading-- back into-- the chambers--. I hope our welcome-- home- parade-- has fireworks!"
end
end
def final_message_summary args
if args.state.scene_history.include? :replied_with_whole_truth
return {
background: 'sprites/inside-observatory.png',
fade: 60,
player: [31, 11],
scenes: [[60, 0, 4, 32, :final_decision_side_of_home]],
storylines: [
[30, 10, 5, 4, "I can't-- imagine-- what they are feeling-- right now. But at least- they- know everything---, and we can- concentrate-- on rebuilding--- this world-- right- off the bat. I can't-- wait to see the future-- they'll-- help- build."],
]
}
else
return {
background: 'sprites/inside-observatory.png',
fade: 60,
player: [31, 11],
scenes: [[60, 0, 4, 32, :final_decision_side_of_home]],
storylines: [
[30, 10, 5, 4, "They all sounded-- so happy. I know- they'll-- be in for a tough- dose- of reality--- when they- arrive. But- at least- they'll-- be around-- all- of us. We'll-- help them- cope."],
]
}
end
end
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---storyline_serenity_alive-rb'>Rpg Narrative - Return Of Serenity - storyline_serenity_alive.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/storyline_serenity_alive.rb
def serenity_alive_side_of_home args
{
fade: 60,
background: 'sprites/side-of-home.png',
player: [16, 13],
scenes: [
[52, 24, 11, 5, :serenity_alive_mountain_pass],
],
render_override: :blinking_light_side_of_home_render
}
end
def serenity_alive_mountain_pass args
{
background: 'sprites/mountain-pass-zoomed-out.png',
player: [4, 4],
scenes: [
[18, 47, 5, 5, :serenity_alive_path_to_observatory],
],
storylines: [
[18, 13, 5, 5, "Hnnnnnnnggg. My legs-- are still sore- from yesterday."]
],
render_override: :blinking_light_mountain_pass_render
}
end
def serenity_alive_path_to_observatory args
{
background: 'sprites/path-to-observatory.png',
player: [60, 4],
scenes: [
[0, 26, 5, 5, :serenity_alive_observatory]
],
storylines: [
[22, 20, 10, 10, "This spot--, on the mountain, right here, it's-- perfect. This- is where- I'll-- yeet-- the person-- who is playing-- this- prank- on me."]
],
render_override: :blinking_light_path_to_observatory_render
}
end
def serenity_alive_observatory args
{
background: 'sprites/observatory.png',
player: [60, 2],
scenes: [
[28, 39, 4, 10, :serenity_alive_inside_observatory]
],
render_override: :blinking_light_observatory_render
}
end
def serenity_alive_inside_observatory args
{
background: 'sprites/inside-observatory.png',
player: [60, 2],
storylines: [],
scenes: [
[30, 18, 5, 12, :serenity_alive_inside_mainframe]
],
render_override: :blinking_light_inside_observatory_render
}
end
def serenity_alive_inside_mainframe args
{
background: 'sprites/mainframe.png',
fade: 60,
player: [30, 4],
scenes: [
[*hotspot_top, :serenity_alive_ship_status],
],
storylines: [
[22, 45, 17, 4, (serenity_alive_last_reply args)],
[45, 45, 4, 4, (serenity_alive_current_message args)],
]
}
end
def serenity_alive_ship_status args
{
background: 'sprites/serenity.png',
fade: 60,
player: [30, 10],
scenes: [
[30, 50, 4, 4, :serenity_alive_ship_status_reviewed]
],
storylines: [
[30, 8, 4, 4, "Serenity? THE--- Mission-- Serenity?! How is that possible? They- are supposed-- to be dead."],
[30, 10, 4, 4, "I... can't-- believe-- it. I- can access-- Serenity's-- computer? I- guess my \"superpower----\" isn't limited-- by proximity-- to- a machine--."],
*serenity_alive_shared_ship_status(args)
]
}
end
def serenity_alive_ship_status_reviewed args
{
background: 'sprites/serenity.png',
fade: 60,
scenes: [
[*hotspot_bottom, :serenity_alive_time_to_reply]
],
storylines: [
[0, 62, 62, 3, "Okay. Reviewing-- everything--, it looks- like- I- can- take- the batteries--- from the Stasis--- Chambers--- and- Engine--- to keep- the crew-- alive-- and-- their-- location--- pinpointed---."],
]
}
end
def serenity_alive_time_to_reply args
decision_graph serenity_alive_current_message(args),
"Okay... time to deliver the bad news...",
[:replied_to_serenity_alive_firmly, "Firm-- Reply", serenity_alive_firm_reply],
[:replied_to_serenity_alive_kindly, "Sugar-- Coated---- Reply", serenity_alive_sugarcoated_reply]
end
def serenity_alive_shared_ship_status args
[
*ship_control_hotspot( 0, 50,
"Stasis-- Chambers--: Online, All chambers-- are powered. Battery--- Allocation---: 3--- of-- 3--, Hmmm. They don't-- need this to be powered-- right- now. Everyone-- is awake.",
nil,
nil,
nil),
*ship_control_hotspot(12, 35,
"Life- Support--: Offline, Unable--- to- Sustain-- Life. Battery--- Allocation---: 0--- of-- 3---, Okay. That is definitely---- not a good thing.",
nil,
nil,
nil),
*ship_control_hotspot(24, 20,
"Navigation: Offline, Unable--- to- Calculate--- Location. Battery--- Allocation---: 0--- of-- 3---, Whelp. No wonder-- Sasha-- can't-- get- any-- readings. Their- Navigation--- is completely--- offline.",
nil,
nil,
nil),
*ship_control_hotspot(36, 35,
"COMM: Underpowered----, Limited--- to- Text-- Based-- COMM. Battery--- Allocation---: 1--- of-- 3---, It's-- lucky- that- their- COMM---- system was able to survive-- twenty-- years--. Just- barely-- it seems.",
nil,
nil,
nil),
*ship_control_hotspot(48, 50,
"Engine: Online, Full- Control-- Available. Battery--- Allocation---: 3--- of-- 3---, Hmmm. No point of having an engine-- online--, if you don't- know- where you're-- going.",
nil,
nil,
nil)
]
end
def serenity_alive_firm_reply
"Serenity, you are at a distance-- farther-- than- Neptune. All- of the ship's-- systems-- are failing. Please- move the batteries---- from- the Stasis-- Chambers-- over- to- Life-- Support--. I also-- need- you to move-- the batteries---- from- the Engines--- to your Navigation---- System."
end
def serenity_alive_sugarcoated_reply
"So... you- are- a teeny--- tiny--- bit--- farther-- from Earth- than you think. And you have a teeny--- tiny--- problem-- with your ship. Please-- move the batteries--- from the Stasis--- Chambers--- over to Life--- Support---. I also need you to move the batteries--- from the Engines--- to your- Navigation--- System. Don't-- worry-- Sasha. I'll-- get y'all-- home."
end
def replied_to_serenity_alive_firmly args
{
background: 'sprites/inside-observatory.png',
fade: 60,
player: [32, 21],
scenes: [
[*hotspot_bottom_right, :serenity_alive_path_from_observatory]
],
storylines: [
[30, 18, 5, 12, "Buffer-- has been set to: #{serenity_alive_firm_reply.quote}"],
*serenity_alive_reply_completed_shared_hotspots(args),
]
}
end
def replied_to_serenity_alive_kindly args
{
background: 'sprites/inside-observatory.png',
fade: 60,
player: [32, 21],
scenes: [
[*hotspot_bottom_right, :serenity_alive_path_from_observatory]
],
storylines: [
[30, 18, 5, 12, "Buffer-- has been set to: #{serenity_alive_sugarcoated_reply.quote}"],
*serenity_alive_reply_completed_shared_hotspots(args),
]
}
end
def serenity_alive_path_from_observatory args
{
fade: 60,
background: 'sprites/path-to-observatory.png',
player: [4, 21],
scenes: [
[*hotspot_bottom_right, :serenity_bio_infront_of_home]
],
storylines: [
[22, 20, 10, 10, "I'm not sure what's-- worse. Waiting-- for Sasha's-- reply. Or jumping-- off- from- right- here."]
]
}
end
def serenity_alive_reply_completed_shared_hotspots args
[
[30, 10, 5, 4, "I guess it wasn't-- a joke- after-- all."],
[40, 10, 5, 4, "I barely-- remember--- the- history----- of the crew."],
[50, 10, 5, 4, "It probably--- wouldn't-- hurt- to- refresh-- my memory--."]
]
end
def serenity_alive_last_reply args
if args.state.scene_history.include? :replied_to_introduction_seriously
return "Buffer--: \"Hello, Who- is sending-- this message--?\""
else
return "Buffer--: \"New- phone. Who dis?\""
end
end
def serenity_alive_current_message args
if args.state.scene_history.include? :replied_to_introduction_seriously
"This- is Sasha. The Serenity--- crew-- is out of hibernation---- and ready-- for Earth reentry--. But, it seems like we are having-- trouble-- with our Navigation---- systems. Please advise.".quote
else
"LOL! Thanks for the laugh. I needed that. This- is Sasha. The Serenity--- crew-- is out of hibernation---- and ready-- for Earth reentry--. But, it seems like we are having-- trouble-- with our Navigation---- systems. Can you help me out- babe?".quote
end
end
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---storyline_serenity_bio-rb'>Rpg Narrative - Return Of Serenity - storyline_serenity_bio.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/storyline_serenity_bio.rb
def serenity_bio_infront_of_home args
{
fade: 60,
background: 'sprites/front-of-home.png',
player: [54, 23],
scenes: [
[44, 34, 8, 14, :serenity_bio_inside_home],
[0, 3, 3, 22, :serenity_bio_library]
]
}
end
def serenity_bio_inside_home args
{
background: 'sprites/inside-home.png',
player: [34, 4],
storylines: [
[34, 4, 4, 4, "I'm--- completely--- exhausted."],
],
scenes: [
[30, 38, 12, 13, :serenity_bio_restless_sleep],
[32, 0, 8, 3, :serenity_bio_infront_of_home],
]
}
end
def serenity_bio_restless_sleep args
{
fade: 60,
background: 'sprites/inside-home.png',
storylines: [
[32, 38, 10, 13, "I can't-- seem to sleep. I know nothing-- about the- crew-. Maybe- I- should- go read- up- on- them."],
],
scenes: [
[32, 0, 8, 3, :serenity_bio_infront_of_home],
]
}
end
def serenity_bio_library args
{
background: 'sprites/library.png',
fade: 60,
player: [30, 7],
scenes: [
[21, 35, 3, 18, :serenity_bio_book]
]
}
end
def serenity_bio_book args
{
background: 'sprites/book.png',
fade: 60,
player: [6, 52],
storylines: [
[ 4, 50, 56, 4, "The Title-- Reads: Never-- Forget-- Mission-- Serenity---"],
[ 4, 38, 8, 8, "Name: Matthew--- R. Sex: Male--- Age-- at-- Departure: 36-----"],
[14, 38, 46, 8, "Tribute-- Text: Matthew graduated-- Magna-- Cum-- Laude-- from MIT--- with-- a- PHD---- in Aero-- Nautical--- Engineering. He was immensely--- competitive, and had an insatiable---- thirst- for aerial-- battle. From the age of twenty, he remained-- undefeated--- in the Israeli-- Air- Force- \"Blue Flag\" combat-- exercises. By the age of 29--- he had already-- risen through- the ranks, and became-- the Lieutenant--- General--- of Lufwaffe. Matthew-- volenteered-- to- pilot-- Mission-- Serenity. To- this day, his wife- and son- are pillars-- of strength- for us. Rest- in Peace- Matthew, we are sorry-- that- news of the pregancy-- never-- reached- you. Please forgive us."],
[4, 26, 8, 8, "Name: Aanka--- P. Sex: Female--- Age-- at-- Departure: 9-----"],
[14, 26, 46, 8, "Tribute-- Text: Aanka--- gratuated--- Magna-- Cum- Laude-- from MIT, at- the- age- of eight, with a- PHD---- in Astro-- Physics. Her-- IQ--- was over 390, the highest-- ever- recorded--- IQ-- in- human-- history. She changed- the landscape-- of Physics-- with her efforts- in- unravelling--- the mysteries--- of- Dark- Matter--. Anka discovered-- the threat- of Halley's-- Comet-- collision--- with Earth. She spear headed-- the global-- effort-- for Misson-- Serenity. Her- multilingual--- address-- to- the world-- brought- us all hope."],
[4, 14, 8, 8, "Name: Sasha--- N. Sex: Female--- Age-- at-- Departure: 29-----"],
[14, 14, 46, 8, "Tribute-- Text: Sasha gratuated-- Magna-- Cum- Laude-- from MIT--- with-- a- PHD---- in Computer---- Science----. She-- was-- brilliant--, strong- willed--, and-- a-- stunningly--- beautiful--- woman---. Sasha---- is- the- creator--- of the world's--- first- Ruby--- Quantum-- Machine---. After-- much- critical--- acclaim--, the Quantum-- Computer-- was placed in MIT's---- Museam-- next- to- Richard--- G. and Thomas--- K.'s---- Lisp-- Machine---. Her- engineering--- skills-- were-- paramount--- for Mission--- Serenity's--- success. Humanity-- misses-- you-- dearly,-- Sasha--. Life-- shines-- a dimmer-- light-- now- that- your- angelic- voice-- can never- be heard- again."],
],
scenes: [
[*hotspot_bottom, :serenity_bio_finally_to_bed]
]
}
end
def serenity_bio_finally_to_bed args
{
fade: 60,
background: 'sprites/inside-home.png',
player: [35, 3],
storylines: [
[34, 4, 4, 4, "Maybe-- I'll-- be able-- to sleep- now..."],
],
scenes: [
[32, 38, 10, 13, :bad_dream],
]
}
end
def bad_dream args
{
fade: 120,
background: 'sprites/inside-home.png',
player: [34, 35],
storylines: [
[34, 34, 4, 4, "Man. I did not- sleep- well- at all..."],
],
scenes: [
[32, -1, 8, 3, :bad_dream_observatory]
]
}
end
def bad_dream_observatory args
{
background: 'sprites/inside-observatory.png',
fade: 120,
player: [51, 12],
storylines: [
[50, 10, 4, 4, "Breathe, Hiro. Just see what's there... everything--- will- be okay."]
],
scenes: [
[30, 18, 5, 12, :bad_dream_inside_mainframe]
],
render_override: :blinking_light_inside_observatory_render
}
end
def bad_dream_inside_mainframe args
{
player: [32, 4],
background: 'sprites/mainframe.png',
fade: 120,
storylines: [
[22, 45, 17, 4, (bad_dream_last_reply args)],
],
scenes: [
[45, 45, 4, 4, :bad_dream_everyone_dead],
]
}
end
def bad_dream_everyone_dead args
{
background: 'sprites/mainframe.png',
storylines: [
[22, 45, 17, 4, (bad_dream_last_reply args)],
[45, 45, 4, 4, "Hi-- Hiro. This is Sasha. By the time- you get this- message, chances-- are we will- already-- be- dead. The batteries--- got- damaged-- during-- removal. And- we don't-- have enough-- power-- for Life-- Support. The air-- is- already--- starting-- to taste- bad. It... would- have been- nice... to go- on a date--- with- you-- when-- I- got- back- to Earth. Anyways, good-- bye-- Hiro-- XOXOXO----"],
[22, 5, 17, 4, "Meh. Whatever, I didn't-- want to save them anyways. What- a pain- in my ass."],
],
scenes: [
[*hotspot_bottom, :anka_inside_room]
]
}
end
def bad_dream_last_reply args
if args.state.scene_history.include? :replied_to_serenity_alive_firmly
return "Buffer--: #{serenity_alive_firm_reply.quote}"
else
return "Buffer--: #{serenity_alive_sugarcoated_reply.quote}"
end
end
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---storyline_serenity_introduction-rb'>Rpg Narrative - Return Of Serenity - storyline_serenity_introduction.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/storyline_serenity_introduction.rb
# decision_graph "Message from Sasha",
# "I should reply.",
# [:replied_to_introduction_seriously, "Reply Seriously", "Who is this?"],
# [:replied_to_introduction_humorously, "Reply Humorously", "New phone who dis?"]
def reply_to_introduction args
decision_graph "\"Mission-- control--, your- main- comm-- channels-- seem-- to be down. My apologies-- for- using-- this low- level-- exploit--. What's-- going-- on down there? We are ready-- for reentry--.\" Message--- Timestamp---: 4- hours-- 23--- minutes-- ago--.",
"Whoever-- pulled- off this exploit-- knows their stuff. I should reply--.",
[:replied_to_introduction_seriously, "Serious Reply", "Hello, Who- is sending-- this message--?"],
[:replied_to_introduction_humorously, "Humorous Reply", "New phone, who dis?"]
end
def replied_to_introduction_seriously args
{
background: 'sprites/inside-observatory.png',
fade: 60,
player: [32, 21],
scenes: [
*replied_to_introduction_shared_scenes(args)
],
storylines: [
[30, 18, 5, 12, "Buffer-- has been set to: \"Hello, Who- is sending-- this message--?\""],
*replied_to_introduction_shared_storylines(args)
]
}
end
def replied_to_introduction_humorously args
{
background: 'sprites/inside-observatory.png',
fade: 60,
player: [32, 21],
scenes: [
*replied_to_introduction_shared_scenes(args)
],
storylines: [
[30, 18, 5, 12, "Buffer-- has been set to: \"New- phone. Who dis?\""],
*replied_to_introduction_shared_storylines(args)
]
}
end
def replied_to_introduction_shared_storylines args
[
[30, 10, 5, 4, "It's-- going-- to take a while-- for this reply-- to make it's-- way back."],
[40, 10, 5, 4, "4- hours-- to send a message-- at light speed?! How far away-- is the sender--?"],
[50, 10, 5, 4, "I know- I've-- read about-- light- speed- travel-- before--. Maybe-- the library--- still has that- poster."]
]
end
def replied_to_introduction_shared_scenes args
[[60, 0, 4, 32, :replied_to_introduction_observatory]]
end
def replied_to_introduction_observatory args
{
background: 'sprites/observatory.png',
player: [28, 39],
scenes: [
[60, 0, 4, 32, :replied_to_introduction_path_to_observatory]
]
}
end
def replied_to_introduction_path_to_observatory args
{
background: 'sprites/path-to-observatory.png',
player: [0, 26],
scenes: [
[60, 0, 4, 20, :replied_to_introduction_mountain_pass]
],
}
end
def replied_to_introduction_mountain_pass args
{
background: 'sprites/mountain-pass-zoomed-out.png',
player: [21, 48],
scenes: [
[0, 0, 15, 4, :replied_to_introduction_side_of_home]
],
storylines: [
[15, 28, 5, 3, "At least I'm-- getting-- my- exercise-- in- for- today--."]
]
}
end
def replied_to_introduction_side_of_home args
{
background: 'sprites/side-of-home.png',
player: [58, 29],
scenes: [
[2, 0, 61, 2, :speed_of_light_front_of_home]
],
}
end
</code></pre>
<h3 id='----rpg-narrative---return-of-serenity---storyline_speed_of_light-rb'>Rpg Narrative - Return Of Serenity - storyline_speed_of_light.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_narrative/return_of_serenity/app/storyline_speed_of_light.rb
def speed_of_light_front_of_home args
{
background: 'sprites/front-of-home.png',
player: [54, 23],
scenes: [
[44, 34, 8, 14, :speed_of_light_inside_home],
[0, 3, 3, 22, :speed_of_light_outside_library]
]
}
end
def speed_of_light_inside_home args
{
background: 'sprites/inside-home.png',
player: [35, 4],
storylines: [
[30, 38, 12, 13, "Can't- sleep right now. I have to- find- out- why- it took- over-- 4- hours-- to receive-- that message."]
],
scenes: [
[32, 0, 8, 3, :speed_of_light_front_of_home],
]
}
end
def speed_of_light_outside_library args
{
background: 'sprites/outside-library.png',
player: [55, 19],
scenes: [
[49, 39, 6, 10, :speed_of_light_library],
[61, 11, 3, 20, :speed_of_light_front_of_home]
]
}
end
def speed_of_light_library args
{
background: 'sprites/library.png',
player: [30, 7],
scenes: [
[3, 50, 10, 3, :speed_of_light_celestial_bodies_diagram]
]
}
end
def speed_of_light_celestial_bodies_diagram args
{
background: 'sprites/planets.png',
fade: 60,
player: [30, 3],
scenes: [
[56 - 2, 10, 5, 5, :speed_of_light_distance_discovered]
],
storylines: [
[30, 2, 4, 4, "Here- it is! This is a diagram--- of the solar-- system--. It was printed-- over-- fifty-- years- ago. Geez-- that's-- old."],
[ 0 - 2, 10, 5, 5, "The label- reads: Sun. The length- of the Astronomical-------- Unit-- (AU), is the distance-- from the Sun- to the Earth. Which is about 150--- million--- kilometers----."],
[ 7 - 2, 10, 5, 5, "The label- reads: Mercury. Distance from Sun: 0.39AU------------ or- 3----- light-- minutes--."],
[14 - 2, 10, 5, 5, "The label- reads: Venus. Distance from Sun: 0.72AU------------ or- 6----- light-- minutes--."],
[21 - 2, 10, 5, 5, "The label- reads: Earth. Distance from Sun: 1.00AU------------ or- 8----- light-- minutes--."],
[28 - 2, 10, 5, 5, "The label- reads: Mars. Distance from Sun: 1.52AU------------ or- 12----- light-- minutes--."],
[35 - 2, 10, 5, 5, "The label- reads: Jupiter. Distance from Sun: 5.20AU------------ or- 45----- light-- minutes--."],
[42 - 2, 10, 5, 5, "The label- reads: Saturn. Distance from Sun: 9.53AU------------ or- 79----- light-- minutes--."],
[49 - 2, 10, 5, 5, "The label- reads: Uranus. Distance from Sun: 19.81AU------------ or- 159----- light-- minutes--."],
# [56 - 2, 15, 4, 4, "The label- reads: Neptune. Distance from Sun: 30.05AU------------ or- 4.1----- light-- hours--."],
[63 - 2, 10, 5, 5, "The label- reads: Pluto. Wait. WTF? Pluto-- isn't-- a planet."],
]
}
end
def speed_of_light_distance_discovered args
{
background: 'sprites/planets.png',
scenes: [
[13, 0, 44, 3, :speed_of_light_end_of_day]
],
storylines: [
[ 0 - 2, 10, 5, 5, "The label- reads: Sun. The length- of the Astronomical-------- Unit-- (AU), is the distance-- from the Sun- to the Earth. Which is about 150--- million--- kilometers----."],
[ 7 - 2, 10, 5, 5, "The label- reads: Mercury. Distance from Sun: 0.39AU------------ or- 3----- light-- minutes--."],
[14 - 2, 10, 5, 5, "The label- reads: Venus. Distance from Sun: 0.72AU------------ or- 6----- light-- minutes--."],
[21 - 2, 10, 5, 5, "The label- reads: Earth. Distance from Sun: 1.00AU------------ or- 8----- light-- minutes--."],
[28 - 2, 10, 5, 5, "The label- reads: Mars. Distance from Sun: 1.52AU------------ or- 12----- light-- minutes--."],
[35 - 2, 10, 5, 5, "The label- reads: Jupiter. Distance from Sun: 5.20AU------------ or- 45----- light-- minutes--."],
[42 - 2, 10, 5, 5, "The label- reads: Saturn. Distance from Sun: 9.53AU------------ or- 79----- light-- minutes--."],
[49 - 2, 10, 5, 5, "The label- reads: Uranus. Distance from Sun: 19.81AU------------ or- 159----- light-- minutes--."],
[56 - 2, 10, 5, 5, "The label- reads: Neptune. Distance from Sun: 30.05AU------------ or- 4.1----- light-- hours--. What?! The message--- I received-- was from a source-- farther-- than-- Neptune?!"],
[63 - 2, 10, 5, 5, "The label- reads: Pluto. Dista- Wait... Pluto-- isn't-- a planet. People-- thought- Pluto-- was a planet-- back- then?--"],
]
}
end
def speed_of_light_end_of_day args
{
fade: 60,
background: 'sprites/inside-home.png',
player: [35, 0],
storylines: [
[35, 10, 4, 4, "Wonder-- what the reply-- will be. Who- the hell is contacting--- me from beyond-- Neptune? This- has to be some- kind- of- joke."]
],
scenes: [
[31, 38, 10, 12, :serenity_alive_side_of_home]
]
}
end
</code></pre>
<h3 id='----rpg-roguelike---roguelike-starting-point---constants-rb'>Rpg Roguelike - Roguelike Starting Point - constants.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_roguelike/01_roguelike_starting_point/app/constants.rb
SHOW_LEGEND = true
SOURCE_TILE_SIZE = 16
DESTINATION_TILE_SIZE = 16
TILE_SHEET_SIZE = 256
TILE_R = 0
TILE_G = 0
TILE_B = 0
TILE_A = 255
</code></pre>
<h3 id='----rpg-roguelike---roguelike-starting-point---legend-rb'>Rpg Roguelike - Roguelike Starting Point - legend.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_roguelike/01_roguelike_starting_point/app/legend.rb
def tick_legend args
return unless SHOW_LEGEND
legend_padding = 16
legend_x = 1280 - TILE_SHEET_SIZE - legend_padding
legend_y = 720 - TILE_SHEET_SIZE - legend_padding
tile_sheet_sprite = [legend_x,
legend_y,
TILE_SHEET_SIZE,
TILE_SHEET_SIZE,
'sprites/simple-mood-16x16.png', 0,
TILE_A,
TILE_R,
TILE_G,
TILE_B]
if args.inputs.mouse.point.inside_rect? tile_sheet_sprite
mouse_row = args.inputs.mouse.point.y.idiv(SOURCE_TILE_SIZE)
tile_row = 15 - (mouse_row - legend_y.idiv(SOURCE_TILE_SIZE))
mouse_col = args.inputs.mouse.point.x.idiv(SOURCE_TILE_SIZE)
tile_col = (mouse_col - legend_x.idiv(SOURCE_TILE_SIZE))
args.outputs.primitives << [legend_x - legend_padding * 2,
mouse_row * SOURCE_TILE_SIZE, 256 + legend_padding * 2, 16, 128, 128, 128, 64].solid
args.outputs.primitives << [mouse_col * SOURCE_TILE_SIZE,
legend_y - legend_padding * 2, 16, 256 + legend_padding * 2, 128, 128, 128, 64].solid
sprite_key = sprite_lookup.find { |k, v| v == [tile_row, tile_col] }
if sprite_key
member_name, _ = sprite_key
member_name = member_name_as_code member_name
args.outputs.labels << [660, 70, "# CODE SAMPLE (place in the tick_game method located in main.rb)", -1, 0]
args.outputs.labels << [660, 50, "# GRID_X, GRID_Y, TILE_KEY", -1, 0]
args.outputs.labels << [660, 30, "args.outputs.sprites << tile_in_game( 5, 6, #{member_name} )", -1, 0]
else
args.outputs.labels << [660, 50, "Tile [#{tile_row}, #{tile_col}] not found. Add a key and value to app/sprite_lookup.rb:", -1, 0]
args.outputs.labels << [660, 30, "{ \"some_string\" => [#{tile_row}, #{tile_col}] } OR { some_symbol: [#{tile_row}, #{tile_col}] }.", -1, 0]
end
end
# render the sprite in the top right with a padding to the top and right so it's
# not flush against the edge
args.outputs.sprites << tile_sheet_sprite
# carefully place some ascii arrows to show the legend labels
args.outputs.labels << [895, 707, "ROW --->"]
args.outputs.labels << [943, 412, " ^"]
args.outputs.labels << [943, 412, " |"]
args.outputs.labels << [943, 394, "COL ---+"]
# use the tile sheet to print out row and column numbers
args.outputs.sprites << 16.map_with_index do |i|
sprite_key = i % 10
[
tile(1280 - TILE_SHEET_SIZE - legend_padding * 2 - SOURCE_TILE_SIZE,
720 - legend_padding * 2 - (SOURCE_TILE_SIZE * i),
sprite(sprite_key)),
tile(1280 - TILE_SHEET_SIZE - SOURCE_TILE_SIZE + (SOURCE_TILE_SIZE * i),
720 - TILE_SHEET_SIZE - legend_padding * 3, sprite(sprite_key))
]
end
end
</code></pre>
<h3 id='----rpg-roguelike---roguelike-starting-point---main-rb'>Rpg Roguelike - Roguelike Starting Point - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_roguelike/01_roguelike_starting_point/app/main.rb
require 'app/constants.rb'
require 'app/sprite_lookup.rb'
require 'app/legend.rb'
def tick args
tick_game args
tick_legend args
end
def tick_game args
# setup the grid
args.state.grid.padding = 104
args.state.grid.size = 512
# set up your game
# initialize the game/game defaults. ||= means that you only initialize it if
# the value isn't alread initialized
args.state.player.x ||= 0
args.state.player.y ||= 0
args.state.enemies ||= [
{ x: 10, y: 10, type: :goblin, tile_key: :G },
{ x: 15, y: 30, type: :rat, tile_key: :R }
]
args.state.info_message ||= "Use arrow keys to move around."
# handle keyboard input
# keyboard input (arrow keys to move player)
new_player_x = args.state.player.x
new_player_y = args.state.player.y
player_direction = ""
player_moved = false
if args.inputs.keyboard.key_down.up
new_player_y += 1
player_direction = "north"
player_moved = true
elsif args.inputs.keyboard.key_down.down
new_player_y -= 1
player_direction = "south"
player_moved = true
elsif args.inputs.keyboard.key_down.right
new_player_x += 1
player_direction = "east"
player_moved = true
elsif args.inputs.keyboard.key_down.left
new_player_x -= 1
player_direction = "west"
player_moved = true
end
#handle game logic
# determine if there is an enemy on that square,
# if so, don't let the player move there
if player_moved
found_enemy = args.state.enemies.find do |e|
e[:x] == new_player_x && e[:y] == new_player_y
end
if !found_enemy
args.state.player.x = new_player_x
args.state.player.y = new_player_y
args.state.info_message = "You moved #{player_direction}."
else
args.state.info_message = "You cannot move into a square an enemy occupies."
end
end
args.outputs.sprites << tile_in_game(args.state.player.x,
args.state.player.y, '@')
# render game
# render enemies at locations
args.outputs.sprites << args.state.enemies.map do |e|
tile_in_game(e[:x], e[:y], e[:tile_key])
end
# render the border
border_x = args.state.grid.padding - DESTINATION_TILE_SIZE
border_y = args.state.grid.padding - DESTINATION_TILE_SIZE
border_size = args.state.grid.size + DESTINATION_TILE_SIZE * 2
args.outputs.borders << [border_x,
border_y,
border_size,
border_size]
# render label stuff
args.outputs.labels << [border_x, border_y - 10, "Current player location is: #{args.state.player.x}, #{args.state.player.y}"]
args.outputs.labels << [border_x, border_y + 25 + border_size, args.state.info_message]
end
def tile_in_game x, y, tile_key
tile($gtk.args.state.grid.padding + x * DESTINATION_TILE_SIZE,
$gtk.args.state.grid.padding + y * DESTINATION_TILE_SIZE,
tile_key)
end
</code></pre>
<h3 id='----rpg-roguelike---roguelike-starting-point---sprite_lookup-rb'>Rpg Roguelike - Roguelike Starting Point - sprite_lookup.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_roguelike/01_roguelike_starting_point/app/sprite_lookup.rb
def sprite_lookup
{
0 => [3, 0],
1 => [3, 1],
2 => [3, 2],
3 => [3, 3],
4 => [3, 4],
5 => [3, 5],
6 => [3, 6],
7 => [3, 7],
8 => [3, 8],
9 => [3, 9],
'@' => [4, 0],
A: [ 4, 1],
B: [ 4, 2],
C: [ 4, 3],
D: [ 4, 4],
E: [ 4, 5],
F: [ 4, 6],
G: [ 4, 7],
H: [ 4, 8],
I: [ 4, 9],
J: [ 4, 10],
K: [ 4, 11],
L: [ 4, 12],
M: [ 4, 13],
N: [ 4, 14],
O: [ 4, 15],
P: [ 5, 0],
Q: [ 5, 1],
R: [ 5, 2],
S: [ 5, 3],
T: [ 5, 4],
U: [ 5, 5],
V: [ 5, 6],
W: [ 5, 7],
X: [ 5, 8],
Y: [ 5, 9],
Z: [ 5, 10],
a: [ 6, 1],
b: [ 6, 2],
c: [ 6, 3],
d: [ 6, 4],
e: [ 6, 5],
f: [ 6, 6],
g: [ 6, 7],
h: [ 6, 8],
i: [ 6, 9],
j: [ 6, 10],
k: [ 6, 11],
l: [ 6, 12],
m: [ 6, 13],
n: [ 6, 14],
o: [ 6, 15],
p: [ 7, 0],
q: [ 7, 1],
r: [ 7, 2],
s: [ 7, 3],
t: [ 7, 4],
u: [ 7, 5],
v: [ 7, 6],
w: [ 7, 7],
x: [ 7, 8],
y: [ 7, 9],
z: [ 7, 10],
'|' => [ 7, 12]
}
end
def sprite key
$gtk.args.state.reserved.sprite_lookup[key]
end
def member_name_as_code raw_member_name
if raw_member_name.is_a? Symbol
":#{raw_member_name}"
elsif raw_member_name.is_a? String
"'#{raw_member_name}'"
elsif raw_member_name.is_a? Fixnum
"#{raw_member_name}"
else
"UNKNOWN: #{raw_member_name}"
end
end
def tile x, y, tile_row_column_or_key
tile_extended x, y, DESTINATION_TILE_SIZE, DESTINATION_TILE_SIZE, TILE_R, TILE_G, TILE_B, TILE_A, tile_row_column_or_key
end
def tile_extended x, y, w, h, r, g, b, a, tile_row_column_or_key
row_or_key, column = tile_row_column_or_key
if !column
row, column = sprite row_or_key
else
row, column = row_or_key, column
end
if !row
member_name = member_name_as_code tile_row_column_or_key
raise "Unabled to find a sprite for #{member_name}. Make sure the value exists in app/sprite_lookup.rb."
end
# Sprite provided by Rogue Yun
# http://www.bay12forums.com/smf/index.php?topic=144897.0
# License: Public Domain
{
x: x,
y: y,
w: w,
h: h,
tile_x: column * 16,
tile_y: (row * 16),
tile_w: 16,
tile_h: 16,
r: r,
g: g,
b: b,
a: a,
path: 'sprites/simple-mood-16x16.png'
}
end
$gtk.args.state.reserved.sprite_lookup = sprite_lookup
</code></pre>
<h3 id='----rpg-roguelike---roguelike-line-of-sight---main-rb'>Rpg Roguelike - Roguelike Line Of Sight - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_roguelike/02_roguelike_line_of_sight/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- lambda: A way to define a block and its parameters with special syntax.
For example, the syntax of lambda looks like this:
my_lambda = -> { puts "This is my lambda" }
Reminders:
- args.outputs.labels: An array. The values generate a label.
The parameters are [X, Y, TEXT, SIZE, ALIGNMENT, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.
- ARRAY#inside_rect?: Returns whether or not the point is inside a rect.
- product: Returns an array of all combinations of elements from all arrays.
- find: Finds all elements of a collection that meet requirements.
- abs: Returns the absolute value.
=end
# This sample app allows the player to move around in the dungeon, which becomes more or less visible
# depending on the player's location, and also has enemies.
class Game
attr_accessor :args, :state, :inputs, :outputs, :grid
# Calls all the methods needed for the game to run properly.
def tick
defaults
render_canvas
render_dungeon
render_player
render_enemies
print_cell_coordinates
calc_canvas
input_move
input_click_map
end
# Sets default values and initializes variables
def defaults
outputs.background_color = [0, 0, 0] # black background
# Initializes empty canvas, dungeon, and enemies collections.
state.canvas ||= []
state.dungeon ||= []
state.enemies ||= []
# If state.area doesn't have value, load_area_one and derive_dungeon_from_area methods are called
if !state.area
load_area_one
derive_dungeon_from_area
# Changing these values will change the position of player
state.x = 7
state.y = 5
# Creates new enemies, sets their values, and adds them to the enemies collection.
state.enemies << state.new_entity(:enemy) do |e| # declares each enemy as new entity
e.x = 13 # position
e.y = 5
e.previous_hp = 3
e.hp = 3
e.max_hp = 3
e.is_dead = false # the enemy is alive
end
update_line_of_sight # updates line of sight by adding newly visible cells
end
end
# Adds elements into the state.area collection
# The dungeon is derived using the coordinates of this collection
def load_area_one
state.area ||= []
state.area << [8, 6]
state.area << [7, 6]
state.area << [7, 7]
state.area << [8, 9]
state.area << [7, 8]
state.area << [7, 9]
state.area << [6, 4]
state.area << [7, 3]
state.area << [7, 4]
state.area << [6, 5]
state.area << [7, 5]
state.area << [8, 5]
state.area << [8, 4]
state.area << [1, 1]
state.area << [0, 1]
state.area << [0, 2]
state.area << [1, 2]
state.area << [2, 2]
state.area << [2, 1]
state.area << [2, 3]
state.area << [1, 3]
state.area << [1, 4]
state.area << [2, 4]
state.area << [2, 5]
state.area << [1, 5]
state.area << [2, 6]
state.area << [3, 6]
state.area << [4, 6]
state.area << [4, 7]
state.area << [4, 8]
state.area << [5, 8]
state.area << [5, 9]
state.area << [6, 9]
state.area << [7, 10]
state.area << [7, 11]
state.area << [7, 12]
state.area << [7, 12]
state.area << [7, 13]
state.area << [8, 13]
state.area << [9, 13]
state.area << [10, 13]
state.area << [11, 13]
state.area << [12, 13]
state.area << [12, 12]
state.area << [8, 12]
state.area << [9, 12]
state.area << [10, 12]
state.area << [11, 12]
state.area << [12, 11]
state.area << [13, 11]
state.area << [13, 10]
state.area << [13, 9]
state.area << [13, 8]
state.area << [13, 7]
state.area << [13, 6]
state.area << [12, 6]
state.area << [14, 6]
state.area << [14, 5]
state.area << [13, 5]
state.area << [12, 5]
state.area << [12, 4]
state.area << [13, 4]
state.area << [14, 4]
state.area << [1, 6]
state.area << [6, 6]
end
# Starts with an empty dungeon collection, and adds dungeon cells into it.
def derive_dungeon_from_area
state.dungeon = [] # starts as empty collection
state.area.each do |a| # for each element of the area collection
state.dungeon << state.new_entity(:dungeon_cell) do |d| # declares each dungeon cell as new entity
d.x = a.x # dungeon cell position using coordinates from area
d.y = a.y
d.is_visible = false # cell is not visible
d.alpha = 0 # not transparent at all
d.border = [left_margin + a.x * grid_size,
bottom_margin + a.y * grid_size,
grid_size,
grid_size,
*blue,
255] # sets border definition for dungeon cell
d # returns dungeon cell
end
end
end
def left_margin
40 # sets left margin
end
def bottom_margin
60 # sets bottom margin
end
def grid_size
40 # sets size of grid square
end
# Updates the line of sight by calling the thick_line_of_sight method and
# adding dungeon cells to the newly_visible collection
def update_line_of_sight
variations = [-1, 0, 1]
# creates collection of newly visible dungeon cells
newly_visible = variations.product(variations).flat_map do |rise, run| # combo of all elements
thick_line_of_sight state.x, state.y, rise, run, 15, # calls thick_line_of_sight method
lambda { |x, y| dungeon_cell_exists? x, y } # checks whether or not cell exists
end.uniq# removes duplicates
state.dungeon.each do |d| # perform action on each element of dungeons collection
d.is_visible = newly_visible.find { |v| v.x == d.x && v.y == d.y } # finds match inside newly_visible collection
end
end
#Returns a boolean value
def dungeon_cell_exists? x, y
# Finds cell coordinates inside dungeon collection to determine if dungeon cell exists
state.dungeon.find { |d| d.x == x && d.y == y }
end
# Calls line_of_sight method to add elements to result collection
def thick_line_of_sight start_x, start_y, rise, run, distance, cell_exists_lambda
result = []
result += line_of_sight start_x, start_y, rise, run, distance, cell_exists_lambda
result += line_of_sight start_x - 1, start_y, rise, run, distance, cell_exists_lambda # one left
result += line_of_sight start_x + 1, start_y, rise, run, distance, cell_exists_lambda # one right
result
end
# Adds points to the result collection to create the player's line of sight
def line_of_sight start_x, start_y, rise, run, distance, cell_exists_lambda
result = [] # starts as empty collection
points = points_on_line start_x, start_y, rise, run, distance # calls points_on_line method
points.each do |p| # for each point in collection
if cell_exists_lambda.call(p.x, p.y) # if the cell exists
result << p # add it to result collection
else # if cell does not exist
return result # return result collection as it is
end
end
result # return result collection
end
# Finds the coordinates of the points on the line by performing calculations
def points_on_line start_x, start_y, rise, run, distance
distance.times.map do |i| # perform an action
[start_x + run * i, start_y + rise * i] # definition of point
end
end
def render_canvas
return
outputs.borders << state.canvas.map do |c| # on each element of canvas collection
c.border # outputs border
end
end
# Outputs the dungeon cells.
def render_dungeon
outputs.solids << [0, 0, grid.w, grid.h] # outputs black background for grid
# Sets the alpha value (opacity) for each dungeon cell and calls the cell_border method.
outputs.borders << state.dungeon.map do |d| # for each element in dungeon collection
d.alpha += if d.is_visible # if cell is visible
255.fdiv(30) # increment opacity (transparency)
else # if cell is not visible
255.fdiv(600) * -1 # decrease opacity
end
d.alpha = d.alpha.cap_min_max(0, 255)
cell_border d.x, d.y, [*blue, d.alpha] # sets blue border using alpha value
end.reject_nil
end
# Sets definition of a cell border using the parameters
def cell_border x, y, color = nil
[left_margin + x * grid_size,
bottom_margin + y * grid_size,
grid_size,
grid_size,
*color]
end
# Sets the values for the player and outputs it as a label
def render_player
outputs.labels << [grid_x(state.x) + 20, # positions "@" text in center of grid square
grid_y(state.y) + 35,
"@", # player is represented by a white "@" character
1, 1, *white]
end
def grid_x x
left_margin + x * grid_size # positions horizontally on grid
end
def grid_y y
bottom_margin + y * grid_size # positions vertically on grid
end
# Outputs enemies onto the screen.
def render_enemies
state.enemies.map do |e| # for each enemy in the collection
alpha = 255 # set opacity (full transparency)
# Outputs an enemy using a label.
outputs.labels << [
left_margin + 20 + e.x * grid_size, # positions enemy's "r" text in center of grid square
bottom_margin + 35 + e.y * grid_size,
"r", # enemy's text
1, 1, *white, alpha]
# Creates a red border around an enemy.
outputs.borders << [grid_x(e.x), grid_y(e.y), grid_size, grid_size, *red]
end
end
#White labels are output for the cell coordinates of each element in the dungeon collection.
def print_cell_coordinates
return unless state.debug
state.dungeon.each do |d|
outputs.labels << [grid_x(d.x) + 2,
grid_y(d.y) - 2,
"#{d.x},#{d.y}",
-2, 0, *white]
end
end
# Adds new elements into the canvas collection and sets their values.
def calc_canvas
return if state.canvas.length > 0 # return if canvas collection has at least one element
15.times do |x| # 15 times perform an action
15.times do |y|
state.canvas << state.new_entity(:canvas) do |c| # declare canvas element as new entity
c.x = x # set position
c.y = y
c.border = [left_margin + x * grid_size,
bottom_margin + y * grid_size,
grid_size,
grid_size,
*white, 30] # sets border definition
end
end
end
end
# Updates x and y values of the player, and updates player's line of sight
def input_move
x, y, x_diff, y_diff = input_target_cell
return unless dungeon_cell_exists? x, y # player can't move there if a dungeon cell doesn't exist in that location
return if enemy_at x, y # player can't move there if there is an enemy in that location
state.x += x_diff # increments x by x_diff (so player moves left or right)
state.y += y_diff # same with y and y_diff ( so player moves up or down)
update_line_of_sight # updates visible cells
end
def enemy_at x, y
# Finds if coordinates exist in enemies collection and enemy is not dead
state.enemies.find { |e| e.x == x && e.y == y && !e.is_dead }
end
#M oves the user based on their keyboard input and sets values for target cell
def input_target_cell
if inputs.keyboard.key_down.up # if "up" key is in "down" state
[state.x, state.y + 1, 0, 1] # user moves up
elsif inputs.keyboard.key_down.down # if "down" key is pressed
[state.x, state.y - 1, 0, -1] # user moves down
elsif inputs.keyboard.key_down.left # if "left" key is pressed
[state.x - 1, state.y, -1, 0] # user moves left
elsif inputs.keyboard.key_down.right # if "right" key is pressed
[state.x + 1, state.y, 1, 0] # user moves right
else
nil # otherwise, empty
end
end
# Goes through the canvas collection to find if the mouse was clicked inside of the borders of an element.
def input_click_map
return unless inputs.mouse.click # return unless the mouse is clicked
canvas_entry = state.canvas.find do |c| # find element from canvas collection that meets requirements
inputs.mouse.click.inside_rect? c.border # find border that mouse was clicked inside of
end
puts canvas_entry # prints canvas_entry value
end
# Sets the definition of a label using the parameters.
def label text, x, y, color = nil
color ||= white # color is initialized to white
[x, y, text, 1, 1, *color] # sets label definition
end
def green
[60, 200, 100] # sets color saturation to shade of green
end
def blue
[50, 50, 210] # sets color saturation to shade of blue
end
def white
[255, 255, 255] # sets color saturation to white
end
def red
[230, 80, 80] # sets color saturation to shade of red
end
def orange
[255, 80, 60] # sets color saturation to shade of orange
end
def pink
[255, 0, 200] # sets color saturation to shade of pink
end
def gray
[75, 75, 75] # sets color saturation to shade of gray
end
# Recolors the border using the parameters.
def recolor_border border, r, g, b
border[4] = r
border[5] = g
border[6] = b
border
end
# Returns a boolean value.
def visible? cell
# finds cell's coordinates inside visible_cells collections to determine if cell is visible
state.visible_cells.find { |c| c.x == cell.x && c.y == cell.y}
end
# Exports dungeon by printing dungeon cell coordinates
def export_dungeon
state.dungeon.each do |d| # on each element of dungeon collection
puts "state.dungeon << [#{d.x}, #{d.y}]" # prints cell coordinates
end
end
def distance_to_cell cell
distance_to state.x, cell.x, state.y, cell.y # calls distance_to method
end
def distance_to from_x, x, from_y, y
(from_x - x).abs + (from_y - y).abs # finds distance between two cells using coordinates
end
end
$game = Game.new
def tick args
$game.args = args
$game.state = args.state
$game.inputs = args.inputs
$game.outputs = args.outputs
$game.grid = args.grid
$game.tick
end
</code></pre>
<h3 id='----rpg-tactical---hexagonal-grid---main-rb'>Rpg Tactical - Hexagonal Grid - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_tactical/hexagonal_grid/app/main.rb
class HexagonTileGame
attr_gtk
def defaults
state.tile_scale = 1.3
state.tile_size = 80
state.tile_w = Math.sqrt(3) * state.tile_size.half
state.tile_h = state.tile_size * 3/4
state.tiles_x_count = 1280.idiv(state.tile_w) - 1
state.tiles_y_count = 720.idiv(state.tile_h) - 1
state.world_width_px = state.tiles_x_count * state.tile_w
state.world_height_px = state.tiles_y_count * state.tile_h
state.world_x_offset = (1280 - state.world_width_px).half
state.world_y_offset = (720 - state.world_height_px).half
state.tiles ||= state.tiles_x_count.map_with_ys(state.tiles_y_count) do |ordinal_x, ordinal_y|
{
ordinal_x: ordinal_x,
ordinal_y: ordinal_y,
offset_x: (ordinal_y.even?) ?
(state.world_x_offset + state.tile_w.half.half) :
(state.world_x_offset - state.tile_w.half.half),
offset_y: state.world_y_offset,
w: state.tile_w,
h: state.tile_h,
type: :blank,
path: "sprites/hexagon-gray.png",
a: 20
}.associate do |h|
h.merge(x: h[:offset_x] + h[:ordinal_x] * h[:w],
y: h[:offset_y] + h[:ordinal_y] * h[:h]).scale_rect(state.tile_scale)
end.associate do |h|
h.merge(center: {
x: h[:x] + h[:w].half,
y: h[:y] + h[:h].half
}, radius: [h[:w].half, h[:h].half].max)
end
end
end
def input
if inputs.click
tile = state.tiles.find { |t| inputs.click.point_inside_circle? t[:center], t[:radius] }
if tile
tile[:a] = 255
tile[:path] = "sprites/hexagon-black.png"
end
end
end
def tick
defaults
input
render
end
def render
outputs.sprites << state.tiles
end
end
$game = HexagonTileGame.new
def tick args
$game.args = args
$game.tick
end
$gtk.reset
</code></pre>
<h3 id='----rpg-tactical---isometric-grid---main-rb'>Rpg Tactical - Isometric Grid - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_tactical/isometric_grid/app/main.rb
class Isometric
attr_accessor :grid, :inputs, :state, :outputs
def tick
defaults
render
calc
process_inputs
end
def defaults
state.quantity ||= 6 #Size of grid
state.tileSize ||= [262 / 2, 194 / 2] #width and heigth of orange tiles
state.tileGrid ||= [] #Holds ordering of tiles
state.currentSpriteLocation ||= -1 #Current Sprite hovering location
state.tileCords ||= [] #Physical, rendering cordinates
state.initCords ||= [640 - (state.quantity / 2 * state.tileSize[0]), 330] #Location of tile (0, 0)
state.sideSize ||= [state.tileSize[0] / 2, 242 / 2] #Purple & green cube face size
state.mode ||= :delete #Switches between :delete and :insert
state.spriteSelection ||= [['river', 0, 0, 262 / 2, 194 / 2],
['mountain', 0, 0, 262 / 2, 245 / 2],
['ocean', 0, 0, 262 / 2, 194 / 2]] #Storage for sprite information
#['name', deltaX, deltaY, sizeW, sizeH]
#^delta refers to distance from tile cords
#Orders tiles based on tile placement and fancy math. Very left: 0,0. Very bottom: quantity-1, 0, etc
if state.tileGrid == []
tempX = 0
tempY = 0
tempLeft = false
tempRight = false
count = 0
(state.quantity * state.quantity).times do
if tempY == 0
tempLeft = true
end
if tempX == (state.quantity - 1)
tempRight = true
end
state.tileGrid.push([tempX, tempY, true, tempLeft, tempRight, count])
#orderX, orderY, exists?, leftSide, rightSide, order
tempX += 1
if tempX == state.quantity
tempX = 0
tempY += 1
end
tempLeft = false
tempRight = false
count += 1
end
end
#Calculates physical cordinates for tiles
if state.tileCords == []
state.tileCords = state.tileGrid.map do
|val|
x = (state.initCords[0]) + ((val[0] + val[1]) * state.tileSize[0] / 2)
y = (state.initCords[1]) + (-1 * val[0] * state.tileSize[1] / 2) + (val[1] * state.tileSize[1] / 2)
[x, y, val[2], val[3], val[4], val[5], -1] #-1 represents sprite on top of tile. -1 for now
end
end
end
def render
renderBackground
renderLeft
renderRight
renderTiles
renderObjects
renderLabels
end
def renderBackground
outputs.solids << [0, 0, 1280, 720, 0, 0, 0] #Background color
end
def renderLeft
#Shows the pink left cube face
outputs.sprites << state.tileCords.map do
|val|
if val[2] == true && val[3] == true #Checks if the tile exists and right face needs to be rendered
[val[0], val[1] + (state.tileSize[1] / 2) - state.sideSize[1], state.sideSize[0],
state.sideSize[1], 'sprites/leftSide.png']
end
end
end
def renderRight
#Shows the green right cube face
outputs.sprites << state.tileCords.map do
|val|
if val[2] == true && val[4] == true #Checks if it exists & checks if right face needs to be rendered
[val[0] + state.tileSize[0] / 2, val[1] + (state.tileSize[1] / 2) - state.sideSize[1], state.sideSize[0],
state.sideSize[1], 'sprites/rightSide.png']
end
end
end
def renderTiles
#Shows the tile itself. Important that it's rendered after the two above!
outputs.sprites << state.tileCords.map do
|val|
if val[2] == true #Chcekcs if tile needs to be rendered
if val[5] == state.currentSpriteLocation
[val[0], val[1], state.tileSize[0], state.tileSize[1], 'sprites/selectedTile.png']
else
[val[0], val[1], state.tileSize[0], state.tileSize[1], 'sprites/tile.png']
end
end
end
end
def renderObjects
#Renders the sprites on top of the tiles. Order of rendering: top corner to right corner and cascade down until left corner
#to bottom corner.
a = (state.quantity * state.quantity) - state.quantity
iter = 0
loop do
if state.tileCords[a][2] == true && state.tileCords[a][6] != -1
outputs.sprites << [state.tileCords[a][0] + state.spriteSelection[state.tileCords[a][6]][1],
state.tileCords[a][1] + state.spriteSelection[state.tileCords[a][6]][2],
state.spriteSelection[state.tileCords[a][6]][3], state.spriteSelection[state.tileCords[a][6]][4],
'sprites/' + state.spriteSelection[state.tileCords[a][6]][0] + '.png']
end
iter += 1
a += 1
a -= state.quantity * 2 if iter == state.quantity
iter = 0 if iter == state.quantity
break if a < 0
end
end
def renderLabels
#Labels
outputs.labels << [50, 680, 'Click to delete!', 5, 0, 255, 255, 255, 255] if state.mode == :delete
outputs.labels << [50, 640, 'Press \'i\' for insert mode!', 5, 0, 255, 255, 255, 255] if state.mode == :delete
outputs.labels << [50, 680, 'Click to insert!', 5, 0, 255, 255, 255, 255] if state.mode == :insert
outputs.labels << [50, 640, 'Press \'d\' for delete mode!', 5, 0, 255, 255, 255, 255] if state.mode == :insert
end
def calc
calcCurrentHover
end
def calcCurrentHover
#This determines what tile the mouse is hovering (or last hovering) over
x = inputs.mouse.position.x
y = inputs.mouse.position.y
m = (state.tileSize[1] / state.tileSize[0]) #slope
state.tileCords.map do
|val|
#Conditions that makes runtime faster. Checks if the mouse click was between tile dimensions (rectangle collision)
next unless val[0] < x && x < val[0] + state.tileSize[0]
next unless val[1] < y && y < val[1] + state.tileSize[1]
next unless val[2] == true
tempBool = false
if x == val[0] + (state.tileSize[0] / 2)
#The height of a diamond is the height of the diamond, so if x equals that exact point, it must be inside the diamond
tempBool = true
elsif x < state.tileSize[0] / 2 + val[0]
#Uses y = (m) * (x - x1) + y1 to determine the y values for the two diamond lines on the left half of diamond
tempY1 = (m * (x - val[0])) + val[1] + (state.tileSize[1] / 2)
tempY2 = (-1 * m * (x - val[0])) + val[1] + (state.tileSize[1] / 2)
#Checks to see if the mouse click y value is between those temp y values
tempBool = true if y < tempY1 && y > tempY2
elsif x > state.tileSize[0] / 2 + val[0]
#Uses y = (m) * (x - x1) + y1 to determine the y values for the two diamond lines on the right half of diamond
tempY1 = (m * (x - val[0] - (state.tileSize[0] / 2))) + val[1]
tempY2 = (-1 * m * (x - val[0] - (state.tileSize[0] / 2))) + val[1] + state.tileSize[1]
#Checks to see if the mouse click y value is between those temp y values
tempBool = true if y > tempY1 && y < tempY2
end
if tempBool == true
state.currentSpriteLocation = val[5] #Current sprite location set to the order value
end
end
end
def process_inputs
#Makes development much faster and easier
if inputs.keyboard.key_up.r
$dragon.reset
end
checkTileSelected
switchModes
end
def checkTileSelected
if inputs.mouse.down
x = inputs.mouse.down.point.x
y = inputs.mouse.down.point.y
m = (state.tileSize[1] / state.tileSize[0]) #slope
state.tileCords.map do
|val|
#Conditions that makes runtime faster. Checks if the mouse click was between tile dimensions (rectangle collision)
next unless val[0] < x && x < val[0] + state.tileSize[0]
next unless val[1] < y && y < val[1] + state.tileSize[1]
next unless val[2] == true
tempBool = false
if x == val[0] + (state.tileSize[0] / 2)
#The height of a diamond is the height of the diamond, so if x equals that exact point, it must be inside the diamond
tempBool = true
elsif x < state.tileSize[0] / 2 + val[0]
#Uses y = (m) * (x - x1) + y1 to determine the y values for the two diamond lines on the left half of diamond
tempY1 = (m * (x - val[0])) + val[1] + (state.tileSize[1] / 2)
tempY2 = (-1 * m * (x - val[0])) + val[1] + (state.tileSize[1] / 2)
#Checks to see if the mouse click y value is between those temp y values
tempBool = true if y < tempY1 && y > tempY2
elsif x > state.tileSize[0] / 2 + val[0]
#Uses y = (m) * (x - x1) + y1 to determine the y values for the two diamond lines on the right half of diamond
tempY1 = (m * (x - val[0] - (state.tileSize[0] / 2))) + val[1]
tempY2 = (-1 * m * (x - val[0] - (state.tileSize[0] / 2))) + val[1] + state.tileSize[1]
#Checks to see if the mouse click y value is between those temp y values
tempBool = true if y > tempY1 && y < tempY2
end
if tempBool == true
if state.mode == :delete
val[2] = false
state.tileGrid[val[5]][2] = false #Unnecessary because never used again but eh, I like consistency
state.tileCords[val[5]][2] = false #Ensures that the tile isn't rendered
unless state.tileGrid[val[5]][0] == 0 #If tile is the left most tile in the row, right doesn't get rendered
state.tileGrid[val[5] - 1][4] = true #Why the order value is amazing
state.tileCords[val[5] - 1][4] = true
end
unless state.tileGrid[val[5]][1] == state.quantity - 1 #Same but left side
state.tileGrid[val[5] + state.quantity][3] = true
state.tileCords[val[5] + state.quantity][3] = true
end
elsif state.mode == :insert
#adds the current sprite value selected to tileCords. (changes from the -1 earlier)
val[6] = rand(state.spriteSelection.length)
end
end
end
end
end
def switchModes
#Switches between insert and delete modes
if inputs.keyboard.key_up.i && state.mode == :delete
state.mode = :insert
inputs.keyboard.clear
elsif inputs.keyboard.key_up.d && state.mode == :insert
state.mode = :delete
inputs.keyboard.clear
end
end
end
$isometric = Isometric.new
def tick args
$isometric.grid = args.grid
$isometric.inputs = args.inputs
$isometric.state = args.state
$isometric.outputs = args.outputs
$isometric.tick
end
</code></pre>
<h3 id='----rpg-topdown---topdown-starting-point---main-rb'>Rpg Topdown - Topdown Starting Point - main.rb</h3>
<pre><code class="language-ruby"># ./samples/99_genre_rpg_topdown/topdown_starting_point/app/main.rb
=begin
APIs listing that haven't been encountered in previous sample apps:
- reverse: Returns a new string with the characters from original string in reverse order.
For example, the command
"dragonruby".reverse
would return the string
"yburnogard".
Reverse is not only limited to strings, but can be applied to arrays and other collections.
Reminders:
- ARRAY#intersect_rect?: Returns true or false depending on if two rectangles intersect.
- args.outputs.labels: An array. The values generate a label.
The parameters are [X, Y, TEXT, SIZE, ALIGNMENT, RED, GREEN, BLUE, ALPHA, FONT STYLE]
For more information about labels, go to mygame/documentation/02-labels.md.
=end
# This code shows a maze and uses input from the keyboard to move the user around the screen.
# The objective is to reach the goal.
# Sets values of tile size and player's movement speed
# Also creates tile or box for player and generates map
def tick args
args.state.tile_size = 80
args.state.player_speed = 4
args.state.player ||= tile(args, 7, 3, 0, 128, 180)
generate_map args
# Adds walls, goal, and player to args.outputs.solids so they appear on screen
args.outputs.solids << args.state.walls
args.outputs.solids << args.state.goal
args.outputs.solids << args.state.player
# If player's box intersects with goal, a label is output onto the screen
if args.state.player.intersect_rect? args.state.goal
args.outputs.labels << [30, 720 - 30, "You're a wizard Harry!!"] # 30 pixels lower than top of screen
end
move_player args, -1, 0 if args.inputs.keyboard.left # x position decreases by 1 if left key is pressed
move_player args, 1, 0 if args.inputs.keyboard.right # x position increases by 1 if right key is pressed
move_player args, 0, 1 if args.inputs.keyboard.up # y position increases by 1 if up is pressed
move_player args, 0, -1 if args.inputs.keyboard.down # y position decreases by 1 if down is pressed
end
# Sets position, size, and color of the tile
def tile args, x, y, *color
[x * args.state.tile_size, # sets definition for array using method parameters
y * args.state.tile_size, # multiplying by tile_size sets x and y to correct position using pixel values
args.state.tile_size,
args.state.tile_size,
*color]
end
# Creates map by adding tiles to the wall, as well as a goal (that the player needs to reach)
def generate_map args
return if args.state.area
# Creates the area of the map. There are 9 rows running horizontally across the screen
# and 16 columns running vertically on the screen. Any spot with a "1" is not
# open for the player to move into (and is green), and any spot with a "0" is available
# for the player to move in.
args.state.area = [
[1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1,],
[1, 1, 1, 2, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1,], # the "2" represents the goal
[1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
].reverse # reverses the order of the area collection
# By reversing the order, the way that the area appears above is how it appears
# on the screen in the game. If we did not reverse, the map would appear inverted.
#The wall starts off with no tiles.
args.state.walls = []
# If v is 1, a green tile is added to args.state.walls.
# If v is 2, a black tile is created as the goal.
args.state.area.map_2d do |y, x, v|
if v == 1
args.state.walls << tile(args, x, y, 0, 255, 0) # green tile
elsif v == 2 # notice there is only one "2" above because there is only one single goal
args.state.goal = tile(args, x, y, 0, 0, 0) # black tile
end
end
end
# Allows the player to move their box around the screen
def move_player args, *vector
box = args.state.player.shift_rect(vector) # box is able to move at an angle
# If the player's box hits a wall, it is not able to move further in that direction
return if args.state.walls
.any_intersect_rect?(box)
# Player's box is able to move at angles (not just the four general directions) fast
args.state.player =
args.state.player
.shift_rect(vector.x * args.state.player_speed, # if we don't multiply by speed, then
vector.y * args.state.player_speed) # the box will move extremely slow
end
</code></pre>
<h2 id='---oss'>OSS</h2>
<p>
Follows is a source code listing for all files that have been open sourced. This code can be found online at <a href='https://github.com/DragonRuby/dragonruby-game-toolkit-contrib/'>https://github.com/DragonRuby/dragonruby-game-toolkit-contrib/</a>.
</p>
<h3 id='----args-rb'>args.rb</h3>
<pre><code class="language-ruby"># ./dragon/args.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# args.rb has been released under MIT (*only this file*).
module GTK
# This class is the one you'll interact with the most. It's
# constructed by the DragonRuby Runtime and is provided to you on
# each tick.
class Args
include ArgsDeprecated
include Serialize
attr_accessor :inputs
attr_accessor :outputs
attr_accessor :audio
attr_accessor :grid
attr_accessor :recording
attr_accessor :geometry
attr_accessor :fn
attr_accessor :state
attr_accessor :temp_state
attr_accessor :runtime
alias_method :gtk, :runtime
attr_accessor :passes
attr_accessor :wizards
attr_accessor :layout
attr_accessor :easing
attr_accessor :string
def initialize runtime, recording
@inputs = Inputs.new
@outputs = Outputs.new args: self
@audio = {}
@passes = []
@state = OpenEntity.new
@temp_state = OpenEntity.new
@state.tick_count = -1
@runtime = runtime
@recording = recording
@grid = Grid.new runtime
@render_targets = {}
@pixel_arrays = {}
@all_tests = []
@geometry = GTK::Geometry
@fn = GTK::Fn
@wizards = Wizards.new
@layout = GTK::Layout.new @grid.w, @grid.h
@easing = GTK::Easing
@string = String
end
# The number of ticks since the start of the game.
#
# @return [Integer]
def tick_count
@state.tick_count
end
def tick_count= value
@state.tick_count = value
end
def serialize
{
state: state.as_hash,
temp_state: temp_state.as_hash,
inputs: inputs.serialize,
passes: passes.serialize,
outputs: outputs.serialize,
grid: grid.serialize
}
end
def destructure
[grid, inputs, state, outputs, runtime, passes]
end
def clear_pixel_arrays
pixel_arrays_clear
end
def pixel_arrays_clear
@pixel_arrays = {}
end
def pixel_arrays
@pixel_arrays
end
def pixel_array name
name = name.to_s
if !@pixel_arrays[name]
@pixel_arrays[name] = PixelArray.new
end
@pixel_arrays[name]
end
def clear_render_targets
render_targets_clear
end
def render_targets_clear
@render_targets = {}
end
def render_targets
@render_targets
end
def render_target name
name = name.to_s
if !@render_targets[name]
@render_targets[name] = Outputs.new(args: self, target: name, background_color_override: [255, 255, 255, 0])
@passes << @render_targets[name]
end
@render_targets[name]
end
def solids
@outputs.solids
end
def static_solids
@outputs.static_solids
end
def sprites
@outputs.sprites
end
def static_sprites
@outputs.static_sprites
end
def labels
@outputs.labels
end
def static_labels
@outputs.static_labels
end
def lines
@outputs.lines
end
def static_lines
@outputs.static_lines
end
def borders
@outputs.borders
end
def static_borders
@outputs.static_borders
end
def primitives
@outputs.primitives
end
def static_primitives
@outputs.static_primitives
end
def keyboard
@inputs.keyboard
end
def click
return nil unless @inputs.mouse.click
@inputs.mouse.click.point
end
def click_at
return nil unless @inputs.mouse.click
@inputs.mouse.click.created_at
end
def mouse
@inputs.mouse
end
# @see Inputs#controller_one
# @return (see Inputs#controller_one)
def controller_one
@inputs.controller_one
end
# @see Inputs#controller_two
# @return (see Inputs#controller_two)
def controller_two
@inputs.controller_two
end
def autocomplete_methods
[:inputs, :outputs, :gtk, :state, :geometry, :audio, :grid, :layout, :fn]
end
end
end
</code></pre>
<h3 id='----assert-rb'>assert.rb</h3>
<pre><code class="language-ruby"># ./dragon/assert.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# assert.rb has been released under MIT (*only this file*).
module GTK
=begin
This is a tiny assertion api for the unit testing portion of Game Toolkit.
@example
1. Create a file called tests.rb under mygame.
2. Any method that begins with the word test_ will be considered a test.
def test_this_works args, assert
assert.equal! 1, 1
end
3. To run a test, save the file while the game is running.
@example
To add an assertion open up this class and write:
class Assert
def custom_assertion actual, expected, message = nil
# this tells Game Toolkit that an assertion was performed (so that the test isn't marked inconclusive).
@assertion_performed = true
# perform your custom logic here and raise an exception to denote a failure.
raise "Some Error. #{message}."
end
end
=end
class Assert
attr :assertion_performed
=begin
Use this if you are throwing your own exceptions and you want to mark the tests as ran (so that it wont be marked as inconclusive).
=end
def ok!
@assertion_performed = true
end
=begin
Assert if a value is a truthy value. All assert methods take an optional final parameter that is the message to display to the user.
@example
def test_does_this_work args, assert
some_result = Person.new
assert.true! some_result
# OR
assert.true! some_result, "Person was not created."
end
=end
def true! value, message = nil
@assertion_performed = true
if !value
message = "#{value} was not truthy.\n#{message}"
raise "#{message}"
end
nil
end
=begin
Assert if a value is a falsey value.
@example
def test_does_this_work args, assert
some_result = nil
assert.false! some_result
end
=end
def false! value, message = nil
@assertion_performed = true
if value
message = "#{value} was not falsey.\n#{message}"
raise message
end
nil
end
=begin
Assert if two values are equal.
@example
def test_does_this_work args, assert
a = 1
b = 1
assert.equal! a, b
end
=end
def equal! actual, expected, message = nil
@assertion_performed = true
if actual != expected
actual_string = "#{actual}#{actual.nil? ? " (nil) " : " " }".strip
message = "actual:\n#{actual_string}\n\ndid not equal\n\nexpected:\n#{expected}\n#{message}"
raise message
end
nil
end
def not_equal! actual, expected, message = nil
@assertion_performed = true
if actual == expected
actual_string = "#{actual}#{actual.nil? ? " (nil) " : " " }".strip
message = "actual:\n#{actual_string}\n\nequaled\n\nexpected:\n#{expected}\n#{message}"
raise message
end
nil
end
=begin
Assert if a value is explicitly nil (not false).
@example
def test_does_this_work args, assert
a = nil
b = false
assert.nil! a # this will pass
assert.nil! b # this will throw an exception.
end
=end
def nil! value, message = nil
@assertion_performed = true
if !value.nil?
message = "#{value} was supposed to be nil, but wasn't.\n#{message}"
raise message
end
nil
end
end
end
</code></pre>
<h3 id='----attr_gtk-rb'>attr_gtk.rb</h3>
<pre><code class="language-ruby"># ./dragon/attr_gtk.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# attr_gtk.rb has been released under MIT (*only this file*).
# @private
module AttrGTK
attr_accessor :args
def keyboard
args.inputs.keyboard
end
def grid
args.grid
end
def state
args.state
end
def temp_state
args.temp_state
end
def inputs
args.inputs
end
def outputs
args.outputs
end
def gtk
args.gtk
end
def passes
args.passes
end
def pixel_arrays
args.pixel_arrays
end
def geometry
args.geometry
end
def layout
args.layout
end
def new_entity entity_type, init_hash = nil, &block
args.state.new_entity entity_type, init_hash, &block
end
def new_entity_strict entity_type, init_hash = nil, &block
args.state.new_entity_strict entity_type, init_hash, &block
end
end
</code></pre>
<h3 id='----attr_sprite-rb'>attr_sprite.rb</h3>
<pre><code class="language-ruby"># ./dragon/attr_sprite.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# attr_sprite.rb has been released under MIT (*only this file*).
# @private
module AttrRect
include GTK::Geometry
def left
(@x || self.x)
end
def right
(@x || self.x) + (@w || self.w)
end
def bottom
(@y || self.y)
end
def top
(@y || self.y) + (@h || self.h)
end
def x1
(@x || self.x)
end
def y1
(@y || self.y)
end
end
module AttrSprite
include AttrRect
attr_accessor :x, :y, :w, :h, :path, :angle, :a, :r, :g, :b, :tile_x,
:tile_y, :tile_w, :tile_h, :flip_horizontally,
:flip_vertically, :angle_anchor_x, :angle_anchor_y, :id,
:source_x, :source_y, :source_w, :source_h, :blendmode_enum
def primitive_marker
:sprite
end
def sprite
self
end
def x1= value
@x = value
end
def y1= value
@y = value
end
end
</code></pre>
<h3 id='----console-rb'>console.rb</h3>
<pre><code class="language-ruby"># ./dragon/console.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# console.rb has been released under MIT (*only this file*).
# Contributors outside of DragonRuby who also hold Copyright:
# - Kevin Fischer: https://github.com/kfischer-okarin
module GTK
class Console
include ConsoleDeprecated
attr_accessor :show_reason, :log, :logo, :background_color,
:text_color, :animation_duration,
:max_log_lines, :max_history, :log,
:last_command_errored, :last_command, :error_color, :shown_at,
:header_color, :archived_log, :last_log_lines, :last_log_lines_count,
:suppress_left_arrow_behavior, :command_set_at,
:toast_ids, :bottom,
:font_style, :menu
def initialize
@font_style = FontStyle.new(font: 'font.ttf', size_enum: -1.5, line_height: 1.1)
@menu = Menu.new self
@disabled = false
@log_offset = 0
@visible = false
@toast_ids = []
@archived_log = []
@log = [ 'Console ready.' ]
@max_log_lines = 1000 # I guess...?
@max_history = 1000 # I guess...?
@log_invocation_count = 0
@command_history = []
@command_history_index = -1
@nonhistory_input = ''
@logo = 'console-logo.png'
@history_fname = 'console_history.txt'
@background_color = Color.new [0, 0, 0, 224]
@text_color = Color.new [255, 255, 255]
@error_color = Color.new [200, 50, 50]
@header_color = Color.new [100, 200, 220]
@code_color = Color.new [210, 168, 255]
@comment_color = Color.new [0, 200, 100]
@animation_duration = 1.seconds
@shown_at = -1
load_history
end
def console_text_width
@console_text_width ||= ($gtk.logical_width - 20).idiv(font_style.letter_size.x)
end
def save_history
$gtk.ffi_file.write_root @history_fname, (@command_history.reverse.join "\n")
end
def load_history
@command_history.clear
str = $gtk.ffi_file.read @history_fname
return if str.nil? # no history to load.
str.chomp!("\n") # Don't let endlines at the end cause extra blank line.
str.chomp!("\r")
str.each_line { |s|
s.chomp!("\n")
s.chomp!("\r")
if s.length > 0
@command_history.unshift s
break if @command_history.length >= @max_history
end
}
@command_history.uniq!
end
def disable
@disabled = true
end
def enable
@disabled = false
end
def add_sprite obj
@log_invocation_count += 1
obj[:id] ||= "id_#{obj[:path]}_#{Time.now.to_i}".to_sym
if @last_line_log_index &&
@last_sprite_line.is_a?(Hash) &&
@last_sprite_line[:id] == obj[:id]
@log[@last_line_log_index] = obj
return
end
@log << obj
@last_line_log_index = @log.length - 1
@last_sprite_line = obj
nil
end
def add_primitive obj
if obj.is_a? Hash
add_sprite obj
else
add_text obj
end
nil
end
def add_text obj
@last_log_lines_count ||= 1
@log_invocation_count += 1
str = obj.to_s
log_lines = []
str.each_line do |s|
s.wrapped_lines(self.console_text_width).each do |l|
log_lines << l
end
end
if log_lines == @last_log_lines
@last_log_lines_count += 1
new_log_line_with_count = @last_log_lines.last + " (#{@last_log_lines_count})"
if log_lines.length > 1
@log = @log[0..-(@log.length - log_lines.length)] + log_lines[0..-2] + [new_log_line_with_count]
else
@log = @log[0..-2] + [new_log_line_with_count]
end
return
end
log_lines.each do |l|
@log.shift if @log.length > @max_log_lines
@log << l
end
@last_log_lines_count = 1
@last_log_lines = log_lines
nil
end
def ready?
visible? && @toggled_at.elapsed?(@animation_duration, Kernel.global_tick_count)
end
def hidden?
!@visible
end
def visible?
@visible
end
def open reason = nil
show reason
end
def show reason = nil
@shown_at = Kernel.global_tick_count
@show_reason = reason
toggle if hidden?
end
# @gtk
def hide
if visible?
toggle
@archived_log += @log
if @archived_log.length > @max_log_lines
@archived_log = @archived_log.drop(@archived_log.length - @max_log_lines)
end
@log.clear
@show_reason = nil
clear_toast
end
end
def close
hide
end
def clear_toast
@toasted_at = nil
@toast_duration = 0
end
def toggle
@visible = !@visible
@toggled_at = Kernel.global_tick_count
end
def currently_toasting?
return false if hidden?
return false unless @show_reason == :toast
return false unless @toasted_at
return false if @toasted_at.elapsed?(5.seconds, Kernel.global_tick_count)
return true
end
def toast_extended id = nil, duration = nil, *messages
if !id.is_a?(Symbol)
raise <<-S
* ERROR:
args.gtk.console.toast has the following signature:
def toast id, *messages
end
The id property uniquely defines the message and must be
a symbol.
After that, you can provide all the objects you want to
look at.
Example:
args.gtk.console.toast :say_hello,
\"Hello world.\",
args.state.tick_count
Toast messages autohide after 5 seconds.
If you need to look at something for longer, use
args.gtk.console.perma_toast instead (which you can manually dismiss).
S
end
return if currently_toasting?
return if @toast_ids.include? id
@toasted_at = Kernel.global_tick_count
log_once_info :perma_toast_tip, "Use console.perma_toast to show the toast for longer."
dwim_duration = 5.seconds
add_text "* toast :#{id}"
puts "* TOAST: :#{id}"
messages.each do |message|
lines = message.to_s.wrapped_lines(self.console_text_width)
dwim_duration += lines.length.seconds
add_text "** #{message}"
puts "** #{message}"
end
show :toast
@toast_duration += duration || dwim_duration
@toast_ids << id
set_command "$gtk.console.hide"
end
def perma_toast id = nil, messages
toast_extended id, 600.seconds, *messages
end
def toast id = nil, *messages
toast_extended id, nil, *messages
end
def console_toggle_keys
[
:backtick!,
:tilde!,
:superscript_two!,
:section_sign!,
:ordinal_indicator!,
:circumflex!,
]
end
def console_toggle_key_down? args
args.inputs.keyboard.key_down.any? console_toggle_keys
end
def try_search_docs exception
string_e = "#{exception}"
@last_command_errored = true
if (string_e.include? "wrong number of arguments")
method_name = ((string_e.split ":")[0].gsub "'", "")
if !(method_name.include? " ")
results = (Kernel.__docs_search_results__ method_name)
if !results.include? "* DOCS: No results found."
puts (results.join "\n")
puts <<-S
* INFO: #{results.length} matches(s) found in DOCS for ~#{method_name}~ (see above).
You can search the documentation yourself using the following command in the Console:
#+begin_src ruby
docs_search \"#{method_name}\"
#+end_src
S
log_once_info :exported_search_results, "The search results above has been seen in logs/puts.txt and docs/search_results.txt."
end
end
end
rescue Exception => se
puts <<-S
* FATAL: ~GTK::Console#try_search_docs~
There was an exception searching for docs (~GTK::Console#try_search_docs~). You might want to let DragonRuby know about this.
** INNER EXCEPTION
#{se}
S
end
def eval_the_set_command
cmd = current_input_str.strip
if cmd.length != 0
@log_offset = 0
prompt.clear
@command_history.pop while @command_history.length >= @max_history
@command_history.unshift cmd
@command_history_index = -1
@nonhistory_input = ''
if cmd == 'quit' || cmd == ':wq' || cmd == ':q!' || cmd == ':q' || cmd == ':wqa'
$gtk.request_quit
elsif cmd.start_with? ':'
send ((cmd.gsub '-', '_').gsub ':', '')
else
puts "-> #{cmd}"
begin
@last_command = cmd
Kernel.eval("$results = (#{cmd})")
if $results.nil?
puts "=> nil"
elsif $results == :console_silent_eval
# do nothing since the console is silent
else
puts "=> #{$results}"
end
@last_command_errored = false
rescue Exception => e
try_search_docs e
# if an exception is thrown and the bactrace includes something helpful, then show it
if (e.backtrace || []).first && (e.backtrace.first.include? "(eval)")
puts "* EXCEPTION: #{e}"
else
puts "* EXCEPTION: #{e}\n#{e.__backtrace_to_org__}"
end
end
end
end
end
def inputs_scroll_up_full? args
return false if @disabled
args.inputs.keyboard.key_down.pageup ||
(args.inputs.keyboard.key_up.b && args.inputs.keyboard.key_up.control)
end
def scroll_to_bottom
@log_offset = 0
end
def scroll_up_full
@log_offset += lines_on_one_page
@log_offset = @log.size if @log_offset > @log.size
end
def inputs_scroll_up_half? args
return false if @disabled
args.inputs.keyboard.ctrl_u
end
def scroll_up_half
@log_offset += lines_on_one_page.idiv(2)
@log_offset = @log.size if @log_offset > @log.size
end
def inputs_scroll_down_full? args
return false if @disabled
args.inputs.keyboard.key_down.pagedown ||
(args.inputs.keyboard.key_up.f && args.inputs.keyboard.key_up.control)
end
def scroll_down_full
@log_offset -= lines_on_one_page
@log_offset = 0 if @log_offset < 0
end
def inputs_scroll_down_half? args
return false if @disabled
args.inputs.keyboard.ctrl_d
end
def inputs_clear_command? args
return false if @disabled
args.inputs.keyboard.escape || args.inputs.keyboard.ctrl_g
end
def scroll_down_half
@log_offset -= lines_on_one_page.idiv(2)
@log_offset = 0 if @log_offset < 0
end
def mouse_wheel_scroll args
@inertia ||= 0
if args.inputs.mouse.wheel && args.inputs.mouse.wheel.y > 0
@inertia = 1
elsif args.inputs.mouse.wheel && args.inputs.mouse.wheel.y < 0
@inertia = -1
end
if args.inputs.mouse.click
@inertia = 0
end
return if @inertia == 0
if @inertia != 0
@inertia = (@inertia * 0.7)
if @inertia > 0
@log_offset -= 1
elsif @inertia < 0
@log_offset += 1
end
end
if @inertia.abs < 0.01
@inertia = 0
end
if @log_offset > @log.size
@log_offset = @log.size
elsif @log_offset < 0
@log_offset = 0
end
end
def process_inputs args
if console_toggle_key_down? args
args.inputs.text.clear
toggle
end
return unless visible?
args.inputs.text.each { |str| prompt << str }
args.inputs.text.clear
mouse_wheel_scroll args
@log_offset = 0 if @log_offset < 0
if args.inputs.keyboard.key_down.enter
eval_the_set_command
elsif args.inputs.keyboard.key_down.v
if args.inputs.keyboard.key_down.control || args.inputs.keyboard.key_down.meta
prompt << $gtk.ffi_misc.getclipboard
end
elsif args.inputs.keyboard.key_down.home
prompt.move_cursor_home
elsif args.inputs.keyboard.key_down.end
prompt.move_cursor_end
elsif args.inputs.keyboard.key_down.up
if @command_history_index == -1
@nonhistory_input = current_input_str
end
if @command_history_index < (@command_history.length - 1)
@command_history_index += 1
self.current_input_str = @command_history[@command_history_index].dup
end
elsif args.inputs.keyboard.key_down.down
if @command_history_index == 0
@command_history_index = -1
self.current_input_str = @nonhistory_input
@nonhistory_input = ''
elsif @command_history_index > 0
@command_history_index -= 1
self.current_input_str = @command_history[@command_history_index].dup
end
elsif args.inputs.keyboard.key_down.left
if args.inputs.keyboard.key_down.control
prompt.move_cursor_left_word
else
prompt.move_cursor_left
end
elsif args.inputs.keyboard.key_down.right
if args.inputs.keyboard.key_down.control
prompt.move_cursor_right_word
else
prompt.move_cursor_right
end
elsif inputs_scroll_up_full? args
scroll_up_full
elsif inputs_scroll_down_full? args
scroll_down_full
elsif inputs_scroll_up_half? args
scroll_up_half
elsif inputs_scroll_down_half? args
scroll_down_half
elsif inputs_clear_command? args
prompt.clear
@command_history_index = -1
@nonhistory_input = ''
elsif args.inputs.keyboard.key_down.backspace
prompt.backspace
elsif args.inputs.keyboard.key_down.delete
prompt.delete
elsif args.inputs.keyboard.key_down.tab
prompt.autocomplete
end
args.inputs.keyboard.key_down.clear
args.inputs.keyboard.key_up.clear
args.inputs.keyboard.key_held.clear
end
def write_primitive_and_return_offset(args, left, y, str, archived: false)
if str.is_a?(Hash)
padding = 10
args.outputs.reserved << [left + 10, y + 5, str[:w], str[:h], str[:path]].sprite
return str[:h] + padding
else
write_line args, left, y, str, archived: archived
return line_height_px
end
end
def write_line(args, left, y, str, archived: false)
color = color_for_log_entry(str)
color = color.mult_alpha(0.5) if archived
args.outputs.reserved << font_style.label(x: left.shift_right(10), y: y, text: str, color: color)
end
def should_tick?
return false if !@toggled_at
return false if slide_progress == 0
return false if @disabled
return visible?
end
def render args
return if !@toggled_at
return if slide_progress == 0
@bottom = top - (h * slide_progress)
args.outputs.reserved << [left, @bottom, w, h, *@background_color.mult_alpha(slide_progress)].solid
args.outputs.reserved << [right.shift_left(110), @bottom.shift_up(630), 100, 100, @logo, 0, (80.0 * slide_progress).to_i].sprite
y = @bottom + 2 # just give us a little padding at the bottom.
prompt.render args, x: left.shift_right(10), y: y
y += line_height_px * 1.5
args.outputs.reserved << line(y: y, color: @text_color.mult_alpha(slide_progress))
y += line_height_px.to_f / 2.0
((@log.size - @log_offset) - 1).downto(0) do |idx|
offset_after_write = write_primitive_and_return_offset args, left, y, @log[idx]
y += offset_after_write
break if y > top
end
# past log separator
args.outputs.reserved << line(y: y + line_height_px.half, color: @text_color.mult_alpha(0.25 * slide_progress))
y += line_height_px
((@archived_log.size - @log_offset) - 1).downto(0) do |idx|
offset_after_write = write_primitive_and_return_offset args, left, y, @archived_log[idx], archived: true
y += offset_after_write
break if y > top
end
render_log_offset args
args.outputs.reserved << { x: 10.from_right, y: @bottom + 10,
text: "Press CTRL+g or ESCAPE to clear the prompt.",
vertical_alignment_enum: 0,
alignment_enum: 2, r: 80, g: 80, b: 80 }.label!
end
def render_log_offset args
return if @log_offset <= 0
args.outputs.reserved << font_style.label(
x: right.shift_left(5),
y: top.shift_down(5 + line_height_px),
text: "[#{@log_offset}/#{@log.size}]",
color: @text_color,
alignment_enum: 2
)
end
def include_error_marker? text
include_any_words?(text.gsub('OutputsDeprecated', ''), error_markers)
end
def error_markers
["exception:", "error:", "undefined method", "failed", "syntax", "deprecated"]
end
def include_subdued_markers? text
(text.start_with? "* INFO: ") && (include_any_words? text, subdued_markers)
end
def include_any_words? text, words
words.any? { |w| text.downcase.include?(w) && !text.downcase.include?(":#{w}") }
end
def subdued_markers
["reloaded", "exported the", "~require~"]
end
def calc args
if visible? &&
@show_reason == :toast &&
@toasted_at &&
@toasted_at.elapsed?(@toast_duration, Kernel.global_tick_count)
hide
end
if !$gtk.paused? && visible? && (show_reason == :exception || show_reason == :exception_on_load)
hide
end
if $gtk.files_reloaded.length > 0
clear_toast
@toast_ids.clear
end
end
def tick args
begin
return if @disabled
render args
process_inputs args
return unless should_tick?
calc args
prompt.tick
menu.tick args
rescue Exception => e
begin
puts "#{e}"
puts "* FATAL: The GTK::Console console threw an unhandled exception and has been reset. You should report this exception (along with reproduction steps) to DragonRuby."
rescue
end
@disabled = true
$stdout.puts e
$stdout.puts "* FATAL: The GTK::Console console threw an unhandled exception and has been reset. You should report this exception (along with reproduction steps) to DragonRuby."
end
end
def set_command_with_history_silent command, histories, show_reason = nil
set_command_extended command: command, histories: histories, show_reason: show_reason
end
def defaults_set_command_extended
{
command: "puts 'Hello World'",
histories: [],
show_reason: nil,
force: false
}
end
def set_command_extended opts
opts = defaults_set_command_extended.merge opts
@command_history.concat opts[:histories]
@command_history << opts[:command] if @command_history[-1] != opts[:command]
self.current_input_str = opts[:command] if @command_set_at != Kernel.global_tick_count || opts[:force]
@command_set_at = Kernel.global_tick_count
@command_history_index = -1
save_history
end
def set_command_with_history command, histories, show_reason = nil
set_command_with_history_silent command, histories, show_reason
show show_reason
end
# @gtk
def set_command command, show_reason = nil
set_command_silent command, show_reason
show show_reason
end
def set_command_silent command, show_reason = nil
set_command_with_history_silent command, [], show_reason
end
def set_system_command command, show_reason = nil
if $gtk.platform == "Mac OS X"
set_command_silent "$gtk.system \"open #{command}\""
else
set_command_silent "$gtk.system \"start #{command}\""
end
end
def system_command
if $gtk.platform == "Mac OS X"
"open"
else
"start"
end
end
private
def w
$gtk.logical_width
end
def h
$gtk.logical_height
end
# methods top; left; right
# Forward to grid
%i[top left right].each do |method|
define_method method do
$gtk.args.grid.send(method)
end
end
def line_height_px
font_style.line_height_px
end
def lines_on_one_page
(h - 4).idiv(line_height_px)
end
def line(y:, color:)
[left, y, right, y, *color].line
end
def include_row_marker? log_entry
log_entry[0] == "|"
end
def include_header_marker? log_entry
return false if (log_entry.strip.include? ".rb")
(log_entry.start_with? "* ") ||
(log_entry.start_with? "** ") ||
(log_entry.start_with? "*** ") ||
(log_entry.start_with? "**** ")
end
def code? log_entry
(just_symbol? log_entry) || (codeblock_marker? log_entry)
end
def just_symbol? log_entry
scrubbed = log_entry.gsub("*", "").strip
(scrubbed.start_with? ":") && (!scrubbed.include? " ") && (!scrubbed.include? "=>")
end
def code_comment? log_entry
return true if log_entry.strip.start_with?("# ")
return false
end
def codeblock_marker? log_entry
return true if log_entry.strip.start_with?("#+begin_src")
return true if log_entry.strip.start_with?("#+end_src")
return false
end
def color_for_log_entry(log_entry)
if code? log_entry
@code_color
elsif code_comment? log_entry
@comment_color
elsif include_row_marker? log_entry
@text_color
elsif include_error_marker? log_entry
@error_color
elsif include_subdued_markers? log_entry
@text_color.mult_alpha(0.5)
elsif include_header_marker? log_entry
@header_color
elsif log_entry.start_with?("====")
@header_color
else
@text_color
end
end
def prompt
@prompt ||= Prompt.new(font_style: font_style, text_color: @text_color, console_text_width: console_text_width)
end
def current_input_str
prompt.current_input_str
end
def current_input_str=(str)
prompt.current_input_str = str
end
def clear
@archived_log.clear
@log.clear
@prompt.clear
:console_silent_eval
end
def slide_progress
return 0 if !@toggled_at
if visible?
@slide_progress = @toggled_at.global_ease(@animation_duration, :flip, :quint, :flip)
else
@slide_progress = @toggled_at.global_ease(@animation_duration, :flip, :quint)
end
@slide_progress
end
end
end
</code></pre>
<h3 id='----console_color-rb'>console_color.rb</h3>
<pre><code class="language-ruby"># ./dragon/console_color.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# console_color.rb has been released under MIT (*only this file*).
# Contributors outside of DragonRuby who also hold Copyright:
# - Kevin Fischer: https://github.com/kfischer-okarin
module GTK
class Console
class Color
def initialize(color)
@color = color
@color << 255 if @color.size == 3
end
def mult_alpha(alpha_modifier)
Color.new [@color[0], @color[1], @color[2], (@color[3].to_f * alpha_modifier).to_i]
end
# Support splat operator
def to_a
@color
end
def to_s
"GTK::Console::Color #{to_h}"
end
def to_h
{ r: @color[0], g: @color[1], b: @color[2], a: @color[3] }
end
end
end
end
</code></pre>
<h3 id='----console_font_style-rb'>console_font_style.rb</h3>
<pre><code class="language-ruby"># ./dragon/console_font_style.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# console_font_style.rb has been released under MIT (*only this file*).
# Contributors outside of DragonRuby who also hold Copyright:
# - Kevin Fischer: https://github.com/kfischer-okarin
module GTK
class Console
class FontStyle
attr_reader :font, :size_enum, :line_height
def initialize(font:, size_enum:, line_height:)
@font = font
@size_enum = size_enum
@line_height = line_height
end
def letter_size
@letter_size ||= $gtk.calcstringbox 'W', size_enum, font
end
def line_height_px
@line_height_px ||= letter_size.y * line_height
end
def label(x:, y:, text:, color:, alignment_enum: 0)
{
x: x,
y: y.shift_up(line_height_px), # !!! FIXME: remove .shift_up(line_height_px) when we fix coordinate origin on labels.
text: text,
font: font,
size_enum: size_enum,
alignment_enum: alignment_enum,
**color.to_h,
}.label!
end
end
end
end
</code></pre>
<h3 id='----console_menu-rb'>console_menu.rb</h3>
<pre><code class="language-ruby"># ./dragon/console_menu.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# console_menu.rb has been released under MIT (*only this file*).
module GTK
class Console
class Menu
attr_accessor :buttons
def initialize console
@console = console
end
def record_clicked
$recording.start 100
end
def replay_clicked
$replay.start 'replay.txt'
end
def reset_clicked
$gtk.reset
end
def scroll_up_clicked
@console.scroll_up_half
end
def scroll_down_clicked
@console.scroll_down_half
end
def show_menu_clicked
@menu_shown = :visible
end
def close_clicked
@menu_shown = :hidden
@console.hide
end
def hide_menu_clicked
@menu_shown = :hidden
end
def framerate_diagnostics_clicked
@console.scroll_to_bottom
$gtk.framerate_diagnostics
end
def itch_wizard_clicked
@console.scroll_to_bottom
$wizards.itch.restart
end
def docs_clicked
@console.scroll_to_bottom
log Kernel.docs_classes
end
def scroll_end_clicked
@console.scroll_to_bottom
end
def custom_buttons
[]
end
def tick args
return unless @console.visible?
@menu_shown ||= :hidden
if $gtk.production
@buttons = [
(button id: :record, row: 0, col: 9, text: "record gameplay", method: :record_clicked),
(button id: :replay, row: 0, col: 10, text: "start replay", method: :replay_clicked),
*custom_buttons
]
elsif @menu_shown == :hidden
@buttons = [
(button id: :show_menu, row: 0, col: 10, text: "show menu", method: :show_menu_clicked),
]
else
@buttons = [
(button id: :scroll_up, row: 0, col: 6, text: "scroll up", method: :scroll_up_clicked),
(button id: :scroll_down, row: 0, col: 7, text: "scroll down", method: :scroll_down_clicked),
(button id: :scroll_down, row: 0, col: 8, text: "scroll end", method: :scroll_end_clicked),
(button id: :close, row: 0, col: 9, text: "close console", method: :close_clicked),
(button id: :hide, row: 0, col: 10, text: "hide menu", method: :hide_menu_clicked),
(button id: :record, row: 1, col: 7, text: "record gameplay", method: :record_clicked),
(button id: :replay, row: 1, col: 8, text: "start replay", method: :replay_clicked),
(button id: :record, row: 1, col: 9, text: "framerate diagnostics", method: :framerate_diagnostics_clicked),
(button id: :reset, row: 1, col: 10, text: "reset game", method: :reset_clicked),
(button id: :reset, row: 2, col: 10, text: "docs", method: :docs_clicked),
(button id: :reset, row: 2, col: 9, text: "itch wizard", method: :itch_wizard_clicked),
*custom_buttons
]
end
# render
args.outputs.reserved << @buttons.map { |b| b[:primitives] }
# inputs
if args.inputs.mouse.click
clicked = @buttons.find { |b| args.inputs.mouse.inside_rect? b[:rect] }
if clicked
args.inputs.mouse.click = nil
send clicked[:method]
end
end
end
def rect_for_layout row, col
col_width = 100
row_height = 50
col_margin = 5
row_margin = 5
x = (col_margin + (col * col_width) + (col * col_margin))
y = (row_margin + (row * row_height) + (row * row_margin) + row_height).from_top
{ x: x, y: y, w: col_width, h: row_height }
end
def button args
id, row, col, text, method = args[:id], args[:row], args[:col], args[:text], args[:method]
font_height = @console.font_style.line_height_px.half
{
id: id,
rect: (rect_for_layout row, col),
text: text,
method: method
}.let do |entity|
primitives = []
primitives << entity[:rect].solid!(a: 164)
primitives << entity[:rect].border!(r: 255, g: 255, b: 255)
primitives << text.wrapped_lines(5)
.map_with_index do |l, i|
[
entity[:rect][:x] + entity[:rect][:w].half,
entity[:rect][:y] + entity[:rect][:h].half + font_height - (i * (font_height + 2)),
l, -3, 1, 255, 255, 255
]
end.labels
entity.merge(primitives: primitives)
end
end
def serialize
{
not_supported: "#{self}"
}
end
end
end
end
</code></pre>
<h3 id='----console_prompt-rb'>console_prompt.rb</h3>
<pre><code class="language-ruby"># ./dragon/console_prompt.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# console_prompt.rb has been released under MIT (*only this file*).
# Contributors outside of DragonRuby who also hold Copyright:
# - Kevin Fischer: https://github.com/kfischer-okarin
module GTK
class Console
class Prompt
# ? Can be changed, it was just taken from my editor settings :>
WORD_LIMITER_CHARS = "`~!@#$%^&*-=+()[]{}\|;:'\",.<>/?_ \t\n\0".chars
attr_accessor :current_input_str, :font_style, :console_text_width, :last_input_str, :last_input_str_changed
def initialize(font_style:, text_color:, console_text_width:)
@prompt = '-> '
@current_input_str = ''
@font_style = font_style
@text_color = text_color
@cursor_color = Color.new [187, 21, 6]
@console_text_width = console_text_width
@cursor_position = 0
update_cursor_position_px
@last_autocomplete_prefix = nil
@next_candidate_index = 0
end
def update_cursor_position_px
@cursor_position_px = ($gtk.calcstringbox (@prompt + @current_input_str[0...@cursor_position]), @font_style.size_enum, @font_style.font).x
end
def current_input_str=(str)
@current_input_str = str
@cursor_position = str.length
update_cursor_position_px
end
def <<(str)
@current_input_str = @current_input_str[0...@cursor_position] + str + @current_input_str[@cursor_position..-1]
@cursor_position += str.length
update_cursor_position_px
@current_input_changed_at = Kernel.global_tick_count
reset_autocomplete
end
def backspace
return if current_input_str.length.zero? || @cursor_position.zero?
@current_input_str = @current_input_str[0...(@cursor_position - 1)] + @current_input_str[@cursor_position..-1]
@cursor_position -= 1
update_cursor_position_px
reset_autocomplete
end
def delete
return if current_input_str.length.zero? || @cursor_position == current_input_str.length
@cursor_position += 1
backspace
end
def move_cursor_left
@cursor_position -= 1 if @cursor_position > 0
update_cursor_position_px
end
def move_cursor_left_word
return if @cursor_position.zero?
new_pos = @cursor_position - 1
(is_word_boundary? @current_input_str[new_pos]) ?
(new_pos -= 1 until !(is_word_boundary? @current_input_str[new_pos - 1]) || new_pos.zero?):
(new_pos -= 1 until (is_word_boundary? @current_input_str[new_pos - 1]) || new_pos.zero?)
@cursor_position = new_pos
update_cursor_position_px
end
def move_cursor_right
@cursor_position += 1 if @cursor_position < current_input_str.length
update_cursor_position_px
end
def move_cursor_right_word
return if @cursor_position.equal? str_len
new_pos = @cursor_position + 1
(is_word_boundary? @current_input_str[new_pos]) ?
(new_pos += 1 until !(is_word_boundary? @current_input_str[new_pos]) || (new_pos.equal? str_len)):
(new_pos += 1 until (is_word_boundary? @current_input_str[new_pos]) || (new_pos.equal? str_len))
@cursor_position = new_pos
update_cursor_position_px
end
def move_cursor_home
@cursor_position = 0
update_cursor_position_px
end
def move_cursor_end
@cursor_position = str_len
update_cursor_position_px
end
def clear
@current_input_str = ''
@cursor_position = 0
update_cursor_position_px
reset_autocomplete
end
def autocomplete
if !@last_autocomplete_prefix
@last_autocomplete_prefix = calc_autocomplete_prefix
puts "* AUTOCOMPLETE CANDIDATES: #{current_input_str}.."
pretty_print_strings_as_table method_candidates(@last_autocomplete_prefix)
else
candidates = method_candidates(@last_autocomplete_prefix)
return if candidates.empty?
candidate = candidates[@next_candidate_index]
candidate = candidate[0..-2] + " = " if candidate.end_with? '='
@next_candidate_index += 1
@next_candidate_index = 0 if @next_candidate_index >= candidates.length
self.current_input_str = display_autocomplete_candidate(candidate)
update_cursor_position_px
end
rescue Exception => e
puts "* BUG: Tab autocompletion failed. Let us know about this.\n#{e}"
end
def pretty_print_strings_as_table items
if items.length == 0
puts <<-S.strip
+--------+
| (none) |
+--------+
S
else
# figure out the largest string
string_width = items.sort_by { |c| -c.to_s.length }.first
# add spacing to each side of the string which represents the cell width
cell_width = string_width.length + 2
# add spacing to each side of the cell to represent the column width
column_width = cell_width + 2
# determine the max number of columns that can fit on the screen
columns = @console_text_width.idiv column_width
columns = items.length if items.length < columns
# partition the original list of items into a string to be printed
items.each_slice(columns).each_with_index do |cells, i|
pretty_print_row_seperator string_width, cell_width, column_width, columns
pretty_print_row cells, string_width, cell_width, column_width, columns
end
pretty_print_row_seperator string_width, cell_width, column_width, columns
end
end
def pretty_print_row cells, string_width, cell_width, column_width, columns
# if the number of cells doesn't match the number of columns, then pad the array with empty values
cells += (columns - cells.length).map { "" }
# right align each cell value
formated_row = "|" + cells.map do |c|
"#{" " * (string_width.length - c.length) } #{c} |"
end.join
# remove separators between empty values
formated_row = formated_row.gsub(" | ", " ")
puts formated_row
end
def pretty_print_row_separator string_width, cell_width, column_width, columns
# this is a joint: +--------
column_joint = "+#{"-" * cell_width}"
# multiple joints create a row separator: +----+----+
puts (column_joint * columns) + "+"
end
def render(args, x:, y:)
args.outputs.reserved << font_style.label(x: x, y: y, text: "#{@prompt}#{current_input_str}", color: @text_color)
args.outputs.reserved << (@cursor_color.to_h.merge x: x + @cursor_position_px + 0.5,
y: y + 5,
x2: x + @cursor_position_px + 0.5,
y2: y + @font_style.letter_size.y + 4)
args.outputs.reserved << (@cursor_color.to_h.merge x: x + @cursor_position_px + 1,
y: y + 5,
x2: x + @cursor_position_px + 1,
y2: y + @font_style.letter_size.y + 4)
# debugging rectangle for string
# args.outputs.reserved << (@cursor_color.to_h.merge x: x,
# y: y + 5,
# w: @cursor_position_px,
# h: @font_style.letter_size.y).border
end
def tick
if (@current_input_changed_at) &&
(@current_input_changed_at < Kernel.global_tick_count) &&
(@last_input_str != @current_input_str)
@last_input_str_changed = true
@last_input_str = "#{@current_input_str}"
@current_input_changed_at = nil
else
@last_input_str_changed = false
end
end
private
def last_period_index
current_input_str.rindex('.')
end
def calc_autocomplete_prefix
if last_period_index
current_input_str[(last_period_index + 1)..-1]
else
current_input_str
end
end
def current_object
return Kernel unless last_period_index
Kernel.eval(current_input_str[0...last_period_index])
rescue NameError
nil
end
def method_candidates(prefix)
current_object.autocomplete_methods.map(&:to_s).select { |m| m.start_with? prefix }
end
def display_autocomplete_candidate(candidate)
if last_period_index
@current_input_str[0..last_period_index] + candidate.to_s
else
candidate.to_s
end
end
def reset_autocomplete
@last_autocomplete_prefix = nil
@next_candidate_index = 0
end
def is_word_boundary? char
# Alternative method
# (WORD_LIMITER_CHARS - [char]).length != WORD_LIMITER_CHARS.length
# Production code
WORD_LIMITER_CHARS.include? char
end
def str_len
@current_input_str.length
end
end
end
end
</code></pre>
<h3 id='----controller-rb'>controller.rb</h3>
<pre><code class="language-ruby"># ./dragon/controller.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# controller.rb has been released under MIT (*only this file*).
module GTK
# @gtk
class Controller
# Access to keys that have been pressed down.
#
# @return [Controller::Keys]
# @gtk
attr_reader :key_down
# Access to keys that have been released up.
#
# @return [Controller::Keys]
# @gtk
attr_reader :key_up
# Access to keys that have been held down.
#
# @return [Controller::Keys]
# @gtk
attr_reader :key_held
# @gtk
attr_accessor :left_analog_x_raw,
:left_analog_y_raw,
:left_analog_x_perc,
:left_analog_y_perc,
:right_analog_x_raw,
:right_analog_y_raw,
:right_analog_x_perc,
:right_analog_y_perc
def initialize
@key_down = Controller::Keys.new
@key_up = Controller::Keys.new
@key_held = Controller::Keys.new
@left_analog_x_raw = 0
@left_analog_y_raw = 0
@left_analog_x_perc = 0
@left_analog_y_perc = 0
@right_analog_x_raw = 0
@right_analog_y_raw = 0
@right_analog_x_perc = 0
@right_analog_y_perc = 0
end
def serialize
{
key_down: @key_down.serialize,
key_held: @key_held.serialize,
key_up: @key_up.serialize
}
end
# Clear all current key presses.
#
# @return [void]
def clear
@key_down.clear
@key_up.clear
@key_held.clear
end
def up
@key_up.up || @key_held.up
end
def down
@key_up.down || @key_held.down
end
def left
@key_up.left || @key_held.left
end
def right
@key_up.right || @key_held.right
end
# Activates a key into the down position.
#
# @param key [Symbol] The key to press down.
#
# @return [void]
def activate_down(key)
key_down.activate(key)
key_held.deactivate(key)
key_up.deactivate(key)
end
# Activates a key into the held down position.
#
# @param key [Symbol] The key to hold down.
#
# @return [void]
def activate_held(key)
key_down.deactivate(key)
key_held.activate(key) unless key_held.send(key)
key_up.deactivate(key)
end
# Activates a key release into the up position.
#
# @param key [Symbol] The key release up.
#
# @return [void]
def activate_up(key)
key_down.deactivate(key)
key_held.deactivate(key)
key_up.activate(key)
end
include DirectionalInputHelperMethods
end
end
</code></pre>
<h3 id='----controller/config-rb'>controller/config.rb</h3>
<pre><code class="language-ruby"># ./dragon/controller/config.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# controller/config.rb has been released under MIT (*only this file*).
# !!! FIXME: add console command to forget custom binding(s)
# !!! FIXME: add console command to forget replace existing binding(s)
# !!! FIXME: add console command go into play_around mode to make sure controller isn't wonky.
module GTK
class Controller
class Config
def initialize runtime
@runtime = runtime
@raw_joysticks = {} # things that aren't game controllers to try to configure.
@target = nil
@animation_duration = (1.5).seconds
@toggled_at = 0
@fading = 0
@current_part = 0
@part_alpha = 0
@part_alpha_increment = 10
@joystick_state = {}
@playing_around = false
@used_bindings = {}
@bindings = []
@parts = [
[ 919, 282, 'A button', 'a' ],
[ 960, 323, 'B button', 'b' ],
[ 878, 323, 'X button', 'x' ],
[ 919, 365, 'Y button', 'y' ],
[ 433, 246, 'left stick left', '-leftx' ],
[ 497, 246, 'left stick right', '+leftx' ],
[ 466, 283, 'left stick up', '-lefty' ],
[ 466, 218, 'left stick down', '+lefty' ],
[ 466, 246, 'left stick button', 'leftstick' ],
[ 741, 246, 'right stick left', '-rightx' ],
[ 802, 246, 'right stick right', '+rightx' ],
[ 773, 283, 'right stick up', '-righty' ],
[ 773, 218, 'right stick down', '+righty' ],
[ 772, 246, 'right stick button', 'rightstick' ],
[ 263, 465, 'left shoulder button', 'leftshoulder' ],
[ 263, 503, 'left trigger', 'lefttrigger' ],
[ 977, 465, 'right shoulder button', 'rightshoulder' ],
[ 977, 503, 'right trigger', 'righttrigger' ],
[ 318, 365, 'D-pad up', 'dpup' ],
[ 360, 322, 'D-pad right', 'dpright' ],
[ 318, 280, 'D-pad down', 'dpdown' ],
[ 275, 322, 'D-pad left', 'dpleft' ],
[ 570, 402, 'select/back button', 'back'],
[ 619, 448, 'guide/home button', 'guide' ],
[ 669, 402, 'start button', 'start' ],
]
end
def rawjoystick_connected jid, joystickname, guid
return if jid < 0
@raw_joysticks[jid] = { name: joystickname, guid: guid }
end
def rawjoystick_disconnected jid
return if jid < 0
if @raw_joysticks[jid] != nil
@raw_joysticks.delete(jid)
@runtime.ffi_misc.close_raw_joystick(jid)
# Fade out the config screen if we were literally configuring this controller right now.
if [email protected]? && @target[0] == jid
@target[0] = nil
@toggled_at = Kernel.global_tick_count
@fading = -1
end
end
end
def build_binding_string
bindingstr = ''
skip = false
for i in [email protected]
if skip ; skip = false ; next ; end
binding = @bindings[i]
next if binding.nil?
part = @parts[i][3]
# clean up string:
# if axis uses -a0 for negative and +a0 for positive, just make it "leftx:a0" instead of "-leftx:-a0,+leftx:+a0"
# if axis uses +a0 for negative and -a0 for positive, just make it "leftx:a0~" instead of "-leftx:+a0,+leftx:-a0"
if part == '-leftx' || part == '-lefty' || part == '-rightx' || part == '-righty'
nextbinding = @bindings[i+1]
if binding.start_with?('-a') && nextbinding.start_with?('+a') && binding[2..-1] == nextbinding[2..-1]
skip = true
part = part[1..-1]
binding = binding[1..-1]
elsif binding.start_with?('+a') && nextbinding.start_with?('-a') && binding[2..-1] == nextbinding[2..-1]
skip = true
part = part[1..-1]
binding = "#{binding[1..-1]}~"
end
end
bindingstr += "#{!bindingstr.empty? ? ',' : ''}#{part}:#{binding}"
end
details = @target[1]
# !!! FIXME: no String.delete in mRuby?!?! Maybe so when upgrading.
#name = details[:name].delete(',')
# !!! FIXME: ...no regexp either... :/
#name = details[:name].gsub(/,/, ' ') # !!! FIXME: will SDL let you escape these instead?
unescaped = details[:name]
name = ''
for i in 0..unescaped.length-1
ch = unescaped[i]
name += (ch == ',') ? ' ' : ch
end
return "#{details[:guid]},#{name},platform:#{@runtime.platform},#{bindingstr}"
end
def move_to_different_part part
if !@joystick_state[:axes].nil?
@joystick_state[:axes].each { |i| i[:farthestval] = i[:startingval] if !i.nil? }
end
@current_part = part
end
def previous_part
if @current_part > 0
# remove the binding that we previous had here so it can be reused.
bindstr = @bindings[@current_part - 1]
@bindings[@current_part - 1] = nil
@used_bindings[bindstr] = nil
move_to_different_part @current_part - 1
end
end
def next_part
if @current_part < (@parts.length - 1)
move_to_different_part @current_part + 1
else
@playing_around = true
end
end
def set_binding bindstr
return false if !@used_bindings[bindstr].nil?
@used_bindings[bindstr] = @current_part
@bindings[@current_part] = bindstr
return true
end
# Called when a lowlevel joystick moves an axis.
def rawjoystick_axis jid, axis, value
return if @target.nil? || jid != @target[0] || @fading != 0 # skip if not currently considering this joystick.
@joystick_state[:axes] ||= []
@joystick_state[:axes][axis] ||= {
moving: false,
startingval: 0,
currentval: 0,
farthestval: 0
}
# this is the logic from SDL's controllermap.c, more or less, since this is hard to get right from scratch.
state = @joystick_state[:axes][axis]
state[:currentval] = value
if !state[:moving]
state[:moving] = true
state[:startingval] = value
state[:farthestval] = value
end
current_distance = (value - state[:startingval]).abs
farthest_distance = (state[:farthestval] - state[:startingval]).abs
if current_distance > farthest_distance
state[:farthestval] = value
farthest_distance = (state[:farthestval] - state[:startingval]).abs
end
# If we've gone out far enough and started to come back, let's bind this axis
if (farthest_distance >= 16000) && (current_distance <= 10000)
next_part if set_binding("#{(state[:farthestval] < 0) ? '-' : '+'}a#{axis}")
end
end
# Called when a lowlevel joystick moves a hat.
def rawjoystick_hat jid, hat, value
return if @target.nil? || jid != @target[0] || @fading != 0 # skip if not currently considering this joystick.
@joystick_state[:hats] ||= []
@joystick_state[:hats][hat] = value
return if value == 0 # 0 == centered, skip it
next_part if set_binding("h#{hat}.#{value}")
end
# Called when a lowlevel joystick moves a button.
def rawjoystick_button jid, button, pressed
return if @target.nil? || jid != @target[0] || @fading != 0 # skip if not currently considering this joystick.
@joystick_state[:buttons] ||= []
@joystick_state[:buttons][button] = pressed
return if !pressed
next_part if set_binding("b#{button}")
end
def calc_fading
if @fading == 0
return 255
elsif @fading > 0 # fading in
percent = @toggled_at.global_ease(@animation_duration, :flip, :quint, :flip)
if percent >= 1.0
percent = 1.0
@fading = 0
end
else # fading out
percent = @toggled_at.global_ease(@animation_duration, :flip, :quint)
if percent <= 0.0
percent = 0.0
@fading = 0
end
end
return (percent * 255.0).to_i
end
def render_basics args, msg, fade=255
joystickname = @target[1][:name]
args.outputs.primitives << [0, 0, $gtk.logical_width, $gtk.logical_height, 255, 255, 255, fade].solid
args.outputs.primitives << [0, 0, $gtk.logical_width, $gtk.logical_height, 'dragonruby-controller.png', 0, fade, 255, 255, 255].sprite
args.outputs.primitives << [$gtk.logical_width / 2, 700, joystickname, 2, 1, 0, 0, 0, fade].label
args.outputs.primitives << [$gtk.logical_height / 2, 650, msg, 0, 1, 0, 0, 0, 255].label if !msg.empty?
end
def render_part_highlight args, part, alpha=255
partsize = 41
args.outputs.primitives << [part[0], part[1], partsize, partsize, 255, 0, 0, alpha].border
args.outputs.primitives << [part[0]-1, part[1]-1, partsize+2, partsize+2, 255, 0, 0, alpha].border
args.outputs.primitives << [part[0]-2, part[1]-2, partsize+4, partsize+4, 255, 0, 0, alpha].border
end
def choose_target
if @target.nil?
while !@raw_joysticks.empty?
t = @raw_joysticks.shift # see if there's a joystick waiting on us.
next if t[0] < 0 # just in case.
next if t[1][:guid].nil? # did we already handle this guid? Dump it.
@target = t
break
end
return false if @target.nil? # nothing to configure at the moment.
@toggled_at = Kernel.global_tick_count
@fading = 1
@current_part = 0
@part_alpha = 0
@part_alpha_increment = 10
@joystick_state = {}
@used_bindings = {}
@playing_around = false
@bindings = []
end
return true
end
def render_part_highlight_from_bindstr args, bindstr, alpha=255
partidx = @used_bindings[bindstr]
return if partidx.nil?
render_part_highlight args, @parts[partidx], alpha
end
def play_around args
return false if !@playing_around
if args.inputs.keyboard.key_down.escape
@current_part = 0
@part_alpha = 0
@part_alpha_increment = 10
@used_bindings = {}
@playing_around = false
@bindings = []
elsif args.inputs.keyboard.key_down.space
jid = @target[0]
bindingstr = build_binding_string
#puts("new controller binding: '#{bindingstr}'")
@runtime.ffi_misc.add_controller_config bindingstr
@runtime.ffi_misc.convert_rawjoystick_to_controller jid
@target[0] = -1 # Conversion closes the raw joystick.
# Handle any other pending joysticks that have the same GUID (so if you plug in four of the same model, we're already done!)
guid = @target[1][:guid]
@raw_joysticks.each { |jid, details|
if details[:guid] == guid
@runtime.ffi_misc.convert_rawjoystick_to_controller jid
details[:guid] = nil
end
}
# Done with this guy.
@playing_around = false
@toggled_at = Kernel.global_tick_count
@fading = -1
return false
end
render_basics args, 'Now play around with the controller, and make sure it feels right!'
args.outputs.primitives << [$gtk.logical_width / 2, 90, '[ESCAPE]: Reconfigure, [SPACE]: Save this configuration', 0, 1, 0, 0, 0, 255].label
axes = @joystick_state[:axes]
if !axes.nil?
for i in 0..axes.length-1
next if axes[i].nil?
value = axes[i][:currentval]
next if value.nil? || (value.abs < 16000)
render_part_highlight_from_bindstr args, "#{value < 0 ? '-' : '+'}a#{i}"
end
end
hats = @joystick_state[:hats]
if !hats.nil?
for i in 0..hats.length-1
value = hats[i]
next if value.nil? || (value == 0)
render_part_highlight_from_bindstr args, "h#{i}.#{value}"
end
end
buttons = @joystick_state[:buttons]
if !buttons.nil?
for i in 0..buttons.length-1
value = buttons[i]
next if value.nil? || !value
render_part_highlight_from_bindstr args, "b#{i}"
end
end
return true
end
def should_tick?
return true if @play_around
return true if @target
return false
end
def tick args
return true if play_around args
return false if !choose_target
jid = @target[0]
if @fading == 0
# Cancel config?
if args.inputs.keyboard.key_down.escape
# !!! FIXME: prompt to ignore this joystick forever or just this run
@toggled_at = Kernel.global_tick_count
@fading = -1
end
end
if @fading == 0
if args.inputs.keyboard.key_down.backspace
previous_part
elsif args.inputs.keyboard.key_down.space
next_part
end
end
fade = calc_fading
if (@fading < 0) && (fade == 0)
@runtime.ffi_misc.close_raw_joystick(jid) if jid >= 0
@target = nil # done with this controller
return false
end
render_basics args, (@fading >= 0) ? "We don't recognize this controller, so tell us about it!" : '', fade
return true if fade < 255 # all done for now
part = @parts[@current_part]
args.outputs.primitives << [$gtk.logical_width / 2, 575, "Please press the #{part[2]}.", 0, 1, 0, 0, 0, 255].label
render_part_highlight args, part, @part_alpha
args.outputs.primitives << [$gtk.logical_width / 2, 90, '[ESCAPE]: Ignore controller, [BACKSPACE]: Go back one button, [SPACE]: Skip this button', 0, 1, 0, 0, 0, 255].label
@part_alpha += @part_alpha_increment
if (@part_alpha_increment > 0) && (@part_alpha >= 255)
@part_alpha = 255
@part_alpha_increment = -10
elsif (@part_alpha_increment < 0) && (@part_alpha <= 0)
@part_alpha = 0
@part_alpha_increment = 10
end
return true
end
end
end
end
</code></pre>
<h3 id='----controller/keys-rb'>controller/keys.rb</h3>
<pre><code class="language-ruby"># ./dragon/controller/keys.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# controller/keys.rb has been released under MIT (*only this file*).
module GTK
class Controller
class Keys
include Serialize
LABELS = [
:up, :down, :left, :right,
:a, :b, :x, :y,
:l1, :r1,
:l2, :r2,
:l3, :r3,
:start, :select, :home,
:directional_up, :directional_down, :directional_left, :directional_right
].freeze
LABELS.each do |label|
attr label
end
def back
@select
end
def back= value
@select = value
end
def guide
@home
end
def guide= value
@home = value
end
# Activate a key.
#
# @return [void]
def activate key
instance_variable_set("@#{key}", Kernel.tick_count + 1)
end
# Deactivate a key.
#
# @return [void]
def deactivate key
instance_variable_set("@#{key}", nil)
end
# Clear all key inputs.
#
# @return [void]
def clear
LABELS.each { |label| deactivate(label) }
end
def truthy_keys
LABELS.select { |label| send(label) }
end
end
end
end
</code></pre>
<h3 id='----directional_input_helper_methods-rb'>directional_input_helper_methods.rb</h3>
<pre><code class="language-ruby"># ./dragon/directional_input_helper_methods.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# directional_input_helper_methods.rb has been released under MIT (*only this file*).
module GTK
# This is a module that contains normalization of behavior related to `up`|`down`|`left`|`right` on keyboards and controllers.
module DirectionalInputHelperMethods
def self.included klass
key_state_methods = [:key_held, :key_down]
directional_methods = [:up, :down, :left, :right]
method_results = (directional_methods + key_state_methods).map {|m| [m, klass.instance_methods.include?(m)] }
error_message = <<-S
* ERROR
The GTK::DirectionalKeys module should only be included in objects that respond to the following api hierarchy:
- (#{ directional_methods.join("|") })
- key_held.(#{ directional_methods.join("|") })
- key_down.(#{ directional_methods.join("|") })
#{klass} does not respond to all of these methods (here is the diagnostics):
#{method_results.map {|m, r| "- #{m}: #{r}"}.join("\n")}
Please implement the methods that returned false inthe list above.
S
unless method_results.map {|m, result| result}.all?
raise error_message
end
end
# Returns a signal indicating left (`-1`), right (`1`), or neither ('0').
#
# @return [Integer]
def left_right
return -1 if self.left
return 1 if self.right
return 0
end
# Returns a signal indicating up (`1`), down (`-1`), or neither ('0').
#
# @return [Integer]
def up_down
return 1 if self.up
return -1 if self.down
return 0
end
# Returns a normal vector (in the form of an Array with two values). If no directionals are held/down, the function returns nil.
#
# The possible results are:
#
# - ~nil~ which denotes that no directional input exists.
# - ~[ 0, 1]~ which denotes that only up is being held/pressed.
# - ~[ 0, -1]~ which denotes that only down is being held/pressed.
# - ~[-0.707, 0.707]~ which denotes that right and up are being pressed/held.
# - ~[-0.707, -0.707]~ which denotes that left and down are being pressed/held.
#
# @gtk
def directional_vector
lr, ud = [self.left_right, self.up_down]
if lr == 0 && ud == 0
return nil
elsif lr.abs == ud.abs
return [45.vector_x * lr.sign, 45.vector_y * ud.sign, ud.sign]
else
return [lr, ud]
end
end
def directional_angle
return nil unless directional_vector
Math.atan2(up_down, left_right).to_degrees
end
def method_missing m, *args
# combine the key with ctrl_
if m.to_s.start_with?("ctrl_")
other_key = m.to_s.split("_").last
define_singleton_method(m) do
return self.key_up.send(other_key.to_sym) && self.key_up.control
end
return send(m)
else
# see if the key is either held or down
define_singleton_method(m) do
self.key_down.send(m) || self.key_held.send(m)
end
return send(m)
end
end
end
end
</code></pre>
<h3 id='----easing-rb'>easing.rb</h3>
<pre><code class="language-ruby"># ./dragon/easing.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# easing.rb has been released under MIT (*only this file*).
module GTK
module Easing
def self.ease start_tick, current_tick, duration, *definitions
ease_extended start_tick,
current_tick,
start_tick + duration,
(initial_value *definitions),
(final_value *definitions),
*definitions
end
def self.ease_extended start_tick, current_tick, end_tick, default_before, default_after, *definitions
definitions.flatten!
definitions = [:identity] if definitions.length == 0
duration = end_tick - start_tick
elapsed = current_tick - start_tick
y = elapsed.percentage_of(duration).cap_min_max(0, 1)
definitions.map do |definition|
y = Easing.exec_definition(definition, start_tick, duration, y)
end
y
end
def self.ease_spline start_tick, current_tick, duration, spline
ease_spline_extended start_tick, current_tick, start_tick + duration, spline
end
def self.ease_spline_extended start_tick, current_tick, end_tick, spline
return spline[-1][-1] if current_tick >= end_tick
duration = end_tick - start_tick
t = (current_tick - start_tick).fdiv duration
time_allocation_per_curve = 1.fdiv(spline.length)
curve_index, curve_t = t.fdiv(time_allocation_per_curve).let do |spline_t|
[spline_t.to_i, spline_t - spline_t.to_i]
end
Geometry.cubic_bezier curve_t, *spline[curve_index]
end
def self.initial_value *definitions
definitions.flatten!
return Easing.exec_definition (definitions.at(-1) || :identity), 0, 10, 0
end
def self.final_value *definitions
definitions.flatten!
return Easing.exec_definition (definitions.at(-1) || :identity), 0, 10, 1.0
end
def self.exec_definition definition, start_tick, duration, x
if definition.is_a? Symbol
return Easing.send(definition, x).cap_min_max(0, 1)
elsif definition.is_a? Proc
return definition.call(x, start_tick, duration).cap_min_max(0, 1)
end
raise <<-S
* ERROR:
I don't know how to execute easing function with definition #{definition}.
S
end
def self.identity x
x
end
def self.flip x
1 - x
end
def self.quad x
x * x
end
def self.cube x
x * x * x
end
def self.quart x
x * x * x * x * x
end
def self.quint x
x * x * x * x * x * x
end
end
end
Easing = GTK::Easing
</code></pre>
<h3 id='----entity-rb'>entity.rb</h3>
<pre><code class="language-ruby"># ./dragon/entity.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# entity.rb has been released under MIT (*only this file*).
module GTK
class Entity
def self.id!
@id ||= 0
@id += 1
@id
end
def self.__reset_id__!
@id = 0
end
def self.strict_entities
@strict_entities ||= {}
@strict_entities
end
def self.parse_serialization_data data
r = Entity.parse_serialization_data data
return r if r.is_a? OpenEntity
return r if r.is_a? StrictEntity
raise <<-S
* ERROR:
The save data looks to be corrupt.
S
end
def self.parse_serialization_data value
if value.is_a?(Hash) && value[:entity_id] && value[:entity_strict]
o = new_entity_strict value[:entity_name], value
o.load_entity_data! value
return o
elsif value.is_a?(Hash) && value[:entity_id]
o = OpenEntity.new
o.load_entity_data! value
return o
elsif value.is_a? Array
return value.map { |entry| Entity.parse_serialization_data entry }
else
return value
end
end
def self.new_entity entity_type, init_hash = nil, block = nil
n = OpenEntity.new(entity_type)
n.entity_type = entity_type
n.created_at = Kernel.tick_count
n.global_created_at = Kernel.global_tick_count
if init_hash
init_hash.each do |k, v|
n.as_hash[k] = v
end
end
block.call(n) if block
n
end
def self.new_entity_strict entity_type, init_hash = nil, block = nil
if !Entity.strict_entities[entity_type]
init_hash ||= { }
n = new_entity entity_type, init_hash, block
klass = Class.new(StrictEntity)
klass.class_eval do
init_hash.each do |k, v|
attr_accessor k
end
n.as_hash.each do |k, v|
attr_accessor k if !init_hash[k]
end
end
Entity.strict_entities[entity_type] = klass
end
klass = Entity.strict_entities[entity_type]
(klass.new entity_type, init_hash, block)
end
end
end
</code></pre>
<h3 id='----geometry-rb'>geometry.rb</h3>
<pre><code class="language-ruby"># ./dragon/geometry.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# geometry.rb has been released under MIT (*only this file*).
module GTK
module Geometry
def self.rotate_point point, angle, around = nil
s = Math.sin a.to_radians
c = Math.cos a.to_radians
px = point.x
py = point.y
cx = 0
cy = 0
if around
cx = around.x
cy = around.y
end
point.merge(x: ((px - cx) * c - (py - cy) * s) + cx,
y: ((px - cx) * s + (py - cy) * c) + cy)
end
# Returns f(t) for a cubic Bezier curve.
def self.cubic_bezier t, a, b, c, d
s = 1 - t
s0 = 1
s1 = s
s2 = s * s
s3 = s * s * s
t0 = 1
t1 = t
t2 = t * t
t3 = t * t * t
1 * s3 * t0 * a +
3 * s2 * t1 * b +
3 * s1 * t2 * c +
1 * s0 * t3 * d
end
# Returns true if a primitive's rectangle is entirely inside another primitive's rectangle.
# @gtk
def inside_rect? outer, tolerance = 0.0
Geometry.inside_rect? self, outer, tolerance
end
# Returns true if a primitive's rectangle overlaps another primitive's rectangle.
# @gtk
def intersect_rect? other, tolerance = 0.1
Geometry.intersect_rect? self, other, tolerance
end
def intersects_rect? *args
Geometry.intersects_rect?(*args)
end
def scale_rect_extended percentage_x: percentage_x,
percentage_y: percentage_y,
anchor_x: anchor_x,
anchor_y: anchor_y
Geometry.scale_rect_extended self,
percentage_x: percentage_x,
percentage_y: percentage_y,
anchor_x: anchor_x,
anchor_y: anchor_y
end
# Scales a primitive rect by a percentage.
# @gtk
def scale_rect percentage, *anchors
Geometry.scale_rect self, percentage, *anchors
end
# Returns the angle from one primitive to another primitive.
# @gtk
def angle_to other_point
Geometry.angle_to self, other_point
end
# Returns the angle to one primitive from another primitive.
# @gtk
def angle_from other_point
Geometry.angle_from self, other_point
end
# Returns true if a primitive is within a circle specified by the circle's center and radius.
# @gtk
def point_inside_circle? circle_center_point, radius
Geometry.point_inside_circle? self, circle_center_point, radius
end
def self.center_inside_rect rect, other_rect
offset_x = (other_rect.w - rect.w).half
offset_y = (other_rect.h - rect.h).half
new_rect = rect.shift_rect(0, 0)
new_rect.x = other_rect.x + offset_x
new_rect.y = other_rect.y + offset_y
new_rect
rescue Exception => e
raise e, <<-S
* ERROR:
center_inside_rect for self #{self} and other_rect #{other_rect}.\n#{e}.
S
end
def center_inside_rect other_rect
Geometry.center_inside_rect self, other_rect
end
def self.center_inside_rect_x rect, other_rect
offset_x = (other_rect.w - rect.w).half
new_rect = rect.shift_rect(0, 0)
new_rect.x = other_rect.x + offset_x
new_rect.y = other_rect.y
new_rect
rescue Exception => e
raise e, <<-S
* ERROR:
center_inside_rect_x for self #{self} and other_rect #{other_rect}.\n#{e}.
S
end
def center_inside_rect_x other_rect
Geometry.center_inside_rect_x self, other_rect
end
def self.center_inside_rect_y rect, other_rect
offset_y = (other_rect.h - rect.h).half
new_rect = rect.shift_rect(0, 0)
new_rect.x = other_rect.x
new_rect.y = other_rect.y + offset_y
new_rect
rescue Exception => e
raise e, <<-S
* ERROR:
center_inside_rect_y for self #{self} and other_rect #{other_rect}.\n#{e}.
S
end
def center_inside_rect_y other_rect
Geometry.center_inside_rect_y self, other_rect
end
# Returns a primitive that is anchored/repositioned based off its rectangle.
# @gtk
def anchor_rect anchor_x, anchor_y
current_w = self.w
current_h = self.h
delta_x = -1 * (anchor_x * current_w)
delta_y = -1 * (anchor_y * current_h)
self.shift_rect(delta_x, delta_y)
end
def angle_given_point other_point
raise ":angle_given_point has been deprecated use :angle_from instead."
end
# @gtk
def self.shift_line line, x, y
if line.is_a?(Array) || line.is_a?(Hash)
new_line = line.dup
new_line.x += x
new_line.x2 += x
new_line.y += y
new_line.y2 += y
new_line
else
raise "shift_line for #{line} is not supported."
end
end
def self.intersects_rect? *args
raise <<-S
intersects_rect? (with an \"s\") has been deprecated.
Use intersect_rect? instead (remove the \"s\").
* NOTE:
Ruby's naming convention is to *never* include the \"s\" for
interrogative method names (methods that end with a ?). It
doesn't sound grammatically correct, but that has been the
rule for a long time (and why intersects_rect? has been deprecated).
S
end
# @gtk
def self.line_y_intercept line
line.y - line_slope(line) * line.x
end
# @gtk
def self.angle_between_lines line_one, line_two, replace_infinity: nil
m_line_one = line_slope line_one, replace_infinity: replace_infinity
m_line_two = line_slope line_two, replace_infinity: replace_infinity
Math.atan((m_line_one - m_line_two) / (1 + m_line_two * m_line_one)).to_degrees
end
# @gtk
def self.line_slope line, replace_infinity: nil
return replace_infinity if line.x2 == line.x
(line.y2 - line.y).fdiv(line.x2 - line.x)
.replace_infinity(replace_infinity)
end
def self.line_rise_run line
rise = (line.y2 - line.y).to_f
run = (line.x2 - line.x).to_f
if rise.abs > run.abs && rise != 0
rise = rise.fdiv rise.abs
run = run.fdiv rise.abs
elsif run.abs > rise.abs && run != 0
rise = rise.fdiv run.abs
run = run.fdiv run.abs
else
rise = rise / rise.abs if rise != 0
run = run / run.abs if run != 0
end
return { x: run , y: rise }
end
# @gtk
def self.ray_test point, line
slope = (line.y2 - line.y).fdiv(line.x2 - line.x)
if line.x > line.x2
point_two, point_one = [point_one, point_two]
end
r = ((line.x2 - line.x) * (point.y - line.y) -
(point.x - line.x) * (line.y2 - line.y))
if r == 0
return :on
elsif r < 0
return :right if slope >= 0
return :left
elsif r > 0
return :left if slope >= 0
return :right
end
end
# @gtk
def self.line_rect line
if line.x > line.x2
x = line.x2
y = line.y2
x2 = line.x
y2 = line.y
else
x = line.x
y = line.y
x2 = line.x2
y2 = line.y2
end
w = x2 - x
h = y2 - y
{ x: x, y: y, w: w, h: h }
end
# @gtk
def self.line_intersect line_one, line_two
m1 = line_slope(line_one)
m2 = line_slope(line_two)
b1 = line_y_intercept(line_one)
b2 = line_y_intercept(line_two)
x = (b1 - b2) / (m2 - m1)
y = (-b2.fdiv(m2) + b1.fdiv(m1)).fdiv(1.fdiv(m1) - 1.fdiv(m2))
[x, y]
end
def self.contract_intersect_rect?
[:left, :right, :top, :bottom]
end
# @gtk
def self.intersect_rect? rect_one, rect_two, tolerance = 0.1
return false if ((rect_one.x + rect_one.w) - tolerance) < (rect_two.x + tolerance)
return false if (rect_one.x + tolerance) > ((rect_two.x + rect_two.w) - tolerance)
return false if ((rect_one.y + rect_one.h) - tolerance) < (rect_two.y + tolerance)
return false if (rect_one.y + tolerance) > ((rect_two.y + rect_two.h) - tolerance)
return true
rescue Exception => e
context_help_rect_one = (rect_one.__help_contract_implementation contract_intersect_rect?)[:not_implemented_methods]
context_help_rect_two = (rect_two.__help_contract_implementation contract_intersect_rect?)[:not_implemented_methods]
context_help = ""
if context_help_rect_one && context_help_rect_one.length > 0
context_help += <<-S
rect_one needs to implement the following methods: #{context_help_rect_one}
You may want to try include the ~AttrRect~ module which will give you these methods.
S
end
if context_help_rect_two && context_help_rect_two.length > 0
context_help += <<-S
* FAILURE REASON:
rect_two needs to implement the following methods: #{context_help_rect_two}
NOTE: You may want to try include the ~GTK::Geometry~ module which will give you these methods.
S
end
raise e, <<-S
* ERROR:
:intersect_rect? failed for
- rect_one: #{rect_one}
- rect_two: #{rect_two}
#{context_help}
\n#{e}
S
end
# @gtk
def self.to_square size, x, y, anchor_x = 0.5, anchor_y = nil
anchor_y ||= anchor_x
x = x.shift_left(size * anchor_x)
y = y.shift_down(size * anchor_y)
[x, y, size, size]
rescue Exception => e
raise e, ":to_square failed for size: #{size} x: #{x} y: #{y} anchor_x: #{anchor_x} anchor_y: #{anchor_y}.\n#{e}"
end
# @gtk
def self.distance point_one, point_two
Math.sqrt((point_two.x - point_one.x)**2 + (point_two.y - point_one.y)**2)
rescue Exception => e
raise e, ":distance failed for point_one: #{point_one} point_two #{point_two}.\n#{e}"
end
# @gtk
def self.angle_from start_point, end_point
d_y = end_point.y - start_point.y
d_x = end_point.x - start_point.x
Math::PI.+(Math.atan2(d_y, d_x)).to_degrees
rescue Exception => e
raise e, ":angle_from failed for start_point: #{start_point} end_point: #{end_point}.\n#{e}"
end
# @gtk
def self.angle_to start_point, end_point
angle_from end_point, start_point
rescue Exception => e
raise e, ":angle_to failed for start_point: #{start_point} end_point: #{end_point}.\n#{e}"
end
# @gtk
def self.point_inside_circle? point, circle_center_point, radius
(point.x - circle_center_point.x) ** 2 + (point.y - circle_center_point.y) ** 2 < radius ** 2
rescue Exception => e
raise e, ":point_inside_circle? failed for point: #{point} circle_center_point: #{circle_center_point} radius: #{radius}.\n#{e}"
end
# @gtk
def self.inside_rect? inner_rect, outer_rect, tolerance = 0.0
return nil if !inner_rect
return nil if !outer_rect
inner_rect.x + tolerance >= outer_rect.x - tolerance &&
(inner_rect.x + inner_rect.w) - tolerance <= (outer_rect.x + outer_rect.w) + tolerance &&
inner_rect.y + tolerance >= outer_rect.y - tolerance &&
(inner_rect.y + inner_rect.h) - tolerance <= (outer_rect.y + outer_rect.h) + tolerance
rescue Exception => e
raise e, ":inside_rect? failed for inner_rect: #{inner_rect} outer_rect: #{outer_rect}.\n#{e}"
end
# @gtk
def self.scale_rect_extended rect,
percentage_x: percentage_x,
percentage_y: percentage_y,
anchor_x: anchor_x,
anchor_y: anchor_y
anchor_x ||= 0.0
anchor_y ||= 0.0
percentage_x ||= 1.0
percentage_y ||= 1.0
new_w = rect.w * percentage_x
new_h = rect.h * percentage_y
new_x = rect.x + (rect.w - new_w) * anchor_x
new_y = rect.y + (rect.h - new_h) * anchor_y
if rect.is_a? Array
return [
new_x,
new_y,
new_w,
new_h,
*rect[4..-1]
]
elsif rect.is_a? Hash
return rect.merge(x: new_x, y: new_y, w: new_w, h: new_h)
else
rect.x = new_x
rect.y = new_y
rect.w = new_w
rect.h = new_h
return rect
end
rescue Exception => e
raise e, ":scale_rect_extended failed for rect: #{rect} percentage_x: #{percentage_x} percentage_y: #{percentage_y} anchors_x: #{anchor_x} anchor_y: #{anchor_y}.\n#{e}"
end
# @gtk
def self.scale_rect rect, percentage, *anchors
anchor_x, anchor_y = *anchors.flatten
anchor_x ||= 0
anchor_y ||= anchor_x
Geometry.scale_rect_extended rect,
percentage_x: percentage,
percentage_y: percentage,
anchor_x: anchor_x,
anchor_y: anchor_y
rescue Exception => e
raise e, ":scale_rect failed for rect: #{rect} percentage: #{percentage} anchors [#{anchor_x} (x), #{anchor_y} (y)].\n#{e}"
end
def self.rect_to_line rect
l = rect.to_hash.line
l.merge(x2: l.x + l.w - 1,
y2: l.y + l.h)
end
def self.rect_center_point rect
{ x: rect.x + rect.w.half, y: rect.y + rect.h.half }
end
def rect_center_point
Geometry.rect_center_point self
end
end # module Geometry
end # module GTK
</code></pre>
<h3 id='----grid-rb'>grid.rb</h3>
<pre><code class="language-ruby"># ./dragon/grid.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# grid.rb has been released under MIT (*only this file*).
module GTK
class Grid
include Serialize
SCREEN_Y_DIRECTION = -1.0
# The coordinate system currently in use.
#
# @return [Symbol] `:bottom_left` or `:center`
attr_accessor :name
# Returns the "x" coordinate indicating the bottom of the screen.
#
# @return [Float]
attr_accessor :bottom
# Returns the "x" coordinate indicating the top of the screen.
#
# @return [Float]
attr_accessor :top
# Returns the "y" coordinate indicating the left of the screen.
#
# @return [Float]
attr_accessor :left
# Returns the "y" coordinate indicating the right of the screen.
#
# @return [Float]
attr_accessor :right
# Returns the "x" coordinate indicating the center of the screen.
#
# @return [Float]
attr_accessor :center_x
# Returns the "y" coordinate indicating the center of the screen.
#
# @return [Float]
attr_accessor :center_y
# Returns the bottom left and top right coordinates in a single list.
#
# @return [[Float, Float, Float, Float]]
attr_accessor :rect
# Returns the "x" coordinate of the origin.
#
# @return [Float]
attr_accessor :origin_x
# Returns the "y" coordinate of the origin.
#
# @return [Float]
attr_accessor :origin_y
attr_accessor :left_margin, :bottom_margin
def initialize runtime
@runtime = runtime
@ffi_draw = runtime.ffi_draw
origin_bottom_left!
end
# Returns `x` plus the origin "x".
#
# @return [Float]
def transform_x x
@origin_x + x
end
# Returns `x` minus the origin "x".
#
# @return [Float]
def untransform_x x
x - @origin_x
end
# Returns `y` plus the origin "y".
#
# @return [Float]
def transform_y y
@origin_y + y * SCREEN_Y_DIRECTION
end
# Returns `y` minus the origin "y".
#
# @return [Float]
def untransform_y y
@origin_y + y * SCREEN_Y_DIRECTION
end
def ffi_draw
@ffi_draw
end
def ffi_draw= value
@ffi_draw = value
end
# Sets the rendering coordinate system to have its origin in the bottom left.
#
# @return [void]
# @gtk
def origin_bottom_left!
return if @name == :bottom_left
@name = :bottom_left
@origin_x = 0.0
@origin_y = @runtime.logical_height
@left = 0.0
@right = @runtime.logical_width
@top = @runtime.logical_height
@bottom = 0.0
@left_margin = 0.0
@bottom_margin = 0.0
@center_x = @runtime.logical_width.half
@center_y = @runtime.logical_height.half
@rect = [@left, @bottom, @runtime.logical_width, @runtime.logical_height].rect
@center = [@center_x, @center_y].point
@ffi_draw.set_grid @origin_x, @origin_y, SCREEN_Y_DIRECTION
end
# Sets the rendering coordinate system to have its origin in the center.
#
# @return [void]
# @gtk
def origin_center!
return if @name == :center
@name = :center
@origin_x = @runtime.logical_width.half
@origin_y = @runtime.logical_height.half
@left = [email protected]_width.half
@right = @runtime.logical_width.half
@top = @runtime.logical_height.half
@bottom = [email protected]_height.half
@center_x = 0.0
@center_y = 0.0
@rect = [@left, @bottom, @runtime.logical_width, @runtime.logical_height].rect
@center = [@center_x, @center_y].point
@ffi_draw.set_grid @origin_x, @origin_y, SCREEN_Y_DIRECTION
end
# The logical width used for rendering.
#
# @return [Float]
def w
@runtime.logical_width
end
# Half the logical width used for rendering.
#
# @return [Float]
def w_half
w.half
end
# The logical height used for rendering.
#
# @return [Float]
def h
@runtime.logical_height
end
# Half the logical height used for rendering.
#
# @return [Float]
def h_half
h.half
end
# Returns the coordinates indicating the center of the screen.
#
# @return [[Float, Float]]
def center
@center
end
# Returns the coordinates indicating the bottom right of the screen.
#
# @return [[Float, Float]]
def bottom_right
[@right, @bottom].point
end
def x
0
end
def y
0
end
end
end
</code></pre>
<h3 id='----inputs-rb'>inputs.rb</h3>
<pre><code class="language-ruby"># ./dragon/inputs.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# inputs.rb has been released under MIT (*only this file*).
module GTK
# Represents all the keys available on the keyboard.
# @gtk
class KeyboardKeys
include Serialize
# @gtk
attr_accessor :exclamation_point,
:zero, :one, :two, :three, :four,
:five, :six, :seven, :eight, :nine,
:backspace, :delete, :escape, :enter, :tab,
:open_round_brace, :close_round_brace,
:open_curly_brace, :close_curly_brace,
:open_square_brace, :close_square_brace,
:colon, :semicolon, :equal_sign,
:hyphen, :space, :dollar_sign,
:double_quotation_mark,
:single_quotation_mark,
:backtick,
:tilde, :period, :comma, :pipe,
:underscore,
:a, :b, :c, :d, :e, :f, :g, :h,
:i, :j, :k, :l, :m, :n, :o, :p,
:q, :r, :s, :t, :u, :v, :w, :x,
:y, :z,
:shift, :control, :alt, :meta,
:shift_left, :shift_right,
:control_left, :control_right,
:alt_left, :alt_right,
:meta_left, :meta_right,
:home, :end,
:left, :right, :up, :down, :pageup, :pagedown,
:char, :plus, :at, :forward_slash, :back_slash, :asterisk,
:less_than, :greater_than, :carat, :ampersand, :superscript_two,
:circumflex,
:question_mark, :section_sign, :ordinal_indicator,
:raw_key
def self.sdl_to_key raw_key, modifier
return nil unless (raw_key >= 0 && raw_key <= 255) ||
raw_key == 1073741903 ||
raw_key == 1073741904 ||
raw_key == 1073741905 ||
raw_key == 1073741906 ||
raw_key == 1073741899 ||
raw_key == 1073741902 ||
raw_key == 1073741898 ||
raw_key == 1073741901 ||
(raw_key >= 1073742048 && raw_key <= 1073742055) # Modifier Keys
char = KeyboardKeys.char_with_shift raw_key, modifier
names = KeyboardKeys.char_to_method char, raw_key
names << :alt if (modifier & (256|512)) != 0 # alt key
names << :meta if (modifier & (1024|2048)) != 0 # meta key (command/apple/windows key)
names << :control if (modifier & (64|128)) != 0 # ctrl key
names << :shift if (modifier & (1|2)) != 0 # shift key
names
end
def self.utf_8_char raw_key
return "²" if raw_key == 178
return "§" if raw_key == 167
return "º" if raw_key == 186
return raw_key.chr
end
def self.char_with_shift raw_key, modifier
return nil unless raw_key >= 0 && raw_key <= 255
if modifier != 1 && modifier != 2 && modifier != 3
return utf_8_char raw_key
else
@shift_keys ||= {
'`' => '~', '-' => '_', "'" => '"', "1" => '!',
"2" => '@', "3" => '#', "4" => '$', "5" => '%',
"6" => '^', "7" => '&', "8" => '*', "9" => '(',
"0" => ')', ";" => ":", "=" => "+", "[" => "{",
"]" => "}", '\\'=> "|", '/' => "?", '.' => ">",
',' => "<", 'a' => 'A', 'b' => 'B', 'c' => 'C',
'd' => 'D', 'e' => 'E', 'f' => 'F', 'g' => 'G',
'h' => 'H', 'i' => 'I', 'j' => 'J', 'k' => 'K',
'l' => 'L', 'm' => 'M', 'n' => 'N', 'o' => 'O',
'p' => 'P', 'q' => 'Q', 'r' => 'R', 's' => 'S',
't' => 'T', 'u' => 'U', 'v' => 'V', 'w' => 'W',
'x' => 'X', 'y' => 'Y', 'z' => 'Z'
}
@shift_keys[raw_key.chr.to_s] || raw_key.chr.to_s
end
end
def self.char_to_method_hash
@char_to_method ||= {
'A' => [:a],
'B' => [:b],
'C' => [:c],
'D' => [:d],
'E' => [:e],
'F' => [:f],
'G' => [:g],
'H' => [:h],
'I' => [:i],
'J' => [:j],
'K' => [:k],
'L' => [:l],
'M' => [:m],
'N' => [:n],
'O' => [:o],
'P' => [:p],
'Q' => [:q],
'R' => [:r],
'S' => [:s],
'T' => [:t],
'U' => [:u],
'V' => [:v],
'W' => [:w],
'X' => [:x],
'Y' => [:y],
'Z' => [:z],
"!" => [:exclamation_point],
"0" => [:zero],
"1" => [:one],
"2" => [:two],
"3" => [:three],
"4" => [:four],
"5" => [:five],
"6" => [:six],
"7" => [:seven],
"8" => [:eight],
"9" => [:nine],
"\b" => [:backspace],
"\e" => [:escape],
"\r" => [:enter],
"\t" => [:tab],
"(" => [:open_round_brace],
")" => [:close_round_brace],
"{" => [:open_curly_brace],
"}" => [:close_curly_brace],
"[" => [:open_square_brace],
"]" => [:close_square_brace],
":" => [:colon],
";" => [:semicolon],
"=" => [:equal_sign],
"-" => [:hyphen],
" " => [:space],
"$" => [:dollar_sign],
"\"" => [:double_quotation_mark],
"'" => [:single_quotation_mark],
"`" => [:backtick],
"~" => [:tilde],
"." => [:period],
"," => [:comma],
"|" => [:pipe],
"_" => [:underscore],
"#" => [:hash],
"+" => [:plus],
"@" => [:at],
"/" => [:forward_slash],
"\\" => [:back_slash],
"*" => [:asterisk],
"<" => [:less_than],
">" => [:greater_than],
"^" => [:circumflex],
"&" => [:ampersand],
"²" => [:superscript_two],
"§" => [:section_sign],
"?" => [:question_mark],
'%' => [:percent_sign],
"º" => [:ordinal_indicator],
1073741898 => [:home],
1073741901 => [:end],
1073741903 => [:right],
1073741904 => [:left],
1073741905 => [:down],
1073741906 => [:up],
1073741899 => [:pageup],
1073741902 => [:pagedown],
127 => [:delete],
1073742049 => [:shift_left, :shift],
1073742053 => [:shift_right, :shift],
1073742048 => [:control_left, :control],
1073742052 => [:control_right, :control],
1073742050 => [:alt_left, :alt],
1073742054 => [:alt_right, :alt],
1073742051 => [:meta_left, :meta],
1073742055 => [:meta_right, :meta]
}
end
def self.method_to_key_hash
return @method_to_key_hash if @method_to_key_hash
@method_to_key_hash = {}
string_representation_overrides ||= {
backspace: '\b'
}
char_to_method_hash.each do |k, v|
v.each do |vi|
t = { char_or_raw_key: k }
if k.is_a? Numeric
t[:raw_key] = k
t[:string_representation] = "raw_key == #{k}"
else
t[:char] = k
t[:string_representation] = "\"#{k.strip}\""
end
@method_to_key_hash[vi] = t
end
end
@method_to_key_hash
end
def self.char_to_method char, int = nil
methods = char_to_method_hash[char] || char_to_method_hash[int]
methods ? methods.dup : [char.to_sym || int]
end
def clear
set truthy_keys, false
@scrubbed_ivars = nil
end
# @gtk
def left_right
return -1 if self.left
return 1 if self.right
return 0
end
# @gtk
def up_down
return 1 if self.up
return -1 if self.down
return 0
end
# @gtk
def truthy_keys
get(all).find_all { |_, v| v }
.map { |k, _| k.to_sym }
end
# @gtk
def all? keys
values = get(keys.map { |k| k.without_ending_bang })
all_true = values.all? do |k, v|
v
end
if all_true
keys.each do |k|
clear_key k if k.end_with_bang?
end
end
all_true
end
# @gtk
def any? keys
values = get(keys.map { |k| k.without_ending_bang })
any_true = values.any? do |k, v|
v
end
if any_true
keys.each do |k|
clear_key k if k.end_with_bang?
end
end
any_true
end
# @gtk
def clear_key key
@scrubbed_ivars = nil
self.instance_variable_set("@#{key.without_ending_bang}", false)
end
# @gtk
def all
@scrubbed_ivars ||= self.instance_variables
.reject { |i| i == :@all || i == :@scrubbed_ivars }
.map { |i| i.to_s.gsub("@", "") }
get(@scrubbed_ivars).map { |k, _| k }
end
# @gtk
def get collection
return [] if collection.length == 0
collection.map do |m|
if m.end_with_bang?
clear_after_return = true
end
value = self.instance_variable_get("@#{m.without_ending_bang}".to_sym)
clear_key m if clear_after_return
[m.without_ending_bang, value]
end
end
# @gtk
def set collection, value = true
return if collection.length == 0
@scrubbed_ivars = nil
value = Kernel.tick_count if value
collection.each do |m|
self.instance_variable_set("@#{m.to_s}".to_sym, value)
rescue Exception => e
raise e, <<-S
* ERROR:
Attempted to set the a key on the DragonRuby GTK's Keyboard data
structure, but the property isn't available for raw_key #{raw_key} #{m}.
You should contact DragonRuby and tell them to associate the raw_key #{raw_key}
with a friendly property name (we are open to suggestions if you have any).
[GTK::KeyboardKeys#set, GTK::KeyboardKeys#char_to_method]
S
end
end
def method_missing m, *args
if KeyboardKeys.method_to_key_hash[m.without_ending_bang]
begin
define_singleton_method(m) do
r = self.instance_variable_get("@#{m.without_ending_bang}".to_sym)
clear_key m
return r
end
return self.send m
rescue Exception => e
log_important "#{e}"
end
end
did_you_mean = KeyboardKeys.method_to_key_hash.find_all do |k, v|
k.to_s[0..1] == m.to_s[0..1]
end.map {|k, v| ":#{k} (#{v[:string_representation]})" }
did_you_mean_string = ""
did_you_mean_string = ". Did you mean #{did_you_mean.join ", "}?"
raise <<-S
* ERROR:
#{KeyboardKeys.method_to_key_hash.map { |k, v| "** :#{k} #{v.string_representation}" }.join("\n")}
There is no key on the keyboard called :#{m}#{did_you_mean_string}.
Full list of available keys =:points_up:=.
S
end
def serialize
hash = super
hash.delete(:scrubbed_ivars)
hash[:truthy_keys] = self.truthy_keys
hash
end
end
end
module GTK
# @gtk
class Keyboard
# @return [KeyboardKeys]
# @gtk
attr_accessor :key_up
# @return [KeyboardKeys]
# @gtk
attr_accessor :key_held
# @return [KeyboardKeys]
# @gtk
attr_accessor :key_down
# @return [Boolean]
# @gtk
attr_accessor :has_focus
def initialize
@key_up = KeyboardKeys.new
@key_held = KeyboardKeys.new
@key_down = KeyboardKeys.new
@has_focus = false
end
def p
@key_down.p || @key_held.p
end
# The left arrow or "a" was pressed.
#
# @return [Boolean]
def left
@key_up.left || @key_held.left || a
end
# The right arrow or "d" was pressed.
#
# @return [Boolean]
def right
@key_up.right || @key_held.right || d
end
# The up arrow or "w" was pressed.
#
# @return [Boolean]
def up
@key_up.up || @key_held.up || w
end
# The down arrow or "s" was pressed.
#
# @return [Boolean]
def down
@key_up.down || @key_held.down || s
end
# Clear all current key presses.
#
# @return [void]
def clear
@key_up.clear
@key_held.clear
@key_down.clear
end
def serialize
{
key_up: @key_up.serialize,
key_held: @key_held.serialize,
key_down: @key_down.serialize,
has_focus: @has_focus
}
end
alias_method :inspect, :serialize
# @return [String]
def to_s
serialize.to_s
end
def key
{
down: @key_down.truthy_keys,
held: @key_held.truthy_keys,
down_or_held: (@key_down.truthy_keys + @key_held.truthy_keys).uniq,
up: @key_up.truthy_keys,
}
end
alias_method :keys, :key
include DirectionalInputHelperMethods
end
end
module GTK
class MousePoint
include GTK::Geometry
# @gtk
attr_accessor :x, :y, :point, :created_at, :global_created_at
def initialize x, y
@x = x
@y = y
@point = [x, y]
@created_at = Kernel.tick_count
@global_created_at = Kernel.global_tick_count
end
def w; 0; end
def h; 0; end
def left; x; end
def right; x; end
def top; y; end
def bottom; y; end
def created_at_elapsed
@created_at.elapsed_time
end
def to_hash
serialize
end
def serialize
{
x: @x,
y: @y,
created_at: @created_at,
global_created_at: @global_created_at
}
end
def inspect
serialize.to_s
end
def to_s
serialize.to_s
end
end
# Provides access to the mouse.
#
# @gtk
class Mouse
# @gtk
attr_accessor :moved,
:moved_at,
:global_moved_at,
:up, :has_focus,
:button_bits, :button_left,
:button_middle, :button_right,
:button_x1, :button_x2,
:wheel
attr_accessor :click
attr_accessor :previous_click
attr_accessor :x
attr_accessor :y
def initialize
@x = 0
@y = 0
@has_focus = false
@button_bits = 0
@button_left = false
@button_middle = false
@button_right = false
@button_x1 = false
@button_x2 = false
clear
end
def point
[@x, @y].point
end
def inside_rect? rect
point.inside_rect? rect
end
def inside_circle? center, radius
point.point_inside_circle? center, radius
end
def intersect_rect? other_rect
{ x: point.x, y: point.y, w: 0, h: 0 }.intersect_rect? other_rect
end
alias_method :position, :point
def clear
if @click
@previous_click = MousePoint.new @click.point.x, @click.point.y
@previous_click.created_at = @click.created_at
@previous_click.global_created_at = @click.global_created_at
end
@click = nil
@up = nil
@moved = nil
@wheel = nil
end
def up
@up
end
def down
@click
end
def serialize
result = {}
if @click
result[:click] = @click.to_hash
result[:down] = @click.to_hash
end
result[:up] = @up.to_hash if @up
result[:x] = @x
result[:y] = @y
result[:moved] = @moved
result[:moved_at] = @moved_at
result[:has_focus] = @has_focus
result
end
def to_s
serialize.to_s
end
alias_method :inspect, :to_s
end
# Provides access to multitouch input
#
# @gtk
class FingerTouch
# @gtk
attr_accessor :moved,
:moved_at,
:global_moved_at,
:down_at,
:global_down_at,
:touch_order,
:first_tick_down,
:x, :y
def initialize
@moved = false
@moved_at = 0
@global_moved_at = 0
@down_at = 0
@global_down_at = 0
@touch_order = 0
@first_tick_down = true
@x = 0
@y = 0
end
def point
[@x, @y].point
end
def inside_rect? rect
point.inside_rect? rect
end
def inside_circle? center, radius
point.point_inside_circle? center, radius
end
alias_method :position, :point
def serialize
result = {}
result[:x] = @x
result[:y] = @y
result[:touch_order] = @touch_order
result[:moved] = @moved
result[:moved_at] = @moved_at
result[:global_moved_at] = @global_moved_at
result[:down_at] = @down_at
result[:global_down_at] = @global_down_at
result
end
def to_s
serialize.to_s
end
alias_method :inspect, :to_s
end
end
module GTK
# @gtk
class Inputs
# A list of all controllers.
#
# @return [Controller[]]
# @gtk
attr_reader :controllers
# @return [Keyboard]
# @gtk
attr_reader :keyboard
# @return [Mouse]
# @gtk
attr_reader :mouse
# @return [HTTPRequest[]]
# @gtk
attr_accessor :http_requests
# @return {FingerTouch}
# @gtk
attr_reader :touch
attr_accessor :finger_one, :finger_two
# @gtk
attr_accessor :text, :history
def initialize
@controllers = [Controller.new, Controller.new]
@keyboard = Keyboard.new
@mouse = Mouse.new
@touch = {}
@finger_one = nil
@finger_two = nil
@text = []
@http_requests = []
end
def up
keyboard.up ||
(controller_one && controller_one.up)
end
def down
keyboard.down ||
(controller_one && controller_one.down)
end
def left
keyboard.left ||
(controller_one && controller_one.left)
end
def right
keyboard.right ||
(controller_one && controller_one.right)
end
def directional_vector
keyboard.directional_vector ||
(controller_one && controller_one.directional_vector)
end
def directional_angle
keyboard.directional_angle || (controller_one && controller_one.directional_angle)
end
# Returns a signal indicating right (`1`), left (`-1`), or neither ('0').
#
# @return [Integer]
def left_right
return -1 if self.left
return 1 if self.right
return 0
end
# Returns a signal indicating up (`1`), down (`-1`), or neither ('0').
#
# @return [Integer]
def up_down
return 1 if self.up
return -1 if self.down
return 0
end
# Returns the coordinates of the last click.
#
# @return [Float, Float]
def click
return nil unless @mouse.click
return @mouse.click.point
end
# The first controller.
#
# @return [Controller]
def controller_one
@controllers[0]
end
# The second controller.
#
# @return [Controller]
def controller_two
@controllers[1]
end
# Clears all inputs.
#
# @return [void]
def clear
@mouse.clear
@keyboard.clear
@controllers.each(&:clear)
@touch.clear
@http_requests.clear
@finger_one = nil
@finger_two = nil
end
# @return [Hash]
def serialize
{
controller_one: controller_one.serialize,
controller_two: controller_two.serialize,
keyboard: keyboard.serialize,
mouse: mouse.serialize,
text: text.serialize
}
end
end
end
</code></pre>
<h3 id='----ios_wizard-rb'>ios_wizard.rb</h3>
<pre><code class="language-ruby"># ./dragon/ios_wizard.rb
# Contributors outside of DragonRuby who also hold Copyright: Michał Dudziński
# Copyright 2019 DragonRuby LLC
# MIT License
# ios_wizard.rb has been released under MIT (*only this file*).
class IOSWizard < Wizard
def initialize
@doctor_executed_at = 0
end
def relative_path
(File.dirname $gtk.binary_path)
end
def steps
@steps ||= []
end
def prerequisite_steps
[
:check_for_xcode,
:check_for_brew,
:check_for_certs,
]
end
def app_metadata_retrieval_steps
[
:determine_team_identifier,
:determine_app_name,
:determine_app_id,
]
end
def steps_development_build
[
*prerequisite_steps,
:check_for_device,
:check_for_dev_profile,
*app_metadata_retrieval_steps,
:clear_tmp_directory,
:stage_app,
:development_write_info_plist,
:write_entitlements_plist,
:compile_icons,
:clear_payload_directory,
:create_payload_directory_dev,
:create_payload,
:code_sign_payload,
:create_ipa,
:deploy
]
end
def steps_production_build
[
*prerequisite_steps,
:check_for_distribution_profile,
:determine_app_version,
*app_metadata_retrieval_steps,
:clear_tmp_directory,
:stage_app,
:production_write_info_plist,
:write_entitlements_plist,
:compile_icons,
:clear_payload_directory,
:create_payload_directory_prod,
:create_payload,
:code_sign_payload,
:create_ipa,
:print_publish_help
]
end
def get_reserved_sprite png
sprite_path = ".dragonruby/sprites/wizards/ios/#{png}"
if !$gtk.ivar :rcb_release_mode
sprite_path = "deploy_template/#{sprite_path}"
$gtk.reset_sprite sprite_path
end
if !$gtk.read_file sprite_path
log_error "png #{png} not found."
end
sprite_path
end
def start opts = nil
@opts = opts || {}
if !(@opts.is_a? Hash) || !($gtk.args.fn.eq_any? @opts[:env], :dev, :prod)
raise WizardException.new(
"* $wizards.ios.start needs to be provided an environment option.",
"** For development builds type: $wizards.ios.start env: :dev",
"** For production builds type: $wizards.ios.start env: :prod"
)
end
@production_build = (@opts[:env] == :prod)
@steps = steps_development_build
@steps = steps_production_build if @production_build
@certificate_name = nil
@app_version = opts[:version]
@app_version = "1.0" if @opts[:env] == :dev && !@app_version
init_wizard_status
log_info "Starting iOS Wizard so we can deploy to your device."
@start_at = Kernel.global_tick_count
steps.each do |m|
log_info "Running step ~:#{m}~."
result = (send m) || :success if @wizard_status[m][:result] != :success
@wizard_status[m][:result] = result
log_info "Running step ~:#{m}~ complete."
end
nil
rescue Exception => e
if e.is_a? WizardException
$console.log.clear
$console.archived_log.clear
log "=" * $console.console_text_width
e.console_primitives.each do |p|
$console.add_primitive p
end
log "=" * $console.console_text_width
else
log_error e.to_s
log e.__backtrace_to_org__
end
init_wizard_status
$console.set_command "$wizards.ios.start env: :#{@opts[:env]}"
end
def always_fail
return false if $gtk.ivar :rcb_release_mode
return true
end
def check_for_xcode
if !cli_app_exist?(xcodebuild_cli_app)
raise WizardException.new(
"* You need Xcode to use $wizards.ios.start.",
{ w: 75, h: 75, path: get_reserved_sprite("xcode.png") },
"** 1. Go to http://developer.apple.com and register.",
"** 2. Download Xcode 11.3+ from http://developer.apple.com/downloads.",
" NOTE: DO NOT install Xcode from the App Store. Use the link above.",
{ w: 700, h: 359, path: get_reserved_sprite("xcode-downloads.png") },
"** 3. After installing. Open up Xcode to accept the EULA."
)
end
end
def check_for_brew
if !cli_app_exist?('brew')
raise WizardException.new(
"* You need to install Brew.",
{ w: 700, h: 388, path: get_reserved_sprite("brew.png") },
"** 1. Go to http://brew.sh.",
"** 2. Copy the command that starts with `/bin/bash -c` on the site.",
"** 3. Open Terminal and run the command you copied from the website.",
{ w: 700, h: 99, path: get_reserved_sprite("terminal.png") },
)
end
end
def init_wizard_status
@wizard_status = {}
steps.each do |m|
@wizard_status[m] = { result: :not_started }
end
previous_step = nil
next_step = nil
steps.each_cons(2) do |current_step, next_step|
@wizard_status[current_step][:next_step] = next_step
end
steps.reverse.each_cons(2) do |current_step, previous_step|
@wizard_status[current_step][:previous_step] = previous_step
end
end
def restart
init_wizard_status
start
end
def check_for_distribution_profile
@provisioning_profile_path = "profiles/distribution.mobileprovision"
if !($gtk.read_file @provisioning_profile_path)
$gtk.system "mkdir -p #{relative_path}/profiles"
$gtk.system "open #{relative_path}/profiles"
$gtk.system "echo Download the mobile provisioning profile and place it here with the name distribution.mobileprovision > #{relative_path}/profiles/README.txt"
raise WizardException.new(
"* I didn't find a mobile provision.",
"** 1. Go to http://developer.apple.com and click \"Certificates, IDs & Profiles\".",
"** 2. Add an App Identifier.",
"** 3. Select the App IDs option from the list.",
{ w: 700, h: 75, path: get_reserved_sprite("identifiers.png") },
"** 4. Add your Device next. You can use idevice_id -l to get the UUID of your device.",
{ w: 365, h: 69, path: get_reserved_sprite("device-link.png") },
"** 5. Create a Profile. Associate your certs, id, and device.",
{ w: 300, h: 122, path: get_reserved_sprite("profiles.png") },
"** 6. Download the mobile provision and save it to 'profiles/development.mobileprovision'.",
{ w: 200, h: 124, path: get_reserved_sprite("profiles-folder.png") },
)
end
end
def check_for_dev_profile
@provisioning_profile_path = "profiles/development.mobileprovision"
if !($gtk.read_file @provisioning_profile_path)
$gtk.system "mkdir -p #{relative_path}/profiles"
$gtk.system "open #{relative_path}/profiles"
$gtk.system "echo Download the mobile provisioning profile and place it here with the name development.mobileprovision > #{relative_path}/profiles/README.txt"
raise WizardException.new(
"* I didn't find a mobile provision.",
"** 1. Go to http://developer.apple.com and click \"Certificates, IDs & Profiles\".",
"** 2. Add an App Identifier.",
"** 3. Select the App IDs option from the list.",
{ w: 700, h: 75, path: get_reserved_sprite("identifiers.png") },
"** 4. Add your Device next. You can use idevice_id -l to get the UUID of your device.",
{ w: 365, h: 69, path: get_reserved_sprite("device-link.png") },
"** 5. Create a Profile. Associate your certs, id, and device.",
{ w: 300, h: 122, path: get_reserved_sprite("profiles.png") },
"** 6. Download the mobile provision and save it to 'profiles/development.mobileprovision'.",
{ w: 200, h: 124, path: get_reserved_sprite("profiles-folder.png") },
)
end
end
def provisioning_profile_path environment
return "profiles/distribution.mobileprovision" if environment == :prod
return "profiles/development.mobileprovision"
end
def ios_metadata_template
<<-S
# ios_metadata.txt is used by the Pro version of DragonRuby Game Toolkit to create iOS apps.
# Information about the Pro version can be found at: http://dragonruby.org/toolkit/game#purchase
# teamid needs to be set to your assigned Team Id which can be found at https://developer.apple.com/account/#/membership/
teamid=
# appid needs to be set to your application identifier which can be found at https://developer.apple.com/account/resources/identifiers/list
appid=
# appname is the name you want to show up underneath the app icon on the device. Keep it under 10 characters.
appname=
S
end
def ios_metadata
contents = $gtk.read_file 'metadata/ios_metadata.txt'
if !contents
$gtk.write_file 'metadata/ios_metadata.txt', ios_metadata_template
contents = $gtk.read_file 'metadata/ios_metadata.txt'
end
kvps = contents.each_line
.reject { |l| l.strip.length == 0 || (l.strip.start_with? "#") }
.map do |l|
key, value = l.split("=")
[key.strip.to_sym, value.strip]
end.flatten
Hash[*kvps]
end
def game_metadata
contents = $gtk.read_file 'metadata/game_metadata.txt'
kvps = contents.each_line
.reject { |l| l.strip.length == 0 || (l.strip.start_with? "#") }
.map do |l|
key, value = l.split("=")
[key.strip.to_sym, value.strip]
end.flatten
Hash[*kvps]
end
def raise_ios_metadata_required
raise WizardException.new(
"* mygame/metadata/ios_metadata.txt needs to be filled out.",
"You need to update metadata/ios_metadata.txt with a valid teamid, appname, and appid.",
"Instructions for where the values should come from are within metadata/ios_metadata.txt."
)
end
def determine_team_identifier
@team_id = (ios_metadata.teamid || "")
raise_ios_metadata_required if @team_id.strip.length == 0
log_info "Team Identifer is: #{@team_id}"
end
def determine_app_name
@app_name = (ios_metadata.appname || "")
raise_ios_metadata_required if @app_name.strip.length == 0
log_info "App name is: #{@app_name}."
end
def provisioning_profile_xml environment
xml = $gtk.read_file (provisioning_profile_path environment)
scrubbed = xml.each_line.map do |l|
if l.strip.start_with? "<"
if l.start_with? '</plist>'
'</plist>'
elsif l.include? "Apple Inc."
nil
elsif l.include? '<data>'
nil
else
l
end
else
nil
end
end.reject { |l| !l }.join
$gtk.parse_xml scrubbed
end
def determine_app_id
@app_id = ios_metadata.appid
raise_ios_metadata_required if @app_id.strip.length == 0
log_info "App Identifier is set to : #{@app_id}"
end
def set_app_name name
@app_name = name
start
end
def set_dev_profile path
if !$gtk.read_file path
log_error "I couldn't find a development profile at #{path}."
ask_for_dev_profile
else
@provisioning_profile_path = path
start
end
end
def clear_tmp_directory
sh "rm -rf #{tmp_directory}"
end
def stage_app
log_info "Staging."
sh "mkdir -p #{tmp_directory}"
sh "cp -R #{relative_path}/dragonruby-ios.app \"#{tmp_directory}/#{@app_name}.app\""
end
def set_app_id id
log_info = "App Id set to: #{id}"
@app_id = id
start
end
def check_for_device
log_info "Looking for device."
if !cli_app_exist?(idevice_id_cli_app)
raise WizardException.new(
"* It doesn't look like you have the libimobiledevice iOS protocol library installed.",
"** 1. Open Terminal.",
{ w: 700, h: 99, path: get_reserved_sprite("terminal.png") },
"** 2. Run: `brew install libimobiledevice`.",
{ w: 500, h: 93, path: get_reserved_sprite("brew-install-libimobiledevice.png") },
)
end
if connected_devices.length == 0
raise WizardException.new("* I couldn't find any connected devices. Connect your iOS device to your Mac and try again.")
end
@device_id = connected_devices.first
log_info "I will be using device with UUID #{@device_id}"
end
def check_for_certs
log_info "Attempting to find certificates on your computer."
if !cli_app_exist?(security_cli_app)
raise WizardException.new(
"* It doesn't look like you have #{security_cli_app}.",
"** 1. Open Disk Utility and run First Aid.",
{ w: 700, h: 148, path: get_reserved_sprite("disk-utility.png") },
)
end
if valid_certs.length == 0
raise WizardException.new(
"* It doesn't look like you have any valid certs installed.",
"** 1. Open Xcode.",
"** 2. Log into your developer account. Xcode -> Preferences -> Accounts.",
{ w: 700, h: 98, path: get_reserved_sprite("login-xcode.png") },
"** 3. After loggin in, select Manage Certificates...",
{ w: 700, h: 115, path: get_reserved_sprite("manage-certificates.png") },
"** 4. Add a certificate for Apple Development.",
{ w: 700, h: 217, path: get_reserved_sprite("add-cert.png") },
)
raise "You do not have any Apple development certs on this computer."
end
if @production_build
@certificate_name = valid_certs.find_all { |f| f[:name].include? "Distribution" }.first[:name]
else
@certificate_name = valid_certs.find_all { |f| f[:name].include? "Development" }.first[:name]
end
log_info "I will be using Certificate: '#{@certificate_name}'."
end
def idevice_id_cli_app
"idevice_id"
end
def security_cli_app
"/usr/bin/security"
end
def xcodebuild_cli_app
"xcodebuild"
end
def valid_certs
certs = sh("#{security_cli_app} -q find-identity -p codesigning -v").each_line.map do |l|
if l.include?(")") && !l.include?("Developer ID") && (l.include?("Development") || l.include?("Distribution"))
l.strip
else
nil
end
end.reject_nil.map do |l|
number, id, name = l.split(' ', 3)
name = name.gsub("\"", "") if name
{
number: 1,
id: id,
name: name
}
end
end
def connected_devices
sh("idevice_id -l").strip.each_line.map do |l|
l.strip
end.reject { |l| l.length == 0 }
end
def cli_app_exist? app
`which #{app}`.strip.length != 0
end
def write_entitlements_plist
if @production_build
entitlement_plist_string = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>application-identifier</key>
<string>:app_id</string>
<key>beta-reports-active</key>
<true/>
</dict>
</plist>
XML
else
entitlement_plist_string = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>application-identifier</key>
<string>:app_id</string>
<key>get-task-allow</key>
<true/>
</dict>
</plist>
XML
end
log_info "Creating Entitlements.plist"
$gtk.write_file_root "tmp/ios/Entitlements.plist", entitlement_plist_string.gsub(":app_id", "#{@team_id}.#{@app_id}").strip
$gtk.write_file_root "tmp/ios/Entitlements.txt", entitlement_plist_string.gsub(":app_id", "#{@team_id}.#{@app_id}").strip
sh "/usr/bin/plutil -convert binary1 \"#{tmp_directory}/Entitlements.plist\""
sh "/usr/bin/plutil -convert xml1 \"#{tmp_directory}/Entitlements.plist\""
@entitlement_plist_written = true
end
def code_sign_payload
log_info "Signing app with #{@certificate_name}."
sh "CODESIGN_ALLOCATE=\"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate\" /usr/bin/codesign -f -s \"#{@certificate_name}\" --entitlements #{tmp_directory}/Entitlements.plist \"#{tmp_directory}/ipa_root/Payload/#{@app_name}.app\""
sh "CODESIGN_ALLOCATE=\"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate\" /usr/bin/codesign -f -s \"#{@certificate_name}\" --entitlements #{tmp_directory}/Entitlements.plist \"#{tmp_directory}/ipa_root/Payload/#{@app_name}.app/Runtime\""
@code_sign_completed = true
end
def write_info_plist_distribution
log_info "Adding Info.plist."
<<-XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>20D91</string>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleName</key>
<string>:app_name</string>
<key>CFBundleDisplayName</key>
<string>A Dark Room</string>
<key>CFBundleIdentifier</key>
<string>:app_id</string>
<key>CFBundleExecutable</key>
<string>:app_name</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>:app_version</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>:app_version</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>:app_version</string>
<key>CFBundleIcons</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconName</key>
<string>AppIcon</string>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon60x60</string>
</array>
</dict>
</dict>
<key>CFBundleIcons~ipad</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconName</key>
<string>AppIcon</string>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon60x60</string>
<string>AppIcon76x76</string>
<string>AppIcon83.5x83.5</string>
</array>
</dict>
</dict>
<key>UILaunchStoryboardName</key>
<string>SimpleSplash</string>
<key>UIRequiresFullScreen</key>
<true/>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>MinimumOSVersion</key>
<string>10.3</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>iPhoneOS</string>
</array>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon20x20</string>
<string>AppIcon29x29</string>
<string>AppIcon40x40</string>
<string>AppIcon60x60</string>
</array>
<key>UIDeviceFamily</key>
<array>
<integer>1</integer>
<integer>2</integer>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleDefault</string>
<key>UIBackgroundModes</key>
<array>
</array>
<key>DTXcode</key>
<string>0124</string>
<key>DTXcodeBuild</key>
<string>12D4e</string>
<key>DTSDKName</key>
<string>iphoneos14.4</string>
<key>DTSDKBuild</key>
<string>18D46</string>
<key>DTPlatformName</key>
<string>iphoneos</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformVersion</key>
<string>14.4</string>
<key>DTPlatformBuild</key>
<string>18D46</string>
</dict>
</plist>
XML
end
def development_write_info_plist
log_info "Adding Info.plist."
info_plist_string = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>google.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
<key>BuildMachineOSBuild</key>
<string>20D91</string>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>:app_name</string>
<key>CFBundleExecutable</key>
<string>Runtime</string>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon60x60</string>
</array>
<key>CFBundleIcons</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon60x60</string>
</array>
<key>CFBundleIconName</key>
<string>AppIcon</string>
</dict>
</dict>
<key>CFBundleIcons~ipad</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon60x60</string>
<string>AppIcon76x76</string>
<string>AppIcon83.5x83.5</string>
</array>
<key>CFBundleIconName</key>
<string>AppIcon</string>
</dict>
</dict>
<key>CFBundleIdentifier</key>
<string>:app_id</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>:app_version</string>
<key>CFBundleName</key>
<string>:app_name</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>:app_version</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>iPhoneOS</string>
</array>
<key>CFBundleVersion</key>
<string>:app_version</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>18D46</string>
<key>DTPlatformName</key>
<string>iphoneos</string>
<key>DTPlatformVersion</key>
<string>14.4</string>
<key>DTSDKBuild</key>
<string>18D46</string>
<key>DTSDKName</key>
<string>iphoneos14.4</string>
<key>DTXcode</key>
<string>0124</string>
<key>DTXcodeBuild</key>
<string>12D4e</string>
<key>MinimumOSVersion</key>
<string>14.4</string>
<key>UIAppFonts</key>
<array/>
<key>UIBackgroundModes</key>
<array/>
<key>UIDeviceFamily</key>
<array>
<integer>1</integer>
<integer>2</integer>
</array>
<key>UILaunchImages</key>
<array>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>7.0</string>
<key>UILaunchImageName</key>
<string>Default-568h@2x</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{320, 568}</string>
</dict>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>7.0</string>
<key>UILaunchImageName</key>
<string>Default-667h@2x</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{375, 667}</string>
</dict>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>7.0</string>
<key>UILaunchImageName</key>
<string>Default-736h@3x</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{414, 736}</string>
</dict>
</array>
<key>UILaunchStoryboardName</key>
<string>SimpleSplash</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UIRequiresFullScreen</key>
<true/>
<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleDefault</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
XML
# <string>UIInterfaceOrientationPortrait</string>
# <string>UIInterfaceOrientationLandscapeRight</string>
info_plist_string.gsub!(":app_name", @app_name)
info_plist_string.gsub!(":app_id", @app_id)
$gtk.write_file_root "tmp/ios/#{@app_name}.app/Info.plist", info_plist_string.strip
$gtk.write_file_root "tmp/ios/Info.txt", info_plist_string.strip
@info_plist_written = true
end
def production_write_info_plist
log_info "Adding Info.plist."
info_plist_string = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>20D91</string>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>:app_name</string>
<key>CFBundleExecutable</key>
<string>Runtime</string>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon60x60</string>
</array>
<key>CFBundleIcons</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon60x60</string>
</array>
<key>CFBundleIconName</key>
<string>AppIcon</string>
</dict>
</dict>
<key>CFBundleIcons~ipad</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon60x60</string>
<string>AppIcon76x76</string>
<string>AppIcon83.5x83.5</string>
</array>
<key>CFBundleIconName</key>
<string>AppIcon</string>
</dict>
</dict>
<key>CFBundleIdentifier</key>
<string>:app_id</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>:app_version</string>
<key>CFBundleName</key>
<string>:app_name</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>:app_version</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>iPhoneOS</string>
</array>
<key>CFBundleVersion</key>
<string>:app_version</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>18D46</string>
<key>DTPlatformName</key>
<string>iphoneos</string>
<key>DTPlatformVersion</key>
<string>14.4</string>
<key>DTSDKBuild</key>
<string>18D46</string>
<key>DTSDKName</key>
<string>iphoneos14.4</string>
<key>DTXcode</key>
<string>0124</string>
<key>DTXcodeBuild</key>
<string>12D4e</string>
<key>MinimumOSVersion</key>
<string>14.4</string>
<key>UIAppFonts</key>
<array/>
<key>UIBackgroundModes</key>
<array/>
<key>UIDeviceFamily</key>
<array>
<integer>1</integer>
<integer>2</integer>
</array>
<key>UILaunchImages</key>
<array>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>7.0</string>
<key>UILaunchImageName</key>
<string>Default-568h@2x</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{320, 568}</string>
</dict>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>7.0</string>
<key>UILaunchImageName</key>
<string>Default-667h@2x</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{375, 667}</string>
</dict>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>7.0</string>
<key>UILaunchImageName</key>
<string>Default-736h@3x</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{414, 736}</string>
</dict>
</array>
<key>UILaunchStoryboardName</key>
<string>SimpleSplash</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UIRequiresFullScreen</key>
<true/>
<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleDefault</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
XML
# <string>UIInterfaceOrientationPortrait</string>
# <string>UIInterfaceOrientationLandscapeRight</string>
info_plist_string.gsub!(":app_name", @app_name)
info_plist_string.gsub!(":app_id", @app_id)
info_plist_string.gsub!(":app_version", @app_version)
$gtk.write_file_root "tmp/ios/#{@app_name}.app/Info.plist", info_plist_string.strip
$gtk.write_file_root "tmp/ios/Info.txt", info_plist_string.strip
@info_plist_written = true
end
def device_orientation_xml
return "UIInterfaceOrientationLandscapeRight" if $gtk.logical_width > $gtk.logical_height
return "UIInterfaceOrientationPortrait"
end
def tmp_directory
"#{relative_path}/tmp/ios"
end
def app_path
"#{tmp_directory}/#{@app_name}.app"
end
def root_folder
"#{relative_path}/#{$gtk.cli_arguments[:dragonruby]}"
end
def embed_mobileprovision
sh %Q[cp #{@provisioning_profile_path} "#{app_path}/embedded.mobileprovision"]
sh %Q[/usr/bin/plutil -convert binary1 "#{app_path}/Info.plist"]
end
def clear_payload_directory
sh %Q[rm "#{@app_name}".ipa]
sh %Q[rm -rf "#{app_path}/app"]
sh %Q[rm -rf "#{app_path}/sounds"]
sh %Q[rm -rf "#{app_path}/sprites"]
sh %Q[rm -rf "#{app_path}/data"]
sh %Q[rm -rf "#{app_path}/fonts"]
end
def stage_app
sh %Q[cp -r "#{root_folder}/app/" "#{app_path}/app/"]
sh %Q[cp -r "#{root_folder}/sounds/" "#{app_path}/sounds/"]
sh %Q[cp -r "#{root_folder}/sprites/" "#{app_path}/sprites/"]
sh %Q[cp -r "#{root_folder}/data/" "#{app_path}/data/"]
sh %Q[cp -r "#{root_folder}/fonts/" "#{app_path}/fonts/"]
end
def create_payload
sh %Q[mkdir -p #{tmp_directory}/ipa_root/Payload]
sh %Q[cp -r "#{app_path}" "#{tmp_directory}/ipa_root/Payload"]
sh %Q[chmod -R 755 "#{tmp_directory}/ipa_root/Payload"]
end
def create_payload_directory_dev
# write dev machine's ip address for hotloading
$gtk.write_file "app/server_ip_address.txt", $gtk.ffi_misc.get_local_ip_address.strip
embed_mobileprovision
clear_payload_directory
stage_app
end
def create_payload_directory_prod
# production builds does not hotload ip address
sh %Q[rm "#{root_folder}/app/server_ip_address.txt"]
embed_mobileprovision
stage_app
# production build marker
sh %Q[mkdir -p "#{app_path}/metadata/"]
sh %Q[touch metadata/DRAGONRUBY_PRODUCTION_BUILD]
end
def create_ipa
do_zip
sh "cp \"#{tmp_directory}/ipa_root/archive.zip\" \"#{tmp_directory}/#{@app_name}.ipa\""
end
def do_zip
$gtk.write_file_root "tmp/ios/do_zip.sh", <<-SCRIPT
pushd #{tmp_directory}/ipa_root/
zip -q -r archive.zip Payload
popd
SCRIPT
sh "sh #{tmp_directory}/do_zip.sh"
end
def sh cmd
log_info cmd.strip
result = `#{cmd}`
if result.strip.length > 0
log_info result.strip.each_line.map(&:strip).join("\n")
end
result
end
def deploy
sh "XCODE_DIR=\"/Applications/Xcode.app/Contents/Developer\" \"#{relative_path}/dragonruby-deploy-ios\" -d \"#{@device_id}\" \"#{tmp_directory}/#{@app_name}.ipa\""
log_info "Check your device!!"
end
def print_publish_help
has_transporter = (sh "ls /Applications/Transporter.app").include? "Contents"
if !has_transporter
$gtk.openurl "https://apps.apple.com/us/app/transporter/id1450874784?mt=12"
$console.set_command "$wizards.ios.start env: :#{@opts[:env]}, version: \"#{@opts[:version]}\""
raise WizardException.new(
"* To upload your app, Download Transporter from the App Store https://apps.apple.com/us/app/transporter/id1450874784?mt=12."
)
else
sh "mkdir ./tmp/ios/intermediary_artifacts"
sh "mv \"#{tmp_directory}/#{@app_name}.app\" #{tmp_directory}/intermediary_artifacts/"
sh "mv \"#{tmp_directory}/do_zip.sh\" #{tmp_directory}/intermediary_artifacts"
sh "mv \"#{tmp_directory}/Entitlements.plist\" #{tmp_directory}/intermediary_artifacts"
sh "mv \"#{tmp_directory}/ipa_root\" #{tmp_directory}/intermediary_artifacts/"
sh "open /Applications/Transporter.app"
sh "open ./tmp/ios/"
end
end
def compile_icons
cmd = <<-S
"/Applications/Xcode.app/Contents/Developer/usr/bin/actool" --output-format human-readable-text \
--notices --warnings --platform iphoneos \
--minimum-deployment-target 10.3 \
--target-device iphone \
--target-device ipad --app-icon 'AppIcon' \
--output-partial-info-plist '#{app_path}/AssetCatalog-Info.plist' \
--compress-pngs --compile "#{app_path}" \
"#{app_path}/Assets.xcassets"
S
sh cmd
end
def stage_native_libs
sh "cp -r \"#{root_folder}/native/\" \"#{app_path}/native/\""
sh "CODESIGN_ALLOCATE=\"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate\" /usr/bin/codesign -f -s \"#{@certificate_name}\" --entitlements #{tmp_directory}/Entitlements.plist \"#{tmp_directory}/#{@app_name}.app/native/ios-device/ext.dylib\""
end
def set_version version
@app_version = version
start env: @opts[:env], version: version
end
def app_version
log_info "Attempting to retrieve App Version from metadata/ios_metadata.txt."
ios_version_number = (ios_metadata.version || "").strip
if ios_version_number.length == 0
log_info "Not found. Attempting to retrieve App Version from metadata/game_metadata.txt."
ios_version_number = (game_metadata.version || "").strip
end
ios_version_number
end
def determine_app_version
@app_version = app_version
return if @app_version
end
end
</code></pre>
<h3 id='----itch_wizard-rb'>itch_wizard.rb</h3>
<pre><code class="language-ruby"># ./dragon/itch_wizard.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# itch_wizard.rb has been released under MIT (*only this file*).
class ItchWizard < Wizard
def steps
[
:check_metadata,
:deploy,
]
end
def write_blank_metadata
$gtk.write_file metadata_file_path, <<-S.strip
#devid=myname
#devtitle=My Name
#gameid=mygame
#gametitle=My Game
#version=0.1
#icon=metadata/icon.png
S
end
def check_metadata
metadata_text = $gtk.read_file metadata_file_path
if !metadata_text
write_blank_metadata
end
if metadata_text.strip.each_line.to_a.length < 6
write_blank_metadata
end
log "* INFO: Contents of #{metadata_file_path}:"
log "#+begin_src txt"
metadata_text.each_line { |l| log " #{l}" }
log "#+end_src"
metadata = get_metadata
if metadata[:dev_id].start_with?("#") || !@dev_id
log "* PROMPT: Please provide your username for Itch."
$console.set_command "$wizards.itch.set_dev_id \"#{metadata[:dev_id]}\""
return :need_dev_id
end
if metadata[:dev_title].start_with?("#") || !@dev_title
log "* PROMPT: Please provide developer's/company's name that you want displayed."
$console.set_command "$wizards.itch.set_dev_title \"#{metadata[:dev_title]}\""
return :need_dev_title
end
if metadata[:game_id].start_with?("#") || !@game_id
log "* PROMPT: Please provide the id for you game. This is the id you specified when you set up a new game page on Itch."
$console.set_command "$wizards.itch.set_game_id \"#{metadata[:game_id]}\""
return :need_game_id
end
if metadata[:game_title].start_with?("#") || !@game_title
log "* PROMPT: Please provide the display name for your game. (This can include spaces)"
$console.set_command "$wizards.itch.set_game_title \"#{metadata[:game_title]}\""
return :need_game_title
end
if metadata[:version].start_with?("#") || !@version
log "* PROMPT: Please provide the version for your game."
$console.set_command "$wizards.itch.set_version \"#{metadata[:version]}\""
return :need_version
end
if metadata[:icon].start_with?("#") || !@icon
log "* PROMPT: Please provide icon path for your game."
$console.set_command "$wizards.itch.set_icon \"#{metadata[:icon]}\""
return :need_icon
end
puts "here!! success!!!"
return :success
end
def set_dev_id value
@dev_id = value
start
end
def set_dev_title value
@dev_title = value
start
end
def set_game_id value
@game_id = value
start
end
def set_game_title value
@game_title = value
start
end
def set_version value
@version = value
start
end
def set_icon value
@icon = value
write_metadata
start
end
def write_metadata
text = ""
if @dev_id
text += "devid=#{@dev_id}\n"
else
text += "#devid=myname\n"
end
if @dev_title
text += "devtitle=#{@dev_title}\n"
else
text += "#devtitle=My Name\n"
end
if @game_id
text += "gameid=#{@game_id}\n"
else
text += "#gameid=gameid\n"
end
if @game_title
text += "gametitle=#{@game_title}\n"
else
text += "#gametitle=Game Name\n"
end
if @version
text += "version=#{@version}\n"
else
text += "#version=0.1\n"
end
if @icon
text += "icon=#{@icon}\n"
else
text += "#icon=metadata/icon.png\n"
end
$gtk.write_file metadata_file_path, text
end
def relative_path
(File.dirname $gtk.binary_path)
end
def package_command
"#{File.join $gtk.get_base_dir, 'dragonruby-publish'}"
end
def deploy
log_info "* Running dragonruby-publish: #{package_command}"
$gtk.openurl "http://itch.io/dashboard" if $gtk.platform == "Mac OS X"
if $gtk.platform? :mac
$gtk.exec "rm -rf ./builds"
end
results = $gtk.exec "#{package_command} --only-package"
puts File.expand_path("./builds")
log "#+begin_src"
log results
log "#+end_src"
if $gtk.platform? :mac
$gtk.exec "open ./builds/"
elsif $gtk.platform? :windows
$gtk.exec "powershell \"ii .\""
end
$gtk.openurl "https://itch.io/dashboard"
:success
end
def start
log "================"
log "* INFO: Starting Itch Wizard."
@start_at = Kernel.global_tick_count
steps.each do |m|
begin
log_info "Running Itch Wizard Step: ~$wizards.itch.#{m}~"
result = (send m) || :success
@wizard_status[m][:result] = result
if result != :success
log_info "Exiting wizard. :#{result}"
break
end
rescue Exception => e
if e.is_a? WizardException
$console.log.clear
$console.archived_log.clear
log "=" * $console.console_text_width
e.console_primitives.each do |p|
$console.add_primitive p
end
log "=" * $console.console_text_width
$console.set_command (e.console_command || "$wizards.itch.start")
else
log_error "Step #{m} failed."
log_error e.to_s
$console.set_command "$wizards.itch.start"
end
break
end
end
end
def reset
@dev_id = nil
@dev_title = nil
@game_id = nil
@game_title = nil
@version = nil
@icon = nil
init_wizard_status
end
def restart
reset
start
end
def initialize
reset
end
def init_wizard_status
@wizard_status = {}
steps.each do |m|
@wizard_status[m] = { result: :not_started }
end
previous_step = nil
next_step = nil
steps.each_cons(2) do |current_step, next_step|
@wizard_status[current_step][:next_step] = next_step
end
steps.reverse.each_cons(2) do |current_step, previous_step|
@wizard_status[current_step][:previous_step] = previous_step
end
end
end
</code></pre>
<h3 id='----layout-rb'>layout.rb</h3>
<pre><code class="language-ruby"># ./dragon/layout.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# layout.rb has been released under MIT (*only this file*).
module GTK
class Margin
attr :left, :right, :top, :bottom
def initialize
@left = 0
@right = 0
@top = 0
@bottom = 0
end
def serialize
{
left: @left,
right: @right,
top: @top,
bottom: @bottom,
}
end
def inspect
serialize.to_s
end
def to_s
serialize.to_s
end
end
class SafeArea
attr :w, :h, :margin
def initialize
@w = 0
@h = 0
@margin = Margin.new
end
def serialize
{
w: @w,
h: @h,
margin: @margin.serialize
}
end
def inspect
serialize.to_s
end
def to_s
serialize.to_s
end
end
class GridArea
attr :w, :h, :margin, :gutter, :col_count, :row_count, :cell_w, :cell_h, :outer_gutter
def initialize
@w = 0
@h = 0
@gutter = 0
@outer_gutter = 0
@col_count = 0
@row_count = 0
@margin = Margin.new
end
def serialize
{
w: @w,
h: @h,
gutter: @gutter,
outer_gutter: @outer_gutter,
col_count: @col_count,
row_count: @row_count,
margin: @margin.serialize
}
end
def inspect
serialize.to_s
end
def to_s
serialize.to_s
end
end
class ControlArea
attr :cell_size, :w, :h, :margin
def initialize
@margin = Margin.new
end
def serialize
{
cell_size: @cell_size,
w: @w,
h: @h,
margin: @margin.serialize,
}
end
def inspect
serialize.to_s
end
def to_s
serialize.to_s
end
end
class Device
attr :w, :h, :safe_area, :grid_area, :control_area, :name, :aspect
def initialize
@name = ""
@w = 0
@h = 0
@safe_area = SafeArea.new
@grid_area = GridArea.new
@control_area = ControlArea.new
@aspect = AspectRatio.new
end
def assert! result, message
return if result
raise message
end
def check_math!
assert! (@control_area.w + @control_area.margin.left + @control_area.margin.right) == @w, "Math for Width didn't pan out."
assert! (@control_area.h + @control_area.margin.top + @control_area.margin.bottom) == @h, "Math for Height didn't pan out."
end
def serialize
{
name: @name,
w: @w,
h: @h,
aspect: @aspect.serialize,
safe_area: @safe_area.serialize,
grid_area: @grid_area.serialize,
control_area: @control_area.serialize
}
end
def inspect
serialize.to_s
end
def to_s
serialize.to_s
end
end
class AspectRatio
attr :w, :h, :u
def initialize
@w = 0
@h = 0
@u = 0
end
def serialize
{
w: @w,
h: @h,
u: @u
}
end
def inspect
serialize.to_s
end
def to_s
serialize.to_s
end
end
class Layout
attr :w, :h, :rect_cache
def initialize w, h
@w = w
@h = h
@rect_cache = {}
init_device @w, @h
end
def u_for_16x9 w, h
u = (w.fdiv 16).floor
u = (h.fdiv 9).floor if (u * 9) > h
{
u: u,
w: u * 16,
h: u * 9
}
end
def font_relative_size_enum size_enum
base_line_logical = 22
base_line_actual = font_size_med
target_logical = size_enum
target_logical = 1 if target_logical <= 0
(base_line_actual / base_line_logical) * target_logical
end
def font_px_to_pt px
(px / 1.33333).floor
end
def font_pt_to_px pt
pt * 1.333333
end
def font_size_cell
(cell_height / 1.33333)
end
def font_size_xl
font_size_cell
end
def font_size_lg
font_size_cell * 0.8
end
def font_size_med
font_size_cell * 0.7
end
def font_size_sm
font_size_cell * 0.6
end
def font_size_xs
font_size_cell * 0.5
end
def font_size
font_size_cell * 0.7
end
def logical_rect
@logical_rect ||= { x: 0,
y: 0,
w: @w,
h: @h }
end
def safe_rect
@safe_rect ||= { x: 0,
y: 0,
w: @w,
h: @h }
end
def control_rect
@control_rect ||= { x: device.control_area.margin.left,
y: device.control_area.margin.top,
w: device.control_area.w,
h: device.control_area.h }
end
def row_count
device.grid_area.row_count
end
def row_max_index
row_count - 1
end
def col_count
device.grid_area.col_count
end
def col_max_index
col_count - 1
end
def gutter_height
device.grid_area.gutter
end
def gutter_width
device.grid_area.gutter
end
def outer_gutter
device.grid_area.outer_gutter
end
def cell_height
device.control_area.cell_size
end
def cell_width
device.control_area.cell_size
end
def rect_defaults
{
row: nil,
col: nil,
h: 1,
w: 1,
dx: 0,
dx_ratio: 1,
dy: 0,
dy_ratio: 1,
dh_ratio: 1,
dw_ratio: 1,
merge: nil,
rect: :control_rect
}
end
def row n
(rect row: n, col: 0, w: 0, h: 0).x
end
def row_from_bottom n
(rect row: row_count - n, col: 0, w: 0, h: 0).x
end
def col n
(rect row: 0, col: n, w: 0, h: 0).y
end
def col_from_right n
(rect row: 0, col: col_max_index - n, w: 0, h: 0).y
end
def w n
(rect row: 0, col: 0, w: n, h: 1).w
end
def h n
(rect row: 0, col: 0, w: 1, h: n).h
end
def rect_group opts
group = opts.group
r = opts.row || 0
r = row_max_index - opts.row_from_bottom if opts.row_from_bottom
c = opts.col || 0
c = col_max_index - opts.col_from_right if opts.col_from_right
drow = opts.drow || 0
dcol = opts.dcol || 0
w = opts.w || 0
h = opts.h || 0
merge = opts[:merge]
running_row = r
running_col = c
running_col = calc_col_offset(opts.col_offset) if opts.col_offset
running_row = calc_row_offset(opts.row_offset) if opts.row_offset
group.map do |i|
group_layout_opts = i.layout || {}
group_layout_opts = group_layout_opts.merge row: running_row,
col: running_col,
merge: merge,
w: w, h: h
result = (rect group_layout_opts).merge i
if (i.is_a? Hash) && (i.primitive_marker == :label)
if i.alignment_enum == 1
result.x += result.w.half
elsif i.alignment_enum == 2
result.x += result.w
end
end
running_row += drow
running_col += dcol
result
end
end
def calc_row_offset opts = {}
count = opts[:count] || opts[:length] || 0
h = opts.h || 1
(row_count - (count * h)) / 2.0
end
def calc_col_offset opts = {}
count = opts[:count] || opts[:length] || 0
w = opts.w || 1
(col_count - (count * w)) / 2.0
end
def point opts = {}
opts.w = 1
opts.h = 1
opts.row ||= 0
opts.col ||= 0
r = rect opts
r.x += r.w * opts.col_anchor if opts.col_anchor
r.y += r.h * opts.row_anchor if opts.row_anchor
r
end
def rect *all_opts
if all_opts.length == 1
opts = all_opts.first
else
opts = {}
all_opts.each do |o|
opts.merge! o
end
end
opts.row = row_max_index - opts.row_from_bottom if opts.row_from_bottom
opts.col = col_max_index - opts.col_from_right if opts.col_from_right
opts = rect_defaults.merge opts
opts.row ||= 0
opts.col ||= 0
result = send opts[:rect]
if opts[:row] && opts[:col] && opts[:w] && opts[:h]
col = rect_col opts[:col], opts[:w]
row = rect_row opts[:row], opts[:h]
result = control_rect.merge x: col.x,
y: row.y,
w: col.w,
h: row.h,
center_x: col.center_x,
center_y: row.center_y
elsif opts[:row] && !opts[:col]
result = rect_row opts[:row], opts[:h]
elsif !opts[:row] && opts[:col]
result = rect_col opts[:col], opts[:w]
else
raise "LayoutTheory::rect unable to process opts #{opts}."
end
if opts[:max_height] && opts[:max_height] >= 0
if result[:h] > opts[:max_height]
delta = (result[:h] - opts[:max_height]) * 2
result[:y] += delta
result[:h] = opts[:max_height]
end
end
if opts[:max_width] && opts[:max_width] >= 0
if result[:w] > opts[:max_width]
delta = (result[:w] - opts[:max_width]) * 2
result[:x] += delta
result[:w] = opts[:max_width]
end
end
result[:x] += opts[:dx]
result[:y] += opts[:dy]
if opts[:include_row_gutter]
result[:x] -= device.grid_area.gutter
result[:w] += device.grid_area.gutter * 2
end
if opts[:include_col_gutter]
result[:y] -= device.grid_area.gutter
result[:h] += device.grid_area.gutter * 2
end
result[:x] += opts[:dx] if opts[:dx]
result[:x] *= opts[:dx_ratio] if opts[:dx_ratio]
result[:y] += opts[:dy] if opts[:dy]
result[:y] *= opts[:dy_ratio] if opts[:dy_ratio]
result[:w] += opts[:dw] if opts[:dw]
result[:w] *= opts[:dw_ratio] if opts[:dw_ratio]
result[:h] += opts[:dh] if opts[:dh]
result[:h] *= opts[:dh_ratio] if opts[:dh_ratio]
result.merge! opts[:merge] if opts[:merge]
result[:row] = opts[:row]
result[:col] = opts[:col]
result[:h] = result[:h].clamp 0
result[:w] = result[:w].clamp 0
if $gtk.args.grid.name == :center
result[:x] -= 640
result[:y] -= 360
end
result
end
def rect_center reference, target
delta_x = (reference.w - target.w).fdiv 2
delta_y = (reference.h - target.h).fdiv 2
[target.x - delta_x, target.y - delta_y, target.w, target.h]
end
def rect_row index, h
@rect_cache[:row] ||= {}
@rect_cache[:row][index] ||= {}
return @rect_cache[:row][index][h] if @rect_cache[:row][index][h]
row_h = (device.grid_area.gutter * (h - 1)) +
(device.control_area.cell_size * h)
row_h = row_h.to_i
row_h -= 1 if row_h.odd?
row_y = (control_rect.y) +
(device.grid_area.gutter * index) +
(device.control_area.cell_size * index)
row_y = row_y.to_i
row_y += 1 if row_y.odd? && (index + 1) > @device.grid_area.row_count.half
row_y += 1 if row_y.odd? && (index + 1) <= @device.grid_area.row_count.half
row_y = device.h - row_y - row_h
result = control_rect.merge y: row_y, h: row_h, center_y: (row_y + row_h.half)
@rect_cache[:row][index][h] = result
@rect_cache[:row][index][h]
end
def rect_col index, w
@rect_cache[:col] ||= {}
@rect_cache[:col][index] ||= {}
return @rect_cache[:col][index][w] if @rect_cache[:col][index][w]
col_x = (control_rect.x) +
(device.grid_area.gutter * index) +
(device.control_area.cell_size * index)
col_x = col_x.to_i
col_x -= 1 if col_x.odd? && (index + 1) < @device.grid_area.col_count.half
col_x += 1 if col_x.odd? && (index + 1) >= @device.grid_area.col_count.half
col_w = (device.grid_area.gutter * (w - 1)) +
(device.control_area.cell_size * w)
col_w = col_w.to_i
col_w -= 1 if col_w.odd?
result = control_rect.merge x: col_x, w: col_w, center_x: (col_x + col_w.half)
@rect_cache[:col][index][w] = result
@rect_cache[:col][index][w]
end
def device
@device
end
def init_device w, h
@device = Device.new
@device.w = w
@device.h = h
@device.name = "Device"
@device.aspect.w = (u_for_16x9 w, h)[:w]
@device.aspect.h = (u_for_16x9 w, h)[:h]
@device.aspect.u = (u_for_16x9 w, h)[:u]
@device.safe_area.w = @device.aspect.u * 16
@device.safe_area.h = @device.aspect.u * 9
@device.safe_area.margin.left = ((@device.w - @device.safe_area.w).fdiv 2).floor
@device.safe_area.margin.right = ((@device.w - @device.safe_area.w).fdiv 2).floor
@device.safe_area.margin.top = ((@device.h - @device.safe_area.h).fdiv 2).floor
@device.safe_area.margin.bottom = ((@device.h - @device.safe_area.h).fdiv 2).floor
@device.grid_area.outer_gutter = @device.w / 80
@device.grid_area.gutter = @device.w / 160
@device.grid_area.w = @device.safe_area.w - (@device.grid_area.outer_gutter * 2)
@device.grid_area.h = @device.safe_area.h - (@device.grid_area.outer_gutter * 2)
@device.grid_area.margin.left = ((@device.w - @device.grid_area.w).fdiv 2).floor
@device.grid_area.margin.right = ((@device.w - @device.grid_area.w).fdiv 2).floor
@device.grid_area.margin.top = ((@device.h - @device.grid_area.h).fdiv 2).floor
@device.grid_area.margin.bottom = ((@device.h - @device.grid_area.h).fdiv 2).floor
@device.grid_area.col_count = 24
@device.grid_area.row_count = 12
@device.grid_area.cell_w = ((@device.aspect.w - (@device.grid_area.outer_gutter * 2)) - ((@device.grid_area.col_count - 1) * @device.grid_area.gutter)).fdiv @device.grid_area.col_count
@device.grid_area.cell_h = ((@device.aspect.h - (@device.grid_area.outer_gutter * 2)) - ((@device.grid_area.row_count - 1) * @device.grid_area.gutter)).fdiv @device.grid_area.row_count
@device.control_area.cell_size = @device.grid_area.cell_w
@device.control_area.cell_size = @device.grid_area.cell_h if @device.grid_area.cell_h < @device.grid_area.cell_w && @device.grid_area.cell_h > 0
@device.control_area.cell_size = @device.control_area.cell_size.floor
@device.control_area.w = (@device.control_area.cell_size * @device.grid_area.col_count) + (@device.grid_area.gutter * (@device.grid_area.col_count - 1))
@device.control_area.h = (@device.control_area.cell_size * @device.grid_area.row_count) + (@device.grid_area.gutter * (@device.grid_area.row_count - 1))
@device.control_area.margin.left = (@device.w - @device.control_area.w).fdiv 2
@device.control_area.margin.right = (@device.w - @device.control_area.w).fdiv 2
@device.control_area.margin.top = (@device.h - @device.control_area.h).fdiv 2
@device.control_area.margin.bottom = (@device.h - @device.control_area.h).fdiv 2
@device
end
def debug_primitives opts = {}
@primitives ||= col_count.map_with_index do |col|
row_count.map_with_index do |row|
cell = rect row: row, col: col
center = Geometry.rect_center_point cell
[
cell.merge(opts).border,
cell.merge(opts)
.label!(x: center.x,
y: center.y,
text: "#{row},#{col}",
size_enum: -3,
vertical_alignment_enum: 1,
alignment_enum: 1)
]
end
end
@primitives
end
def serialize
{
device: @device.serialize,
}
end
def inspect
serialize.to_s
end
def to_s
serialize.to_s
end
def reset
@primitives = nil
@rect_cache ||= {}
@rect_cache.clear
end
end
end
</code></pre>
<h3 id='----log-rb'>log.rb</h3>
<pre><code class="language-ruby"># ./dragon/log.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# log.rb has been released under MIT (*only this file*).
XTERM_COLOR = {
black: "\u001b[30m",
red: "\u001b[31m",
green: "\u001b[32m",
yellow: "\u001b[33m",
blue: "\u001b[34m",
magenta: "\u001b[35m",
cyan: "\u001b[36m",
white: "\u001b[37m",
bright_black: "\u001b[30;1m",
bright_red: "\u001b[31;1m",
bright_green: "\u001b[32;1m",
bright_yellow: "\u001b[33;1m",
bright_blue: "\u001b[34;1m",
bright_magenta: "\u001b[35;1m",
bright_cyan: "\u001b[36;1m",
bright_white: "\u001b[37;1m",
reset: "\u001b[0m",
}
module GTK
class Log
def self.write_to_log_and_puts *args
return if $gtk.production
$gtk.append_file_root 'logs/log.txt', args.join("\n") + "\n"
args.each { |obj| $gtk.log obj, self }
end
def self.write_to_log_and_print *args
return if $gtk.production
$gtk.append_file_root 'logs/log.txt', args.join("\n")
Object.print(*args)
end
def self.puts_important *args
return if $gtk.production
$gtk.append_file_root 'logs/log.txt', args.join("\n")
$gtk.notify! "Important notification occurred."
args.each { |obj| $gtk.log obj }
end
def self.puts *args
message_id, message = args
message ||= message_id
write_to_log_and_puts message
end
def self.multiline? *args
return true if args.length > 1
return !args[0].to_s.multiline?
end
def self.join_lines args
return "" if args.length == 0
return args if args.is_a? String
return args[0] if args.length == 1
return args.to_s.join("\n")
end
def self.headline name
@asterisk_count ||= 1
@asterisk_count = @asterisk_count.greater(1)
result_from_yield = join_lines yield
result_from_yield = result_from_yield.each_line.map { |l| " #{l}" }.join
r ="#{"*" * @asterisk_count} #{name}\n#{result_from_yield}"
@asterisk_count -= 1
@asterisk_count = @asterisk_count.greater(1)
r
end
def self.dynamic_block
"#+BEGIN:
#{join_lines yield}
#+END:
"
end
def self.puts_error *args
args ||= []
title = args[0]
additional = args[1..-1] || []
additional = "" if additional.length == 0
if !title.multiline? && join_lines(additional).multiline?
message = headline "ERROR: #{title}" do
dynamic_block do
additional
end
end
elsif title.multiline?
message = headline "ERROR: " do
dynamic_block do
args
end
end
else
message = "* ERROR: #{title} #{additional}".strip
end
self.puts message
end
def self.puts_info *args
args ||= []
title = args[0]
additional = args[1..-1] || []
additional = "" if additional.length == 0
if !title.multiline? && join_lines(additional).multiline?
message = headline "INFO: #{title}" do
dynamic_block do
additional
end
end
elsif title.multiline?
message = headline "INFO: " do
dynamic_block do
args
end
end
else
message = "* INFO: #{title} #{additional}".strip
end
self.puts message
end
def self.reset
@once = {}
nil
end
def self.puts_once *ids, message
id = "#{ids}"
@once ||= {}
return if @once[id]
@once[id] = id
if !$gtk.cli_arguments[:replay] && !$gtk.cli_arguments[:record]
$gtk.notify!("Open the DragonRuby Console by pressing [`] [~] [²] [^] [º] or [§]. [Message ID: #{id}].")
end
write_to_log_and_puts ""
write_to_log_and_puts "#{message.strip}"
write_to_log_and_puts ""
write_to_log_and_puts "[Message ID: #{id}]"
write_to_log_and_puts ""
end
def self.puts_once_info *ids, message
id = "#{ids}"
@once ||= {}
return if @once[id]
@once[id] = id
log_info message
end
def self.print *args
write_to_log_and_print(*args)
end
end
end
class Object
def log_print *args
GTK::Log.print(*args)
end
def log_important *args
GTK::Log.puts_important(*args)
end
def log *args
GTK::Log.puts(*args)
end
def log_with_color xterm_escape_code, *args
log_print xterm_escape_code
log(*args)
ensure
log_reset_color
end
def log_reset_color
log_print XTERM_COLOR[:reset]
end
def log_black *args
log_with_color XTERM_COLOR[:black], *args
end
def log_red *args
log_with_color XTERM_COLOR[:red], *args
end
def log_green *args
log_with_color XTERM_COLOR[:green], *args
end
def log_yellow *args
log_with_color XTERM_COLOR[:yellow], *args
end
def log_blue *args
log_with_color XTERM_COLOR[:blue], *args
end
def log_magenta *args
log_with_color XTERM_COLOR[:magenta], *args
end
def log_cyan *args
log_with_color XTERM_COLOR[:cyan], *args
end
def log_white *args
log_with_color XTERM_COLOR[:white], *args
end
def log_bright_black *args
log_with_color XTERM_COLOR[:bright_black], *args
end
def log_bright_red *args
log_with_color XTERM_COLOR[:bright_red], *args
end
def log_bright_green *args
log_with_color XTERM_COLOR[:bright_green], *args
end
def log_bright_yellow *args
log_with_color XTERM_COLOR[:bright_yellow], *args
end
def log_bright_blue *args
log_with_color XTERM_COLOR[:bright_blue], *args
end
def log_bright_magenta *args
log_with_color XTERM_COLOR[:bright_magenta], *args
end
def log_bright_cyan *args
log_with_color XTERM_COLOR[:bright_cyan], *args
end
def log_bright_white *args
log_with_color XTERM_COLOR[:bright_white], *args
end
def log_error *args
GTK::Log.puts_error(*args)
end
def log_info *args
GTK::Log.puts_info(*args)
end
def log_once *ids, message
GTK::Log.puts_once(*ids, message)
end
def log_once_info *ids, message
GTK::Log.puts_once_info(*ids, message)
end
end
</code></pre>
<h3 id='----metadata-rb'>metadata.rb</h3>
<pre><code class="language-ruby"># ./dragon/metadata.rb
# Contributors outside of DragonRuby who also hold Copyright: Michał Dudziński
# Copyright 2021 DragonRuby LLC
# MIT License
# metadata.rb has been released under MIT (*only this file*).
module Metadata
def metadata_file_path
"metadata/game_metadata.txt"
end
def get_metadata
metadata = $gtk.read_file metadata_file_path
if !metadata
write_blank_metadata
metadata = $gtk.read_file metadata_file_path
end
dev_id, dev_title, game_id, game_title, version, icon = *metadata.each_line.to_a
{
dev_id: dev_id.strip,
dev_title: dev_title.strip,
game_id: game_id.strip,
game_title: game_title.strip,
version: version.strip,
icon: icon.strip
}
end
def write_blank_metadata
$gtk.write_file metadata_file_path, <<-S.strip
#devid=myname
#devtitle=My Name
#gameid=mygame
#gametitle=My Game
#version=0.1
#icon=metadata/icon.png
S
end
end
</code></pre>
<h3 id='----numeric-rb'>numeric.rb</h3>
<pre><code class="language-ruby"># ./dragon/numeric.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# numeric.rb has been released under MIT (*only this file*).
class Numeric
include ValueType
include NumericDeprecated
alias_method :gt, :>
alias_method :gte, :>=
alias_method :lt, :<
alias_method :lte, :<=
alias_method :__original_eq_eq__, :== unless Numeric.instance_methods.include? :__original_eq_eq__
def to_layout_row opts = {}
$layout.rect(row: self,
col: opts.col || 0,
w: opts.w || 0,
h: opts.h || 0).y
end
def to_layout_col opts = {}
$layout.rect(row: 0,
col: self,
w: opts.w || 0,
h: opts.h || 0).x
end
def to_layout_w
$layout.rect(row: 0, col: 0, w: self, h: 1).w
end
def to_layout_h
$layout.rect(row: 0, col: 0, w: 1, h: self).h
end
def to_layout_row_from_bottom opts = {}
($layout.row_max_index - self).to_layout_row opts
end
def to_layout_col_from_right opts = {}
($layout.col_max_index - self).to_layout_col opts
end
# Converts a numeric value representing seconds into frames.
#
# @gtk
def seconds
self * 60
end
# Divides the number by `2.0` and returns a `float`.
#
# @gtk
def half
self / 2.0
end
def third
self / 3.0
end
def quarter
self / 4.0
end
def to_byte
clamp(0, 255).to_i
end
def clamp *opts
min = (opts.at 0)
max = (opts.at 1)
return min if min && self < min
return max if max && self > max
return self
end
def clamp_wrap min, max
max, min = min, max if min > max
return self if self >= min && self <= max
return min if min == max
if self < min
overflow = min - self
return (max - overflow).clamp_wrap min, max
end
if self > max
overflow = self - max
return (min + overflow).clamp_wrap min, max
end
return self
end
def elapsed_time tick_count_override = nil
(tick_count_override || Kernel.tick_count) - self
end
def elapsed_time_percent duration
elapsed_time.percentage_of duration
end
def new?
elapsed_time == 0
end
# Returns `true` if the numeric value has passed a duration/offset number.
# `Kernel.tick_count` is used to determine if a number represents an elapsed
# moment in time.
#
# @gtk
def elapsed? offset = 0, tick_count_override = Kernel.tick_count
(self + offset) < tick_count_override
end
def frame_index *opts
frame_count_or_hash, hold_for, repeat, tick_count_override = opts
if frame_count_or_hash.is_a? Hash
frame_count = frame_count_or_hash[:count]
hold_for = frame_count_or_hash[:hold_for]
repeat = frame_count_or_hash[:repeat]
tick_count_override = frame_count_or_hash[:tick_count_override]
else
frame_count = frame_count_or_hash
end
tick_count_override ||= Kernel.tick_count
animation_frame_count = frame_count
animation_frame_hold_time = hold_for
animation_length = animation_frame_hold_time * animation_frame_count
return nil if Kernel.tick_count < self
if !repeat && (self + animation_length) < (tick_count_override - 1)
return nil
else
return self.elapsed_time.-(1).idiv(animation_frame_hold_time) % animation_frame_count
end
rescue Exception => e
raise <<-S
* ERROR:
#{opts}
#{e}
S
end
def zero?
self == 0
end
def zero
0
end
def one
1
end
def two
2
end
def five
5
end
def ten
10
end
alias_method :gt, :>
alias_method :above?, :>
alias_method :right_of?, :>
alias_method :lt, :<
alias_method :below?, :<
alias_method :left_of?, :<
def shift_right i
self + i
end
def shift_left i
shift_right(i * -1)
rescue Exception => e
raise_immediately e, :shift_left, i
end
def shift_up i
self + i
rescue Exception => e
raise_immediately e, :shift_up, i
end
def shift_down i
shift_up(i * -1)
rescue Exception => e
raise_immediately e, :shift_down, i
end
# This provides a way for a numeric value to be randomized based on a combination
# of two options: `:sign` and `:ratio`.
#
# @gtk
def randomize *definitions
result = self
if definitions.include?(:sign)
result = rand_sign
end
if definitions.include?(:ratio)
result = rand * result
elsif definitions.include?(:int)
result = (rand result)
end
result
end
def rand_sign
return self * -1 if rand > 0.5
self
end
def rand_ratio
self * rand
end
def remainder_of_divide n
mod n
end
# Easing function progress/percentage for a specific point in time.
#
# @gtk
def ease_extended tick_count_override, duration, default_before, default_after, *definitions
GTK::Easing.ease_extended self,
tick_count_override,
self + duration,
default_before,
default_after,
*definitions
end
# Easing function progress/percentage for a specific point in time.
#
# @gtk
def global_ease duration, *definitions
ease_extended Kernel.global_tick_count,
duration,
GTK::Easing.initial_value(*definitions),
GTK::Easing.final_value(*definitions),
*definitions
end
# Easing function progress/percentage for a specific point in time.
#
# @gtk
def ease duration, *definitions
ease_extended Kernel.tick_count,
duration,
GTK::Easing.initial_value(*definitions),
GTK::Easing.final_value(*definitions),
*definitions
end
# Easing function progress/percentage for a specific point in time.
#
# @gtk
def ease_spline_extended tick_count_override, duration, spline
GTK::Easing.ease_spline_extended self,
tick_count_override,
self + duration,
spline
end
# Easing function progress/percentage for a specific point in time.
#
# @gtk
def global_ease_spline duration, spline
ease_spline_extended Kernel.global_tick_count,
duration,
spline
end
# Easing function progress/percentage for a specific point in time.
#
# @gtk
def ease_spline duration, spline
ease_spline_extended Kernel.tick_count,
duration,
spline
end
# Converts a number representing an angle in degrees to radians.
#
# @gtk
def to_radians
self * Math::PI.fdiv(180)
end
# Converts a number representing an angle in radians to degrees.
#
# @gtk
def to_degrees
self / Math::PI.fdiv(180)
end
# Given `self`, a rectangle primitive is returned.
#
# @example
# 5.to_square 100, 300 # returns [100, 300, 5, 5]
#
# @gtk
def to_square x, y, anchor_x = 0.5, anchor_y = nil
GTK::Geometry.to_square(self, x, y, anchor_x, anchor_y)
end
# Returns a normal vector for a number that represents an angle in degrees.
#
# @gtk
def vector max_value = 1
[vector_x(max_value), vector_y(max_value)]
end
# Returns the y component of a normal vector for a number that represents an angle in degrees.
#
# @gtk
def vector_y max_value = 1
max_value * Math.sin(self.to_radians)
end
# Returns the x component of a normal vector for a number that represents an angle in degrees.
#
# @gtk
def vector_x max_value = 1
max_value * Math.cos(self.to_radians)
end
def x_vector max_value = 1
vector_x max_value
end
def y_vector max_value = 1
vector_y max_value
end
def mod n
self % n
end
def mod_zero? *ns
ns.any? { |n| mod(n) == 0 }
end
def zmod? n
(self % n) == 0
end
def multiply n
self * n
end
def fmult n
self * n.to_f
end
def imult n
(self * n).to_i
end
def mult n
self * n
end
# @gtk
def fdiv n
self / n.to_f
end
# Divides `self` by a number `n` as a float, and converts it `to_i`.
#
# @gtk
def idiv n
(self / n.to_f).to_i
end
# Returns a numeric value that is a quantity `magnitude` closer to
#`self`. If the distance between `self` and `target` is less than
#the `magnitude` then `target` is returned.
#
# @gtk
def towards target, magnitude
return self if self == target
delta = (self - target).abs
return target if delta < magnitude
return self - magnitude if self > target
return self + magnitude
end
# Given `self` and a number representing `y` of a grid. This
# function will return a one dimensional array containing the value
# yielded by an implicit block.
#
# @example
# 3.map_with_ys 2 do |x, y|
# x * y
# end
# # x y x y x y x y x y x y
# # 0*0, 0*1 1*0 1*1 2*0 2*1
# # => [ 0, 0, 0, 1, 0, 2]
#
# @gtk
def map_with_ys ys, &block
self.times.flat_map do |x|
ys.map_with_index do |y|
yield x, y
end
end
rescue Exception => e
raise_immediately e, :map_with_ys, [self, ys]
end
def combinations other_int
self.numbers.product(other_int.numbers)
end
def percentage_of n
(self / n.to_f).cap_min_max(0, 1)
end
def cap i
return i if self > i
self
end
def cap_min_max min, max
return min if self < min
return max if self > max
self
end
def lesser other
return other if other < self
self
end
def greater other
return other if other > self
self
end
def subtract i
self - i
end
def minus i
self - i
end
def add i
self + i
end
def plus i
self + i
end
def numbers
(0..self).to_a
end
def >= other
return false if !other
return gte other
end
def > other
return false if !other
return gt other
end
def <= other
return false if !other
return lte other
end
def < other
return false if !other
return gt other
end
# @gtk
def map
unless block_given?
raise <<-S
* ERROR:
A block is required for Numeric#map.
S
end
self.to_i.times.map do
yield
end
end
def each
unless block_given?
raise <<-S
* ERROR:
A block is required for Numeric#each.
S
end
self.to_i.times do
yield
end
end
def times_with_index
unless block_given?
raise <<-S
* ERROR:
A block is required for Numeric#times_with_index.
S
end
self.to_i.times.with_index do |i|
yield i
end
end
def each_with_index
unless block_given?
raise <<-S
* ERROR:
A block is required for Numeric#each_with_index.
S
end
self.to_i.times.with_index do |i|
yield i
end
end
# @gtk
def map_with_index
unless block_given?
raise <<-S
* ERROR:
A block is required for Numeric#map.
S
end
self.to_i.times.map do |i|
yield i
end
end
def __raise_arithmetic_exception__ other, m, e
raise <<-S
* ERROR:
Attempted to invoke :#{m} on #{self} with the right hand argument of:
#{other}
The object above is not a Numeric.
#{e}
S
end
def - other
return self unless other
self - other
rescue Exception => e
__raise_arithmetic_exception__ other, :-, e
end
def + other
return self unless other
self + other
rescue Exception => e
__raise_arithmetic_exception__ other, :+, e
end
def * other
return self unless other
self * other
rescue Exception => e
__raise_arithmetic_exception__ other, :*, e
end
def / other
return self unless other
self / other
rescue Exception => e
__raise_arithmetic_exception__ other, :/, e
end
def serialize
self
end
def self.from_top n
return 720 - n unless $gtk
$gtk.args.grid.top - n
end
def from_top
Numeric.from_top self
end
def self.from_right n
return 1280 - n unless $gtk
$gtk.args.grid.right - n
end
def from_right
Numeric.from_right self
end
def self.clamp n, min, max
n.clamp min, max
end
def mid? l, r
(between? l, r) || (between? r, l)
end
end
class Fixnum
include ValueType
alias_method :__original_eq_eq__, :== unless Fixnum.instance_methods.include? :__original_eq_eq__
alias_method :__original_add__, :+ unless Fixnum.instance_methods.include? :__original_add__
alias_method :__original_subtract__, :- unless Fixnum.instance_methods.include? :__original_subtract__
alias_method :__original_multiply__, :* unless Fixnum.instance_methods.include? :__original_multiply__
alias_method :__original_divide__, :- unless Fixnum.instance_methods.include? :__original_divide__
# Returns `true` if the numeric value is evenly divisible by 2.
#
# @gtk
def even?
return (self % 2) == 0
end
# Returns `true` if the numeric value is *NOT* evenly divisible by 2.
#
# @gtk
def odd?
return !even?
end
def + other
return self unless other
self + other
rescue Exception => e
__raise_arithmetic_exception__ other, :+, e
end
def * other
return self unless other
self * other
rescue Exception => e
__raise_arithmetic_exception__ other, :*, e
end
def / other
return self unless other
self / other
rescue Exception => e
__raise_arithmetic_exception__ other, :/, e
end
def - other
return self unless other
self - other
rescue Exception => e
__raise_arithmetic_exception__ other, :-, e
end
# Returns `-1` if the number is less than `0`. `+1` if the number
# is greater than `0`. Returns `0` if the number is equal to `0`.
#
# @gtk
def sign
return -1 if self < 0
return 1 if self > 0
return 0
end
# Returns `true` if number is greater than `0`.
#
# @gtk
def pos?
sign > 0
end
# Returns `true` if number is less than `0`.
#
# @gtk
def neg?
sign < 0
end
# Returns the cosine of a represented in degrees (NOT radians).
#
# @gtk
def cos
Math.cos(self.to_radians)
end
# Returns the cosine of a represented in degrees (NOT radians).
#
# @gtk
def sin
Math.sin(self.to_radians)
end
def to_sf
"%.2f" % self
end
def ifloor int
(self.idiv int.to_i) * int.to_i
end
end
class Float
include ValueType
alias_method :__original_add__, :+ unless Float.instance_methods.include? :__original_add__
alias_method :__original_subtract__, :- unless Float.instance_methods.include? :__original_subtract__
alias_method :__original_multiply__, :* unless Float.instance_methods.include? :__original_multiply__
alias_method :__original_divide__, :- unless Float.instance_methods.include? :__original_divide__
def - other
return self unless other
super
rescue Exception => e
__raise_arithmetic_exception__ other, :-, e
end
def + other
return self unless other
super
rescue Exception => e
__raise_arithmetic_exception__ other, :+, e
end
def * other
return self unless other
super
rescue Exception => e
__raise_arithmetic_exception__ other, :*, e
end
def / other
return self unless other
super
rescue Exception => e
__raise_arithmetic_exception__ other, :/, e
end
def serialize
self
end
# @gtk
def sign
return -1 if self < 0
return 1 if self > 0
return 0
end
def replace_infinity scalar
return self if !scalar
return self unless self.infinite?
return -scalar if self < 0
return scalar if self > 0
end
def to_sf
"%.2f" % self
end
def ifloor int
(self.idiv int.to_i) * int.to_i
end
end
class Integer
alias_method :__original_round__, :round unless Integer.instance_methods.include? :__original_round__
alias_method :__original_add__, :+ unless Integer.instance_methods.include? :__original_add__
alias_method :__original_subtract__, :- unless Integer.instance_methods.include? :__original_subtract__
alias_method :__original_multiply__, :* unless Integer.instance_methods.include? :__original_multiply__
alias_method :__original_divide__, :- unless Integer.instance_methods.include? :__original_divide__
def round *args
__original_round__
end
def nan?
false
end
def center other
(self - other).abs.fdiv(2)
end
end
</code></pre>
<h3 id='----remote_hotload_client-rb'>remote_hotload_client.rb</h3>
<pre><code class="language-ruby"># ./dragon/remote_hotload_client.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# hotload_client.rb has been released under MIT (*only this file*).
module GTK
class RemoteHotloadClient
attr :args
def gtk
args.gtk
end
def state
local_state
end
def initialize local_ip_address
local_state.local_ip_address = local_ip_address
end
def tick
return unless server_available?
return unless server_needed?
if should_tick? && server_needed? && !local_state.notified
if server_available?
remote_log "* REMOTE CLIENT INFO: Hotload server found at #{get_server_ip_address}:9001."
end
local_state.notified = true
end
tick_process_file_retrieval
tick_process_queue
tick_changes
tick_http_boot
end
def should_tick?
(game_state.tick_count.mod_zero? 60) && game_state.tick_count > 5.seconds
end
def game_state
args.state
end
def local_state
@local_state ||= OpenEntity.new
@local_state.hotload_client ||= @local_state.new_entity(:hotload_client,
notes: "This entity is used by DragonRuby Game Toolkit to provide you hotloading on remote machines.",
changes: { },
changes_queue: [],
reloaded_files_times: [])
@local_state.hotload_client
end
def remote_log message
log message
args.gtk.http_post "http://#{get_server_ip_address}:9001/dragon/log/", { message: "=======\n#{message}\n=======\n" }, ["Content-Type: application/x-www-form-urlencoded"]
end
def get_server_ip_address
return local_state.ip_address if local_state.ip_address
local_state.ip_address ||= ((gtk.read_file 'app/server_ip_address.txt') || "").strip
local_state.ip_address
end
def server_available?
return false if gtk.platform == 'Emscripten'
get_server_ip_address.length != 0
end
def server_needed?
return false if gtk.platform == 'Emscripten'
local_state.local_ip_address != get_server_ip_address
end
def tick_changes
return unless should_tick?
local_state.greatest_tick ||= 0
local_state.last_greatest_tick ||= 0
tick_http_changes
end
def tick_http_boot
return if local_state.booted_at
if !local_state.http_boot
# first retrieve changes.txt which has the following format
# file with latest change,
# latest file update_time key
# tmp/src_backup/src_backup_app_main.rb, 1597926596, app/main.rb
local_state.http_boot = args.gtk.http_get "http://#{get_server_ip_address}:9001/dragon/boot/"
elsif local_state.http_boot && local_state.http_boot[:http_response_code] == 200
local_state.last_greatest_tick = local_state.http_boot[:response_data].strip.to_i
local_state.greatest_tick = local_state.http_boot[:response_data].strip.to_i
local_state.booted_at = local_state.greatest_tick
remote_log '* REMOTE CLIENT INFO: HTTP GET for local_state. boot.txt succeeded.'
remote_log "* REMOTE CLIENT INFO: Looking for changes after: #{local_state.greatest_tick}."
elsif local_state.http_boot && local_state.http_boot[:http_response_code] == -1 && local_state.http_boot[:complete]
remote_log '* REMOTE CLIENT INFO: HTTP GET for boot.txt failed. Retrying.'
local_state.http_boot = nil
end
end
def tick_http_changes
return unless local_state.booted_at
if !local_state.http_changes
local_state.http_changes = args.gtk.http_get "http://#{get_server_ip_address}:9001/dragon/changes/"
end
if local_state.http_changes && local_state.http_changes[:http_response_code] == 200 && local_state.booted_at
local_state.last_greatest_tick = local_state.greatest_tick
# if the retrieval of changes.txt was successful
local_state.http_changes[:response_data].each_line do |l|
if l.strip.length != 0
# within reload state for that specific changes hash
# set the last time the file was updated
file_name, updated_at, key = l.strip.split(',')
file_name.strip!
updated_at.strip!
key.strip!
updated_at = updated_at.to_i
file_name = file_name.gsub("tmp/src_backup/", "")
# keep an internal clock that denotes that current time on the
# dev machine
if updated_at > local_state.greatest_tick
local_state.greatest_tick = updated_at
# create a new entry in change tracking for the file
# for every file where the file was last updated, find all the ones where the time is not the same
# and queue those to be retrieved and required
# if the last time the dev machine time was retrieved is less than the file time changed
# then queue the file for reload
current_updated_at = (local_state.changes[key] || { updated_at: 0 })[:updated_at]
if updated_at > current_updated_at
remote_log "* REMOTE CLIENT INFO: Queueing file #{file_name} for update."
local_state.changes[key] = { key: key,
latest_file: file_name,
updated_at: updated_at }
local_state.changes_queue << local_state.changes[key]
end
end
end
end
# set the greatest tick/current time of the machine
local_state.http_changes = nil
elsif local_state.http_changes && local_state.http_changes[:http_response_code] == -1 && local_state.http_change[:complete] && local_state.booted_at
local_state.http_changes = nil
end
end
def tick_process_queue
return if local_state.http_file_changes # don't pop a file off the queue if there is an http request in flight
return if local_state.processing_file_changes # don't pop a file if there is a file currently being processed
return unless local_state.changes_queue.length > 0 # return if the queue is empty
# if it isn't empty, pop the first file off the queue (FIFO)
local_state.processing_file_changes = local_state.changes_queue.shift
# create an http request for the file
url = "http://#{get_server_ip_address}:9001/dragon/#{local_state.processing_file_changes[:latest_file]}"
remote_log "* REMOTE CLIENT INFO: Getting new version of #{local_state.processing_file_changes[:latest_file]} (#{url})."
local_state.http_file_changes = args.gtk.http_get url
end
def tick_process_file_retrieval
return if !local_state.http_file_changes
# if the http request has finished successfully
if local_state.http_file_changes[:http_response_code] == 200
file_key = local_state.processing_file_changes[:key]
# notify that a file will be reloaded
remote_log "* REMOTE CLIENT INFO: Loading #{file_key}: #{local_state.processing_file_changes[:latest_file]}"
remote_log "#{local_state.http_file_changes[:response_data]}"
# write the latest file with what came back from the response data
gtk.write_file "#{file_key}", local_state.http_file_changes[:response_data]
# nil out the currently processing file so a new item can be processed from the queue
# local_state.reloaded_files_times << local_state.processing_file_changes[:key]
local_state.http_file_changes = nil
local_state.processing_file_changes = nil
end
end
end
end
</code></pre>
<h3 id='----runtime/autocomplete-rb'>runtime/autocomplete.rb</h3>
<pre><code class="language-ruby"># ./dragon/runtime/autocomplete.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# autocomplete.rb has been released under MIT (*only this file*).
module GTK
class Runtime
module Autocomplete
def autocomplete_parse opts
if opts[:file] && !opts[:text]
opts[:text] = read_file opts[:file]
end
text = opts[:text]
index = opts[:index]
sum = 0
lines = text.each_line.to_a.map do |l|
sum += l.length
{ line: l, length: l.length, sum: sum }
end
cursor_line = lines.find { |l| l[:sum] >= index }
previous_line = lines.find { |l| l[:sum] < index }
previous_line ||= { sum: 0 }
if cursor_line
sub_index = index - previous_line[:sum]
word = (cursor_line[:line][0..sub_index - 1]).strip
token = (word.split " ")[-1]
dots = (token.split ".").flat_map { |s| s.split "[" }.flat_map { |s| s.split "]" }.flat_map { |s| s.split "(" }.flat_map { |s| s.split ")" }
dot = dots[-1]
end
{
text: opts[:text],
file: opts[:file],
index: opts[:index],
cursor_line: cursor_line,
previous_line: previous_line,
word: word,
token: token,
dots: dots,
dot: dot
}
end
def autocomplete_filter_methods keys, *ignores
ignores ||= []
ignores = [ignores].flatten
keys = keys.map { |k| k.to_s }
keys = keys.reject { |k| k.include? '"' }
.reject { |k| k.start_with? "'" }
.reject { |k| k.include? "," }
.reject { |k| k.start_with? "#" }
others = ["def", "end"] +
[ :entity_keys_by_ref,
:entity_name,
:as_hash,
:clear!,
:created_at_elapsed,
:entity_id,
"entity_id=",
"tick_count=",
:global_created_at_elapsed,
:load_entity_data!,
:meta,
:meta!,
:new?,
:old?,
:__original_eq_eq__, :set!,
:update_entity_keys_by_ref,
:with_meta] +
ignores + keys.find_all { |k| k.to_s.to_i.to_s == k.to_s }
final = (keys - (others.map { |m| m.to_s })).uniq
final
end
def suggest_autocompletion opts
parse_result = autocomplete_parse opts
return [] unless parse_result[:cursor_line]
text = parse_result[:text]
word = parse_result[:word]
token = parse_result[:token]
dots = parse_result[:dots]
dot = parse_result[:dot]
return [] if word.strip.start_with? "#"
if word[-1] == "." && token
lookup = {
'args' => lambda { $gtk.args.autocomplete_methods },
'inputs' => lambda { $gtk.args.inputs.autocomplete_methods },
'geometry' => lambda { $gtk.args.geometry.autocomplete_methods },
'outputs' => lambda { $gtk.args.outputs.autocomplete_methods },
'layout' => lambda { $gtk.args.layouts.autocomplete_methods },
'keyboard' => lambda { $gtk.args.keyboard.autocomplete_methods },
'key_down' => lambda { $gtk.args.keyboard.key_down.autocomplete_methods },
'key_up' => lambda { $gtk.args.keyboard.key_up.autocomplete_methods },
'state' => lambda { $gtk.args.state.autocomplete_methods },
'fn' => lambda { $gtk.args.fn.autocomplete_methods },
'$gtk' => lambda { $gtk.autocomplete_methods },
'gtk' => lambda { $gtk.autocomplete_methods },
'mouse' => lambda { $gtk.args.inputs.mouse.autocomplete_methods },
'click' => lambda { [:x, :y, :point] }
}
lookup_result = lookup[dot]
return autocomplete_filter_methods lookup_result.call if lookup_result
if dot[0].upcase == dot[0] && (Object.const_defined? dot.to_sym)
return (Object.const_get dot.to_sym).autocomplete_methods
end
start_collecting = false
dots_after_state = dots.find_all do |s|
if s == "state"
start_collecting = true
false
else
start_collecting
end
end
target = $gtk.args.state
dots_after_state.each do |k|
target = target.as_hash[k.to_sym] if target.respond_to? :as_hash
end
if target.respond_to? :as_hash
return autocomplete_filter_methods target.as_hash.keys
else
return autocomplete_filter_methods target.autocomplete_methods
end
end
text = text.each_line.reject { |l| l.strip.start_with? "#" }.join "\n"
text = text.each_line.map { |l| l.split("#").first }.join "\n"
text.gsub!("[", " ")
text.gsub!("]", " ")
text.gsub!("(", " ")
text.gsub!(")", " ")
text.gsub!(":", "")
text.gsub!(".", " ")
text.gsub!("=", " ")
return (autocomplete_filter_methods (text.split " "),
:gtk, :false, :true, :args, :suppress_mailbox, :end)
end
end # end Autocomplete
end # end Runtime
end # end GTK
</code></pre>
<h3 id='----runtime/benchmark-rb'>runtime/benchmark.rb</h3>
<pre><code class="language-ruby"># ./dragon/runtime/benchmark.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# benchmark.rb has been released under MIT (*only this file*).
module GTK
class Runtime
module Benchmark
def benchmark_single iterations, name, proc
log <<-S
** Invoking :#{name}...
S
time_start = Time.now
idx = 0
r = nil
while idx < iterations
r = proc.call
idx += 1
end
result = (Time.now - time_start).round 3
{ name: name,
time: result,
time_ms: (result * 1000).to_i }
end
def benchmark opts = {}
iterations = opts.iterations
log <<-S
* BENCHMARK: Started
** Caller: #{(caller || []).first}
** Iterations: #{iterations}
S
procs = opts.find_all { |k, v| v.respond_to? :call }
times = procs.map do |(name, proc)|
benchmark_single iterations, name, proc
end.sort_by { |r| r.time }
first_place = times.first
second_place = times.second || first_place
times = times.map do |candidate|
average_time = first_place.time
.add(candidate.time)
.abs
.fdiv(2)
difference_percentage = 0
if average_time == 0
difference_percentage = 0
else
difference_percentage = first_place.time
.subtract(candidate.time)
.abs
.fdiv(average_time)
.imult(100)
end
difference_time = ((first_place.time - candidate.time) * 1000).round
candidate.merge(difference_percentage: difference_percentage,
difference_time: difference_time)
end
too_small_to_measure = false
if (first_place.time + second_place.time) == 0
too_small_to_measure = true
difference_percentage = 0
log <<-S
* BENCHMARK: Average time for experiments were too small. Increase the number of iterations.
S
else
difference_percentage = (((first_place.time - second_place.time).abs.fdiv((first_place.time + second_place.time).abs.fdiv(2))) * 100).round
end
difference_time = first_place.time.-(second_place.time).*(1000).abs.round
r = {
iterations: iterations,
first_place: first_place,
second_place: second_place,
difference_time: difference_time,
difference_percentage: difference_percentage,
times: times,
too_small_to_measure: too_small_to_measure
}
log_message = []
only_one_result = first_place.name == second_place.name
if only_one_result
log <<-S
* BENCHMARK: #{r.first_place.name} completed in #{r.first_place.time_ms}ms."
S
else
log <<-S
* BENCHMARK: #{r.message}
** Fastest: #{r.first_place.name.inspect}
** Second: #{r.second_place.name.inspect}
** Margin: #{r.difference_percentage}% (#{r.difference_time.abs}ms) #{r.first_place.time_ms}ms vs #{r.second_place.time_ms}ms.
** Times:
#{r.times.map { |t| "*** #{t.name}: #{t.time_ms}ms (#{t.difference_percentage}% #{t.difference_time.abs}ms)." }.join("\n")}
S
end
r
end
end
end
end
</code></pre>
<h3 id='----runtime/draw-rb'>runtime/draw.rb</h3>
<pre><code class="language-ruby"># ./dragon/runtime/draw.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# draw.rb has been released under MIT (*only this file*).
module GTK
class Runtime
module Draw
def primitives pass
if $top_level.respond_to? :primitives_override
return $top_level.tick_render @args, pass
end
fn.each_send pass.solids, self, :draw_solid
fn.each_send pass.static_solids, self, :draw_solid
fn.each_send pass.sprites, self, :draw_sprite
fn.each_send pass.static_sprites, self, :draw_sprite
fn.each_send pass.primitives, self, :draw_primitive
fn.each_send pass.static_primitives, self, :draw_primitive
fn.each_send pass.labels, self, :draw_label
fn.each_send pass.static_labels, self, :draw_label
fn.each_send pass.lines, self, :draw_line
fn.each_send pass.static_lines, self, :draw_line
fn.each_send pass.borders, self, :draw_border
fn.each_send pass.static_borders, self, :draw_border
if !$gtk.production
fn.each_send pass.debug, self, :draw_primitive
fn.each_send pass.static_debug, self, :draw_primitive
end
fn.each_send pass.reserved, self, :draw_primitive
fn.each_send pass.static_reserved, self, :draw_primitive
rescue Exception => e
pause!
pretty_print_exception_and_export! e
end
def draw_solid s
return unless s
if s.respond_to? :draw_override
s.draw_override @ffi_draw
else
@ffi_draw.draw_solid_2 s.x, s.y, s.w, s.h,
s.r, s.g, s.b, s.a,
(s.blendmode_enum || 1)
end
rescue Exception => e
raise_conversion_for_rendering_failed s, e, :solid
end
def draw_sprite s
return unless s
if s.respond_to? :draw_override
s.draw_override @ffi_draw
else
@ffi_draw.draw_sprite_4 s.x, s.y, s.w, s.h,
(s.path || '').to_s,
s.angle,
s.a, s.r, s.g, s.b,
s.tile_x, s.tile_y, s.tile_w, s.tile_h,
!!s.flip_horizontally, !!s.flip_vertically,
s.angle_anchor_x, s.angle_anchor_y,
s.source_x, s.source_y, s.source_w, s.source_h,
(s.blendmode_enum || 1)
end
rescue Exception => e
raise_conversion_for_rendering_failed s, e, :sprite
end
def draw_screenshot s
return unless s
if s.respond_to? :draw_override
s.draw_override @ffi_draw
else
@ffi_draw.draw_screenshot (s.path || '').to_s,
s.x, s.y, s.w, s.h,
s.angle,
s.a, s.r, s.g, s.b,
s.tile_x, s.tile_y, s.tile_w, s.tile_h,
!!s.flip_horizontally, !!s.flip_vertically,
s.angle_anchor_x, s.angle_anchor_y,
s.source_x, s.source_y, s.source_w, s.source_h
end
rescue Exception => e
raise_conversion_for_rendering_failed s, e, :screenshot
end
def draw_label l
return unless l
if l.respond_to? :draw_override
l.draw_override @ffi_draw
else
@ffi_draw.draw_label_3 l.x, l.y,
(l.text || '').to_s,
l.size_enum, l.alignment_enum,
l.r, l.g, l.b, l.a,
l.font,
(l.vertical_alignment_enum || 2),
(l.blendmode_enum || 1)
end
rescue Exception => e
raise_conversion_for_rendering_failed l, e, :label
end
def draw_line l
return unless l
if l.respond_to? :draw_override
l.draw_override @ffi_draw
else
if l.x2
@ffi_draw.draw_line_2 l.x, l.y, l.x2, l.y2,
l.r, l.g, l.b, l.a,
(l.blendmode_enum || 1)
else
w = l.w || 0
w = 1 if w == 0
h = l.h || 0
h = 1 if h == 0
@ffi_draw.draw_line_2 l.x, l.y,
l.x + w - 1,
l.y + h - 1,
l.r, l.g, l.b, l.a,
(l.blendmode_enum || 1)
end
end
rescue Exception => e
raise_conversion_for_rendering_failed l, e, :line
end
def draw_border s
return unless s
if s.respond_to? :draw_override
s.draw_override @ffi_draw
else
@ffi_draw.draw_border_2 s.x, s.y, s.w, s.h,
s.r, s.g, s.b, s.a,
(s.blendmode_enum || 1)
end
rescue Exception => e
raise_conversion_for_rendering_failed s, e, :border
end
def draw_screenshots
@args.outputs.screenshots.each { |s| draw_screenshot s }
end
def pixel_arrays
@args.pixel_arrays.each { |k,v|
if v.pixels.length == (v.width * v.height) # !!! FIXME: warning? exception? Different API?
@ffi_draw.upload_pixel_array k.to_s, v.width.to_i, v.height.to_i, v.pixels
end
}
rescue Exception => e
pause!
pretty_print_exception_and_export! e
end
end
end
end
</code></pre>
<h3 id='----runtime/framerate-rb'>runtime/framerate.rb</h3>
<pre><code class="language-ruby"># ./dragon/runtime/framerate.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# framerate.rb has been released under MIT (*only this file*).
module GTK
class Runtime
module Framerate
def framerate_init
@tick_time = Time.new.to_i
end
def delta_framerate
(current_framerate || 0) - (@previous_framerate || 0)
end
def reset_framerate_calculation
@tick_speed_sum = 0
@tick_speed_count = 0
@previous_framerate = 0
end
def check_framerate
if @framerate_diagnostics_requested
log "================================"
log framerate_get_diagnostics
@framerate_diagnostics_requested = false
end
if !@paused
if @tick_time
@tick_speed_count += 1
@tick_speed_sum += Time.now.to_i - @tick_time
if @tick_speed_count > 60 * 2
if framerate_below_threshold?
@last_framerate = current_framerate
if [email protected]?
if !@framerate_important_notification_happened
log_important framerate_warning_message
else
log framerate_warning_message
end
@framerate_important_notification_happened = true
end
end
@previous_framerate = current_framerate.floor
end
end
@tick_time = Time.new.to_i
else
reset_framerate_calculation
end
rescue
reset_framerate_calculation
end
def framerate_diagnostics
# request framerate diagnostics to be printed at the end of tick
@framerate_diagnostics_requested = true
end
def framerate_below_threshold?
@last_framerate ||= 60
current_framerate < @last_framerate &&
current_framerate < 50 &&
@previous_framerate > current_framerate &&
Kernel.tick_count > 600
end
def current_framerate
return 60 if !@tick_speed_sum || !@tick_speed_sum
r = 100.fdiv(@tick_speed_sum.fdiv(@tick_speed_count) * 100)
if (r.nan? || r.infinite? || r > 58)
r = 60
end
r || 60
rescue
60
end
end # module Framerate
end # end class Runtime
end # end module GTK
</code></pre>
<h3 id='----runtime/framerate_diagnostics-rb'>runtime/framerate_diagnostics.rb</h3>
<pre><code class="language-ruby"># ./dragon/runtime/framerate_diagnostics.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# framerate_diagnostics.rb has been released under MIT (*only this file*).
module GTK
class Runtime
module FramerateDiagnostics
def framerate_get_diagnostics
<<-S
* INFO: Framerate Diagnostics
You can display these diagnostics using:
#+begin_src
def tick args
# ....
# IMPORTANT: Put this at the END of the ~tick~ method.
args.outputs.debug << args.gtk.framerate_diagnostics_primitives
end
#+end_src
** Draw Calls: ~<<~ Invocation Perf Counter
Here is how many times ~args.outputs.PRIMITIVE_ARRAY <<~ was called:
#{$perf_counter_outputs_push_count} times invoked.
If the number above is high, consider batching primitives so you can lower the invocation of ~<<~. For example.
Instead of:
#+begin_src
args.state.enemies.map do |e|
e.alpha = 128
args.outputs.sprites << e # <-- ~args.outputs.sprites <<~ is invoked a lot
end
#+end_src
Do this:
#+begin_src
args.outputs.sprites << args.state
.enemies
.map do |e| # <-- ~args.outputs.sprites <<~ is only invoked once.
e.alpha = 128
e
end
#+end_src
** Array Primitives
~Primitives~ represented as an ~Array~ (~Tuple~) are great for prototyping, but are not as performant as using a ~Hash~.
Here is the number of ~Array~ primitives that were encountered:
#{$perf_counter_primitive_is_array} Array Primitives.
If the number above is high, consider converting them to hashes. For example.
Instead of:
#+begin_src
args.outputs.sprites << [0, 0, 100, 100, 'sprites/enemy.png']
#+begin_end
Do this:
#+begin_src
args.outputs.sprites << { x: 0,
y: 0,
w: 100,
h: 100,
path: 'sprites/enemy.png' }
#+begin_end
** Primitive Counts
Here are the draw counts ordered by lowest to highest z order:
PRIMITIVE COUNT, STATIC COUNT
solids: #{@args.outputs.solids.length}, #{@args.outputs.static_solids.length}
sprites: #{@args.outputs.sprites.length}, #{@args.outputs.static_sprites.length}
primitives: #{@args.outputs.primitives.length}, #{@args.outputs.static_primitives.length}
labels: #{@args.outputs.labels.length}, #{@args.outputs.static_labels.length}
lines: #{@args.outputs.lines.length}, #{@args.outputs.static_lines.length}
borders: #{@args.outputs.borders.length}, #{@args.outputs.static_borders.length}
debug: #{@args.outputs.debug.length}, #{@args.outputs.static_debug.length}
reserved: #{@args.outputs.reserved.length}, #{@args.outputs.static_reserved.length}
** Additional Help
Come to the DragonRuby Discord channel if you need help troubleshooting performance issues. http://discord.dragonruby.org.
Source code for these diagnostics can be found at: [[https://github.com/dragonruby/dragonruby-game-toolkit-contrib/]]
S
end
def framerate_warning_message
<<-S
* WARNING:
Your average framerate dropped below 60 fps for two seconds.
The average FPS was #{current_framerate}.
** How To Disable Warning
If this warning is getting annoying put the following in your tick method:
#+begin_src
args.gtk.log_level = :off
#+end_src
#{framerate_get_diagnostics}
S
end
def current_framerate_primitives
framerate_diagnostics_primitives
end
def framerate_diagnostics_primitives
[
{ x: 0, y: 93.from_top, w: 500, h: 93, a: 128 }.solid!,
{
x: 5,
y: 5.from_top,
text: "More Info via DragonRuby Console: $gtk.framerate_diagnostics",
r: 255,
g: 255,
b: 255,
size_enum: -2
}.label!,
{
x: 5,
y: 20.from_top,
text: "FPS: %.2f" % args.gtk.current_framerate,
r: 255,
g: 255,
b: 255,
size_enum: -2
}.label!,
{
x: 5,
y: 35.from_top,
text: "Draw Calls: #{$perf_counter_outputs_push_count}",
r: 255,
g: 255,
b: 255,
size_enum: -2
}.label!,
{
x: 5,
y: 50.from_top,
text: "Array Primitives: #{$perf_counter_primitive_is_array}",
r: 255,
g: 255,
b: 255,
size_enum: -2
}.label!,
{
x: 5,
y: 65.from_top,
text: "Mouse: #{@args.inputs.mouse.point}",
r: 255,
g: 255,
b: 255,
size_enum: -2
}.label!,
]
end
end
end
end
</code></pre>
<h3 id='----runtime/hotload-rb'>runtime/hotload.rb</h3>
<pre><code class="language-ruby"># ./dragon/runtime/hotload.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# hotlaod.rb has been released under MIT (*only this file*).
module GTK
class Runtime
# @visibility private
module Hotload
def hotload_init
@hotload_if_needed = 0
@mailbox_if_needed = 0
# schema for file_mtimes
# { FILE_PATH: { current: (Time as Fixnum),
# last: (Time as Fixnum) },
# FILE_PATH: { current: (Time as Fixnum),
# last: (Time as Fixnum) } }
@file_mtimes = { }
@suppress_mailbox = true
files_to_reload.each { |f| init_mtimes f }
init_mtimes 'app/mailbox.rb'
end
def hotload_on_write_file file_name
return unless file_name.include? 'mailbox.rb'
@mailbox_if_needed = :force
end
def files_to_reload
if @rcb_release_mode
core_files_to_reload + @required_files
else
[
'dragon/docs.rb',
'dragon/help.rb',
'dragon/kernel_docs.rb',
'dragon/kernel.rb',
'dragon/easing.rb',
'dragon/top_level.rb',
'dragon/log.rb',
'dragon/geometry.rb',
'dragon/attr_gtk.rb',
'dragon/attr_sprite.rb',
'dragon/object.rb',
'dragon/class.rb',
'dragon/string.rb',
'dragon/entity.rb',
'dragon/strict_entity.rb',
'dragon/open_entity.rb',
'dragon/serialize.rb',
'dragon/primitive.rb',
'dragon/nil_class_false_class.rb',
'dragon/symbol.rb',
'dragon/numeric_deprecated.rb',
'dragon/numeric.rb',
'dragon/hash_deprecated.rb',
'dragon/hash.rb',
'dragon/outputs_deprecated.rb',
'dragon/array_docs.rb',
'dragon/array.rb',
'dragon/outputs.rb',
'dragon/inputs.rb',
'dragon/mouse_docs.rb',
'dragon/recording.rb',
'dragon/grid.rb',
'dragon/layout.rb',
'dragon/args_deprecated.rb',
'dragon/fn.rb',
'dragon/args.rb',
'dragon/console_prompt.rb',
'dragon/console_menu.rb',
'dragon/console.rb',
'dragon/assert.rb',
'dragon/tests.rb',
'dragon/controller_config.rb',
'dragon/runtime/draw.rb',
'dragon/runtime/deprecated.rb',
'dragon/runtime/framerate.rb',
'dragon/runtime/c_bridge.rb',
'dragon/runtime/hotload.rb',
'dragon/runtime/backup.rb',
'dragon/runtime/async_require.rb',
'dragon/runtime/autocomplete.rb',
'dragon/api.rb',
'dragon/runtime.rb',
'dragon/trace.rb',
'dragon/readme_docs.rb',
'dragon/hotload_client.rb',
'dragon/wizards.rb',
'dragon/ios_wizard.rb',
'dragon/itch_wizard.rb',
] + core_files_to_reload + @required_files
end
end
def core_files_to_reload
[
'repl.rb',
'app/main.rb',
'app/repl.rb',
'app/tests.rb',
'app/test.rb',
'app/stdin.rb'
]
end
def init_mtimes file
@file_mtimes[file] ||= { current: @ffi_file.mtime(file),
last: @ffi_file.mtime(file) }
end
def hotload_source_files
@hotload_if_needed += 1
return unless @hotload_if_needed == 60
@hotload_if_needed = 0
files_to_reload.each { |f| reload_if_needed f }
console.enable
end
def mailbox_timeout
if @suppress_mailbox
60
else
3
end
end
def check_mailbox
if @mailbox_if_needed == :force # lol
reload_if_needed 'app/mailbox.rb', true
@mailbox_if_needed = 1
return
end
@mailbox_if_needed += 1
return unless @mailbox_if_needed.mod_zero? mailbox_timeout
@mailbox_if_needed = 1
reload_if_needed 'app/mailbox.rb'
end
def hotload_if_needed
return if Kernel.tick_count < 0
hotload_source_files
check_mailbox
end
def on_load_succeeded file
self.files_reloaded << file
self.reloaded_files << file
Trace.untrace_classes!
end
def reset_all_mtimes
@file_mtimes.each do |file, _|
@file_mtimes[file].current = @ffi_file.mtime(file)
@file_mtimes[file].last = @file_mtimes[file].current
end
files_to_reload.each do |file, _|
@file_mtimes[file] ||= {}
@file_mtimes[file].current = @ffi_file.mtime(file)
@file_mtimes[file].last = @file_mtimes[file].current
end
end
def reload_if_needed file, force = false
@file_mtimes[file] ||= { current: @ffi_file.mtime(file), last: @ffi_file.mtime(file) }
@file_mtimes[file].current = @ffi_file.mtime(file)
return if !force && @file_mtimes[file].current == @file_mtimes[file].last
on_load_succeeded file if reload_ruby_file file
@file_mtimes[file].last = @file_mtimes[file].current
end
end
end
end
</code></pre>
<h3 id='----string-rb'>string.rb</h3>
<pre><code class="language-ruby"># ./dragon/string.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# string.rb has been released under MIT (*only this file*).
class String
include ValueType
def self.wrapped_lines_recur word, rest, length, aggregate
if word.nil?
return aggregate
elsif rest[0].nil?
aggregate << word + "\n"
return aggregate
elsif (word + " " + rest[0]).length > length
aggregate << word + "\n"
return wrapped_lines_recur rest[0], rest[1..-1], length, aggregate
elsif (word + " " + rest[0]).length <= length
next_word = (word + " " + rest[0])
return wrapped_lines_recur next_word, rest[1..-1], length, aggregate
else
log <<-S
WARNING:
#{word} is too long to fit in length of #{length}.
S
next_word = (word + " " + rest[0])
return wrapped_lines_recur next_word, rest[1..-1], length, aggregate
end
end
def char_byte
return nil if self.length == 0
c = self.each_char.first.bytes
c = c.first if c.is_a? Enumerable
c
end
def insert_character_at index, char
t = each_char.to_a
t = (t.insert index, char)
t.join
end
def excluding_character_at index
t = each_char.to_a
t.delete_at index
t.join
end
def excluding_last_character
return "" if self.length <= 1
return excluding_character_at(self.length - 1)
end
def end_with_bang?
self[-1] == "!"
end
def without_ending_bang
return self unless end_with_bang?
self[0..-2]
end
def self.wrapped_lines string, length
string.each_line.map do |l|
l = l.rstrip
if l.length < length
l + "\n"
else
words = l.split ' '
wrapped_lines_recur(words[0], words[1..-1], length, []).flatten
end
end.flatten
end
def wrapped_lines length
String.wrapped_lines self, length
end
# @gtk
def wrap length
wrapped_lines(length).join.rstrip
end
# @gtk
def multiline?
include? "\n"
end
def indent_lines amount, char = " "
self.each_line.each_with_index.map do |l, i|
if i == 0
l
else
char * amount + l
end
end.join
end
def quote
"\"#{self}\""
end
def trim
strip
end
def trim!
strip!
end
def ltrim
lstrip
end
def ltrim!
lstrip!
end
def rtrim
rstrip
end
def rtrim!
rstrip!
end
def serialize
self
end
end
</code></pre>
<h3 id='----tests-rb'>tests.rb</h3>
<pre><code class="language-ruby"># ./dragon/tests.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# tests.rb has been released under MIT (*only this file*).
module GTK
class Tests
attr_accessor :failed, :passed, :inconclusive
def initialize
@failed = []
@passed = []
@inconclusive = []
end
def run_test m
args = Args.new $gtk, nil
assert = Assert.new
begin
log_test_running m
send(m, args, assert)
if !assert.assertion_performed
log_inconclusive m
else
log_passed m
end
rescue Exception => e
if test_signature_invalid_exception? e, m
log_test_signature_incorrect m
else
mark_test_failed m, e
end
end
end
def test_methods_focused
Object.methods.find_all { |m| m.start_with?( "focus_test_") }
end
def test_methods
Object.methods.find_all { |m| m.start_with? "test_" }
end
# @gtk
def start
log "* TEST: gtk.test.start has been invoked."
if test_methods_focused.length != 0
@is_running = true
test_methods_focused.each { |m| run_test m }
print_summary
@is_running = false
elsif test_methods.length == 0
log_no_tests_found
else
@is_running = true
test_methods.each { |m| run_test m }
print_summary
@is_running = false
end
end
def mark_test_failed m, e
message = "Failed."
self.failed << { m: m, e: e }
log message
end
def running?
@is_running
end
def log_inconclusive m
self.inconclusive << {m: m}
log "Inconclusive."
end
def log_passed m
self.passed << {m: m}
log "Passed."
end
def log_no_tests_found
log <<-S
No tests were found. To create a test. Define a method
that begins with test_. For example:
#+begin_src
def test_game_over args, assert
end
#+end_src
S
end
def log_test_running m
log "** Running: #{m}"
end
def test_signature_invalid_exception? e, m
e.to_s.include?(m.to_s) && e.to_s.include?("wrong number of arguments")
end
def log_test_signature_incorrect m
log "TEST METHOD INVALID:", <<-S
I found a test method called :#{m}. But it needs to have
the following method signature:
#+begin_src
def #{m} args, assert
end
#+end_src
Please update the method signature to match the code above. If you
did not intend this to be a test method. Rename the method so it does
not start with "test_".
S
end
def print_summary
log "** Summary"
log "*** Passed"
log "#{self.passed.length} test(s) passed."
self.passed.each { |h| log "**** :#{h[:m]}" }
log "*** Inconclusive"
if self.inconclusive.length > 0
log_once :assertion_ok_note, <<-S
NOTE FOR INCONCLUSIVE TESTS: No assertion was performed in the test.
Add assert.ok! at the end of the test if you are using your own assertions.
S
end
log "#{self.inconclusive.length} test(s) inconclusive."
self.inconclusive.each { |h| log "**** :#{h[:m]}" }
log "*** Failed"
log "#{self.failed.length} test(s) failed."
self.failed.each do |h|
log "**** Test name: :#{h[:m]}"
log "#{h[:e].to_s.gsub("* ERROR:", "").strip}\n#{h[:e].__backtrace_to_org__}"
end
end
end
end
</code></pre>
<h3 id='----trace-rb'>trace.rb</h3>
<pre><code class="language-ruby"># ./dragon/trace.rb
# coding: utf-8
# Copyright 2019 DragonRuby LLC
# MIT License
# trace.rb has been released under MIT (*only this file*).
# Contributors outside of DragonRuby who also hold Copyright:
# - Dan Healy: https://github.com/danhealy
module GTK
module Trace
IGNORED_METHODS = [
:define_singleton_method, :raise_immediately, :instance_of?,
:raise_with_caller, :initialize_copy, :class_defined?,
:instance_variable_get, :format, :purge_class, :instance_variable_defined?,
:metadata_object_id, :instance_variable_set, :__printstr__,
:instance_variables, :is_a?, :p, :kind_of?, :==, :log_once,
:protected_methods, :log_once_info, :private_methods, :open,
:!=, :initialize, :object_id, :Hash, :methods, :tick, :!,
:respond_to?, :yield_self, :send, :instance_eval, :then,
:__method__, :__send__, :log_print, :dig, :itself, :log_info,
:remove_instance_variable, :raise, :public_methods, :instance_exec,
:gets, :local_variables, :tap, :__id__, :class, :singleton_class,
:block_given?, :_inspect, :puts, :global_variables, :getc, :iterator?,
:hash, :to_enum, :printf, :frozen?, :print, :original_puts,
:srand, :freeze, :rand, :extend, :eql?, :equal?, :sprintf, :clone,
:dup, :to_s, :primitive_determined?, :inspect, :primitive?, :help,
:__object_methods__, :proc, :__custom_object_methods__, :Float, :enum_for,
:__supports_ivars__?, :nil?, :fast_rand, :or, :and,
:__caller_without_noise__, :__gtk_ruby_string_contains_source_file_path__?,
:__pretty_print_exception__, :__gtk_ruby_source_files__,
:String, :log, :Array, :putsc, :Integer, :===, :here,
:raise_error_with_kind_of_okay_message, :better_instance_information,
:lambda, :fail, :method_missing, :__case_eqq, :caller,
:raise_method_missing_better_error, :require, :singleton_methods,
:!~, :loop, :numeric_or_default, :`, :state, :inputs, :outputs, "args=".to_sym,
:grid, :gtk, :dragon, :args, :passes, :tick, :grep_source, :grep_source_file,
:numeric_or_default, :f_or_default, :s_or_default, :i_or_default,
:comment, :primitive_marker, :xrepl, :repl
]
def self.traced_classes
@traced_classes ||= []
@traced_classes
end
def self.mark_class_as_traced! klass
@traced_classes << klass
end
def self.untrace_classes!
traced_classes.each do |klass|
klass.class_eval do
all_methods = klass.instance_methods false
if klass.instance_methods.respond_to?(:__trace_call_depth__)
undef_method :__trace_call_depth__
end
GTK::Trace.filter_methods_to_trace(all_methods).each do |m|
original_method_name = m
trace_method_name = GTK::Trace.trace_method_name_for m
if klass.instance_methods.include? trace_method_name
alias_method m, trace_method_name
end
end
end
end
$last_method_traced = nil
@traced_classes.clear
$trace_enabled = false
if !$gtk.production
$gtk.write_file_root 'logs/trace.txt', "Add trace!(SOMEOBJECT) to the top of ~tick~ and this file will be populated with invocation information.\n"
end
end
def self.trace_method_name_for m
"__trace_original_#{m}__".to_sym
end
def self.original_method_name_for m
return m unless m.to_s.start_with?("__trace_original_") && m.to_s.end_with?("__")
m[16..-3]
end
def self.filter_methods_to_trace methods
methods.reject { |m| m.start_with? "__trace_" }.reject { |m| IGNORED_METHODS.include? m }
end
def self.trace_times_string
str = []
$trace_performance.sort_by {|method_name, times| -times[:avg] }.each do |method_name, times|
str << "#{method_name}: #{times[:sum].round(2)}/#{times[:count]} #{times[:min]}ms min, #{times[:avg].round(2)}ms avg, #{times[:max]}ms max"
end
str.join("\n")
end
def self.flush_trace pad_with_newline = false
$trace_puts ||= []
puts "(Trace info flushed!)"
if $trace_puts.length > 0
text = $trace_puts.join("").strip + "\n" + self.trace_times_string + "\n"
if pad_with_newline
$gtk.append_file_root 'logs/trace.txt', "\n" + text.strip
else
$gtk.append_file_root 'logs/trace.txt', text.strip
end
end
$trace_puts.clear
end
# @gtk
def self.trace! instance = nil
$trace_history ||= []
$trace_enabled = true
$trace_call_depth ||=0
$trace_performance = Hash.new {|h,k|
h[k] = {
min: 100000,
max: 0,
avg: 0,
sum: 0,
count: 0
}
}
flush_trace
instance = $top_level unless instance
return if Trace.traced_classes.include? instance.class
all_methods = instance.class.instance_methods false
instance.class.class_eval do
attr_accessor :__trace_call_depth__ unless instance.class.instance_methods.include?(:__trace_call_depth__)
GTK::Trace.filter_methods_to_trace(all_methods).each do |m|
original_method_name = m
trace_method_name = GTK::Trace.trace_method_name_for m
alias_method trace_method_name, m
$trace_puts << "Tracing #{m} on #{instance.class}.\n"
define_method(m) do |*args|
instance.__trace_call_depth__ ||= 0
tab_width = " " * (instance.__trace_call_depth__ * 8)
instance.__trace_call_depth__ += 1
$trace_call_depth = instance.__trace_call_depth__
parameters = "#{args}"[1..-2]
$trace_puts << "\n #{tab_width}#{m}(#{parameters})"
execution_time = Time.new
$last_method_traced = trace_method_name
$trace_history << [m, parameters]
result = send(trace_method_name, *args)
class_m = "#{instance.class}##{m}"
completion_time = ((Time.new - execution_time).to_f * 1000).round(2)
$trace_performance[class_m][:min] = [$trace_performance[class_m][:min], completion_time].min
$trace_performance[class_m][:max] = [$trace_performance[class_m][:max], completion_time].max
$trace_performance[class_m][:count] += 1
$trace_performance[class_m][:sum] += completion_time
$trace_performance[class_m][:avg] = $trace_performance[class_m][:sum].fdiv($trace_performance[class_m][:count])
instance.__trace_call_depth__ -= 1
instance.__trace_call_depth__ = instance.__trace_call_depth__.greater 0
$trace_puts << "\n #{tab_width} #{completion_time > 10 ? '!!! ' : ''}#{completion_time}ms success: #{m}"
if instance.__trace_call_depth__ == 0
$trace_puts << "\n"
$trace_history.clear
end
result
rescue Exception => e
instance.__trace_call_depth__ -= 1
instance.__trace_call_depth__ = instance.__trace_call_depth__.greater 0
$trace_puts << "\n #{tab_width} failed: #{m}"
if instance.__trace_call_depth__ == 0
$trace_puts << "\n #{tab_width} #{e}"
$trace_puts << "\n"
end
$trace_call_depth = 0
GTK::Trace.flush_trace true
raise e
end
end
end
mark_class_as_traced! instance.class
end
end
end
</code></pre>
<h3 id='----wizards-rb'>wizards.rb</h3>
<pre><code class="language-ruby"># ./dragon/wizards.rb
# Copyright 2019 DragonRuby LLC
# MIT License
# wizards.rb has been released under MIT (*only this file*).
class Wizard
def metadata_file_path
"metadata/game_metadata.txt"
end
def get_metadata
metadata = $gtk.read_file metadata_file_path
if !metadata
write_blank_metadata
metadata = $gtk.read_file metadata_file_path
end
dev_id, dev_title, game_id, game_title, version, icon = *metadata.each_line.to_a
{
dev_id: dev_id.strip.gsub("#", "").gsub("devid=", ""),
dev_title: dev_title.strip.gsub("#", "").gsub("devtitle=", ""),
game_id: game_id.strip.gsub("#", "").gsub("gameid=", ""),
game_title: game_title.strip.gsub("#", "").gsub("gametitle=", ""),
version: version.strip.gsub("#", "").gsub("version=", ""),
icon: icon.strip.gsub("#", "").gsub("icon=", "")
}
end
end
class WizardException < Exception
attr_accessor :console_primitives
def initialize *console_primitives
@console_primitives = console_primitives
end
end
module GTK
class Wizards
attr_accessor :ios, :itch
def initialize
@ios = IOSWizard.new
@itch = ItchWizard.new
end
end
end
</code></pre>
</div>
</body>
</html>
|