cis441 project milestone 1a
Embed:
(wiki syntax)
Show/hide line numbers
Road.cpp
00001 #include <math.h> 00002 #include "Road.h" 00003 00004 Road::Road(Intersection* intersection, int roadId) { 00005 active_cars = 0x00; 00006 last_car = NULL; 00007 00008 this->intersection = intersection; 00009 this->roadId = roadId; 00010 next_release = 0; 00011 num_cars = 0; 00012 00013 pending_car = new AccCar(num_cars + 5 * (roadId - 1), this, pow(2, num_cars)); 00014 pending_car->set_target_speed(rand() % 11 + 5); 00015 } 00016 00017 int Road::try_enter_car(int time) { 00018 if( next_release <= time && pending_car != NULL ) { 00019 if( last_car == NULL || last_car->position >= pending_car->speed + 2 ) { 00020 pending_car->set_forward_car(last_car); 00021 pending_car->reset(); 00022 active_cars = active_cars | pending_car->flag; 00023 00024 last_car = pending_car; 00025 cars[num_cars] = pending_car; 00026 00027 num_cars++; 00028 00029 if(num_cars < MAX_CARS) { 00030 pending_car = new AccCar(num_cars + 5 * (this->roadId - 1), this, pow(2, num_cars)); 00031 pending_car->set_target_speed(rand() % 11 + 5); 00032 00033 next_release = time + rand() % 3; 00034 } else { 00035 pending_car = NULL; 00036 } 00037 00038 return last_car->id; 00039 } 00040 } 00041 00042 return -1; 00043 } 00044 00045 void Road::let_cars_update() { 00046 if( active_cars > 0x00 ) { 00047 go_flags.set(active_cars); 00048 } 00049 } 00050 00051 void Road::wait_for_car_update() { 00052 if( active_cars > 0x00 ) { 00053 done_flags.wait_all(active_cars); 00054 } 00055 } 00056 00057 void Road::check_exit_cars() { 00058 for( int i=0; i < num_cars; i++ ) { 00059 if(this->cars[i]->position >= 100 ) { 00060 active_cars = active_cars ^ this->cars[i]->flag; 00061 00062 this->cars[i]->position = -1; 00063 this->cars[i]->speed = -1; 00064 } 00065 } 00066 } 00067 00068 void Road::print_status() { 00069 for( int i=0; i < num_cars; i++ ) { 00070 printf("Car %d on road %d: %d -> %d\r\n", cars[i]->id, this->roadId, cars[i]->position, cars[i]->speed); 00071 } 00072 } 00073 00074 void Road::intendToEnter(int carId) { 00075 intersection->intendToEnter(carId, this->roadId); 00076 }
Generated on Wed Jul 20 2022 19:41:08 by
1.7.2
