-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBoard.cs
3494 lines (3240 loc) · 106 KB
/
Board.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
/*
* Created by SharpDevelop.
* User: Joe
* Date: 23/11/2009
* Time: 3:57 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text.RegularExpressions;
using System.IO;
using CAF;
namespace ET2Solver
{
/// <summary>
/// manages drawing tiles on the board
/// </summary>
public class Board
{
// size of board cells
// TODO - workout why it is not creating images at the correct size??
public int cellWidth = 50;
public int cellHeight = 50;
// board title = colsxrowsxnumEdgesxnuminner_seed
public static string title = "";
// board dimensions
public static int num_cols = 16;
public static int num_rows = 16;
public static int max_tiles = 16*16;
public static string boardfilename = "board_16x16.jpg";
public static int num_edges = 5;
public static int num_inner1 = 5;
public static int num_inner1h = 240;
public static int num_inner2 = 12;
public static int num_inner2h = 600;
public static int num_inner3 = 0;
public static int num_inner3h = 0;
// pattern regex strings
public static string edge_pattern_regex = "";
public static string internal_pattern_regex = "";
// board layouts
public static List<string> layouts = new List<string>();
public bool isCancel = false;
// fixed rotation - only use 256 pieces instead of full 1024 (requires balanced tileset)
public bool fixedRotation = false;
public Image image;
public Image blankBoardImage;
private Graphics gboard;
public bool redraw = false;
// matching stats / overlays
public System.Collections.Hashtable matchingTileList = new Hashtable();
public System.Collections.ArrayList swappableTileList = new ArrayList();
public System.Collections.ArrayList overlays = new ArrayList();
public System.Collections.ArrayList swappableOverlays = new ArrayList();
public System.Drawing.Point selectedOverlay = new Point(0,0);
// search string used for interactive search
public string searchMatch = "";
// stats
public System.Collections.ArrayList patternStats = new ArrayList();
public string log_stats = "";
// tileset
public static Int64 seed;
public bool patternImagesLoaded = false;
public List<string> patterns = new List<string>();
public Hashtable patternImages = new Hashtable();
public Tile[] tileset = new Tile[0];
public static int numUniqueTiles = 0;
public List<string> originalTileset = new List<string>();
// model
public int[] tilepos = new int[0];
public int score = 0;
public int maxScore = 0;
// save image of model when saving
public bool saveSolutionImages = false;
public Board()
{
this.patterns.Clear();
string[] filenames = System.IO.Directory.GetFiles(CAF_Application.config.imagePath() + "\\patterns-diagonal", "*.png");
foreach ( string filename in filenames )
{
string pattern = System.IO.Path.GetFileNameWithoutExtension(filename);
this.patterns.Add(pattern.ToUpper());
}
}
public static void defineRegexStrings(Tile[] tilelist)
{
// define regex patterns from analysing tileset
// edge patterns (get from 1 & 3 / top & bottom of ^-... search)
Board.edge_pattern_regex = "[";
Dictionary<string, int[]> searches = new Dictionary<string, int[]>();
searches.Add("^-[^-]{3}|^[^-]{2}-[^-]", new int[]{1,3});
searches.Add("^[^-]-[^-]{2}|^[^-]{3}-", new int[]{0,2});
foreach ( Tile tile in tilelist )
{
foreach ( string search in searches.Keys )
{
if ( Regex.IsMatch(tile.pattern, search, RegexOptions.IgnoreCase) )
{
int[] offsets = searches[search];
foreach ( int i in offsets )
{
char ch = tile.pattern[i];
if ( !Board.internal_pattern_regex.Contains(ch) )
{
Board.internal_pattern_regex += ch;
}
}
}
}
}
if ( Board.edge_pattern_regex.Length == 1 )
{
Board.edge_pattern_regex += "^-";
}
Board.edge_pattern_regex += "]";
// internal patterns (get from [^-]{4} search)
Board.internal_pattern_regex = "[";
string isearch = "[^-]{4}";
foreach ( Tile tile in tilelist )
{
if ( Regex.IsMatch(tile.pattern, isearch, RegexOptions.IgnoreCase) )
{
for ( int i = 0; i <= 3; i++ )
{
if ( !Board.internal_pattern_regex.Contains(tile.pattern[i]) )
{
Board.internal_pattern_regex += tile.pattern[i];
}
}
}
}
if ( Board.internal_pattern_regex.Length == 1 )
{
Board.internal_pattern_regex += "^-";
}
Board.internal_pattern_regex += "]";
}
public void setLayout()
{
bool validLayout = false;
if ( Program.TheMainForm.selBoardLayout.SelectedIndex > -1 )
{
// cols,rows,numEdges,numInner1,numInner1Halves,numInner2,numInner2Halves,numInner3,numInner3Halves
// 16x16x5x5x240x12x600x0x0 title
string[] layout = Program.TheMainForm.selBoardLayout.Text.Split(new char[]{' '}, 2);
string[] layoutParams = layout[0].Split('x');
if ( layoutParams.Length >= 5 )
{
num_cols = System.Convert.ToInt16(layoutParams[0]);
num_rows = System.Convert.ToInt16(layoutParams[1]);
num_edges = System.Convert.ToInt16(layoutParams[2]);
num_inner1 = System.Convert.ToInt16(layoutParams[3]);
num_inner1h = System.Convert.ToInt16(layoutParams[4]);
num_inner2 = System.Convert.ToInt16(layoutParams[5]);
num_inner2h = System.Convert.ToInt16(layoutParams[6]);
num_inner3 = System.Convert.ToInt16(layoutParams[7]);
num_inner3h = System.Convert.ToInt16(layoutParams[8]);
// maximum of 26 edge + inner patterns (A-Z)
int numInternals = Board.num_inner1 + Board.num_inner2 + Board.num_inner3;
// if ( num_cols <= 16 && num_rows <= 16 && num_edges + numInternals <= 26 )
if ( num_cols <= 16 && num_rows <= 16 && num_edges + numInternals > 1 )
{
validLayout = true;
}
}
}
if ( !validLayout )
{
System.Windows.Forms.MessageBox.Show("Invalid board size specified. Using default 16x16.");
// default board layout
num_cols = 16;
num_rows = 16;
num_edges = 5;
num_inner1 = 5;
num_inner1h = 240;
num_inner2 = 12;
num_inner2h = 600;
num_inner3 = 0;
num_inner3h = 0;
}
max_tiles = num_cols * num_rows;
Board.boardfilename = "board_" + num_cols + "x" + num_rows + ".jpg";
if ( !System.IO.File.Exists(CAF_Application.config.imagePath() + "\\boards\\" + Board.boardfilename) )
{
System.Windows.Forms.MessageBox.Show("Could not load board image file: " + CAF_Application.config.imagePath() + "\\boards\\" + Board.boardfilename);
return;
}
this.blankBoardImage = new Bitmap(CAF_Application.config.imagePath() + "\\boards\\" + Board.boardfilename);
Program.TheMainForm.pb_board.Load(CAF_Application.config.imagePath() + "\\boards\\" + Board.boardfilename);
this.gboard = Graphics.FromImage(Program.TheMainForm.pb_board.Image);
this.clear();
if ( Program.TheMainForm.solver != null && Program.TheMainForm.inputS1CurrentSolveMethod.Text != "" )
{
Program.TheMainForm.solver.setSolveMethod(Program.TheMainForm.inputS1CurrentSolveMethod.Text, Program.TheMainForm.solver.solve_path_id);
}
}
public void clear()
{
// clears the model - keeps the tileset
// load backup copy of board image for reclipping when tiles are removed
Program.TheMainForm.textModel.Text = "";
Program.TheMainForm.updateStatusTilesUsed(0);
this.tilepos = new int[Board.max_tiles];
Program.TheMainForm.searchFreeResultsImages.Items.Clear();
Program.TheMainForm.searchUsedResultsImages.Items.Clear();
this.clearOverlays();
this.redraw = true;
}
public void refresh()
{
// refresh board
Program.TheMainForm.pb_board.Refresh();
}
public Point getXYFromColRow(int col, int row)
{
if ( row > Board.num_rows )
{
row = Board.num_rows;
}
if ( row < 1 )
{
row = 1;
}
if ( col > Board.num_cols )
{
col = Board.num_cols;
}
if ( col < 1 )
{
col = 1;
}
int x = (col-1) * (this.cellWidth + 1);
int y = (row-1) * (this.cellHeight + 1);
return new Point(x,y);
}
// create a tileset of images
public bool loadTileSet(string id)
{
this.setLayout();
this.loadPatternImages();
string sourcefile = "tilesets\\" + id + ".txt";
string[] lines = null;
string pattern = "";
int totalScore = 0;
this.maxScore = 0;
//if ( System.IO.File.Exists(sourcefile) )
try
{
Program.TheMainForm.log("Loading tiles from tileset file " + sourcefile);
lines = System.IO.File.ReadAllLines(sourcefile);
}
catch
{
Program.TheMainForm.log("Error - could not open tileset " + sourcefile);
return false;
}
Program.TheMainForm.textTileset.Text = "";
this.tileset = new Tile[lines.Length];
this.originalTileset = new List<string>();
string tileset = "";
// disable tile graphics to speed up loading
Program.TheMainForm.useTileGraphics = false;
for ( int i = 0; i < lines.Length; i++ )
{
pattern = lines[i].Trim();
if ( pattern.Length == 4 )
{
this.tileset[i] = new Tile(i+1, pattern, 1);
totalScore += pattern.Replace("-", "").Length;
this.originalTileset.Add(pattern);
tileset += pattern + "\r\n";
}
}
if ( tileset.Length == 0 )
{
return false;
}
this.tilepos = new int[Board.max_tiles];
Program.TheMainForm.useTileGraphics = true;
Program.TheMainForm.textTileset.Text = tileset;
// save backup of tileset for this.compareBoardToTileset()
Program.TheMainForm.textTileset.Update();
this.maxScore = totalScore / 2;
Program.TheMainForm.updateStatusScore(0);
Board.title = id;
Program.TheMainForm.selectTileSetListId();
Program.TheMainForm.log("Created " + lines.Length + " tiles from tileset file " + sourcefile);
// Program.TheMainForm.loadModelList();
Board.defineRegexStrings(this.tileset);
this.setModel();
this.redraw = true;
this.refresh();
return true;
}
public void setTileset()
{
this.setLayout();
this.loadPatternImages();
string[] lines = Program.TheMainForm.textTileset.Text.Trim().Split('\n');
string pattern = "";
int totalScore = 0;
this.maxScore = 0;
this.tileset = new Tile[lines.Length];
// disable tile graphics to speed up loading
Program.TheMainForm.useTileGraphics = false;
for ( int i = 0; i < lines.Length; i++ )
{
pattern = lines[i].Trim();
if ( pattern.Length == 4 )
{
this.tileset[i] = new Tile(i+1, pattern, 1);
totalScore += pattern.Replace("-", "").Length;
//Program.TheMainForm.log(pattern);
}
}
this.tilepos = new int[Board.max_tiles];
Program.TheMainForm.useTileGraphics = true;
Program.TheMainForm.textTileset.Update();
this.maxScore = totalScore / 2;
Program.TheMainForm.updateStatusScore(0);
Program.TheMainForm.log("Loaded " + lines.Length + " tiles from tileset");
// Program.TheMainForm.loadModelList();
this.redraw = true;
}
public void saveTileset()
{
string id = Program.TheMainForm.textSaveTilesetName.Text;
if ( id.Trim() == "" )
{
System.Windows.Forms.MessageBox.Show("Enter a name for the tileset before saving.");
return;
}
string filename = "tilesets\\" + id + ".txt";
string tileset = Program.TheMainForm.textTileset.Text;
try
{
if ( System.IO.File.Exists(filename) )
{
System.Windows.Forms.DialogResult confirm = System.Windows.Forms.MessageBox.Show("Overwrite " + filename + " ?", "Save Tileset", System.Windows.Forms.MessageBoxButtons.YesNo);
if ( confirm.Equals(System.Windows.Forms.DialogResult.Yes) )
{
System.IO.File.WriteAllText(filename, tileset);
Program.TheMainForm.log("saved tileset to " + filename);
}
}
else
{
System.IO.File.WriteAllText(filename, tileset);
Program.TheMainForm.log("saved tileset to " + filename);
}
}
catch
{
System.Windows.Forms.MessageBox.Show("Error saving tileset " + filename);
}
}
public void getModel()
{
// gets current model from board placements and saves to model text box
string model = "";
for ( int i = 0; i < this.tilepos.Length; i++ )
{
string line = "";
if ( this.tilepos[i] > 0 )
{
// v1 col,row,tileId,rotation
/*
line += this.tileset[this.tilepos[i]-1].col;
line += "," + this.tileset[this.tilepos[i]-1].row;
line += "," + this.tilepos[i];
line += "," + this.tileset[this.tilepos[i]-1].rotation;
model += line + "\r\n";
*/
// v2 format col,row,pattern
// line += this.tileset[this.tilepos[i]-1].col;
// line += "," + this.tileset[this.tilepos[i]-1].row;
// get col,row from board rather than tile as it seems to get mucked up during tileswap etc
int[] colrow = Board.getColRowFromPos(i + 1);
line += colrow[0];
line += "," + colrow[1];
line += "," + this.tileset[this.tilepos[i]-1].pattern;
model += line + "\r\n";
}
}
Program.TheMainForm.textModel.Text = model;
Program.TheMainForm.textModel.Update();
Program.TheMainForm.model_name = "new";
// Program.TheMainForm.selectModelListId();
}
public void setModelData(string[] lines)
{
Tile tile = null;
int i = 0;
// disable tile graphics for faster loading
Program.TheMainForm.useTileGraphics = false;
// use solver for v2 models
Solver s = new Solver();
s.loadTileset();
Array.Sort(lines);
this.tilepos = new int[Board.max_tiles];
List<string> model = new List<string>();
try
{
foreach ( string line in lines )
{
string[] parts = line.Trim().Split(',');
if ( parts.Length >= 3 )
{
int col = 0;
int row = 0;
int tileId;
int rotation = 1;
// v1 format col,row,tileId,rotation
if ( Program.TheMainForm.isNumeric(parts[0]) && Program.TheMainForm.isNumeric(parts[1]) && Program.TheMainForm.isNumeric(parts[2]) && Program.TheMainForm.isNumeric(parts[3]) )
{
col = Convert.ToInt16(parts[0]);
row = Convert.ToInt16(parts[1]);
tileId = Convert.ToInt16(parts[2]);
// skip duplicate tiles only for unique tilesets
if ( Board.numUniqueTiles != Board.max_tiles || ( Board.numUniqueTiles == Board.max_tiles && !this.isTileUsed(tileId) ) )
{
int pos = (row - 1) * Board.num_cols + col;
if ( pos > this.tilepos.Length )
{
throw new Exception("Invalid tile position " + pos + " [" + col + "," + row + "] on line: " + i + 1);
}
else
{
this.tilepos[pos-1] = tileId;
tile = this.tileset[tileId-1];
}
if ( parts.Length >= 4 )
{
rotation = Convert.ToInt16(parts[3]);
}
}
else
{
Program.TheMainForm.log("Skipping duplicate tile: " + tileId + " on line " + i);
tile = null;
}
}
else if ( Program.TheMainForm.isNumeric(parts[0]) && Program.TheMainForm.isNumeric(parts[1]) )
{
// v2 format col,row,pattern
col = Convert.ToInt16(parts[0]);
row = Convert.ToInt16(parts[1]);
if ( col > 0 && row > 0 )
{
string pattern = parts[2];
tileId = s.getTileId(pattern);
if ( Board.numUniqueTiles != Board.max_tiles || ( Board.numUniqueTiles == Board.max_tiles && !this.isTileUsed(tileId) ) )
{
rotation = s.getTileRotationByPattern(pattern);
int pos = (row - 1) * Board.num_cols + col;
this.tilepos[pos-1] = tileId;
if ( pos > this.tilepos.Length )
{
throw new Exception("Invalid tile position " + pos + " [" + col + "," + row + "] on line: " + i + 1);
}
else
{
this.tilepos[pos-1] = tileId;
tile = this.tileset[tileId-1];
}
}
else
{
Program.TheMainForm.log("Skipping duplicate tile: " + tileId + " on line " + i);
tile = null;
}
}
}
if ( tile != null )
{
if ( !this.fixedRotation )
{
tile.rotate(rotation);
}
tile.moveTo(col, row);
//this.drawTile(col, row, tile);
// rewrite model in v2 format
model.Add(col.ToString() + "," + row.ToString() + "," + tile.pattern);
}
i++;
}
Program.TheMainForm.updateStatusTilesUsed(i);
}
Program.TheMainForm.log("Set model with " + i.ToString() + " tiles");
this.updateScore();
Program.TheMainForm.useTileGraphics = true;
Program.TheMainForm.textModel.Text = String.Join("\r\n", model.ToArray());
Program.TheMainForm.textModel.Update();
}
catch (Exception e)
{
Program.TheMainForm.log("Exception: " + e.Message + ", source: " + e.StackTrace);
Program.TheMainForm.log("Error setting model at line " + i);
}
}
public bool loadModel(string id)
{
this.setLayout();
if ( this.tileset.Length == 0 )
{
this.loadTileSet(Board.title);
}
string sourcefile = id;
if ( !System.IO.File.Exists(sourcefile) )
{
sourcefile = "models\\" + Board.title + "-" + id + ".txt";
if ( !System.IO.File.Exists(sourcefile) )
{
sourcefile = "models\\" + id;
}
}
//if ( System.IO.File.Exists(sourcefile) )
try
{
string[] lines = System.IO.File.ReadAllLines(sourcefile);
Program.TheMainForm.log("Read " + lines.Length + " lines from model file " + sourcefile);
this.setModelData(lines);
Program.TheMainForm.model_name = id;
// Program.TheMainForm.selectModelListId();
this.redraw = true;
this.refresh();
return true;
}
catch (Exception e)
{
Program.TheMainForm.log("Exception: " + e.Message + ", source: " + e.StackTrace);
Program.TheMainForm.log("Error loading model " + sourcefile);
this.redraw = true;
this.refresh();
return false;
}
}
public void setModel()
{
if ( this.tileset.Length == 0 )
{
System.Windows.Forms.MessageBox.Show("Load a tileset first.");
return;
}
// disable tile graphics for faster loading
Program.TheMainForm.useTileGraphics = false;
try
{
string[] lines = Program.TheMainForm.textModel.Text.Split('\n');
this.setModelData(lines);
}
catch (Exception e)
{
Program.TheMainForm.log("Exception: " + e.Message + ", source: " + e.StackTrace);
Program.TheMainForm.log("Error setting up model");
}
Program.TheMainForm.useTileGraphics = true;
this.refresh();
this.redraw = true;
Program.TheMainForm.model_name = "new";
// Program.TheMainForm.selectModelListId();
this.drawTiles();
}
public void saveModel()
{
// use file save dialog
System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
saveFileDialog1.FileName = Board.title + "-";
// saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.Filter = Board.title + " models|" + Board.title + "-*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.InitialDirectory = "models";
saveFileDialog1.Title = "Save Model";
// saveFileDialog1.ShowDialog();
bool isFileSelected = false;
if ( saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK && saveFileDialog1.FileName != "" )
{
isFileSelected = true;
}
if ( !isFileSelected )
{
System.Windows.Forms.MessageBox.Show("No destination model filename entered");
return;
}
string filename = saveFileDialog1.FileName;
/*
string id = Program.TheMainForm.textSaveModelName.Text;
if ( id.Trim() == "" )
{
System.Windows.Forms.MessageBox.Show("Enter a name for the model before saving.");
return;
}
string filename = "models\\" + Board.title + "-" + id + ".txt";
*/
string model = Program.TheMainForm.textModel.Text;
try
{
// overwrite prompt not needed when using saveFileDialog
/*
if ( System.IO.File.Exists(filename) )
{
System.Windows.Forms.DialogResult confirm = System.Windows.Forms.MessageBox.Show("Overwrite " + filename + " ?", "Save Model", System.Windows.Forms.MessageBoxButtons.YesNo);
if ( confirm.Equals(System.Windows.Forms.DialogResult.Yes) )
{
System.IO.File.WriteAllText(filename, model);
Program.TheMainForm.log("saved model to " + filename);
}
}
else
{
System.IO.File.WriteAllText(filename, model);
Program.TheMainForm.log("saved model to " + filename);
}
*/
System.IO.File.WriteAllText(filename, model);
Program.TheMainForm.log("saved model to " + filename);
}
catch
{
System.Windows.Forms.MessageBox.Show("Error saving model " + filename);
}
// save image
this.saveModelImage(filename);
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
// Get image codecs for all image formats
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// Find the correct image codec
for(int i=0; i<codecs.Length; i++)
if(codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
public void saveModelImage(string filename)
{
// 2-Aug-2010 no idea why this doesnt work, "generic exception error" not very helpful!
if ( true || !this.saveSolutionImages )
{
return;
}
// Program.TheMainForm.board.drawTiles();
string imagepath = "images-models\\";
if ( !System.IO.File.Exists(imagepath) )
{
System.IO.Directory.CreateDirectory(imagepath);
}
string imagefilename = imagepath + System.IO.Path.GetFileNameWithoutExtension(filename) + ".jpg";
// set encoder parameters
EncoderParameters encoderParams = new EncoderParameters();
encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 80L);
// encode image to memory stream
System.IO.MemoryStream mss = new System.IO.MemoryStream();
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
/*
Program.TheMainForm.log("RawFormat: " + Program.TheMainForm.pb_board.Image.RawFormat.ToString());
Program.TheMainForm.log("Bmp: " + System.Drawing.Imaging.ImageFormat.Bmp.Guid.ToString());
Program.TheMainForm.log("Gif: " + System.Drawing.Imaging.ImageFormat.Gif.Guid.ToString());
Program.TheMainForm.log("Jpeg: " + System.Drawing.Imaging.ImageFormat.Jpeg.Guid.ToString());
Program.TheMainForm.log("Png: " + System.Drawing.Imaging.ImageFormat.Png.Guid.ToString());
Program.TheMainForm.log("MemoryBmp: " + System.Drawing.Imaging.ImageFormat.MemoryBmp.Guid.ToString());
return;
*/
// Program.TheMainForm.pb_board.Image.Save(mss, jpegCodec, encoderParams);
/*
this.gboard.Save();
this.gboard.Dispose();
Program.TheMainForm.pb_board.Image.Save(imagefilename, System.Drawing.Imaging.ImageFormat.Jpeg);
*/
// save memory stream to file
System.IO.FileStream fs = new System.IO.FileStream(imagefilename, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite);
byte[] matriz = mss.ToArray();
fs.Write(matriz, 0, matriz.Length);
mss.Close();
fs.Close();
Program.TheMainForm.log("saved model image to: " + imagefilename);
}
public void drawTile(int col, int row, Tile tile)
{
// remove previous tile if exists
// FIXME - causes slow graphic updates!
/*
Tile oldtile = this.getTileFromColRow(col, row);
if ( oldtile != null )
{
this.removeTile(col, row);
}
*/
if ( tile == null )
{
return;
}
tile.moveTo(col, row);
// draw tile onto board
Point point = this.getXYFromColRow(col, row);
//Program.TheMainForm.log("drawing tile " + tile.title() + " at pos: " + point.X + "," + point.Y);
if ( tile.image == null )
{
tile.updateImage();
}
if ( tile.image != null && this.gboard != null )
{
this.gboard.DrawImage(tile.image, point.X, point.Y);
}
// update tilepos (used tiles)
int pos = (row - 1) * Board.num_cols + col;
this.tilepos[pos-1] = tile.id;
}
public void drawTileId(int col, int row, int tileId, int rotation)
{
// draw tile onto board
Tile tile = this.tileset[tileId-1];
if ( !this.fixedRotation )
{
tile.rotate(rotation);
}
tile.moveTo(col, row);
Point point = this.getXYFromColRow(col, row);
//Program.TheMainForm.log("drawing tile " + tile.title() + " at pos: " + point.X + "," + point.Y);
this.gboard.DrawImage(tile.image, point.X, point.Y);
// update tilepos (used tiles)
int pos = (row - 1) * Board.num_cols + col;
this.tilepos[pos-1] = tileId;
}
public void test()
{
//System.Threading.Thread t = new System.Threading.Thread(this.gboard.test);
//t.Start();
//this.gboard.test();
}
public void updateScore()
{
// col1-15 - check right & down
// row 1-15 - check right & down
// col16 = check down only
// row16 = check right only
// 16,16 = skip
int tileId;
int[] colrow;
int col;
int row;
string match = "";
int score = 0;
Tile tile;
Tile rightTile;
Tile belowTile;
for ( int i = 0; i < this.tilepos.Length; i++ )
{
tileId = this.tilepos[i];
if ( tileId == 0 )
{
continue;
}
colrow = Board.getColRowFromPos(i+1);
col = colrow[0];
row = colrow[1];
tile = this.tileset[tileId-1];
//Program.TheMainForm.log(col + "," + row + " - tileId: " + tileId + ", r: " + tile.rotation + ", pattern: " + tile.pattern);
if ( col != Board.num_cols && row != Board.num_rows )
{
match = "RD";
}
else if ( col == Board.num_cols && row != Board.num_rows )
{
match = "D";
}
else if ( row == Board.num_rows && col != Board.num_cols )
{
match = "R";
}
else
{
match = "";
}
switch ( match )
{
case "RD":
rightTile = this.getTileFromColRow(col+1, row);
if ( rightTile != null && tile.matchRight(rightTile) )
{
score += 1;
}
belowTile = this.getTileFromColRow(col, row+1);
if ( belowTile != null && tile.matchDown(belowTile) )
{
score += 1;
}
break;
case "D":
belowTile = this.getTileFromColRow(col, row+1);
if ( belowTile != null && tile.matchDown(belowTile) )
{
score += 1;
}
break;
case "R":
rightTile = this.getTileFromColRow(col+1, row);
if ( rightTile != null && tile.matchRight(rightTile) )
{
score += 1;
}
break;
}
}
this.score = score;
Program.TheMainForm.updateStatusScore(score);
}
public Tile getTileFromColRow(int col, int row)
{
int pos = (row - 1) * Board.num_cols + col;
if ( this.tilepos.Length < pos )
{
//Program.TheMainForm.log("getTileFromColRow(" + col + "," + row + ")=" + pos + ",N/A");
return null;
}
int tileId = this.tilepos[pos-1];
if ( tileId > 0 )
{
Tile tile = this.tileset[tileId-1];
//Program.TheMainForm.log("getTileFromColRow(" + col + "," + row + ")=" + pos + "," + tile.title());
return tile;
}
else
{
return null;
}
}
public static int[] getColRowFromPos(int pos)
{
Program.TheMainForm.timer.start("getColRowFromPos");
// return col,row for board/cell position (1+)
int[] colrow = new int[2];
int row = (int)Math.Ceiling((double)pos / (double)num_rows);
int col = pos - (row-1) * num_cols;
/*
if ( col == 0 || row == 0 )
{
System.Diagnostics.Debugger.Break();
}
*/
colrow[0] = col;
colrow[1] = row;
Program.TheMainForm.timer.stop("getColRowFromPos");
return colrow;
}
public int[] getColRowFromXY(int x, int y)
{
int[] colrow = new int[2];
int col = (int)Math.Floor((double)x / (this.cellWidth + 1) + 1);
int row = (int)Math.Floor((double)y / (this.cellHeight + 1) + 1);
colrow[0] = col;
colrow[1] = row;
return colrow;
}
public int getTileIdFromColRow(int col, int row)
{
int tileId = 0;
int pos = (row - 1) * Board.num_cols + col;
if ( this.tilepos.Length >= pos )
{
tileId = this.tilepos[pos-1];
}
return tileId;
}
public void rotateTile(int col, int row)
{
Tile tile = this.getTileFromColRow(col, row);
if ( tile != null )
{
if ( !this.fixedRotation )
{
tile.rotate(0);
}
this.updateScore();
this.drawTile(col, row, tile);
}
}
public void removeTile(int col, int row)
{
int pos = (row - 1) * Board.num_cols + col;
if ( this.tilepos.Length >= pos )
{
int tileId = this.tilepos[pos-1];
if ( tileId > 0 && this.tileset[tileId-1] != null )
{
this.tileset[tileId-1].moveTo(0,0);
this.tilepos[pos-1] = 0;
// update score/tile count
this.updateScore();
this.updateTileCount();
// redraw cell
this.clearCell(col, row);
}
}
}
public void clearCell(int col, int row)
{
Point p = this.getXYFromColRow(col, row);
Rectangle srcRect = new Rectangle(p.X, p.Y, this.cellWidth, this.cellHeight);
Rectangle destRect = new Rectangle(p.X, p.Y, this.cellWidth, this.cellHeight);
this.gboard.DrawImage(this.blankBoardImage, srcRect, destRect, System.Drawing.GraphicsUnit.Pixel);
Program.TheMainForm.pb_board.Update();
}
public void updateTileCount()
{
int numTiles = 0;
foreach ( int tileId in this.tilepos )
{
if ( tileId > 0 )
{
numTiles++;