Skip to content

Instantly share code, notes, and snippets.

@miladabc
Created November 16, 2018 20:21
Show Gist options
  • Save miladabc/afcf740e7c767f6a569756813972565a to your computer and use it in GitHub Desktop.
Save miladabc/afcf740e7c767f6a569756813972565a to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Water Agent</title>
<script>
const greenHouse = [
[0, 1, 0],
[1, 0, 1]
];
class Agent {
constructor() {
this.currentPosition = { x: 0, y: 0 };
}
move(greenHouse, direction) {
switch (direction) {
case 'up':
if (this.currentPosition.x === 0)
return console.error('Can not move up');
this.currentPosition.x--;
break;
case 'down':
if (this.currentPosition.x === 1)
return console.error('Can not move down');
this.currentPosition.x++;
break;
case 'left':
if (this.currentPosition.y === 0 && (this.currentPosition.x === 0 || this.currentPosition.x === 1))
return console.error('Can not move left');
this.currentPosition.y--;
break;
case 'right':
if (this.currentPosition.y === 2 && (this.currentPosition.x === 0 || this.currentPosition.x === 1))
return console.error('Can not move right');
this.currentPosition.y++;
break;
default:
console.error('Wrong direction!');
}
console.log(`${direction}:`);
console.log('Current position: ', this.currentPosition);
}
water(greenHouse) {
for (let x = 0; x < greenHouse.length; x++) {
for (let y = 0; y < greenHouse[x].length; y++) {
// If there is a flower, water it
if (greenHouse[x][y])
console.log(`Flower at position ${x}, ${y} has been watered`);
}
}
}
}
const agent = new Agent();
console.log(greenHouse);
console.log('------------------');
agent.move(greenHouse, 'up');
agent.move(greenHouse, 'right');
agent.move(greenHouse, 'right');
agent.move(greenHouse, 'down');
agent.move(greenHouse, 'down');
console.log('------------------');
agent.water(greenHouse);
</script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment