Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created November 25, 2022 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codecademydev/6c3a83013f9b1a4a896d2b2ee5772183 to your computer and use it in GitHub Desktop.
Save codecademydev/6c3a83013f9b1a4a896d2b2ee5772183 to your computer and use it in GitHub Desktop.
Codecademy export
const prompt = require("prompt-sync")({ sigint: true });
const hat = "^";
const hole = "O";
const fieldCharacter = "░";
const pathCharacter = "*";
class Field {
constructor(field) {
this.field = field;
this.x = 0;
this.y = 0;
}
runGame() {
let gameOver = false;
while (!gameOver) {
this.print();
this.requestInput();
gameOver = this.testPosition() ? true : false;
this.field[this.y][this.x] = pathCharacter;
}
}
requestInput() {
const move = prompt(`What's your move..?`).toUpperCase();
switch (move) {
case "W":
this.y -= 1;
break;
case "A":
this.x -= 1;
break;
case "S":
this.x += 1;
break;
case "Z":
this.y += 1;
break;
default:
console.log("Move with W,A,S,Z keys.");
break;
}
}
testPosition() {
switch (this.field[this.y][this.x]) {
case hat:
console.log("Hurray, you win!");
return true;
break;
case hole:
console.log("Oops! You fell in a hole. You lose");
return true;
break;
case fieldCharacter:
return false;
break;
default:
console.log("Out of bounds. You lose.");
return true;
}
}
static generateField(width, height, percentage = 0.1) {
const field = new Array(height).fill().map((arr) => new Array(width));
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let random = Math.random();
field[y][x] = random > percentage ? fieldCharacter : hole;
}
}
field[0][0] = pathCharacter;
const hatLocation = {
x: Math.floor(Math.random() * width),
y: Math.floor(Math.random() * height),
};
while (hatLocation.x === 0 && hatLocation.y === 0) {
hatLocation.x = Math.floor(Math.random() * width);
hatLocation.y = Math.floor(Math.random() * height);
}
field[hatLocation.y][hatLocation.x] = hat;
return field;
}
print() {
let x = [];
for (let i = 0; i < this.field.length; i++) {
x.push(this.field[i].join(""));
}
console.log(x.join("\n"));
}
}
const myField = new Field(Field.generateField(7,10,0.25));
myField.runGame();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment