-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstudent.cc
71 lines (59 loc) · 2.53 KB
/
student.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "student.h"
#include <assert.h>
#include "nameserver.h"
#include "printer.h"
#include "watcardoffice.h"
#include <iostream>
extern MPRNG rand_gen;//!!! TODO: declare on driver
Student::Student(Printer &prt,NameServer &nameServer,WATCardOffice &cardOffice,unsigned int id,unsigned int maxPurchases):
prt(prt),nameServer(nameServer), cardOffice(cardOffice),id(id),maxPurchases(maxPurchases){}
void Student::main(){
//random choose a number of bottle to purchase [1,MaxPurchases]
unsigned int myBottlesCount=rand_gen(1,maxPurchases);
//a random favourite flavour [0,3]
VendingMachine::Flavours myFlavour=VendingMachine::Flavours(rand_gen(3));
prt.print(Printer::Student,id,'S',myFlavour,myBottlesCount);
//create a WatCard via the WATCardOffice with $5 balance
WATCard::FWATCard mycard=cardOffice.create(id,5);
//obtains the location of a vending machine from the nameserver
VendingMachine* mymachine=nameServer.getMachine(id);
WATCard* fcard = NULL;
//a student terminates after purchasing all the soda initally selected
for (unsigned int i=0;i<myBottlesCount;i++){
//before each attempt to buy a soda, a student yield a random number of times [1,10]
yield(rand_gen(1,10));
prt.print(Printer::Student,id,'V',mymachine->getId());
//the student may have to block until the amount transferr appears on their WATCard
//!!! TODO: make exception on vending machine
bool repeat=true;
while(repeat){//for some reason i did not get my drink
try{
fcard=mycard();
mymachine->buy(myFlavour,*fcard);
//if no exception
prt.print(Printer::Student,id,'B',mymachine->getId());
repeat=false;//i just bought it
}
//if a courier has lost student's watcard, lost is raised
//student must crate a new WATCard via WATCardOffice with $5, reattempt without yield
catch(WATCardOffice::Lost e){
mycard=cardOffice.create(id,5);
prt.print(Printer::Student,id,'L');
}
//if vending machine indicates insufficient fund, student transfercurrent soda cost plus $5
catch(VendingMachine::Funds e){
unsigned int amount=5+(mymachine->cost());
mycard=cardOffice.transfer(id,amount,fcard);
}
//if the vending machine is out of flavour, the student obtain a new vending machine
catch(VendingMachine::Stock e){
mymachine=nameServer.getMachine(id);
prt.print(Printer::Student,id,'V',mymachine->getId());
}
}
//update all variable for next purchase
mymachine=nameServer.getMachine(id);
}
prt.print(Printer::Student,id,'F');
delete fcard;
}