type Map = string[][];
class Car {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
move(direction: string, map: Map): boolean {
let newX = this.x;
let newY = this.y;
switch (direction) {
case 'up':
newX--;
break;
case 'down':
newX++;
break;
case 'left':
newY--;
break;
case 'right':
newY++;
break;
default:
console.log("Invalid direction!");
return false;
}
if (
newX < 0 || newX >= map.length ||
newY < 0 || newY >= map[0].length ||
map[newX][newY] === 'W'
) {
console.log("Cannot move there!");
return false;
}
this.x = newX;
this.y = newY;
return true;
}
}
class ParkingGame {
map: Map;
car: Car;
exit: { x: number; y: number };
constructor() {
this.map = [
[' ', ' ', 'W', ' ', ' '],
[' ', 'W', 'W', ' ', ' '],
[' ', ' ', 'C', ' ', ' '],
[' ', 'W', 'W', ' ', ' '],
[' ', ' ', 'E', ' ', ' '],
];
this.car = new Car(2, 2);
this.exit = { x: 4, y: 2 };
}
printMap(): void {
for (let i = 0; i < this.map.length; i++) {
let row = '';
for (let j = 0; j < this.map[i].length; j++) {
if (i === this.car.x && j === this.car.y) {
row += 'C ';
} else if (i === this.exit.x && j === this.exit.y) {
row += 'E ';
} else {
row += this.map[i][j] + ' ';
}
}
console.log(row);
}
}
checkWin(): boolean {
return this.car.x === this.exit.x && this.car.y === this.exit.y;
}
start(): void {
console.log("Welcome to the Parking Game!");
console.log("Use 'up', 'down', 'left', 'right' to move the car (C) to the exit (E).");
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
const play = () => {
this.printMap();
readline.question("Enter direction: ", (direction: string) => {
if (this.car.move(direction, this.map)) {
if (this.checkWin()) {
console.log("Congratulations! You won!");
readline.close();
} else {
play();
}
} else {
play();
}
});
};
play();
}
}
const game = new ParkingGame();
game.start();