commit f08bef4eef2da47e717cd85e0b1b17d0d0c19d65 Author: Nathan Date: Fri Dec 15 18:33:17 2023 +0100 practica diff --git a/autos_de_choque.py b/autos_de_choque.py new file mode 100644 index 0000000..6953dfb --- /dev/null +++ b/autos_de_choque.py @@ -0,0 +1,66 @@ +import threading +import time +import random + +class BumperCar(threading.Thread): + def __init__(self, car_id): + super().__init__() + self.car_id = car_id + self.x = random.randint(0, 99) + self.y = random.randint(0, 49) + self.directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] + + def move(self): + direction = random.choice(self.directions) + self.x = (self.x + direction[0]) % 100 + self.y = (self.y + direction[1]) % 50 + + def run(self): + while True: + time.sleep(0.1) + self.move() + +def visualize_grid(cars): + grid = [['-' for _ in range(100)] for _ in range(50)] + for car in cars: + grid[car.y][car.x] = 'X' + for row in grid: + print(''.join(row)) + +def check_collisions(cars): + collided_cars = set() + for i in range(len(cars)): + for j in range(i + 1, len(cars)): + if cars[i].x == cars[j].x and cars[i].y == cars[j].y: + collided_cars.add((cars[i].car_id, cars[j].car_id)) + return collided_cars + +def remove_collided_cars(cars, collided_cars): + updated_cars = [] + for car in cars: + if car.car_id not in sum(collided_cars, ()): + updated_cars.append(car) + return updated_cars + +def simulation(): + num_cars = 20 + cars = [] + for i in range(num_cars): + cars.append(BumperCar(i)) + + for car in cars: + car.start() + + + while True: + #time.sleep(1) + print("VVV New Grid VVV") + visualize_grid(cars) + collided_cars = check_collisions(cars) + if collided_cars: + print("Collision detected between cars:", collided_cars) + cars = remove_collided_cars(cars, collided_cars) + time.sleep(3) + +if __name__ == "__main__": + simulation() \ No newline at end of file