Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexandreKavalerski committed Jul 7, 2020
2 parents e3f1094 + 0576932 commit d51eefd
Show file tree
Hide file tree
Showing 28 changed files with 5,922 additions and 528 deletions.
20 changes: 20 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\dist\\index.js",
"outFiles": [
"${workspaceFolder}/**/*.js"
]
}
]
}
2 changes: 1 addition & 1 deletion LICENSE.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Copyright 2018 Alexandre Kavalerski
Copyright 2020 Alexandre Kavalerski

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

Expand Down
94 changes: 94 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# A Star Puzzle Solver

A TypeScript lib that solves Puzzle Game problem using the A* Algorithm

## Installation

Use the package manager [npm](https://www.npmjs.com/) to install A* Puzzle Solver.

```bash
npm install a-star-puzzle-solver
```

## How to use

### ES6

```js
import AStarPuzzleSolver from 'a-star-puzzle-solver';

const solution = AStarPuzzleSolver.solvePuzzle(state);
```

### CommonJS

```js
const AStar = require('a-star-puzzle-solver').default;

AStar.solvePuzzle(state);
```

### UMD in Browser

```html
<!-- to import non-minified version -->
<script src="a-star-puzzle-solver.umd.js"></script>

<!-- to import minified version -->
<script src="a-star-puzzle-solver.umd.min.js"></script>
```

After that the library will be available to the Global as `AStarPuzzleSolver`. Follow an example:

```js

const aStar = AStarPuzzleSolver;

const solution = aStar.solvePuzzle(state);
```

## Methods
> This library provides only one method:
### solvePuzzle(initialState)
> Solves the 8 Puzzle Game with provided initial state.
**Arguments**

| Argument | Type | Options |
|----------|---------|-------------------|
|`initialState`|*Array of Arrays of Number* | 'Any state possible'|

**Example**

```js
const state = [
[1, 2, 3],
[4, 5, 6],
[7, 0, 8]
];

const solution = AStar.solvePuzzle(state);
```

**Return**
> This method return an object with:
> - 'state' property: last state visited (the goal state)
> - 'evaluationFunctionValue': an object (wich you can use to access property 'g' that represents the depth traveled)
> - 'previousNode': another Node object with same properties (that you can use to see expanded nodes and operations applied)
**Obs:**
- For more examples of how to use, see './examples' folder
- The goalState considered by the algorithm is:

![](./images/goal-state.jpg)


## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
65 changes: 65 additions & 0 deletions examples/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>A Star Puzzle Solver - Example 01</title>
<script src="../lib/a-star-puzzle-solver.umd.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>

<div class="container">
<div class="col">
<div class="row">

<div class="col-md-4 table-responsive">
<table class="table table-bordered">
<tr>
<td class="text-center td-puzzle"></td>
<td class="text-center td-puzzle"></td>
<td class="text-center td-puzzle"></td>
</tr>
<tr>
<td class="text-center td-puzzle"></td>
<td class="text-center td-puzzle"></td>
<td class="text-center td-puzzle"></td>
</tr>
<tr>
<td class="text-center td-puzzle"></td>
<td class="text-center td-puzzle"></td>
<td class="text-center td-puzzle"></td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="container align-center">
<button type="button" name="btnRandomize" id="btnRandomize" class="btn btn-outline" btn-lg btn-block>Gerar aleatório</button>
<button type="button" name="btnSolution" id="btnSolution" class="btn btn-primary">Solucionar</button>
</div>
</div>

<div class="row">
<ul id="results">
</ul>
</div>

<div class="row">
<div id="viewSolution">
<table class="table table-bordered tb-solution">

</table>
</div>
</div>
</div>
</div>



<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
</html>
118 changes: 118 additions & 0 deletions examples/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
$(document).ready(function () {
const initialState = [0, 1, 2, 3, 4, 5, 6, 7, 8];
initialState.sort((a, b) => Math.random() - Math.random());

renderTDList(initialState);
$("#btnRandomize").on("click", function () {
randomState();
});

$("#btnSolution").on("click", function () {
getSolution();
});
});

function renderTDList(stateList) {
console.log("rendering...");
console.log(stateList);

const list = $("td.td-puzzle");
let pos = 0;
for (let td of list) {
$(td).html(stateList.shift());
pos++;
}
}

function getActualState() {
const list = $("td.td-puzzle");
let state = [[], [], []];
const stateList = [];
for (let td of list) {
stateList.push($(td).text());
}

for (let i in stateList) {
if (i <= 2) {
state[0].push(Number(stateList[i]));
} else if (i <= 5) {
state[1].push(Number(stateList[i]));
} else {
state[2].push(Number(stateList[i]));
}
}
return state;
}

function getSolution() {
const aStar = AStarPuzzleSolver;
const state = getActualState();
console.log(state);
try {
const solution = aStar.solvePuzzle(state);
showResults(solution);
viewSolution(solution);
} catch (err) {
alert(
"O estado inicial é solucionável! Por favor, gere outro estado e tente novamente."
);
}
}

function showResults(solution) {
const markup = `
<li>Problema resolvido!</li>
<li>Custo final: ${solution.evaluationFunctionValue.g}</li>
<li>Nós expandidos: ?</li>
<li>Início da fronteira: ?</li>
`;

$("#results").html(markup);
}

async function viewSolution(solution) {
// const markup = `
// `;

let states = getListOfStates(solution, []);
awaitsToRender(states);

// $("#solution").html(markup);
}

function timer(ms) {
return new Promise((res) => setTimeout(res, ms));
}

async function awaitsToRender(states) {
for (let s of states) {
console.log(s);
await timer(1200);
renderTDList(transformStateInArray(s));
}
}

function transformStateInArray(state) {
let array = [];
for (let l in state) {
for (let c in state[l]) {
array.push(state[l][c]);
}
}
return array;
}

function getListOfStates(node, list) {
if (node.previousNode) {
list.unshift(node.state);
return getListOfStates(node.previousNode, list);
} else {
return list;
}
}

function randomState() {
state = [1, 2, 3, 4, 5, 6, 7, 8, 0];
state.sort((a, b) => Math.random() - Math.random());
renderTDList(state);
}
Binary file added images/goal-state.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions lib/a-star-puzzle-solver.umd.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit d51eefd

Please sign in to comment.