From 00dd266cf634d9bb7d422d42fa9bbae044672e93 Mon Sep 17 00:00:00 2001 From: flifloo Date: Thu, 7 Apr 2022 15:57:22 +0200 Subject: [PATCH] Add Tetrominoe parser from json resource --- Models/Tetrominoe.cs | 8 ++++++ Models/TetrominoeParser.cs | 59 ++++++++++++++++++++++++++++++++++++++ Resources/tetrominoes.json | 9 ++++++ Tetris.csproj | 8 ++++++ 4 files changed, 84 insertions(+) create mode 100644 Models/TetrominoeParser.cs create mode 100644 Resources/tetrominoes.json diff --git a/Models/Tetrominoe.cs b/Models/Tetrominoe.cs index a7b67ae..7cbbdc9 100644 --- a/Models/Tetrominoe.cs +++ b/Models/Tetrominoe.cs @@ -70,6 +70,14 @@ public class Tetrominoe { // ToDO: ascpect technique test } + public Tetrominoe(Grid grid, String shape, Point coordinates, short orientation, Color color) { + _grid = grid; + _shape = TetrominoeParser.Get(shape); + _coordinates = coordinates; + _orientation = orientation; + _color = color; + } + private bool[,] _rotateLeft(bool[,] shape) { bool[,] rotatedArr = new bool[shape.GetLength(1), shape.GetLength(0)]; diff --git a/Models/TetrominoeParser.cs b/Models/TetrominoeParser.cs new file mode 100644 index 0000000..80834dc --- /dev/null +++ b/Models/TetrominoeParser.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Newtonsoft.Json.Linq; + +namespace Tetris.Models; + +public class TetrominoeParser { + private static JObject _content; + + private static JObject content { + get { + if (_content == null) + _content = GetContent(); + + return _content; + } + } + + public static bool[,] Get(String name) { + if (!content.ContainsKey(name)) + throw new Exception("Invalid name"); + + String s = content.GetValue(name).ToString(); + + int width = s.IndexOf('\n'); + if (width < 0) + width = s.Length; + int height = s.Count(c => c == '\n')+1; + + bool[,] g = new bool[width, height]; + + int x = 0; + int y = 0; + for (int i = 0; i < s.Length; i++, x++) { + char c = Char.ToLower(s[i]); + if (c == 'x') + g[x, y] = true; + else if (c == '-') + g[x, y] = false; + else if (c == '\n') { + x = -1; + y++; + } + } + + return g; + } + + public static List List() { + return content.Properties().Select(p => p.Name).ToList(); + } + + + private static JObject GetContent() { + return JObject.Parse(File.ReadAllText(@"Resources\tetrominoes.json")); + } +} diff --git a/Resources/tetrominoes.json b/Resources/tetrominoes.json new file mode 100644 index 0000000..e5b24cd --- /dev/null +++ b/Resources/tetrominoes.json @@ -0,0 +1,9 @@ +{ + "I": "xxxx", + "J": "x--\nxxx", + "L": "--x\nxxx", + "O": "xx\nxx", + "S": "-xx\nxx-", + "T": "-x-\nxxx", + "Z": "xx-\n-xx" +} \ No newline at end of file diff --git a/Tetris.csproj b/Tetris.csproj index 3afffab..a73aac8 100644 --- a/Tetris.csproj +++ b/Tetris.csproj @@ -8,8 +8,16 @@ + + + + + Always + + +