treasure.js
1    //Treasure Quest
2    let numTreasures = Math.floor(Math.random() * 4) + 2;
3    let text = "You're on a deserted island, looking for " + numTreasures + " treasures. ";
4    text += "You have a special compass that tells you how far away you are from the nearest treasure. ";
5    text += "You can travel north, south, east, or west. ";
6    text += "Find that treasure!";
7    alert(text);
8    
9    for (let i = 0; i < numTreasures; i++)
10   {
11     playGame();
12   }
13   
14 function playGame() 15 { 16 let treasures = ["silver tiara", "bar of gold", "magical scepter", "book of spells", "rod of food summoning", "leather jacket"]; 17 18 let index = Math.floor(Math.random() * treasures.length); 19 let treasure = treasures[index]; 20 21 let playerX = Math.floor(Math.random() * 5) + 3; 22 let playerY = Math.floor(Math.random() * 5) + 3; 23 24 if (Math.random() < 0.5) 25 { 26 playerX = -playerX; //start from west 27 } 28 if (Math.random() < 0.5) 29 { 30 playerY = -playerY; //start from south 31 } 32 let steps = []; 33 let distance = getDistance(playerX, playerY); 34 35 while (distance !== 0) 36 { 37 let direction = prompt("You are " + distance + " meters away from the treasure. Will you go north, east, south, or west?"); 38 direction = direction[0].toLowerCase(); 39 40 if (direction === "n") 41 { 42 playerY++; 43 steps.push("north"); 44 } 45 else if (direction === "s") 46 { 47 playerY--; 48 steps.push("south"); 49 } 50 else if (direction === "e") 51 { 52 playerX++; 53 steps.push("east"); 54 } 55 else if (direction === "w") 56 { 57 playerX--; 58 steps.push("west"); 59 } 60 else 61 { 62 alert("That's an invalid direction."); 63 } 64 65 distance = getDistance(playerX, playerY); 66 67 } 68 69 alert("You found the " + treasure + "!"); 70 alert("Your path was " + steps.join(" --> ") + "."); 71 72 } 73
74 function getDistance(x, y) 75 { 76 let distance = Math.sqrt(x ** 2 + y ** 2); 77 distance = Number(distance.toFixed(2)); 78 return distance; 79 } 80