forked from plutoscarab/Rails
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Game.cs
4532 lines (3825 loc) · 125 KB
/
Game.cs
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
// Game.cs
/*
* The monster class. This is where it all happens.
*
* I. DATA
* II. CONSTRUCTORS AND SERIALIZERS
* III. DRAWING ROUTINES
* IV. EVENT HANDLERS
* V. TRAIN MOVEMENT
* VI. BUILDING TRACK
* VII. USER INTERFACE BOUNDARY RECTANGLES
* VIII. TURN MANAGEMENT
* IX. MULTI-LEVEL UNDO FUNCTIONALITY
* X. RANDOM EVENTS
* XI. CONTRACT MANAGEMENT
* XII. COMPUTER INTELLIGENCE
*
*/
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Collections;
using System.Drawing.Imaging;
using System.Security.Cryptography;
namespace Rails
{
public class Game : IDisposable
{
/* CONSTANTS ---------------------------------------------------------------------------------------- */
const int seaMovementCost = 360; // takes six hours to move between sea mileposts
const int loadingTime = 120; // takes two hours to load/unload cargo
const int useTrackCost = 4; // costs 4 to use another player's track
// player colors and color names
public static readonly StaticColorArray TrackColor = new StaticColorArray(new Color[] {Color.Green, Color.Crimson, Color.DodgerBlue, /*Color.MediumOrchid*/ Color.DarkMagenta, Color.FromArgb(255, 177, 0), Color.DarkGray, Color.Black});
public static readonly StaticStringArray ColorName = new StaticStringArray(new string[] {"Green", "Red", "Blue", "Purple", "Gold", "Silver"});
public const int MaxPlayers = 6;
public const int NationalizedTrackColor = 6;
/* PUBLIC FIELDS ------------------------------------------------------------------------------------ */
public Map map; // the map
public GameState state; // the game state (player info, tracks)
/* INTERNAL DATA ------------------------------------------------------------------------------------ */
// USER INTERFACE AND DRAWING
public GameForm form; // the main form
public static Game Current; // the current game
Rectangle statusRect; // the bounds of the game status area (on the right)
bool suppressUI; // prevents mouse clicks while auto-build/auto-move is happening
static Pen[] trackPen = CreatePens(); // Pen objects of each train color
int ptrI = -1, ptrJ = -1; // which milepost the mouse is on
int ptrX = -1, ptrY = -1; // the screen coordinate of the milepost the mouse is on
int mouseCity = -1; // which city the mouse is on
bool mouseCityShow; // whether the mouseover city's commodities are displayed
int mouseContract = -1; // which contract we're mousing over
int mouseCommodity = -1; // which source commodity we're mousing over
int mouseFreight = -1; // which freight car we're mousing over
bool inNextPlayerRect; // if we're in the next-player rectangle
bool inUpgradeRect; // if we're in the upgrade-train rectangle
int contractTop = 214; // the top (y-coord) of the contract display area
int contractHeight = 56; // the height (y-coord) of each contract display rectangle
bool blinkingTrain; // whether or not the train should blink off and on
bool blinkOn; // whether the train is blunked or not (that's a new word)
Timer blinkTimer; // timer to toggle the blinking
// PATH-FINDING FUNCTION POINTERS
FloodMethod trainMovementMethod; // algorithm for finding shortest route for train movement
FloodMethod buildTrackMethod; // algorithm for finding cheapest route for building track
// COMPUTER INTELLIGENCE
bool suspendAI; // causes computer players to pause
Indicator ind; // a display form showing the computer's action
int cilen; // the length of the string describing the action
bool suspendUI; // suppresses display of trains and tracks while computer is experimenting
// MULTI-LEVEL UNDO
Stack UndoStack; // keeps track of game states for Undo feature
// BUILDING TRACK
bool building; // are we currently building track (the left button is down)?
int buildI = -1, buildJ = -1; // the endpoint of the new track
Stack buildStack; // keep track of new track segments so we can abort
int buildCost; // keep track of build cost
// TRAIN MOVEMENT
bool placingLocomotive; // is the user selecting the starting position for their train?
Stack moveStack; // keeps track of train movements for train move automation
Timer moveTimer; // timer for movement animation
bool[,] canReachInTime; // which mileposts could be reached in remaining time
// CONTRACT ANIMATION
DateTime animationStart; // what time we starting animating the contract deletion
TimeSpan animationLength; // how long the contract deletion animation should last
int deadContract = -1; // which contract is being deleted
// RANDOM EVENTS
Random rand; // random number generator for random events
Queue disasters = new Queue(); // the list of currently active random events
// GAME OPTIONS
public Options options; // game variations as selected in the new game dialog
/* CONSTRUCTORS AND SERIALIZERS ---------------------------------------------------------------------- */
// initialize the Pen objects used for drawing the little circle where the mouse is
private static Pen[] CreatePens()
{
Pen[] temp = new Pen[TrackColor.Length];
for (int i=0; i<TrackColor.Length; i++)
temp[i] = new Pen(new SolidBrush(TrackColor[i]), 2.0f);
return temp;
}
void DeserializeGame(BinaryReader reader, bool initialize)
{
int version = reader.ReadInt32();
int mapType;
if (version < 1)
mapType = 0;
else
mapType = reader.ReadInt32();
if (mapType == 0)
{
int seed = reader.ReadInt32();
int width = reader.ReadInt32();
int height = reader.ReadInt32();
if (initialize)
map = new RandomMap(new Size(width, height), seed);
}
else if (mapType == 1)
{
string name = reader.ReadString();
/* int width = */ reader.ReadInt32();
/* int height = */ reader.ReadInt32();
if (initialize)
map = new AuthoredMap(name);
}
else if (mapType == 2)
{
string name = reader.ReadString();
int width = reader.ReadInt32();
int height = reader.ReadInt32();
if (initialize)
map = new RandomMap2(new Size(width, height), name);
}
else if (initialize)
throw new InvalidOperationException();
statusRect.X = reader.ReadInt32();
statusRect.Y = reader.ReadInt32();
statusRect.Width = reader.ReadInt32();
statusRect.Height = reader.ReadInt32();
state = new GameState(reader, map);
Contract.ReadRandom(reader);
options = new Options(reader);
disasters = new Queue();
if (version >= 3)
{
int disasterCount = reader.ReadInt32();
for (int i=0; i<disasterCount; i++)
{
string typeName = reader.ReadString();
Disaster disaster = Disaster.CreateInstance(typeName, reader, map);
if (disaster != null)
disasters.Enqueue(disaster);
}
}
}
private Game()
{
Application.Idle += new EventHandler(Idle);
}
// restore the game from the game save file
public Game(BinaryReader reader) : this()
{
// this.form = form;
Current = this;
DeserializeGame(reader, true);
trainMovementMethod = new FloodMethod(TrainMovementMethod);
buildTrackMethod = new FloodMethod(BuildTrackMethod);
rand = new Random();
UndoStack = new Stack();
}
// write the game to the game save file
public void Save(BinaryWriter writer)
{
writer.Write((int) 3); // version
if (map is RandomMap)
{
writer.Write((int) 0);
writer.Write(((RandomMap) map).Number);
}
else if (map is RandomMap2)
{
writer.Write((int) 2);
writer.Write(((RandomMap2) map).Name);
}
else
{
writer.Write((int) 1);
writer.Write(((AuthoredMap) map).Name);
}
writer.Write(map.ImageSize.Width);
writer.Write(map.ImageSize.Height);
writer.Write(statusRect.X);
writer.Write(statusRect.Y);
writer.Write(statusRect.Width);
writer.Write(statusRect.Height);
state.Save(writer, map);
Contract.SaveRandom(writer);
options.Save(writer);
writer.Write(disasters.Count);
foreach (Disaster disaster in disasters)
{
writer.Write(disaster.GetType().FullName);
disaster.Save(writer);
}
// trainMovementMethod = new FloodMethod(TrainMovementMethod);
// buildTrackMethod = new FloodMethod(BuildTrackMethod);
// rand = new Random();
// UndoStack = new Stack();
}
// start a new game with a specified map and list of players
public Game(Map map, Rectangle statusRect, Player[] playerList, GameForm form, Options options) : this()
{
Current = this;
this.map = map;
this.statusRect = statusRect;
this.form = form;
this.options = options;
rand = new Random();
state = new GameState(playerList, map, options, rand);
trainMovementMethod = new FloodMethod(TrainMovementMethod);
buildTrackMethod = new FloodMethod(BuildTrackMethod);
UndoStack = new Stack();
}
public void Dispose()
{
Application.Idle -= new EventHandler(Idle);
Current = null;
GC.SuppressFinalize(this);
if (moveTimer != null)
moveTimer.Dispose();
if (ind != null)
ind.Dispose();
if (blinkTimer != null)
blinkTimer.Dispose();
}
public byte[] GetData()
{
MemoryStream stream = new MemoryStream();
this.Save(new BinaryWriter(stream));
byte[] buffer = stream.GetBuffer();
byte[] data = new byte[stream.Position];
Array.Copy(buffer, data, data.Length);
stream.Close();
return data;
}
/* DRAWING ROUTINES ---------------------------------------------------------------------------------- */
// draw the game map and status area
public void Paint(PaintEventArgs e)
{
// nothing to do if clip rectangle is empty
if (e.ClipRectangle.Width <= 0 || e.ClipRectangle.Height <= 0)
return;
// only update status window if necessary
if (e.ClipRectangle.Right > map.ImageSize.Width)
{
DrawStatus(e.Graphics);
}
// only update map window if necessary
if (e.ClipRectangle.Left < map.ImageSize.Width)
{
// use image buffering to eliminate redraw flicker
Bitmap bmp = new Bitmap(e.ClipRectangle.Width, e.ClipRectangle.Height);
Graphics g = Graphics.FromImage(bmp);
// make sure the hatch brushes don't jiggle
g.RenderingOrigin = new Point(16 - e.ClipRectangle.X % 16, 16 - e.ClipRectangle.Y % 16);
g.TranslateTransform(-e.ClipRectangle.X, -e.ClipRectangle.Y);
Rectangle destRect = e.ClipRectangle;
Rectangle srcRect = e.ClipRectangle;
// draw the background (water and land)
g.DrawImage(map.Background, destRect, srcRect, GraphicsUnit.Pixel);
// then the train range
DrawTrainRange(g);
// then the tracks
if (!suspendUI) DrawTrack(g);
// then the random events
DrawDisasters(g);
// then the incentive cities
DrawIncentives(g);
// then the foreground (cities, mileposts)
g.DrawImage(map.Foreground, destRect, srcRect, GraphicsUnit.Pixel);
// then the little circle where the mouse is
DrawPointer(g);
// then the highlighted commodity supply locations
DrawProductIcons(g);
// then the train indicators
if (!suspendUI) DrawTrains(g);
// the the highlighted city commodities
DrawMouseCity(g);
// the player comparison plaque
DrawPlaque(g);
g.Dispose();
e.Graphics.DrawImageUnscaled(bmp, e.ClipRectangle.X, e.ClipRectangle.Y);
bmp.Dispose();
}
}
// Draw the little circle where the mouse is, or if we're placing the train, draw the train
// where the mouse is. If we're building track, also draw the cumulative cost so far.
void DrawPointer(Graphics g)
{
if (ptrI == -1)
return;
if (placingLocomotive)
{
DrawTrain(g, ptrX, ptrY, 1, state.CurrentPlayer);
return;
}
g.DrawEllipse(trackPen[state.PlayerInfo[state.CurrentPlayer].TrackColor], ptrX - 5, ptrY - 5, 11, 11);
if (building && state.AccumCost + buildCost > 0)
{
Font f = new Font("Tahoma", 13.0f, FontStyle.Bold);
string s = (state.AccumCost + buildCost).ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
int px = ptrX + 8;
int py = ptrY + 8;
Utility.DrawStringOutlined(g, s, f, Brushes.Black, Brushes.White, px, py);
f.Dispose();
}
}
// determine whether to hide or display the commodities available at the city where the mouse is
void ShowMouseCity(bool show)
{
City city = map.Cities[mouseCity];
int x, y;
if (!map.GetCoord(city.X, city.Y, out x, out y))
return;
Rectangle r;
if (city.Products.Count == 2)
r = new Rectangle(x - 24, y - 58, 83, 67);
else
r = new Rectangle(x + 10, y - 40, 48, 48);
mouseCityShow = show;
form.Invalidate();
}
// hide or display the commodities available at the city where the mouse is
void DrawMouseCity(Graphics g)
{
if (mouseCity == -1 || !mouseCityShow || building)
return;
ArrayList products = map.Cities[mouseCity].Products;
if (products.Count == 0)
return;
if (products.Count == 1)
DrawCityCommodities(g, (int) products[0]);
else
DrawCityCommodities(g, (int) products[0], (int) products[1]);
}
// draw all the track segments
void DrawTrack(Graphics g)
{
int xmin, xmax, ymin, ymax;
int i, j, xx, yy, ii, jj;
// determine which mileposts fall within the clip rectangle and only draw those
RectangleF rect = g.VisibleClipBounds;
map.GetNearest((int) rect.X, (int) rect.Y, out xmin, out ymin);
xmin--;
ymin--;
map.GetNearest((int) rect.Right, (int) rect.Bottom, out xmax, out ymax);
xmax++;
ymax++;
for (int x=xmin; x<=xmax; x++)
for (int y=ymin; y<=ymax; y++)
if (map.GetCoord(x, y, out xx, out yy))
{
for (int d=0; d<3; d++)
if (state.Track[x,y,d] != -1)
if (map.GetAdjacent(x, y, d, out i, out j))
if (map.GetCoord(i, j, out ii, out jj))
{
int pl = state.Track[x, y, d];
int tc;
if (pl == state.NumPlayers)
tc = NationalizedTrackColor;
else
tc = state.PlayerInfo[pl].TrackColor;
// draw either a regular track segment or a bridge segment
if ((map[x, y].WaterMask & (WaterMasks.RiverMask[d] | WaterMasks.InletMask[d])) == 0)
g.DrawImageUnscaled(Images.TrackBitmap[tc, d], (xx+ii)/2-11, (yy+jj)/2-11);
else
g.DrawImageUnscaled(Images.BridgeBitmap[tc, d], (xx+ii)/2-11, (yy+jj)/2-11);
}
}
}
// display the status area to the right of the map
void DrawStatus(Graphics gr)
{
int x = 8;
int lh = 14;
// initialize graphics objects
Bitmap bmp = new Bitmap(statusRect.Width, statusRect.Height); // buffer to eliminate flicker
Graphics g = Graphics.FromImage(bmp);
Font font = new Font("Tahoma", 8.5f);
Font bold = new Font("Tahoma", 8.5f, FontStyle.Bold);
Font small = new Font("Tahoma", 6.0f);
// erase the background
g.FillRectangle(Brushes.Black, 0, 0, bmp.Width, bmp.Height);
// display the turn and player stats
Player pl = state.PlayerInfo[state.CurrentPlayer];
// background color
int colorIndex = pl.TrackColor;
using (Brush brush = new SolidBrush(TrackColor[colorIndex]))
{
g.FillRectangle(brush, 0, 0, statusRect.Width, 64);
}
if (inNextPlayerRect)
{
using (Brush brush = new SolidBrush(Color.FromArgb(64, Color.Black)))
{
g.FillRectangle(brush, NextPlayerRect);
}
}
// turn number
System.Globalization.NumberFormatInfo numberFormat = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
g.DrawString("Turn " + state.Turn.ToString(numberFormat), bold, Brushes.White, x, 8);
// species and icon
bool human = pl.Human;
g.DrawString(state.ThisPlayer.Name, font, Brushes.White, x, 8 + lh);
Icon icon = human ? Images.HumanIcon : Images.ComputerIcon;
g.DrawImage(icon.ToBitmap(), statusRect.Width - 40, 8, 32, 32);
// funds
int funds = pl.Funds;
string fundsStr = Utility.CurrencyString(Math.Abs(funds)) + " in " + (funds < 0 ? "debt" : "the bank");
g.DrawString(fundsStr, font, Brushes.White, 8, 8 + 2*lh);
// loco or placement button
Rectangle rect = TrainUpgradeRect;
if (pl.X == -1)
{
if (inUpgradeRect)
g.FillRectangle(Brushes.DarkBlue, rect);
else
g.FillRectangle(Brushes.DimGray, rect);
g.DrawRectangle(Pens.Black, rect);
g.DrawLine(Pens.White, rect.Left+1, rect.Bottom-1, rect.Left+1, rect.Top+1);
g.DrawLine(Pens.White, rect.Left+1, rect.Top+1, rect.Right-1, rect.Top+1);
g.DrawLine(Pens.DarkSlateGray, rect.Right-1, rect.Top+1, rect.Right-1, rect.Bottom-1);
g.DrawLine(Pens.DarkSlateGray, rect.Right-1, rect.Bottom-1, rect.Left+1, rect.Bottom-1);
StringFormat fmt = new StringFormat();
fmt.Alignment = StringAlignment.Center;
fmt.LineAlignment = StringAlignment.Center;
RectangleF r = RectangleF.FromLTRB(rect.Left, rect.Top, rect.Right, rect.Bottom);
string s = placingLocomotive ? "Now click a map location" : "Click here to place train";
g.DrawString(s, font, Brushes.White, r, fmt);
fmt.Dispose();
}
else
{
if (inUpgradeRect)
g.FillRectangle(Brushes.DarkBlue, rect);
int tux = (rect.Left + rect.Right) / 2;
int tuy = (rect.Top + rect.Bottom) / 2;
g.DrawImageUnscaled(Images.LocoBitmap, tux - Images.LocoBitmap.Width/2, tuy - Images.LocoBitmap.Height/2);
string locoStr = Engine.Description[pl.EngineType] + ": " + Engine.SpeedString[pl.EngineType] + " / dot";
SizeF size = g.MeasureString(locoStr, font);
int lsw = (int) size.Width/2;
int lsh = (int) size.Height/2;
Utility.DrawStringOutlined(g, locoStr, font, Brushes.White, Brushes.Black, tux - lsw, tuy - lsh);
}
// cargo
for (int i=0; i<pl.Cars; i++)
{
rect = FreightRect(i);
if (i == mouseFreight)
g.FillRectangle(Brushes.DarkBlue, rect);
else
g.FillRectangle(Brushes.DimGray, rect);
int product = pl.Cargo[i];
if (product == -1)
g.DrawString("empty", small, Brushes.White, rect.X + 4, rect.Y + 10);
else
g.DrawImage(Products.Icon[product], rect);
}
// map position
int posY = 142;
if (pl.X == -1)
{
g.DrawString("Train not yet positioned", font, Brushes.White, x, posY);
}
else if (map.IsSea(pl.X, pl.Y))
{
g.DrawString("Cargo is aboard ship", font, Brushes.White, x, posY);
}
else if (!map.IsCity(pl.X, pl.Y))
{
g.DrawString("Train is en route", font, Brushes.White, x, posY);
}
else
{
// commodities available at current city
int ci = map[pl.X, pl.Y].CityIndex;
City city = map.Cities[ci];
g.DrawString("At " + city.Name, font, Brushes.White, x, posY);
if (city.Products.Count == 0)
g.DrawString("No commodities", font, Brushes.White, x, posY + lh);
else
{
for (int i=0; i < city.Products.Count; i++)
{
rect = CommodityRect(i);
if (i == mouseCommodity)
g.FillRectangle(Brushes.DarkBlue, rect);
g.DrawImage(Products.Icon[(int) city.Products[i]], rect);
}
}
}
// time remaining
string timeStr = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Time: {0:00}:{1:00} Spent: {2}", state.AccumTime / 60, state.AccumTime % 60, Utility.CurrencyString(state.AccumCost));
g.DrawString(timeStr, font, Brushes.White, 8, contractTop - lh - 8);
// list the contracts
int y = statusRect.Y + contractTop;
int dx = 52;
int dy = contractHeight;
string to = Resource.GetString("Game.To");
float wto = gr.MeasureString(to, font).Width;
// calculate dead-contract animation variables
double clock;
int voffset = 0;
int fade = 0;
int hole = 0;
if (deadContract != -1)
{
clock = 1.0 * (DateTime.Now - animationStart).TotalMilliseconds / animationLength.TotalMilliseconds;
if (clock > 1.0) clock = 1.0;
clock = clock * clock * (3 - 2 * clock);
voffset = (int) (clock * dy);
fade = (int) (255 * clock);
if (options.GroupedContracts)
hole = 3 * (deadContract / 3);
}
if (deadContract == -1)
{
// highlight the mouseover contract unless we're animating a contract deletion
if (mouseContract != -1)
{
g.FillRectangle(Brushes.DarkBlue, 0, y + dy * mouseContract - 4, statusRect.Width, dy);
}
}
// display each contract
Font af = new Font("Tahoma", 14);
for (int i=Player.NumContracts-1; i>=0; i--)
{
// calculate the vertical position
int cy = y + dy * i;
// slide it down if we're animating a contract deletion
if (deadContract != -1 && i < deadContract && i >= hole)
cy += voffset;
// get the contract info
Contract contract = state.ThisPlayer.Contracts[i];
int product = contract.Product;
// draw a green background if we're carrying that product
bool has = false;
for (int j=0; j<state.ThisPlayer.Cars; j++)
if (product == state.ThisPlayer.Cargo[j])
has = true;
if (has)
g.FillRectangle(Brushes.DarkGreen, 0, cy - 4, statusRect.Width, dy);
else if (state.Availability[product] == 0)
// draw a red background if the product is unavailable
g.FillRectangle(Brushes.DarkRed, 0, cy - 4, statusRect.Width, dy);
// get the destination city info
City destination = map.Cities[contract.Destination];
// draw the product icon
g.DrawImageUnscaled(Products.Icon[product], x, cy);
// draw the availability
if (options.LimitedCommodities)
Utility.DrawStringOutlined(g, state.Availability[product].ToString(numberFormat), af, Brushes.Red, Brushes.Black, x, cy);
// draw the name of the product
g.DrawString(Products.Name[product], font, Brushes.White, x + dx, cy);
// draw the name of the destination, with special treatment for major cities
if (map.IsCapital(destination.X, destination.Y))
{
g.DrawString(to, font, Brushes.White, x + dx, cy + lh);
g.DrawString(destination.Name, bold, Brushes.Gold, x + dx + wto , cy + lh);
}
else
g.DrawString(to + destination.Name, font, Brushes.White, x + dx, cy + lh);
// draw the payoff amount
g.DrawString("for " + Utility.CurrencyString(contract.Payoff), font, Brushes.White, x + dx, cy + 2*lh);
// fade out the contract being deleted
if (i == deadContract)
{
Brush dim = new SolidBrush(Color.FromArgb(fade, Color.Black));
g.FillRectangle(dim, 0, cy - 4, statusRect.Width, dy);
dim.Dispose();
}
}
// draw contract group borders
if (this.options.GroupedContracts)
{
using (Pen pen = new Pen(Color.Gray, 1))
{
pen.DashStyle = DashStyle.Dash;
for (int i=3; i<Player.NumContracts; i+=3)
{
int cy = y + dy * i - 4;
g.DrawLine(pen, 0, cy, statusRect.Width, cy);
}
}
}
// clean up
af.Dispose();
font.Dispose();
bold.Dispose();
g.Dispose();
gr.DrawImageUnscaled(bmp, statusRect.X, statusRect.Y);
bmp.Dispose();
}
void DrawCityCommodities(Graphics g, params int[] products)
{
const int radius = 30;
int x, y;
foreach (City city in map.Cities)
if (city.Products.Count > 0)
{
int n = 0;
int whichOne = 0;
for (int p=0; p<city.Products.Count; p++)
foreach (int product in products)
if ((int) city.Products[p] == product)
{
n++;
whichOne = p;
}
if (n == 0)
continue;
if (!map.GetCoord(city.X, city.Y, out x, out y))
continue;
int dx = map.Background.Width / 2 - x;
int dy = map.Background.Height / 2 - y;
int dr = (int) Math.Sqrt(dx * dx + dy * dy);
dx = dx * radius / dr;
dy = dy * radius / dr;
if (n == 1) // draw one icon
{
Bitmap icon = Products.Icon[(int) city.Products[whichOne]];
g.DrawImageUnscaled(icon, x + dx - icon.Width / 2, y + dy - icon.Height / 2, icon.Width, icon.Height);
}
else // draw both icons
{
Bitmap icon = Products.Icon[(int) city.Products[0]];
g.DrawImageUnscaled(icon, x + dx + dy - icon.Width / 2, y + dy - dx - icon.Height / 2, icon.Width, icon.Height);
icon = Products.Icon[(int) city.Products[1]];
g.DrawImageUnscaled(icon, x + dx - dy - icon.Width / 2, y + dy + dx - icon.Height / 2, icon.Width, icon.Height);
}
}
}
// if the mouse is hovering over a contract, indicate the sources and the destinations
void DrawProductIcons(Graphics g)
{
if (mouseContract == -1)
return; // we're not doing that
Contract contract = state.ThisPlayer.Contracts[mouseContract];
int product = contract.Product;
DrawCityCommodities(g, product);
// highlight the destination city with a blue glow
int x, y;
if (map.GetCoord(map.Cities[contract.Destination].X, map.Cities[contract.Destination].Y, out x, out y))
{
g.DrawImageUnscaled(Images.Glow, x - Images.Glow.Width / 2, y - Images.Glow.Height / 2, Images.Glow.Width, Images.Glow.Height);
}
}
// draw all the current disasters
void DrawDisasters(Graphics g)
{
if (disasters.Count == 0)
return;
foreach (Disaster disaster in disasters)
disaster.Draw(g);
}
// show the remaining range of movement for the current player's train
void DrawTrainRange(Graphics g)
{
if (canReachInTime == null)
return;
int xx, yy, R = 8;
Brush brush = new SolidBrush(Color.FromArgb(128, TrackColor[state.ThisPlayer.TrackColor]));
for (int x=0; x<map.GridSize.Width; x++)
for (int y=0; y<map.GridSize.Height; y++)
if (canReachInTime[x, y])
if (map.GetCoord(x, y, out xx, out yy))
g.FillEllipse(brush, xx - R, yy - R, 2 * R, 2 * R);
brush.Dispose();
}
// draw the train indicator
void DrawTrain(Graphics g, int x, int y, int d, int p)
{
g.DrawImageUnscaled(Images.TrainPointer[d], x - 10, y - 10);
g.DrawImageUnscaled(Images.TrainDot[state.PlayerInfo[p].TrackColor], x - 3, y - 3);
}
// draw all the train indicators
void DrawTrains(Graphics g)
{
for (int i=0; i<state.NumPlayers; i++)
{
int j = (state.CurrentPlayer + 1 + i) % state.NumPlayers;
Player pl = state.PlayerInfo[j];
if (pl.X == -1)
continue;
if (j == state.CurrentPlayer && !TrainIsVisible)
continue;
int x, y;
if (map.GetCoord(pl.X, pl.Y, out x, out y))
DrawTrain(g, x, y, pl.D, j);
}
}
// set whether or not the current player's train should be blinking
void BlinkTrain(bool blink)
{
blinkingTrain = blink;
if (blink)
{
if (blinkTimer == null)
{
blinkTimer = new Timer();
blinkTimer.Tick += new EventHandler(BlinkEventHandler);
blinkTimer.Interval = 250;
}
blinkTimer.Start();
}
else
{
if (blinkTimer != null)
blinkTimer.Stop();
}
}
// toggle the train blink state and update the display
void BlinkEventHandler(object sender, EventArgs e)
{
blinkOn = !blinkOn;
int xx, yy;
if (map.GetCoord(state.ThisPlayer.X, state.ThisPlayer.Y, out xx, out yy))
form.Invalidate(new Rectangle(xx - 10, yy - 10, 20, 20));
}
// determine if the train should be displayed
bool TrainIsVisible
{
get
{
return (!blinkingTrain || blinkOn);
}
}
void DrawIncentives(Graphics g)
{
int R = 25;
Brush brush;
if (options.CityIncentives)
{
brush = new HatchBrush(HatchStyle.DiagonalCross, Color.YellowGreen, Color.Transparent);
for (int i=0; i<map.CityCount; i++)
if (state.CityIncentive[i])
{
City city = map.Cities[i];
int xx, yy;
if (map.GetCoord(city.X, city.Y, out xx, out yy))
g.FillEllipse(brush, xx - R, yy - R, 2 * R, 2 * R);
}
brush.Dispose();
}
if (options.FirstToCityBonuses)
{
brush = new HatchBrush(HatchStyle.DottedGrid, Color.Purple, Color.Transparent);
for (int i=0; i<map.CityCount; i++)
if (!state.CityWasVisited[i])
{
City city = map.Cities[i];
int xx, yy;
if (map.GetCoord(city.X, city.Y, out xx, out yy))
g.FillEllipse(brush, xx - R, yy - R, 2 * R, 2 * R);
}
brush.Dispose();
}
}
void InvalidateCity(int cityIndex)
{
if (cityIndex == -1) return;
City city = map.Cities[cityIndex];
int xx, yy;
if (map.GetCoord(city.X, city.Y, out xx, out yy))
form.Invalidate(new Rectangle(xx - 30, yy - 30, 60, 60));
}
bool plaqueEnabled = true;
Point plaqueLocation = Point.Empty;
void DeterminePlaqueLocation()
{
if (plaqueLocation == Point.Empty)
{
int[,] f = new int[map.GridSize.Width, map.GridSize.Height];
for (int x=0; x<map.GridSize.Width; x++)
for (int y=0; y<map.GridSize.Height; y++)
if (x==0 || x==map.GridSize.Width-1 || y == 0 || y == map.GridSize.Height - 1 || map[x, y].Terrain != TerrainType.Inaccessible)
f[x, y] = 0;
else
f[x, y] = int.MaxValue;
int c = 0;
bool ok = true;
int bx = -1, by = -1;
while (ok)
{
ok = false;
int i, j;
for (int x=0; x<map.GridSize.Width; x++)
for (int y=0; y<map.GridSize.Height; y++)
if (f[x, y] == c)
for (int d=0; d<6; d++)
if (map.GetAdjacent(x, y, d, out i, out j))
if (f[i, j] == int.MaxValue)
{
f[i, j] = c + 1;
ok = true;
bx = i; by = j;
}
c++;
}
if (f[bx, by] < 5)
{
plaqueEnabled = false;
return;
}
map.GetCoord(bx, by, out bx, out by);
plaqueLocation = new Point(bx, by);
}
}
void UpdatePlaque()
{
DeterminePlaqueLocation();
int x0 = plaqueLocation.X - Images.Plaque.Width / 2;
int y0 = plaqueLocation.Y - Images.Plaque.Height / 2;
form.Invalidate(new Rectangle(new Point(x0, y0), Images.Plaque.Size));
}
void DrawPlaque(Graphics g)
{
if (!plaqueEnabled)
return;
DeterminePlaqueLocation();
int x0 = plaqueLocation.X - Images.Plaque.Width / 2;
int y0 = plaqueLocation.Y - Images.Plaque.Height / 2;
g.DrawImageUnscaled(Images.Plaque, x0, y0);
char curr = Utility.CurrencyString(0)[0];
string cars = "01²³4";
using (Font font = new Font("Tahoma", 9))
using (StringFormat format = new StringFormat())
{
format.Alignment = StringAlignment.Center;
for (int i=0; i<state.NumPlayers; i++)
{
int x = plaqueLocation.X;
int y = plaqueLocation.Y - (15*state.NumPlayers)/2 + 15 * i;
string s = string.Format("{0}{1} {3}{4} {2}C", curr, state.PlayerInfo[i].Funds, citiesReached[i], Engine.Description[state.PlayerInfo[i].EngineType][0], cars[state.PlayerInfo[i].Cars]);
using (Brush brush = new SolidBrush(Game.TrackColor[state.PlayerInfo[i].TrackColor]))
{
g.DrawString(s, font, brush, x, y, format);
}
}
}
}