cis441 project milestone 1a
Embed:
(wiki syntax)
Show/hide line numbers
AccCar.cpp
00001 #include "AccCar.h" 00002 #include <stdlib.h> 00003 #include <algorithm> 00004 00005 #define TICK 1000 00006 #define MONITOR_DIST 17 00007 #define SAFETY_GAP 2 00008 00009 AccCar::AccCar(int id, Road* road, int flag) { 00010 this->id = id; 00011 this->road = road; 00012 this->flag = flag; 00013 00014 waited = false; 00015 00016 this->thread = NULL; 00017 } 00018 00019 void AccCar::set_forward_car(AccCar* car) { 00020 this->forward_car = car; 00021 } 00022 00023 void AccCar::set_target_speed(int speed) { 00024 this->target_speed = speed; 00025 this->speed = speed; 00026 } 00027 00028 void AccCar::update() { 00029 do { 00030 ThisThread::sleep_for(TICK); 00031 road->go_flags.wait_all(flag); 00032 cycle++; 00033 00034 position = position + speed; 00035 00036 if (cycle % 5 == 0) { 00037 target_speed = rand() % 11 + 5; 00038 } 00039 00040 if( position < 54 ) { 00041 if (forward_car != NULL && forward_car->position > -1) { 00042 if (forward_car->position - position < MONITOR_DIST && forward_car->position < 55) { 00043 road->done_flags.wait_all(forward_car->flag, osWaitForever, false); 00044 00045 int diff = forward_car->position - position; 00046 int maxSafeSpeed = diff - SAFETY_GAP; 00047 00048 speed = std::min(maxSafeSpeed, target_speed); 00049 } else { 00050 speed = target_speed; 00051 } 00052 } else { 00053 speed = target_speed; 00054 } 00055 00056 int distance_to_intersection = 54 - position; 00057 speed = std::min(distance_to_intersection, speed); 00058 00059 } else if( position == 54 ) { 00060 if( waited) { 00061 speed = road->intersection->attemptEnterIntersection(this->id); 00062 } else { 00063 speed = 0; 00064 waited = true; 00065 road->intendToEnter(this->id); 00066 } 00067 } else if( position < 56 ) { 00068 speed = 1; 00069 } else { 00070 if( position == 56 ) { 00071 road->intersection->leaveIntersection(); 00072 } 00073 00074 if (forward_car != NULL && forward_car->position > -1) { 00075 if (forward_car->position - position < MONITOR_DIST ) { 00076 road->done_flags.wait_all(forward_car->flag, osWaitForever, false); 00077 00078 int diff = forward_car->position - position; 00079 int maxSafeSpeed = diff - SAFETY_GAP; 00080 00081 speed = std::min(maxSafeSpeed, target_speed); 00082 } else { 00083 speed = target_speed; 00084 } 00085 00086 } else { 00087 speed = target_speed; 00088 } 00089 } 00090 00091 road->done_flags.set(flag); 00092 } while( position < 100 ); 00093 } 00094 00095 void AccCar::reset() { 00096 road->done_flags.clear(flag); 00097 00098 if (thread != NULL) { 00099 thread->terminate(); 00100 } 00101 00102 thread = new Thread(); 00103 thread->start( callback(this, &AccCar::update) ); 00104 00105 this->position = 0; 00106 this->cycle = 0; 00107 }
Generated on Wed Jul 20 2022 19:41:08 by
1.7.2
