Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let gameBoard = [];
- let empty;
- function generateGameBoard() {
- let $tds = $("#table").find("td"), number = 0;
- while (number < 9) {
- for (let i = 0; i < 3; i++) {
- var aux = [];
- for (let j = 0; j < 3; j++) {
- $($tds[number]).attr("i", i).attr("j", j);
- aux.push($($tds[number]));
- number++;
- }
- gameBoard.push(aux);
- }
- }
- }
- function generateRandom() {
- let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8];
- let randi, randj, dimension = numbers.length, aux;
- while (dimension > 0) {
- randi = Math.floor(Math.random() * numbers.length);
- randj = Math.floor(Math.random() * numbers.length);
- aux = numbers[randi];
- numbers[randi] = numbers[randj];
- numbers[randj] = aux;
- dimension--;
- }
- count = 0;
- for (let i = 0; i < 3; i++) {
- for (let j = 0; j < 3; j++) {
- if (numbers[count] !== 0)
- gameBoard[i][j].html(numbers[count]);
- else
- empty = gameBoard[i][j];
- gameBoard[i][j].click(function () {
- console.log($(this).html() + " i=" + $(this).attr("i") + " j=" + $(this).attr("j"));
- });
- count++;
- }
- }
- }
- function move(keyCode) {
- let i = parseInt(empty.attr("i")), j = parseInt(empty.attr("j"));
- switch (keyCode) {
- case 37:
- console.log("Left");
- moveLeft(i, j);
- break;
- case 39:
- console.log("Right");
- moveRight(i, j);
- break;
- case 38:
- console.log("Up");
- moveUp(i, j);
- break;
- case 40:
- console.log("Down");
- moveDown(i, j);
- break;
- }
- if (checkVictory()) {
- alert("Felicitari!");
- location.reload();
- }
- }
- function startGame() {
- generateGameBoard();
- generateRandom();
- }
- function moveLeft(i, j) {
- if (j !== 2) {
- switchTwo(gameBoard[i][j + 1], gameBoard[i][j]);
- }
- }
- function moveRight(i, j) {
- if (j !== 0) {
- switchTwo(gameBoard[i][j - 1], gameBoard[i][j]);
- }
- }
- function moveUp(i, j) {
- if (i !== 2) {
- switchTwo(gameBoard[i + 1][j], gameBoard[i][j]);
- }
- }
- function moveDown(i, j) {
- if (i !== 0) {
- switchTwo(gameBoard[i - 1][j], gameBoard[i][j]);
- }
- }
- //p2 mereu empty
- function switchTwo(p1, p2) {
- let aux = p1.html();
- p1.html(p2.html());
- p2.html(aux);
- empty = p1;
- }
- function checkVictory() {
- if (gameBoard[2][2].html() === "") {
- let against = ["1", "2", "3", "4", "5", "6", "7", "8", ""], count = 0;
- for (let i = 0; i < 3; i++) {
- for (let j = 0; j < 3; j++) {
- if (against[count] !== gameBoard[i][j].html())
- return false;
- count++;
- }
- }
- return true;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement