fixed moving in labyrinth problem

This commit is contained in:
nbillard 2022-12-01 04:49:58 +01:00
parent d96a662269
commit 80b867a823
2 changed files with 25 additions and 8 deletions

View file

@ -1,3 +1,3 @@
# sokoban # Sokoban
projet Web 3Mic projet Web 3Mic

View file

@ -58,6 +58,7 @@ class Position {
this.x = x; this.x = x;
this.y = y; this.y = y;
} }
move(direction) { move(direction) {
switch (direction) { switch (direction) {
case MoveDirection.Right: case MoveDirection.Right:
@ -92,8 +93,16 @@ class Position {
} }
isWithin(pos) { isWithin(pos) {
return this.x < pos.x && this.y < pos.y return this.x < pos.x && this.y < pos.y;
} }
isEqual(pos) {
return this.x === pos.x && this.y === pos.y;
}
}
const copyPosition = (pos) => {
return new Position(pos.x, pos.y);
} }
class Tile { class Tile {
@ -233,17 +242,22 @@ const generatePlayground = (levelBlueprint, canvasWidth, canvasHeight) => {
canMove(pos) { canMove(pos) {
const foregroundAnswer = this.foreground[pos.y][pos.x].isMovable(); const foregroundAnswer = this.foreground[pos.y][pos.x].isMovable();
const backgroundAnswer = this.background[pos.y][pos.x].isMovable(); const backgroundAnswer = this.background[pos.y][pos.x].isMovable();
if (backgroundAnswer === CanMove.No) { if (backgroundAnswer == CanMove.No) {
return CanMove.No; return CanMove.No;
} else { } else {
return foregroundAnswer; return foregroundAnswer;
} }
}, },
move(direction) { move(direction) {
let aux = this.playerPos; let aux = copyPosition(this.playerPos);
let willMove = false; let willMove = false;
let finishedChecking = false; let finishedChecking = false;
let moveCount = 0;
while (aux.isWithin({x: this.width, y: this.height}) && !finishedChecking) { while (aux.isWithin({x: this.width, y: this.height}) && !finishedChecking) {
console.log("checking at position:");
console.log(aux);
console.log("answer");
console.log(this.canMove(aux));
switch(this.canMove(aux)) { switch(this.canMove(aux)) {
case CanMove.Yes: case CanMove.Yes:
willMove = true; willMove = true;
@ -255,13 +269,16 @@ const generatePlayground = (levelBlueprint, canvasWidth, canvasHeight) => {
break; break;
case CanMove.Maybe: case CanMove.Maybe:
aux.move(direction); aux.move(direction);
moveCount++;
break; break;
} }
} }
if (willMove) { console.log(this.playerPos);
console.log("in playground.move"); console.log("in playground.move");
let posOfObjectToMove = aux; if (willMove) {
while (aux != this.playerPos) { this.playerPos.move(direction);
let posOfObjectToMove = copyPosition(aux);
for (let i = 0; i < moveCount; i++) {
posOfObjectToMove.moveBackwards(direction); posOfObjectToMove.moveBackwards(direction);
console.log("I try to move"); console.log("I try to move");
[this.foreground[aux.y][aux.x], this.foreground[posOfObjectToMove.y][posOfObjectToMove.x]] = [this.foreground[aux.y][aux.x], this.foreground[posOfObjectToMove.y][posOfObjectToMove.x]] =