Skip to content

Instantly share code, notes, and snippets.

@codecademydev

codecademydev/main.js Secret

Created Oct 4, 2020
Embed
What would you like to do?
Codecademy export
const prompt = require('prompt-sync')({sigint: true});
const hat = '^';
const hole = 'O';
const fieldCharacter = '░';
const pathCharacter = '*';
let hatPos;
let currPos;
let gameOn;
class Field {
constructor(h, w, p) {
this._h = h;
this._w = w;
this._p = p;
this._field = [];
this._pos = [];
this.fillField();
this.finalField();
}
get pos(){
return this._pos;
}
fillField() {
for(let i = 0; i < this._h; i++){
let temp = [];
for(let j = 0; j < this._w; j++){
temp.push(fieldCharacter);
}
this._field.push(temp);
}
}
get field() {
return this._field;
}
random(lim) {
return Math.floor(Math.random() * lim);
}
genUniqueArr() {
let randomH = this.random(this._h);
let randomW = this.random(this._w);
this._pos.push([ randomH, randomW ]);
return [randomH, randomW];
}
finalField() {
let area = this._h * this._w;
let percent = Math.ceil(area * (this._p / 100));
for (let i = 0; i < percent; i++) {
let rowcol = this.genUniqueArr();
let col = rowcol[0];
let row = rowcol[1];
this._field[col][row] = hole;
if(i === percent-2){
hatPos = this._field[col][row]
this._field[col][row] = hat;
}
if(i === percent-1){
this._field[col][row] = pathCharacter;
currPos = [col,row];
}
}
}
get showField() {
for(let i= 0; i < this._field.length; i++){
console.log(this._field[i].join(''));
}
}
updateField(x,y){
if(this._field[y][x] === hole){
//console.log('on x '+x+' on y '+y+' is '+this._field[y][x]);
//console.log(this._field);
console.log('You fell into a Hole, Game Over!');
gameOn = false;
}
else if(this._field[y][x] === hat){
//console.log('on x '+x+' on y '+y+'is '+this._field[y][x]);
//console.log(this._field);
console.log('You Won!');
gameOn = false;
}
else if(this._field[y][x] === undefined){
//console.log('on x-'+x+' on y-'+y+' is '+this._field[y][x]);
//console.log(this._field);
console.log('Out of Range Game Over!');
gameOn = false;
}
else{
//console.log('on x '+x+'on y '+y+'is '+this._field[y][x]);
this._field[y][x] = pathCharacter;
//console.log(this._field);
}
}
}
function game(column,row,percent){
const obj = new Field(column, row, percent);
gameOn = true;
let x = currPos[1];
let y = currPos[0];
while(gameOn){
obj.showField;
const input = prompt("Enter Input Left-l/Right-r/Up-u/D-Down: ");
if(input === 'l'){
obj.updateField(--x,y);
}
else if(input === 'r'){
obj.updateField(++x,y);
}
else if(input === 'u'){
obj.updateField(x,--y);
}
else if(input === 'd'){
obj.updateField(x,++y);
}
else{
console.log('Wrong Input\n');
}
}
}
game(4,3,25);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.