From 929abd99515f980fa4ff1444915a1fa9cdba7d0a Mon Sep 17 00:00:00 2001 From: fdai6499 Date: Wed, 18 Jan 2023 12:30:21 +0100 Subject: [PATCH] added some more json and model utils in order wo load data to and from the gamefield --- src/main/java/src/Model.java | 39 ++++++++++++++++++++++++++++++++++++ src/test/java/ModelTest.java | 26 ++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/src/main/java/src/Model.java b/src/main/java/src/Model.java index 8dc95ea..acb087c 100644 --- a/src/main/java/src/Model.java +++ b/src/main/java/src/Model.java @@ -14,6 +14,20 @@ public class Model { public int difficulty; private GameField gameField; + public Model(JSONObject mock, GameField gameField) { + + this.gameField = gameField; + + model = new int[SIZE][]; + + for (int i = 0; i < SIZE; i++) { + model[i] = new int[SIZE]; + } + + jsonToModel(mock); + modelToGameField(); + } + public int getDifficulty() { return difficulty; } @@ -141,4 +155,29 @@ public class Model { return game; } + + public void jsonToModel(JSONObject jsonObject) { + + JSONArray values = (JSONArray) jsonObject.get("values"); + + Iterator iterator = values.iterator(); + + while (iterator.hasNext()) { + + JSONObject next = (JSONObject) iterator.next(); + int x = (int) next.get("x"); + int y = (int) next.get("y"); + int value = (int) next.get("value"); + + setField(x, y, value); + } + } + + public void modelToGameField() { + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + gameField.setValue(i, j, getField(i, j)); + } + } + } } diff --git a/src/test/java/ModelTest.java b/src/test/java/ModelTest.java index 87df513..237aa26 100644 --- a/src/test/java/ModelTest.java +++ b/src/test/java/ModelTest.java @@ -232,4 +232,30 @@ public class ModelTest extends MainFrame { assertEquals(r, value, "x:"+x+", y:"+y+"="+value+"-->"+r+"?"); } } + + @Test + public void test_jsonToModelToGameField() { + + //mock + GameField gf = new GameField(360); + for (int i = 0, k = 13; i < 9; i++) { + for (int j = 0, l = 17; j < 9; j++) { + gf.setValue(i, j, (i*l+j*k)%9); + } + } + Model m = new Model(gf); + JSONObject mock = m.modelToJson(); + + //test + GameField gameField = new GameField(360); + Model model = new Model(mock, gameField); + + for (int i = 0, k = 13; i < 9; i++) { + for (int j = 0, l = 17; j < 9; j++) { + int value = gameField.getValue(i, j); + int expected = (i * k + j * l) % 9; + assertEquals(expected, value, "i:"+i+", j:"+j+"="+value+"-->"+expected+"?"); + } + } + } } \ No newline at end of file