CSE101 Lab 8 – OOP A little story Solved

24.99 $

Category: Tag:

Description

5/5 - (1 vote)

 

Lab 8 – OOP
A little story
Rules of the game
• The race:
• The distance is set in kilometers.
• Each day, the animals move a certain distance.
• The competitors:
• The hare: Fast (5 to 10 km/day), but might not move at all (50% chance).
• The tortoise: Slow (1 to 5 km/day), but always moves.
• Our goals:
• Create classes for the animals, allowing them to move and report their positions.
• Run the race, observing positions daily, until the finish line is reached.
• Apply and understand Python classes, objects, and inheritance.
Why no unit tests?
The participants

Task 1: Create an Animal class

Attributes (TODO →__init__() )
• name: The name of the animal.
• position: The current position of the animal in the race. Initialized at 0.
• race_distance: The total distance of the race. This is used to determine when the race is finished.
Methods (TODO)
• move(): This method is to be implemented in each subclass to determine how the animal moves. In the Animal class, it’s left empty as a placeholder.
• report_position(): This method prints out the current position of the animal. You can print something like “The $name_of_object is at position $position_of_object”
• has_finished(): This method checks if the animal has reached or exceeded the race distance, and thus finished the race. Return a boolean
Task 2: The hare

Polymorphism (TODO)
Rewrite the move() method to follow these behaviors:
• The hare moves faster (between 5 and 10 kilometers per day) but there’s a 50% chance it doesn’t move at all, simulating the hare’s tendency to rest.
• Each day (each turn in our program), the hare will move a certain distance or rest, and its position will be updated accordingly.
Hints: for the resting time probability you can use random() and for the position increment you can get a random distance between 5 to 10 using randint()
Task 2: The hare

class Hare(Animal):
def __init__(self, race_distance):
super().__init__(“Hare”, race_distance)

class Hare(Animal):
def __init__(self, race_distance):
self.name = “Hare” self.position = 0
self.race_distance = race_distance
Task 3: The tortoise

Polymorphism (TODO)
Rewrite the move() method to follow these behaviors:
• The tortoise moves slower (between 1 and 5 kilometers per day), but it moves every day, simulating the tortoise’s steady pace.
• Each day (each turn in our program), the tortoise will move a certain distance, and its position will be updated accordingly.

Task 4: Start the race

# Running the race race_distance = 50 hare = Hare(race_distance) tortoise = Tortoise(race_distance)
while not hare.has_finished() and not tortoise.has_finished():
hare.move() tortoise.move() hare.report_position() tortoise.report_position()
if hare.has_finished() and tortoise.has_finished():
print(“It’s a tie!”)
elif hare.has_finished():
print(“The hare wins!”)
else:
print(“The tortoise wins!”)

  • CSE101-Lab8-main-q6xsdl.zip