Great Deal! Get Instant $10 FREE in Account on First Order + 10% Cashback on Every Order Order Now

Microsoft Word - Assignment2_TreasureHunt Assignment 2 – Treasure Hunt Due Date: Monday, October XXXXXXXXXXat 23:55 Percentage overall grade: 5% Penalties: No late assignments allowed Maximum marks:...

1 answer below »
Microsoft Word - Assignment2_TreasureHunt
Assignment 2 – Treasure Hunt

Due Date: Monday, October XXXXXXXXXXat 23:55
Percentage overall grade: 5%
Penalties: No late assignments allowed
Maximum marks: 100


Assignment Description
You are tasked with creating a single-player treasure hunt game. The game starts off by creating and
displaying a treasure map, similar to the map below:

XXXXXXXXXX
0 . | . . |
1 . . . . .
2 . . . | .
3 . . . . .
4 . . . . .

2 treasure chest(s) still hidden.

Notice that this particular map contains two hidden treasure chests, and three trees (each represented
y a vertical bar character, '|'). The trees act as obstacles, and represent locations that cannot hide
treasure and cannot be searched. All (row, column) locations that display a '.' represent a location that
can be searched, and which may be hiding a treasure chest. The player of the game must enter in (row,
column) guesses for locations to search. If the search location is within half of the treasure map’s width
to the closest treasure chest, the '.' will be replaced by the distance to that nearest treasure chest;
otherwise, it will be marked with a 'u' to indicate that the search was unsuccessful.

For example, if the treasure chests are hidden at (1, 2) and (0,0) (i.e. where the stars are on the map
elow), a guess of (4, 4) would result in the map being updated as follows:

XXXXXXXXXX
0 . | . . |
1 . . . . .
2 . . . | .
3 . . . . .
XXXXXXXXXXu

2 treasure chest(s) still hidden.

On the other hand, a guess of (2, 4) would instead result in the following update:



XXXXXXXXXX
0 . | . . |
1 . . . . .
2 . . . | 2
3 . . . . .
4 . . . . .

2 treasure chest(s) still hidden.

Notice that the distance between the search location and the nearest treasure chest is calculated using
the Pythagorean theorem, as follows:
distance2 = (column distance)2 + (row distance)2
distance = sqrt((column distance)2 + (row distance)2)
where distance is rounded to the nearest integer

When a player guesses the co
ect location of a treasure chest, it is marked on the map with an 'X', as
illustrated below:

XXXXXXXXXX
0 . | . . |
XXXXXXXXXXX . .
2 . . . | .
3 . . . . .
4 . . . . .

1 treasure chest(s) still hidden.

To make the game more interesting, the player must try to find the treasure chests before a pirate does.
The pirate is controlled by the computer, and searches using an automatic pattern. It searches the next
valid unsearched location, starting in the top left corner of the map (0, 0), and working to the right and
then down. The results from the pirate’s search are marked on the map in the same way as for the
player, except that it has a 'P' in front (please see sample_output.txt for examples of this).

The player always gets to go first, and then the player and pirate alternate turns. A complete sample
un of a game is included on eClass as sample_output.txt


Task 1: TreasureMap class
Download and save a copy of the treasure_map.py skeleton code (found on eClass). In this file, you will
find a TreasureMap class definition that must be completed, according to the exact description below.
It also contains some code under if __name__ == "__main__": that you can use to partially
test your class methods. You should add to this code to test ALL of your class methods completely
efore moving on to Task 2.

column distance
ow distance distance
*NOTE*: the following description specifies how other programmers can expect to interact with
instances of TreasureMap. (In our case, how the markers may call your methods while testing and
marking your code). Therefore, it’s very important that you do not change the method signatures – i.e.
do not add extra parameters to the following method definitions.



TreasureMap(size, chests, trees) – The __init__ method requires 3 parameters
esides the self parameter: size, chests, and trees. (More information about these parameters are
included in the method’s docstring.) Using the information passed in with these input parameters, this
method should initialize the four private attributes given in the skeleton code: self.__treasure_map (a
epresentation of the contents of the treasure map), self.__chest_positions, self.__tree_positions, and
self.__num_chests_found. You may add other attributes if required (though they should not be
needed), but none of the attributes should be accessed outside of the TreasureMap class.

display_map() – Prints the contents of the treasure map to the screen, in a grid format, along with
column and row indices. Nothing is returned.

is_position_valid(position) – Checks if a given (row, column) position is a searchable
location on the treasure map. Assertion statements should be included to check that the position
consists of two whole numbers, and that each (row, col) position is not outside the range of the treasure
map. Any AssertionE
ors that are raised by this method should NOT be handled within this
method/class. If all asserts are True, this method should return a tuple containing a Boolean value and a
string message. The Boolean value will be True for valid, searchable positions; False if the position has
already been searched or contains a tree. The message should be one of 3 options (as appropriate):
 "there’s a tree at that location!",
 "location has already been searched!", or
 "searching row: r, col: c" (where r and c are replaced with actual position values).

calculate_distance(pos) – Receives the tuple (row, column) search position as input, and uses
it to calculate the distances between that position and all treasure chests on the map. Each distance is
calculated according to the Pythagorean theorem, rounded to the nearest integer, and stored in a
container. That container of distances is returned from the method.

closest_chest(distances) – Receives the container of distances returned from
calculate_distance(pos), and finds the shortest distance (co
esponding to the chest closest to the
search position). This method returns a tuple of (Boolean, integer), where the integer is the shortest
distance. If that shortest distance is half the size of the treasure map or less, the Boolean value is True;
False if greater than half the size of the treasure map.

update_map(pos, player) – Receives a tuple (row, column) describing the cu
ent search
position, as well as an integer number indicating which player’s turn it cu
ently is (even number means
it’s the player’s turn, odd number means it’s the pirate’s turn). Updates the treasure map at the cu
ent
search position with an 'X', a 'u', or a number. If it is the pirate’s turn, the pirate’s search position is
updated on the treasure map with a 'PX', a 'Pu', or a 'P'+number. This method returns the number of
treasure chests found at the cu
ent search position (should be either 1 or 0).

auto_pirate() – Finds the first searchable position in the treasure map, and returns it as a tuple
(row, column). The scan starts checking at the top-left corner of the map, and moves right. When the
end of a row is reached, the scan continues at the beginning of the next row down, and moves right.
This continues until a searchable position is found.

is_hunt_over() – Returns True if all treasure chests have been found (indicating that the treasure
hunt is over), or False if at least one chest is still hidden.

You may create additional methods to help you
eak down and complete the methods above. These
additional methods can be called within the TreasureMap class, but NOT outside of it. (i.e. they do not
form part of the public interface with TreasureMap instances.) Only the given methods form the public
interface, exactly as presented above.

Test your TreasureMap class thoroughly before moving on. Some starting tests have been provided, but
you will need to include your own under the if __name__ == "__main__": in treasure_map.py.


Task 2: Main program
Once
Answered Same Day Nov 15, 2021

Solution

Yogesh answered on Nov 16 2021
145 Votes
assignment2-2-rqij0cns.py
import treasure_map
# function definitions go here
def start():
global size, chests, trees
filename = input("Enter name of the text file to initialize treasure map: ")
if ".txt" not in filename:
print("Invalid File Extension.")
start()
try:
f = open(filename, "r")
line = f.readlines()
size = int(line[0])
treasure = []
tree = []
for k in range(1, len(line)):
if "TREASURE" in line[k]:
treasure.append(line[k])
if "TREE" in line[k]:
tree.append(line[k])
f.close()
chests = []
trees = []
for el in treasure:
r = int(el[9])
c = int(el[11])
chests.append((r, c))
for elt in tree:
rt = int(elt[5])
ct = int(elt[7])
trees.append((rt, ct))
except:
print("[E
no 2] No such file or directory: '" + filename + "'.")
start()
def getrc():
global position, revert
print("Enter search coordinates: row col")
randc = input()
print(randc)
if len(randc) < 3 or len(randc) >= 4:
print("Inco
ect number of coordinate values entered.")
getrc()
if not (randc[0].isnumeric() and randc[2].isnumeric() and randc[1] == " "):
print("Inco
ect type of coordinate values entered.")
getrc()
position = [randc[0], randc[2]]
try:
revert = game_map.is_position_valid(position)
except AssertionE
or:
print("Position values are not whole numbers!")
getrc()
if not revert[0]:
print(revert[1])
getrc()
if revert[0]:
print(revert[1])
def askque():
ans = input("Would you like to start a new treasure hunt? [Y/N]: ")
if ans.upper() == "Y":
main()
elif ans.upper() == "N":
input("Good Bye...\n")
else:
print("Enter a Valid option...\n")
askque()
def play(player):
getrc()
pos = [int(position[0]), int(position[1])]
game_map.update_map(pos, player)
game_map.display_map()
pcors = game_map.auto_pirate()
game_map.update_map(pcors, player + 1)
game_map.display_map()
if game_map.is_hunt_over():
print("All treasure has been found!")
askque()
else:
player = player + 2
play(player)
def main():
global game_map, playe
player = 0 # Player plays the game first.
start()
game_map = treasure_map.TreasureMap(size, chests, trees)
game_map.display_map()
play(player)
if __name__ == "__main__":
main()
sample_map.txt
5
TREASURE:1,2
TREE:0,1
TREE:2,3
TREASURE:0,0
TREE:0,4
treasure_map.py
import math
class TreasureMap:
TREE_CHAR = " |" # represents tree
UNSEARCHED_CHAR = " ." # represents unsearched location
def __init__(self, size, chests, trees):
"""
Initialize treasure map.
Parameters:
- size (int):
Treasure map is square (size rows by size columns);
can assume that size is always a positive intege
- chests (list):
List of tuples (row, col) describing treasure chest locations
- trees (list):
List of tuples (row, col) describing tree locations
Returns: None
"""
self.__treasure_map = [i for i in range(size)]
self.__chest_positions = [[], []]
self.__tree_positions = [[], []]
self.__num_chests_found = 0
for val in chests:
self.__chest_positions[0].append(val[0])
self.__chest_positions[1].append(val[1])
for val in trees:
self.__tree_positions[0].append(val[0])
self.__tree_positions[1].append(val[1])
self.__num_chests_found = len(self.__chest_positions[0])
self.rows = [i for i in range(size)]
...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here