-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathTetrisComponent.cs
433 lines (391 loc) · 14.8 KB
/
TetrisComponent.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
using Grasshopper;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Special;
using Rhino.Geometry;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
// In order to load the result of this wizard, you will also need to
// add the output bin/ folder of this project to the list of loaded
// folder in Grasshopper.
// You can use the _GrasshopperDeveloperSettings Rhino command for that.
namespace Tetris
{
public class TetrisComponent : GH_Component
{
/// <summary>
/// Each implementation of GH_Component must provide a public
/// constructor without any arguments.
/// Category represents the Tab in which the component will appear,
/// Subcategory the panel. If you use non-existing tab or panel names,
/// new tabs/panels will automatically be created.
/// </summary>
public TetrisComponent()
: base("Tetris", "Tetris",
"Description",
"Qiu", "Tetris")
{
}
/// <summary>
/// Registers all the input parameters for this component.
/// </summary>
protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
{
pManager.AddTextParameter("control", "control", "Input control string:\ndirections=ctrl+directions\nhome=counter CW\nend=Drop\ndelete=pause", GH_ParamAccess.item, "");
//added restart feature in to right click button event
//pManager.AddBooleanParameter("restart", "restart", "", GH_ParamAccess.item,false);
}
/// <summary>
/// Registers all the output parameters for this component.
/// </summary>
protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
{
pManager.AddTextParameter("string", "string", "", GH_ParamAccess.item);
}
private readonly Color[] tileImages = new Color[]
{
Color.FromArgb(50,0,0,0),
Color.Cyan,
Color.Blue,
Color.Orange,
Color.Yellow,
Color.Green,
Color.Purple,
Color.Red
};
string output = String.Empty;
public bool isPress = false;
private GameState gameState = new GameState();
private GH_Markup[,] imageControls;
private GH_Markup[,] nextBlockCells;
private GH_Scribble nextText;
private GH_Scribble scoreText;
public async override void AddedToDocument(GH_Document document)
{
base.AddedToDocument(document);
imageControls = SetupGameCanvas(gameState.GameGrid);
await GameLoop(document);
}
/// <summary>
/// This is the method that actually does the work.
/// </summary>
/// <param name="DA">The DA object can be used to retrieve data from input parameters and
/// to store data in output parameters.</param>
protected override void SolveInstance(IGH_DataAccess DA)
{
string control = string.Empty;
DA.GetData("control", ref control);
//Due to the EXPIRE mechanism, the subscription needs to be removed first, and then the event subscription needs to be added.
if (control == "")
{
Message = "Inside Control Mode";
Instances.DocumentEditor.KeyDown -= this.GhKeydown;
Instances.DocumentEditor.KeyDown += this.GhKeydown;
}
else
{
Message = "Remote Control Mode";
Instances.DocumentEditor.KeyDown -= this.GhKeydown;
ParseControl(control);
}
DA.SetData(0, output);
}
protected override void AppendAdditionalComponentMenuItems(ToolStripDropDown menu)
{
base.AppendAdditionalComponentMenuItems(menu);
Menu_AppendItem(menu, "Restart", (o, e) =>
{
gameState = new GameState();
RemoveExpiredGrid(OnPingDocument());
imageControls = SetupGameCanvas(gameState.GameGrid);
});
}
public override void RemovedFromDocument(GH_Document document)
{
base.RemovedFromDocument(document);
RemoveExpiredGrid(document);
}
private GH_Markup[,] SetupGameCanvas(GameGrid grid)
{
var doc = OnPingDocument();
//Setup Grid
GH_Markup[,] imageControls = new GH_Markup[grid.Rows, grid.Columns];
int cellSize = 50;
for (int r = 0; r < grid.Rows; r++)
{
for (int c = 0; c < grid.Columns; c++)
{
imageControls[r, c] = ConstructGrid(cellSize, 150 + c * cellSize, 150 + r * cellSize, tileImages[0]);
}
}
foreach (var comp in imageControls)
{
doc.AddObject(comp, false);
}
//Setup Score
scoreText = new GH_Scribble();
scoreText.CreateAttributes();
scoreText.Attributes.Pivot = new PointF(300, 100);
scoreText.Font = GH_FontServer.NewFont(GH_FontServer.Script.FontFamily, 40f, FontStyle.Bold);
scoreText.NickName = "ScoreText";
scoreText.Text = "Score : " + gameState.Score.ToString();
doc.AddObject(scoreText, false);
//Setup NextBlockCells
nextBlockCells = new GH_Markup[4, 4];
for (int r = 0; r < nextBlockCells.GetLength(0); r++)
{
for (int c = 0; c < nextBlockCells.GetLength(1); c++)
{
nextBlockCells[r, c] = ConstructGrid(cellSize, 750 + c * cellSize, 450 + r * cellSize, tileImages[0]);
}
}
foreach (var comp in nextBlockCells)
{
doc.AddObject(comp, false);
}
//Setup Next
nextText = new GH_Scribble();
nextText.CreateAttributes();
nextText.Attributes.Pivot = new PointF(800, 400);
nextText.Font = GH_FontServer.NewFont(GH_FontServer.Script.FontFamily, 40f, FontStyle.Bold);
nextText.NickName = "NextText";
nextText.Text = "Next";
doc.AddObject(nextText, false);
return imageControls;
}
private void RemoveExpiredGrid(GH_Document doc)
{
//markup is not ActiveObject!
//var obj=doc.ActiveObjects();
List<IGH_DocumentObject> markupList = doc.Objects.Where(x => x.GetType() == typeof(GH_Markup) || x.GetType() == typeof(GH_Scribble)).ToList();
doc.RemoveObjects(markupList, true);
}
private GH_Markup ConstructGrid(int cellSize, int pivotX, int pivotY, Color color, int width = 1)
{
List<Point3d> gridPts = new List<Point3d> { new Point3d(0, 0, 0), new Point3d(cellSize, 0, 0), new Point3d(cellSize, -cellSize, 0), new Point3d(0, -cellSize, 0) };
gridPts.Add(gridPts[0]);
var markGrid = new GH_Markup();
markGrid.CreateAttributes();
Polyline markLine = new Polyline(gridPts);
markGrid.Marks.Add(markLine);
markGrid.Attributes.Pivot = new PointF(0, 0);
ChangeCellColor(ref markGrid, color, width);
markGrid.Attributes.Pivot = new PointF(pivotX, pivotY);
return markGrid;
}
private async Task GameLoop(GH_Document document)
{
Draw(gameState);
while (!gameState.GameOver)
{
//change delay to set level of difficulty
int delay = 500;
await Task.Delay(delay);
//add Pause feature later
//if (gameState.Pause)
//{
// await Task.Delay(2000);
//}
gameState.MoveBlockDown();
Draw(gameState);
}
//if the component has been removed, Game over should not displayed
List<IGH_DocumentObject> tetrisComponents = document.Objects.Where(x => x.GetType() == typeof(TetrisComponent)).ToList();
if (tetrisComponents.Count > 0)
{
bool isThisCompInDoc = false;
foreach (var item in tetrisComponents)
{
if (item.InstanceGuid == this.InstanceGuid)
{
isThisCompInDoc = true;
break;
}
}
if (isThisCompInDoc)
{
MessageBox.Show("Game Over!\nScore : " + gameState.Score.ToString());
}
}
}
private void Draw(GameState gameState)
{
DrawGrid(gameState.GameGrid);
//It's Painter Mode,Draw ghostBlock first,so that the GhostBlock will be behind the Block
DrawGhostBlock(gameState.CurrentBlock);
DrawBlock(gameState.CurrentBlock);
DrawNextBlock(gameState.BlockQueue);
scoreText.Text = "Score : " + gameState.Score.ToString();
scoreText.Attributes.ExpireLayout();
scoreText.OnDisplayExpired(true);
//Update Screen Display,Important
Instances.RedrawAll();
}
private void DrawNextBlock(BlockQueue blockQueue)
{
//Setup next cells
for (int r = 0; r < nextBlockCells.GetLength(0); r++)
{
for (int c = 0; c < nextBlockCells.GetLength(1); c++)
{
bool isChangedColor = ChangeCellColor(ref nextBlockCells[r, c], tileImages[0]);
}
}
//Draw next block
Block next = blockQueue.NextBlock;
var test = next.TilePositionsInNext();
foreach (Position p in next.TilePositionsInNext())
{
bool isChangedColor = ChangeCellColor(ref nextBlockCells[p.Row, p.Column], tileImages[next.Id]);
}
}
private void DrawGhostBlock(Block block)
{
int dropDistance = gameState.BlockDropDistance();
foreach (Position p in block.TilePositions())
{
Color ghostColor = GetGhostColor(tileImages[block.Id]);
bool isChangedColor = ChangeCellColor(ref imageControls[p.Row + dropDistance, p.Column], ghostColor);
}
}
private Color GetGhostColor(Color color)
{
Color result = color;
if (color.A > 100)
{
result = Color.FromArgb(70, color);
}
return result;
}
private void DrawBlock(Block block)
{
foreach (Position p in block.TilePositions())
{
bool isChangedColor = ChangeCellColor(ref imageControls[p.Row, p.Column], tileImages[block.Id]);
}
}
private void DrawGrid(GameGrid grid)
{
for (int r = 0; r < grid.Rows; r++)
{
for (int c = 0; c < grid.Columns; c++)
{
int id = grid[r, c];
bool isChangedColor = ChangeCellColor(ref imageControls[r, c], tileImages[id]);
}
}
}
private bool ChangeCellColor(ref GH_Markup cell, Color color, int width = 1)
{
bool isChanged = false;
var attributes = (GH_MarkupAttributes)cell.Attributes;
if (attributes.Properties.Colour != color)
{
isChanged = true;
var prop = new GH_MarkupProperties();
prop.Colour = color;
if (color.A > 50)
{
prop.Width = 10;
}
else
{
prop.Width = 1;
}
attributes.Properties = prop;
}
return isChanged;
}
private void GhKeydown(object sender, KeyEventArgs e)
{
if (gameState.GameOver)
{
return;
}
switch (e.KeyCode)
{
case Keys.Left:
gameState.MoveBlockLeft();
break;
case Keys.Right:
gameState.MoveBlockRight();
break;
case Keys.Down:
gameState.MoveBlockDown();
break;
case Keys.Up:
gameState.RotateBlockCW();
break;
case Keys.Home:
gameState.RotateBlockCCW();
break;
case Keys.End:
gameState.DropBlock();
break;
case Keys.Delete:
gameState.Pause = !gameState.Pause;
break;
default:
return;
}
Draw(gameState);
}
private void ParseControl(string control)
{
if (gameState.GameOver)
{
return;
}
switch (control)
{
case "Left":
gameState.MoveBlockLeft();
break;
case "Right":
gameState.MoveBlockRight();
break;
case "Down":
gameState.MoveBlockDown();
break;
case "Up":
gameState.RotateBlockCW();
break;
case "Home":
gameState.RotateBlockCCW();
break;
case "Drop":
gameState.DropBlock();
break;
//case Keys.Delete:
// gameState.Pause = !gameState.Pause;
// break;
default:
return;
}
Draw(gameState);
}
/// <summary>
/// Provides an Icon for every component that will be visible in the User Interface.
/// Icons need to be 24x24 pixels.
/// </summary>
protected override System.Drawing.Bitmap Icon
{
get
{
return Properties.Resources.T;
}
}
/// <summary>
/// Each component must have a unique Guid to identify it.
/// It is vital this Guid doesn't change otherwise old ghx files
/// that use the old ID will partially fail during loading.
/// </summary>
public override Guid ComponentGuid
{
get { return new Guid("8275dc8c-915a-4b34-96a0-6490428bf3e1"); }
}
}
}