diff --git a/jogo-oito/.gitignore b/jogo-oito/.gitignore deleted file mode 100644 index b83d2226..00000000 --- a/jogo-oito/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target/ diff --git a/jogo-oito/.settings/org.eclipse.core.resources.prefs b/jogo-oito/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 99f26c02..00000000 --- a/jogo-oito/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -encoding/=UTF-8 diff --git a/jogo-oito/.settings/org.eclipse.jdt.core.prefs b/jogo-oito/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index bc0c2fff..00000000 --- a/jogo-oito/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,8 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=18 -org.eclipse.jdt.core.compiler.compliance=18 -org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore -org.eclipse.jdt.core.compiler.release=disabled -org.eclipse.jdt.core.compiler.source=18 diff --git a/jogo-oito/.settings/org.eclipse.m2e.core.prefs b/jogo-oito/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1..00000000 --- a/jogo-oito/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/jogo-oito/src/main/java/AStar.java b/jogo-oito/src/main/java/AStar.java new file mode 100644 index 00000000..a681e5fb --- /dev/null +++ b/jogo-oito/src/main/java/AStar.java @@ -0,0 +1,84 @@ +/* + * Trabalho Jogo dos 8 e Metodos de busca + * + * Inteligencia Artificial - GCC128 + * + * Sistemas de Informação + * Universidade Federal de Lavras + * + * Autor: Alfredo + */ + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.PriorityQueue; +import java.util.Queue; + + +public class AStar { + State estadoInicial; + State estadoFinal; + PriorityQueue pq; + Queue visitados; + + //construtor recebe o array atual e o final para ser utilizado no calculo do custo + public AStar(ArrayList ini, ArrayList fin){ + estadoInicial = new State(ini,fin); + estadoFinal = new State(fin,fin); + pq = new PriorityQueue<>(); + visitados = new LinkedList<>(); + pq.add(estadoInicial); + } + + //resolve a instancia do problema + public void solve(){ + State estadoAtual; + ArrayList children; + boolean flag; + int countMovimentos = 0; + int countAbertos = 0; + + while (!pq.isEmpty()){ + estadoAtual = pq.poll(); + this.visitados.add(estadoAtual); + + //imprime para teste + countMovimentos++; // + System.out.println("Movimento: " + countMovimentos); // + estadoAtual.printState(); // + System.out.println("Cost: " + estadoAtual.getCost()); // + System.out.println(); // + + + + //compara o estado atual com a solução do problema + if (estadoAtual.equals(this.estadoFinal)){ + System.out.println("Resolucao encontrada:"); + estadoAtual.printState(); + System.out.println("Nos abertos repetidos: " + (countAbertos - countMovimentos)); // + return; + } + + + //gera filhos e caso seja diferente de todos visitados, adiciona na fila de prioridade pq + children = estadoAtual.genChildren(); + for (State it : children){ + flag = true; + for(State it2 : this.visitados){ + if (it.equals(it2)){ + flag = false; + break; + } + } + if (flag){ + State auxState = new State(it.n,estadoFinal.n); + pq.add(auxState); + countAbertos++; // + } + } + } + } + + + +} diff --git a/jogo-oito/src/main/java/BFS.java b/jogo-oito/src/main/java/BFS.java new file mode 100644 index 00000000..c3730925 --- /dev/null +++ b/jogo-oito/src/main/java/BFS.java @@ -0,0 +1,84 @@ +/* + * Trabalho Jogo dos 8 e Metodos de busca + * + * Inteligencia Artificial - GCC128 + * + * Sistemas de Informação + * Universidade Federal de Lavras + * + * + * Autor: Alfredo + * + */ + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +public class BFS { + + State estadoInicial; + State estadoFinal; + Queue q; + Queue visitados; + + + //construtor + public BFS(ArrayList ini, ArrayList fin){ + estadoInicial = new State(ini); + estadoFinal = new State(fin); + q = new LinkedList<>(); + visitados = new LinkedList<>(); + q.add(estadoInicial); + } + + //resolve essa instancia do problema + public void solve(){ + State estadoAtual; + ArrayList children; + boolean flag; + int countMovimentos = 0; + int countAbertos = 0; + + while (!q.isEmpty()){ + estadoAtual = q.remove(); + this.visitados.add(estadoAtual); + + + + //imprime para teste + countMovimentos++; // + System.out.println("Movimento: " + countMovimentos); // + estadoAtual.printState(); // + System.out.println(); // + + + + //compara o estado atual com a solução do problema + if (estadoAtual.equals(this.estadoFinal)){ + System.out.println("Resolucao encontrada:"); + estadoAtual.printState(); + System.out.println("Nos abertos repetidos: " + (countAbertos - countMovimentos)); // + return; + } + + + //gera filhos e caso seja diferente de todos visitados, adiciona na fila q + children = estadoAtual.genChildren(); + for (State it : children){ + flag = true; + for(State it2 : this.visitados){ + if (it.equals(it2)){ + flag = false; + break; + } + } + if (flag){ + q.add(it); + countAbertos++; // + } + } + } + } + +} diff --git a/jogo-oito/src/main/java/Enunciado.pdf b/jogo-oito/src/main/java/Enunciado.pdf new file mode 100644 index 00000000..07f35aa8 Binary files /dev/null and b/jogo-oito/src/main/java/Enunciado.pdf differ diff --git a/jogo-oito/src/main/java/Main.java b/jogo-oito/src/main/java/Main.java new file mode 100644 index 00000000..7e168a62 --- /dev/null +++ b/jogo-oito/src/main/java/Main.java @@ -0,0 +1,96 @@ +/* + * Trabalho Jogo dos 8 e Metodos de busca + * + * Inteligencia Artificial - GCC128 + * + * Sistemas de Informação + * Universidade Federal de Lavras + * + * + * Autor: Alfredo + * + */ + +import java.util.ArrayList; +import java.util.Scanner; + +public class Main { + + public static void main(String[] args) { + // TODO code application logic here + ArrayList estadoInicial = new ArrayList<>(); + ArrayList estadoFinal = new ArrayList<>(); + + + estadoInicial.add(1); + estadoInicial.add(2); + estadoInicial.add(3); + estadoInicial.add(5); + estadoInicial.add(0); + estadoInicial.add(6); + estadoInicial.add(4); + estadoInicial.add(7); + estadoInicial.add(8); + + + estadoFinal.add(1); + estadoFinal.add(2); + estadoFinal.add(3); + estadoFinal.add(4); + estadoFinal.add(5); + estadoFinal.add(6); + estadoFinal.add(7); + estadoFinal.add(8); + estadoFinal.add(0); + + State si = new State(estadoInicial); + State sf = new State(estadoFinal); + + Scanner scanner; + Scanner scanner2; + int option; + int qtdMoves; + + do{ + System.out.println("Estado inicial:"); + si.printState(); + System.out.println(); + + System.out.println("Solucao a ser procurada:"); + sf.printState(); + System.out.println(); + + System.out.println("Digite:"); + System.out.println("1 - Resolver por busca em largura (BFS)"); + System.out.println("2 - Resolver por busca A*"); + System.out.println("3 - Randomizar tabuleiro"); + + scanner = new Scanner(System.in); + + option = scanner.nextInt(); + + switch (option) { + case 1 -> { + BFS bfs = new BFS(si.n,sf.n); + bfs.solve(); + } + case 2 -> { + AStar astar = new AStar(si.n,sf.n); + astar.solve(); + } + + case 3 -> { + System.out.println("Quantos movimentos aleatorios deseja realizar?"); + scanner2 = new Scanner(System.in); + qtdMoves = scanner2.nextInt(); + si.randomize(qtdMoves); + } + + default -> System.out.println("Digite uma opção va3lida"); + } + }while (!(option==1 || option==2)); + + + } + +} diff --git a/jogo-oito/src/main/java/State.java b/jogo-oito/src/main/java/State.java new file mode 100644 index 00000000..cc710767 --- /dev/null +++ b/jogo-oito/src/main/java/State.java @@ -0,0 +1,240 @@ +/* + * Trabalho Jogo dos 8 e Metodos de busca + * + * Inteligencia Artificial - GCC128 + * + * Sistemas de Informação + * Universidade Federal de Lavras + * + * + * Autor: Alfredo + * + */ + +import java.util.ArrayList; +import java.util.Objects; + +public class State implements Comparable{ + + public ArrayList n; + public int cost; + + + //construtor para BFS + public State (ArrayList v){ + n = new ArrayList<>(v); + } + + //construtor para AStar + public State(ArrayList stateIni, ArrayList stateFin){ + n = new ArrayList<>(stateIni); + this.cost = calculateCost(stateFin); //já calcula o custo do estado com relação ao final + } + + + //calcula o custo em relação ao estado final com base em uma tabela de custos pre-calculada + public final int calculateCost(ArrayList stateFinal){ + int totalCost = 0; + int auxFinalIndex; + int[][] costTable = { + {0,1,2,1,2,3,2,3,4}, + {1,0,1,2,1,2,3,2,3}, + {2,1,0,3,2,1,4,3,2}, + {1,2,3,0,1,2,1,2,3}, + {2,1,2,1,0,1,2,1,2}, + {3,2,1,2,1,0,3,2,1}, + {2,3,4,1,2,3,0,1,2}, + {3,2,3,2,1,2,1,0,1}, + {4,3,2,3,2,1,2,1,0} + }; + for(int i=0; i genChildren(){ + ArrayList children = new ArrayList<>(); + State s; + s = this.moveUp(); + if (s != null){ + children.add(s); + } + s = this.moveDown(); + if (s != null){ + children.add(s); + } + s = this.moveLeft(); + if (s != null){ + children.add(s); + } + s = this.moveRight(); + if (s != null){ + children.add(s); + } + return children; + } + + //executa n movimentos para embaralhar o tabuleiro + public void randomize(int n){ + int zeroPos; + int rand; + + for (int i=0; i { //move up + if((zeroPos==0) || (zeroPos==1) || (zeroPos==2)){ + + }else{ + this.n.set(zeroPos, this.n.get(zeroPos-3)); + this.n.set(zeroPos-3, 0); + } + } + case 2 -> { //move down + if((zeroPos==6) || (zeroPos==7) || (zeroPos==8)){ + + }else{ + this.n.set(zeroPos, this.n.get(zeroPos+3)); + this.n.set(zeroPos+3, 0); + } + } + case 3 -> { //move left + if((zeroPos==0) || (zeroPos==3) || (zeroPos==6)){ + + }else{ + this.n.set(zeroPos, this.n.get(zeroPos-1)); + this.n.set(zeroPos-1, 0); + } + } + + case 4 -> {//move right + if((zeroPos==2) || (zeroPos==5) || (zeroPos==8)){ + + }else{ + this.n.set(zeroPos, this.n.get(zeroPos+1)); + this.n.set(zeroPos+1, 0); + } + } + } + } + } + + /** + * compara o objeto com outro recebido + * + * @param o => recebe como parametro outro objeto tipo State para comparação de seus ArrayList + * @return retorna true caso os dois Objetos tenham seus ArrayList com os mesmos valores + */ + @Override + public boolean equals(Object o){ + if (o == null) { + return false; + } + if (o.getClass()!= this.getClass()){ + return false; + } + boolean result = false; + State s = (State) o; + for (int i=0; i getCells() { - return this.board.getCells(); - } - - public void swap(Integer keyCode) { - this.board.swap(keyCode); - } - - public Boolean checkGameOver() { - return this.board.checkGameOver(); - - } - - public void click(Integer cellValue) { - this.board.click(cellValue); - } - -} diff --git a/jogo-oito/src/main/java/interfaces/Edge.java b/jogo-oito/src/main/java/interfaces/Edge.java deleted file mode 100644 index 20e56cd0..00000000 --- a/jogo-oito/src/main/java/interfaces/Edge.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license - * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template - */ -package interfaces; - -import model.Keyboard; - -/** - * - * @author allen - */ -public interface Edge { - - Keyboard getKey(); - - Vertex getCell(); - -} diff --git a/jogo-oito/src/main/java/interfaces/Graph.java b/jogo-oito/src/main/java/interfaces/Graph.java deleted file mode 100644 index e22aad8e..00000000 --- a/jogo-oito/src/main/java/interfaces/Graph.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license - * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Interface.java to edit this template - */ -package interfaces; - -import java.util.List; - -/** - * - * @author allen - */ -public interface Graph { - - void feedback(); - - void setting(); - - void swap(Integer keyCode); - - List getCells(); - - Vertex getEmptyCell(); - - void click(Integer cellValue); - - Boolean checkGameOver(); -} diff --git a/jogo-oito/src/main/java/interfaces/Vertex.java b/jogo-oito/src/main/java/interfaces/Vertex.java deleted file mode 100644 index 4ff55e4b..00000000 --- a/jogo-oito/src/main/java/interfaces/Vertex.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license - * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Interface.java to edit this template - */ -package interfaces; - -import java.util.List; -import model.Keyboard; - -/** - * - * @author allen - */ -public interface Vertex { - - void setValue(Integer value); - - Integer getValue(); - - void creatingHorizontalAdjacent(Vertex cell); - - void creatingVerticalAdjacent(Vertex cell); - - String valueToText(); - - Edge getAdjacentByKeyCode(Keyboard key); - - Vertex click(Keyboard key); - - List getAdjacents(); - - void addAdjacents(Edge edge); - - Vertex swapCells(Integer value); - -} diff --git a/jogo-oito/src/main/java/jogo82.iml b/jogo-oito/src/main/java/jogo82.iml new file mode 100644 index 00000000..1de981c3 --- /dev/null +++ b/jogo-oito/src/main/java/jogo82.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/jogo-oito/src/main/java/model/Adjacent.java b/jogo-oito/src/main/java/model/Adjacent.java deleted file mode 100644 index 6573c4f4..00000000 --- a/jogo-oito/src/main/java/model/Adjacent.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license - * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template - */ -package model; - -import interfaces.Edge; -import interfaces.Vertex; -import java.util.Objects; - -/** - * - * @author allen - */ -public class Adjacent implements Edge{ - - private final Keyboard key; - private final Vertex cell; - - public Adjacent(Keyboard key, Vertex cell) { - this.key = key; - this.cell = cell; - } - - @Override - public Keyboard getKey() { - return this.key; - } - - @Override - public Vertex getCell() { - return this.cell; - } - - @Override - public boolean equals(Object obj) { - return Objects.equals(((Adjacent) obj).getKey(), this.getKey()); - } - -} diff --git a/jogo-oito/src/main/java/model/Cell.java b/jogo-oito/src/main/java/model/Cell.java deleted file mode 100644 index 744d8d39..00000000 --- a/jogo-oito/src/main/java/model/Cell.java +++ /dev/null @@ -1,109 +0,0 @@ -package model; - -import interfaces.Edge; -import interfaces.Vertex; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -public class Cell implements Vertex { - - private Integer value; - private final List adjacents; - public static Integer content; - - public Cell(Integer value) { - this.value = value; - this.adjacents = new ArrayList<>(); - } - - public Cell() { - this.value = Cell.content++; - this.adjacents = new ArrayList<>(); - } - - @Override - public void setValue(Integer value) { - this.value = value; - } - - @Override - public Integer getValue() { - return this.value; - } - - @Override - public void creatingHorizontalAdjacent(Vertex cell) { - this.adjacents.add(new Adjacent(Keyboard.LEFT, cell)); - cell.getAdjacents().add(new Adjacent(Keyboard.RIGHT, this)); - } - - @Override - public void creatingVerticalAdjacent(Vertex cell) { - this.adjacents.add(new Adjacent(Keyboard.UP, cell)); - cell.getAdjacents().add(new Adjacent(Keyboard.DOWN, this)); - } - - @Override - public String valueToText() { - return Optional.of(this.value) - .filter(value -> value != 0) - .map(String::valueOf) - .orElse(""); - } - - @Override - public Edge getAdjacentByKeyCode(Keyboard key) { - Adjacent edge = new Adjacent(key, null); - Integer indexEdge = this.adjacents.indexOf(edge); - return Optional.of(indexEdge) - .filter(index -> index != -1) - .map(this.adjacents::get) - .orElse(null); - } - - @Override - public Vertex click(Keyboard key) { - Edge adjacent = this.getAdjacentByKeyCode(key); - return this.movement(adjacent); - } - - private Vertex movement(Edge adjacent) { - return Optional.ofNullable(adjacent) - .map(Edge::getCell) - .map(this::swapCells) - .orElse(this); - } - - private Vertex swapCells(Vertex movementCell) { - this.setValue(movementCell.getValue()); - movementCell.setValue(0); - return movementCell; - } - - @Override - public Vertex swapCells(Integer value) { - return this.adjacents.stream() - .filter(adjacent -> Objects.equals(adjacent.getCell().getValue(), value)) - .findFirst() - .map(this::movement) - .orElse(this); - } - - @Override - public List getAdjacents() { - return this.adjacents; - } - - @Override - public void addAdjacents(Edge edge) { - this.adjacents.add(edge); - } - - @Override - public boolean equals(Object obj) { - return Objects.equals(this.value, ((Cell) obj).value); - } - -} diff --git a/jogo-oito/src/main/java/model/Keyboard.java b/jogo-oito/src/main/java/model/Keyboard.java deleted file mode 100644 index ada8bb7a..00000000 --- a/jogo-oito/src/main/java/model/Keyboard.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license - * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template - */ -package model; - -import java.awt.event.KeyEvent; -import java.util.Arrays; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; - -public enum Keyboard { - - UP(KeyEvent.VK_UP), - DOWN(KeyEvent.VK_DOWN), - LEFT(KeyEvent.VK_LEFT), - RIGHT(KeyEvent.VK_RIGHT); - - private final Integer value; - - private static final Map map = Arrays.stream(Keyboard.values()) - .collect(Collectors.toMap(Keyboard::getValue, Function.identity())); - - - Keyboard(Integer value) { - this.value = value; - } - - public Integer getValue() { - return value; - } - - public static Keyboard fromValue(Integer value) { - return map.get(value); - } - -} diff --git a/jogo-oito/src/main/java/model/Matrix.java b/jogo-oito/src/main/java/model/Matrix.java deleted file mode 100644 index 29586eaa..00000000 --- a/jogo-oito/src/main/java/model/Matrix.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license - * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template - */ -package model; - -import interfaces.Vertex; -import java.util.ArrayList; -import java.util.List; - -/** - * - * @author allen - */ -public final class Matrix { - - private final Row firstRow; - private final Row secondRow; - private final Row thirdRow; - public static List cells; - - - public Matrix() { - Matrix.cells = new ArrayList<>(); - Cell.content = 1; - this.firstRow = new Row(); - this.secondRow = new Row(); - this.thirdRow = new Row(); - this.defineAdjacent(); - } - - private void defineAdjacent() { - this.firstRow.initial.creatingVerticalAdjacent(secondRow.initial); - this.secondRow.initial.creatingVerticalAdjacent(thirdRow.initial); - - this.firstRow.center.creatingVerticalAdjacent(secondRow.center); - this.secondRow.center.creatingVerticalAdjacent(thirdRow.center); - - this.firstRow.last.creatingVerticalAdjacent(secondRow.last); - this.secondRow.last.creatingVerticalAdjacent(thirdRow.last); - - this.changePositionToValidateTemplate(); - } - - private void changePositionToValidateTemplate(){ - this.thirdRow.last.setValue(0); - } - - - public List getCells() { - return Matrix.cells; - } - - private final class Row { - - public final Cell initial; - public final Cell center; - public final Cell last; - - public Row() { - this.initial = new Cell(); - this.center = new Cell(); - this.last = new Cell(); - this.defineAdjacent(); - this.loadCells(); - } - - public void loadCells() { - Matrix.cells.add(this.initial); - Matrix.cells.add(this.center); - Matrix.cells.add(this.last); - } - - public void defineAdjacent() { - this.initial.creatingHorizontalAdjacent(this.center); - this.center.creatingHorizontalAdjacent(this.last); - } - - } -} diff --git a/jogo-oito/src/main/java/readme.md b/jogo-oito/src/main/java/readme.md new file mode 100644 index 00000000..3b816425 --- /dev/null +++ b/jogo-oito/src/main/java/readme.md @@ -0,0 +1,25 @@ +# Trabalho Jogo dos 8 e Metodos de busca + +

Inteligencia Artificial - GCC128

+ + +

Descrição:

+ +Código em Java para a resolução do Eight-Puzzle-Game
+aplicando métodos de Busca em Largura e A*
+
+ +

Comando para compilar:

+ +javac State.java BFS.java AStar.java Main.java
+
+ + +

Para rodar:

+ +java Main +
+
+[VIDEO]
+https://youtu.be/bvydHQviFbQ + diff --git a/jogo-oito/src/main/java/util/Board.java b/jogo-oito/src/main/java/util/Board.java deleted file mode 100644 index e71e83ea..00000000 --- a/jogo-oito/src/main/java/util/Board.java +++ /dev/null @@ -1,94 +0,0 @@ -package util; - -import interfaces.Graph; -import interfaces.Vertex; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; -import java.util.stream.IntStream; -import model.Keyboard; -import model.Matrix; - -public class Board implements Graph { - - private List cells; - private Vertex emptyCell; - private Integer length; - private Matrix matrix; - - public Board() { - } - - @Override - public void feedback() { - this.matrix = new Matrix(); - this.cells = this.matrix.getCells(); - this.length = cells.size(); - this.defineEmptyCell(); - } - - @Override - public void setting() { - this.matrix = new Matrix(); - this.cells = this.matrix.getCells(); - this.length = cells.size(); - this.shuffleCell(); - this.defineEmptyCell(); - - } - - private void shuffleCell() { - Iterator iterator = this.shuffleValues().iterator(); - this.cells.stream() - .forEach(vertex -> vertex.setValue(iterator.next())); - } - - private List shuffleValues() { - List values = new ArrayList<>(); - this.cells.stream() - .map(Vertex::getValue) - .forEach(values::add); - Collections.shuffle(values); - return values; - } - - private void defineEmptyCell() { - Optional minCell = this.cells.stream() - .min(Comparator.comparing(cell -> cell.getValue())); - minCell.ifPresent(cell -> { - this.emptyCell = cell; - }); - } - - @Override - public void click(Integer cellValue) { - this.emptyCell = this.emptyCell.swapCells(cellValue); - } - - @Override - public void swap(Integer keyCode) { - Keyboard key = Keyboard.fromValue(keyCode); - this.emptyCell = this.emptyCell.click(key); - } - - @Override - public List getCells() { - return this.cells; - } - - @Override - public Vertex getEmptyCell() { - return this.emptyCell; - } - - @Override - public Boolean checkGameOver() { - return IntStream.range(0, this.length) - .allMatch(index -> this.cells.get(index).getValue() == (index + 1) % this.length); - - } - -} diff --git a/jogo-oito/src/main/java/view/JogoDosOito.java b/jogo-oito/src/main/java/view/JogoDosOito.java deleted file mode 100644 index 2b687559..00000000 --- a/jogo-oito/src/main/java/view/JogoDosOito.java +++ /dev/null @@ -1,148 +0,0 @@ -package view; - -import facade.Controller; -import interfaces.Vertex; -import java.awt.Font; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.stream.IntStream; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; - -public class JogoDosOito extends JFrame implements KeyListener { - - private final List buttons; - private final Controller controller; - private JButton reset; - private JButton feedback; - - public JogoDosOito() { - super("Jogo dos Oito"); - this.controller = new Controller(); - this.controller.setting(); - this.buttons = new ArrayList<>(); - } - - private void configureInterface() { - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - setSize(300, 300); - setLayout(new GridLayout(4, 3)); - setVisible(true); - addKeyListener(this); - setFocusable(true); - } - - private void createButtons() { - this.controller.getCells().forEach(cell -> { - JButton button = this.configButton(cell); - add(button); - buttons.add(button); - }); - } - - private Integer textToValue(String text) { - return Optional.ofNullable(text) - .map(Integer::valueOf) - .orElse(0); - } - - private JButton configButton(Vertex cell) { - JButton button = new JButton(); - button.setFont(new Font("Arial", Font.BOLD, 36)); - button.setText(cell.valueToText()); - button.addActionListener((ActionEvent e) -> { - this.controller.click(this.textToValue(button.getText())); - this.updateBoard(); - this.checkGameOver(); - SwingUtilities.getRoot(button).requestFocus(); - }); - return button; - - } - - private void checkGameOver() { - Optional.ofNullable(this.controller.checkGameOver()) - .filter(Boolean::booleanValue) - .ifPresent(gameOver -> { - JOptionPane.showMessageDialog(this, "Parabéns, você venceu!"); - resetGame(); - }); - } - - private void configMenu() { - this.reset = this.configReset(); - this.feedback = this.configFeedback(); - add(this.feedback); - add(this.reset); - add(new JLabel("")); - } - - private JButton configReset() { - JButton buttonReset = new JButton("Reiniciar"); - buttonReset.addActionListener((ActionEvent e) -> { - this.resetGame(); - SwingUtilities.getRoot(buttonReset).requestFocus(); - }); - return buttonReset; - } - - private JButton configFeedback() { - JButton buttonFeedback = new JButton("Gabarito"); - buttonFeedback.addActionListener((ActionEvent e) -> { - this.showFeedback(); - SwingUtilities.getRoot(buttonFeedback).requestFocus(); - }); - return buttonFeedback; - } - - - private void resetGame() { - this.controller.setting(); - this.updateBoard(); - } - - private void showFeedback() { - this.controller.feedback(); - this.updateBoard(); - } - - private void updateBoard() { - List cells = this.controller.getCells(); - IntStream.range(0, cells.size()) - .forEach(index -> { - JButton button = this.buttons.get(index); - button.setText(cells.get(index).valueToText()); - }); - } - - @Override - public void keyTyped(KeyEvent e) { - } - - @Override - public void keyPressed(KeyEvent e) { - this.controller.swap(e.getKeyCode()); - this.updateBoard(); - this.checkGameOver(); - } - - @Override - public void keyReleased(KeyEvent e) { - } - - public static void main(String[] args) { - JogoDosOito game = new JogoDosOito(); - game.createButtons(); - game.configMenu(); - game.configureInterface(); - - } -}