From f76e948f389cf75b081a15e731c00cb4ab298c16 Mon Sep 17 00:00:00 2001 From: POGROTH THE HYPED <82341064+magicalmonke@users.noreply.github.com> Date: Sat, 22 Jun 2024 08:57:43 +0200 Subject: [PATCH] Implement PuzzleModel class --- .../me/taako/swt/prog2/model/PuzzleModel.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/main/java/me/taako/swt/prog2/model/PuzzleModel.java b/src/main/java/me/taako/swt/prog2/model/PuzzleModel.java index f553ede..6ce11ea 100644 --- a/src/main/java/me/taako/swt/prog2/model/PuzzleModel.java +++ b/src/main/java/me/taako/swt/prog2/model/PuzzleModel.java @@ -1,4 +1,48 @@ package me.taako.swt.prog2.model; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.IntStream; + public class PuzzleModel { + private final int size; + private final List tiles; + + public PuzzleModel(int rows, int cols) { + this.size = rows * cols; + this.tiles = new ArrayList<>(size); + initTiles(); + shuffleTiles(); + } + + private void initTiles() { + IntStream.range(0, size) + .forEach(tiles::add); + } + + private void shuffleTiles() { + Collections.shuffle(tiles); + } + + public int getTile(int index) { + return tiles.get(index); + } + + public int getSize() { + return size; + } + + public boolean isTileCorrect(int index) { + return tiles.get(index) == index; + } + + public boolean isSolved() { + return IntStream.range(0, size) + .allMatch(this::isTileCorrect); + } + + public void swapTiles(int index1, int index2) { + Collections.swap(tiles, index1, index2); + } }