-
Notifications
You must be signed in to change notification settings - Fork 1
Home
Welcome to the Gotham City wiki!
###Gotham City ####Team Information
- Team Name: Team Gotham City
- Team E-Mail: usc-csci201-fall2013-team31-l@mymaillists.usc.edu
- Team Mentor: Sarah Whang sarahwha@usc.edu
####Resources
####Team Members
No. | Name (First (Nickname) Last) | USC Email | GitHub Username | Role |
---|---|---|---|---|
1 | Meruyert Aitbayeva | aitbayev@usc.edu | @aitbayev | |
2 | William (Hunter) McNichols | wmcnicho@usc.edu | @wmcnicho | |
3 | Brice Roland | broland@usc.edu | @broland | |
4 | Nikhil Bedi | nbedi@usc.edu | @nikhilbedi | |
5 | Evan Coutre | coutre@usc.edu | @ecoutre | Team Leader |
####Team Meetings
Meeting | Time | Location |
---|---|---|
Lab | Wed. 10:00am | SAL 109 |
Weekly Meeting 1 | Tues. 05:00pm to 10:00pm | GFS 112 |
Weekly Meeting 2 | Thur. 05:00pm to 10:30pm | SAL 125 |
General meetings | Tues./Thur. 05:00pm to 10:30pm | WPH B34 |
##Design Docs
###Market Design
![Market Design] (http://i.imgur.com/3oUpeEI.png) ![Market Design] (https://raw.github.com/usc-csci201-fall2013/team31/master/docs/market.PNG?token=4757129__eyJzY29wZSI6IlJhd0Jsb2I6dXNjLWNzY2kyMDEtZmFsbDIwMTMvdGVhbTMxL21hc3Rlci9kb2NzL21hcmtldC5QTkciLCJleHBpcmVzIjoxMzg3MzM4OTkyfQ%3D%3D--53b17821712d94d6d719a0d00650058fbc4dc56d)
data
MarketWorker workers
MarkerCashier cashier;
class Item{
String name
Int price
Int quantity
}
class Order{
String type
Int quantity
boolean delivery
Customer customer
}
Cashier
List<Check> orders
List<RestaurantOrder> restOrders
class Check{
Customer c;
List<Order> orders;
Double amountue;
Double moneyGiven;
Boolean delivery;
state {pending, checking, counting, delivering}
}
class RestaurantOrder{
Role cookRole;
Role cashRole;
Double amountue;
Double moneyGiven;
state {pending, checking, counting, delivering}
}
//messages
needFood(MarketCustomer mcr){ //when customer just arrives to the market and in a wating line
waitingCustomers.add(mcr);
if (waitingCustomers.size()==1 ){
currentCustomer = mcr;
System.out.println("Current customer " + currentCustomer.getName());
stateChanged();
}
}
hereIsMoneyRestaurant(Role role, double money){ //restaurant paying
for(RestaurantOrder order: restaurantOrders){
if (order.cashierRole== role){
order.moneyGiven = money;
order.state = RestaurantOrder.State.paying;
stateChanged();
}
}
}
INeed(List<Order> o){ //here customer passes what he needs
checks.add(new Check(o));
customersInMarket.add(o.get(0).customer);
stateChanged();
}
public void INeedFood(Map<String, Integer> food, Role role, Role cashier){ //order from restaurant
restaurantOrders.add(new RestaurantOrder(food, role, cashier));
stateChanged();
}
public void hereIsMoney(MarketCustomer c, double money){ //customer paying
for (Check check: checks){
if (check.c == c){
check.moneyGiven = money;
check.state = Check.CheckState.gotMoney;
stateChanged();
}
}
}
//scheduler
for (Check check: checks){
if (check.state == Check.CheckState.gotMoney && check.c == currentCustomer){
check.state = Check.CheckState.paid;
GiveChangeCustomer(check);
return true;
}
if (check.state == Check.CheckState.pending && check.c == currentCustomer){
check.state = Check.CheckState.checkingAmount;
checkQuantity(check);
return true;
}
}
if (currentCustomer != null){
System.out.println("there is a customer" + currentCustomer.getName());
Ask(currentCustomer);
return true;
}
for (RestaurantOrder restaurantOrder: restaurantOrders){
if (restaurantOrder.state == RestaurantOrder.State.pending){
restaurantOrder.state = RestaurantOrder.State.processing;
ProcessRestaurantOrder(restaurantOrder);
return true;
}
if (restaurantOrder.state == RestaurantOrder.State.paying){
restaurantOrder.state = RestaurantOrder.State.paid;
GiveChangeRestaurant(restaurantOrder);
return true;
}
}
return false;
}
public void Ask(MarketCustomer c){
c.NextCustomerPlease();
}
public void checkQuantity(Check check){
for (Order order: check.orders){
Item i = (inventory.get(order.choice));
if (i.quantity == 0){
order.customer.outOf(order);
check.orders.remove(order);
}
}
worker.Bring(check.orders);
for (Order o: check.orders){
Item item = (inventory.get(o.choice));
item.quantity = item.quantity - o.quantity;
check.amountDue = check.amountDue + (item.price*o.quantity);
}
check.c.amountDue(check.amountDue);
}
public void ProcessRestaurantOrder(RestaurantOrder o){
Map<String, Integer> temp = o.foodNeeded;
for (Map.Entry<String, Integer> entry: temp.entrySet()){ //for now market has always enough
int quant = entry.getValue();
String choice = entry.getKey();
Item i = (inventory.get(choice));
System.out.println(i.type);
i.quantity = i.quantity - quant;
o.amountDue = o.amountDue + (i.price*quant);
}
myPerson.Do("Amount due " + o.amountDue);
if (o.cashierRole == cashier4){
((Restaurant4CashierRole) o.cashierRole).amountDue(o.amountDue, this);
}
worker.SendFood(temp, o.cookRole);
}
public void GiveChangeRestaurant(RestaurantOrder order){
double i = order.moneyGiven - order.amountDue;
((Restaurant4CashierRole) order.cashierRole).HereIsYourChange(i, this);
restaurantOrders.remove(order);
}
public void GiveChangeCustomer(Check check){
check.c.HereIsChange(check.moneyGiven - check.amountDue);
waitingCustomers.remove(currentCustomer);
if (waitingCustomers.size()!=0){
currentCustomer = waitingCustomers.get(0);
stateChanged();
}
else{
currentCustomer = null;
stateChanged();
}
checks.remove(check);
}
Customer
Cashier cashier;
private List<Order> orders = new ArrayList<Order>();
public enum CustomerState {needFood, choseGroceries, movingToCashier, atCashier, ordering, inALine, paying, amountDue, gotChange, leaving, moving, gettingItems, gotItems };
public void getGroceries(){
for (Map.Entry<String, Integer> entry: myPerson.groceryList.entrySet() ){
orders.add(new Order(this, entry.getKey(), entry.getValue(), false));
}
state = CustomerState.needFood;
stateChanged();
}
public void startBuildingMessaging(){
getGroceries();
cashier = myPerson.markets.get(0).getCashier();
}
public void AtCashier(){//from gui
state = CustomerState.atCashier;
stateChanged();
}
public void ArrivedToGetItem(){
state = CustomerState.gettingItems;
stateChanged();
}
public void amountDue(double amount){
amountDue = amount;
state = CustomerState.amountDue;
stateChanged();
}
public void HereIsChange(double change){
money = money+change;
state = CustomerState.gotChange;
stateChanged();
}
public void HereIsYourStuff(Map<String, Integer> map){
myPerson.groceryBag = map;
myPerson.groceryList.clear();
state = CustomerState.gotItems;
stateChanged();
}
public void NextCustomerPlease(){
state = CustomerState.choseGroceries;
stateChanged();
}
//scheduler
if (state == CustomerState.needFood){
state =CustomerState.inALine;
tellCashier();
return true;
}
if (state == CustomerState.choseGroceries){
state = CustomerState.movingToCashier;
MoveToCashier();
return true;
}
if (state == CustomerState.atCashier){
state = CustomerState.ordering;
makePurchase();
return true;
}
if (state == CustomerState.amountDue){
state = CustomerState.paying;
DoPay();
return true;
}
if (state == CustomerState.gotChange){
state = CustomerState.moving;
GetItems();
return true;
}
if (state == CustomerState.moving){
state = CustomerState.gettingItems;
Waiting();
return true;
}
if (state == CustomerState.gotItems){
state = CustomerState.leaving;
Leave();
return true;
}
return false;
}
OrderItem(){
cashier.Ineed(this, choice, quantity)
}
public void GetItems(){
customerGui.DoGetItems();
}
public void DoPay(){
double payment = round(amountDue);
myPerson.setMoney((float) (myPerson.getMoney() - payment)) ;
cashier.hereIsMoney(this, payment);
}
public void tellCashier(){
cashier.needFood(this);
}
public void MoveToCashier(){
customerGui.DoMoveToCashier();
}
public void makePurchase(){
cashier.INeed(orders);
}
Pay(){
cashier.HereIsMoney(money);
}
GetItem(){
doMoveToGetItem();
}
Leave(){
DoLeave();
}
Worker
private List<CustomerDelivery> deliveries = new ArrayList<CustomerDelivery>();
private List<RestaurantDelivery> restDeliveries = new ArrayList<RestaurantDelivery>();
public Map<String, Item> inventory = new HashMap<String, Item>();
public static class CustomerDelivery{
List<Order> orders = new ArrayList<Order>();
MarketCustomer customer;
public DeliveryState state;
boolean d;
public enum DeliveryState {pending, getting, delivering, delivered};
}
public static class RestaurantDelivery{
private Role cookRole;
private Map<String, Integer> foods;
//Location
public DeliveryState state;
public enum DeliveryState {pending, getting, delivering, delivered};
}
public void Bring(List<Order> o){ //for customer
deliveries.add(new CustomerDelivery(o));
stateChanged();
}
public List<CustomerDelivery> getCustomerDeliveries(){
return deliveries;
}
public List<RestaurantDelivery> getRestaurantDeliveries(){
return restDeliveries;
}
public Map<String, Item> getInventory(){
return inventory;
}
public void SendFood(Map<String, Integer> things, Role role){
restDeliveries.add(new RestaurantDelivery(things, role));
stateChanged();
}
public void Brought(MarketCustomer c){
delivering.release();
for (int i=0; i<deliveries.size(); i++){
if (deliveries.get(i).customer == c){
HandIn(deliveries.get(i));
stateChanged();
}
}
}
public void Sent(Role role){
delivering.release();
for (int i=0; i<restDeliveries.size(); i++){
if (restDeliveries.get(i).cookRole == role){
((Restaurant4CookRole) restDeliveries.get(0).cookRole).HereIsYourFood(restDeliveries.get(i).foods);
restDeliveries.remove(restDeliveries.get(i));
stateChanged();
}
}
}
public boolean pickAndExecuteAnAction(){
for (CustomerDelivery delivery: deliveries){
if (delivery.state == CustomerDelivery.DeliveryState.pending){
delivery.state = CustomerDelivery.DeliveryState.getting;
Bring(delivery);
return true;
}
}
for (RestaurantDelivery delivery: restDeliveries){
if (delivery.state == RestaurantDelivery.DeliveryState.pending){
delivery.state = RestaurantDelivery.DeliveryState.getting;
Send(delivery);
return true;
}
}
workerGui.DefaultPos();
return false;
}
public void Bring(CustomerDelivery d){
workerGui.DoBring(d.customer);
}
public void HandIn(CustomerDelivery d){
Map<String, Integer> f= new HashMap<String, Integer>();
for (int i=0; i<d.orders.size(); i++){
f.put(d.orders.get(i).getChoice(), d.orders.get(i).getQuantity());
}
d.customer.HereIsYourStuff(f);
deliveries.remove(d);
stateChanged();
}
//restaurant
public void Send(RestaurantDelivery d){
workerGui.DoSend(d.foods, d.cookRole);
}
BankTellerRole
Data
List <MyCustomer> customers;
BankGreeterRole greeter;
BankDatabase bankDatabase;
ArrayList<Table> tables;
Int position;
class MyCustomer = { BankCustomerRole c, BankCustomerState s, double transactionAmount, int accountNumber /*if more than one*/ }
enum BankCustomerState = { waiting, depositing, withdrawing, openingAccount, closingAccount, needALoan, gettingLoan, done }; Messaging
NeedATransaction( BankCustomerRole c, String type, transaction amount ) {
MyCustomer c2 = new MyCustomer(c, type, amount);
c2.s = waiting;
switch(type) {
case “deposit”: c2.s = depositing; break;
case “withdrawal”: c2.s = withdrawing; break;
//…continued for all states
}
customers.add(c2);
}
DoneAndLeaving ( BankCustomerRole c ) {
MyCustomer mc = customers.get(find(c));
mc.s = done;}
Scheduling
If there exists c in customers such that c.state = depositing, then depositFunds(c)
If there exists c in customers such that c.state = withdrawing, then withdrawFunds(c)
If there exists c in customers such that c.state = openingAccount, then openAccount(c)
If there exists c in customers such that c.state = depositing, then closeAccount(c)
If there exists c in customers such that c.state = needALoan, then checkLoanCredentials(c)
If there exists c in customers such that c.state = done, then handleDoneState(c)
Actions
depositFunds( MyCustomer c) {
BankAccount acc = bankDatabase.accounts.
get(c.c.name);
acc.deposit(c.transactionAmount);
c.c.HereIsReceipt(new Receipt(acc.balance, c.transactionAmount));}
withdrawFunds( MyCustomer c) {
BankAccount acc = bankDatabase.accounts.
get(c.c.name);
double cash = acc.withdraw(c.transactionAmount);
c.c.HereIsReceiptAndMoney(new Receipt(acc.balance, c.transactionAmount), cash);}
openAccount( MyCustomer c) {
BankAccount acc = bankDatabase.addAccount(c.name, c.transactionAmount);
c.c.HereIsReceiptAndAccountInfo(new Receipt(acc.balance), acc.accountNumber);
}
closeAccount( MyCustomer c) {
BankAccount acc = bankDatabase.removeAccount(c.name, c.accountNumber);
c.c.HereIsReceiptAndAccountInfo(new Receipt(acc.balance), accountNumber);
}
checkLoanCredentials(MyCustomer c) {
if(c.c.person.stateOfWealth == rich || c.c.person.stateOfWealth == adequate) {
//check for enough money within bank //database
bankDatabase.safeBalance -= c.transactionAmount;
c.c.HereIsLoan(new receipt(c.transactionAmount), c.transactionAmount);
bankDatabase.loanHolders.add(c, c.transactionAmount);
}
Else {
c.c.NotEligibleForLoan();
}
}
handleDoneState(MyCustomer c) {
customers.remove(c);
greeter.ReadyForCustomer(this);
}
//Classes Created for Data
Class Receipt { double transactionAmount, originalBalance, newBalance; }
Class BankAccount {double accountBalance, int accountNumber, String accountholderName }
Class BankDatabase { double safeBalance, Map accounts {String holderName, BankAccount account}, Map loanHolders {String holderName, double loanValueOwed} }
BankCustomerRole
Data
BankCustomerGui gui;
BankGreeterRole greeter;
BankTellerRole teller;
List<Transaction> transactionList;
class Transaction {
String transactionType;
double transactionAmount;
}
enum state = (waiting, goingToTeller, atTeller, receivedReceipt, done)
List<int> accountsHeld;
List<Receipt> receipts;
//greeter.needATeller() called in constructor //(Hack) – to be replaced with the hack from gui Messaging
waitHere( int pos ) { gui.goToLinePosition(pos); state = waiting }
GoToTeller(BankTellerRole t, int pos) {
teller = t;
gui.GoToTeller(pos);
state = goingToTeller
}
setupTransactions(){
if person.accountNumber = 0, add addAccount to transactionList
if person.moneyState = low, add withdrawal to transactionList
if person.moneyState = high, add deposit to transactionList
//need a loan and close accounts determined by future gui
}
atTeller() { state = atTeller; }
HereIsReceipt( Receipt r ) {
receipts.add(r);
state = receivedReceipt;
}
HereIsReceiptAndCash( Receipt r, Cash c ) {
receipts.add(r);
person.cash += c;
state = receivedReceipt;
}
HereIsReceiptandAccountInfo( Receipt r, int newAccount ) {
Receipts.add(r);
accountsHeld.add(newAccount);
state = receivedReceipt;
}
Scheduling
If state = atTeller then teller.NeedATransaction(this, transactionType, transactionAmount);
If state = receivedReceipt then handleEndOfTransaction(); Actions
handleEndOfTransaction() {
if(/*Another transaction is needed*/) {
state = atTeller;
//set transactionType, transactionAmount, etc.
}
else
teller.DoneAndLeaving(this);
}
BankGreeterRole
Data
List <MyCustomer> customers = NULL;
ArrayList<BankTellerRole> tellers;
Map tellerAvailability <BankTellerRole teller, Boolean isAvailable>;
Int linePosition; //for GUI; may change in //type/implementation
class MyCustomer = { Customer c, state s }
enum state = (waiting, inLine goingToTeller); Messaging
NeedATeller( BankCustomerRole c ) {
MyCustomer c2 = new MyCustomer(c);
c2.s = waiting;
customers.add(c2); }
ReadyForCustomer ( BankTeller teller ) {
tellerAvailability.get(teller.name) = true;
}
Scheduling
If there exists c in myCustomers such that c.s = waiting || = inLine && there exists t in tellerAvailability where isAvailable = true, SendToTeller(c, t);
If there exists c in myCustomers such that c.s = waiting, SendToLinePosition(c);
Actions
SendToTeller( MyCustomer c, BankTellerRole t) {
c.c.goToTeller(t, t.position);
customers.remove(0);
tellerAvailability.get(t) = false; }
SendtoLineposition( MyCustomer c ) {
c.c.waitHere(linePosition);
linePosition += //Gui increment
c.s = inLine;
}
###House Design ![home_diagram] (https://raw.github.com/usc-csci201-fall2013/team31/master/docs/homedesign.jpg?token=3289054__eyJzY29wZSI6IlJhd0Jsb2I6dXNjLWNzY2kyMDEtZmFsbDIwMTMvdGVhbTMxL21hc3Rlci9kb2NzL2hvbWVkZXNpZ24uanBnIiwiZXhwaXJlcyI6MTM4NjEyMjMzM30%3D--6757069a2db859a18b399ee8f349ebb373655e9a)
![home_diagram] (http://i.imgur.com/iq6GthO.jpg) ![home_diagram] (https://raw.github.com/usc-csci201-fall2013/team31/master/docs/homedesign.jpg?token=4757129__eyJzY29wZSI6IlJhd0Jsb2I6dXNjLWNzY2kyMDEtZmFsbDIwMTMvdGVhbTMxL21hc3Rlci9kb2NzL2hvbWVkZXNpZ24uanBnIiwiZXhwaXJlcyI6MTM4NzMzODg5MX0%3D--17bbfca2ee76e4b636232dea69ede0882380494d)
Home Resident Role
DATA:
private String name;
Timer timer = new Timer();
private ResidentGui residentGui;
String type;
public PersonAgent person;
// public PersonAgent accountHolder;
private Home home;
private double wallet;
public Map<String, Food> fridgeFoods
public Map<String, Food> foods
public Map<String, Integer> groceryList
public Map<String, Integer> groceryBag
private List<RentBill> rentBills = new ArrayList<RentBill>();
public enum HomeState {DoingNothing, CheckingFoodSupply, Cooking, Plating, Eating, Clearing, LeavingHome, GoingToBed, Sleeping, PayingRent, checkingMailbox, GoingToMailbox, checkingGroceryBag, PuttingGroceriesInFridge, GoingToPutGroceriesInFridge, GoingToFridgeToCheckFood, LeftHouse};
public HomeState state = HomeState.DoingNothing;// The start state
public enum HomeEvent {none, gotHungry, collectedIngredients, EmptyFridge, doneCooking, donePlating, doneEating, doneClearing, gotSleepy, doneSleeping, payRent, atFridge, checkMailbox, atMailbox, checkGroceryBag, putGroceriesInFridge, leaveHome, LeftHouse};
public HomeEvent event = HomeEvent.none;
ResidentRole(PersonAgent p) {
name = myPerson.name;
Food f = new Food("Chicken");
fridgeFoods.put("Chicken", f);
f = new Food("Steak");
fridgeFoods.put("Steak", f);
f = new Food("Pizza");
fridgeFoods.put("Pizza", f);
f = new Food("Salad");
fridgeFoods.put("Salad", f);
}
public void startBuildingMessaging(){
state = HomeState.DoingNothing;
event = HomeEvent.none;
msgCheckMailbox(); //message to start Home gui
}
MESSAGES
//initial starting message
public void msgCheckMailbox() {
state = DoingNothing;
event = checkMailbox;
stateChanged();
}
public void atMailbox() {
event = atMailbox;
stateChanged();
}
public void atFridge() {
event = atFridge;
stateChanged();
}
public void gotSleepy() {
event = gotSleepy;
}
public void wakeUp() {
//stateChanged();
}
Scheduler
public boolean pickAndExecuteAnAction() {
//mailbox scheduling events
if (state ==DoingNothing && event ==checkMailbox) {
state =GoingToMailbox;
goToMailbox();
}
if (state ==GoingToMailbox && event ==atMailbox) {
state =checkingMailbox;
checkMail();
return true;
}
if (state ==checkingMailbox && event ==payRent) {
state =PayingRent;
payRent(home.getRentBills());
return true;
}
if (state == PayingRent && event == none) {
state = DoingNothing;
returnToHomePosition();
return true;
}
if (state == checkingMailbox && event == none) {
state = DoingNothing;
returnToHomePosition();
return true;
}
//grocery bag scheduling events
if (myPerson.groceryBag.size() >){
checkGroceryBag();
state = DoingNothing;
return true;
}
if (state == DoingNothing && event == putGroceriesInFridge) {
state = GoingToPutGroceriesInFridge;
goToFridge();
return true;
}
if (state == GoingToPutGroceriesInFridge && event == atFridge) {
state = PuttingGroceriesInFridge;
putGroceriesInFridge(myPerson.getGroceryBag());
return true;
}
if (state == PuttingGroceriesInFridge && event == none) {
state = DoingNothing;
returnToHomePosition();
return true;
}
//got hungry scheduling events
if (state == DoingNothing && event == gotHungry) {
state = GoingToFridgeToCheckFood;
goToFridge();
return true;
}
if (state == GoingToFridgeToCheckFood && event == atFridge) {
state = CheckingFoodSupply;
type = checkFoodSupply();
return true;
}
if (state == CheckingFoodSupply && event == EmptyFridge) {
state = LeavingHome; // LeavingRestaurant
exitHome();
return true;
}
if (state == CheckingFoodSupply && event == collectedIngredients) {
state = Cooking;
goToStove(type);
return true;
}
if (state == Cooking && event == doneCooking) {
state = Plating;
goToPlatingArea();
return true;
}
if (state == Plating && event == donePlating) {
state = Eating;
goToTable();
return true;
}
if (state == Eating && event == doneEating) {
state = Clearing;
goToSink();
return true;
}
if (state == Clearing && event == doneClearing) {
state = DoingNothing;
returnToHomePosition();
return true;
}
if((myPerson.hungerState == HungerState.FeedingHunger ||
myPerson.hungerState == HungerState.Famished ||
myPerson.hungerState == HungerState.Hungry ||
myPerson.hungerState == HungerState.Starving) && event == none){
state = DoingNothing;
gotHungry();
return true;
}
if (state == DoingNothing && event == gotSleepy)
state = Sleeping;
goToBed();
return true;
}
if(state == DoingNothing && event == none) {
state = checkingMailbox;
return true;
}
}
ACTIONS
//checking mailbox when walking in and paying rent bills
public void goToMailbox() {
residentGui.DoGoToMailbox();
}
public void checkMail() {
if (rentBills.size() > 0) {
event = payRent;
}
else {
event = none;
}
}
public void payRent(List<RentBill> rentBills) {
for (RentBill rb : rentBills) {
if (rb.state == RentState.NotPaid) {
myPerson.goPayBill(rb);
}
}
event = none;
}
//checking grocery bag when walking in and putting groceries in fridge
public void checkGroceryBag() {
if (groceryBag.size() > 0) {
event = putGroceriesInFridge;
} else
event = none;
}
public void goToFridge() {
residentGui.DoGoToFridge();
}
public void putGroceriesInFridge(Map<String, Integer> groceryBag) {
groceryBag = myPerson.groceryBag;
int temp = groceryBag.get("Chicken");
fridgeFoods.get("Chicken").setAmount(groceryBag.get("Chicken"));
fridgeFoods.get("Steak").setAmount(fridgeFoods.get("Steak").getAmount() + groceryBag.get("Steak"));
checkedGroceryBag = false;
myPerson.groceryBag.clear();
event = none;
}
//got hungry events
public void gotHungry() {
System.out.println("I'm hungry");
event = gotHungry;
stateChanged();
}
public String checkFoodSupply() {
if(!myPerson.groceryBag.isEmpty())
putGroceriesInFridge(myPerson.groceryBag);
String choice = randomizeFoodChoice();
Food f = fridgeFoods.get(choice);
if (checkInventory(f)) {
int amount = f.getAmount() - 1;
f.setAmount(amount);
if (amount <= f.getLowThreshold()) {
addToGroceryList(f);
}
event = collectedIngredients;
} else {
addToGroceryList(f);
event = EmptyFridge;
}
if(myPerson.moneyState != MoneyState.Low){
event = HomeEvent.EmptyFridge;
}
return choice;
}
public void goToStove(String type) {
residentGui.DoGoToStove();
}
public void atStove() {
Food myChoice = new Food(type);
DoCooking(myChoice); // cooking timer
}
private void DoCooking(Food f) {
int cookingTime = f.getCookingTime();
timer.schedule(new TimerTask() {
public void run() {
event = doneCooking;
stateChanged();
}
}, cookingTime * 150);
}
public void goToPlatingArea() {
residentGui.DoGoToPlatingArea();
}
public void atPlatingArea() {
DoPlating();
}
private void DoPlating() {
System.out.println("Do plating");
timer.schedule(new TimerTask() {
public void run() {
print("done plating statechanged");
event = HomeEvent.donePlating;
stateChanged();
}
}, 1500);
//residentGui.plating = false;
}
public void goToTable() {
residentGui.DoGoToTable();
}
public void AtTable() {
DoEatFood();
}
public void DoEatFood(){
timer.schedule(new TimerTask() {
public void run() {
event = doneEating;
hungry = false;
myPerson.justAte();
}
}, 1500);
}
public void goToSink() {
residentGui.DoClearFood();
}
public void atSink() {
clearFood();
}
public void clearFood() {
stateChanged();
timer.schedule(new TimerTask() {
public void run() {
event = doneClearing;
stateChanged();
}
}, 1500);
}
//leaving home
public void exitHome() {
residentGui.DoExitHome();
state = LeftHouse;
event = LeftHouse;
}
public void returnToHomePosition() {
residentGui.DoReturnToHomePosition();
event = none;
}
public void goToBed() {
residentGui.DoGoToBed();
DoSleeping();
}
public void atBed() {
residentGui.sleeping = true;
event = doneSleeping;
}
public void exited() {
myPerson.leftBuilding(this);
}
private boolean checkInventory(Food f) {
int amount = f.getAmount();
if (amount > 0) {
return true;
}
return false;
}
private void addToGroceryList(Food f) {
groceryList.put(f.getType(), f.getCapacity());
myPerson.homeNeedsGroceries(groceryList);
}
Landlord
DATA
public PersonAgent person;
public float rent;
private List<RentBill> rentBills;
private List<Home> homesOwned ;
int currentTime;
int timeToSendBills;
Random random = new Random();
public enum HomeOwnerState {none, sendBills, sendingBills, billsSent}
private HomeOwnerState hOwnerState = HomeOwnerState.none;//The start state
//messages
public void msgSendRentBills() { //message from World Clock Timer
hOwnerState = sendBills;
stateChanged();
}
//scheduler
public boolean pickAndExecuteAnAction() {
if(hOwnerState == sendBills){
hOwnerState = sendingBills;
sendRentBills();
return true;
}
return false;
}
//actions
public void sendRentBills() {
for(Home h: homesOwned) {
RentBill rb;
rb = myPerson.new RentBill(myPerson, rent);
rentBills.add(rb);
h.setRentBills(rentBills);
}
}
private float getRent() {
rent = random.nextInt(14) + 1; //randomizes rent amount from $1-15
return rent;
}
###General Design
####PersonAgent Design Some Images
A PRELIMINARY design where we control the person.
Data
float money;
Clock currentTime;
List<Role> roles;
List<BuildingAgent> properties;
List<Restaurant> restaurants;
List<Market> markets;
Bank bank;
Home myHome;
enum TransportationState {walking, bus, car}
enum MoneyState {plenty, low, processing, needToDeposit, broke}
enum HomeRentState {payBill, payingBill, billPaid, noBillToPay}
enum WorkState {offWork, timeForWork, headedToWork, atWork, timeToLeaveWork, leavingWork}
enum EatingState {eatAtRestaurant, headedToRestaurant, eatingAtRestaurant, eatAtHome, headedToHome, eatingAtHome, getGroceries, gettingGroceries}
enum currentLocation {}
List<RentBill> rentBills;
class RentBill {
enum state;
float amount;
s
}
class Job {state, Role role}
//Job myJob;
Restaurant currentRestaurantPreference;
//Some sort of a task/Errand list using a TaskState?
Gui Messages
eatAtRestaurant(Restaurant r) {EatingState = eatAtRestaurant}
eatAtHome() { EatingState = eatAtHome}
hereIsMoney(float amount) {money += amount; }
preferredTransportation(String type) {TransportationState = makeState(type);}
Role Messages
homeNeedsGroceries() {
//The customer can get a default grocery list for now
//May also need to set grocery buying to a different state than eating
EatingState = getGroceries;
}
goPayBill(RentBill rb) {
RentState = payBill;
rentBills.add(rb);
}
doneEatingAtRestaurant() {
//time to leave
roles.remove(roles.find(customerRole));
}
doneAtMarket() {}
doneAtBank() {}
doneWithWork(WorkState = timeToLeaveWork;) {//should receive money magically for now}
goToWork() {WorkState = timeForWork;}
Person Scheduler
Work
if WorkState = timeForWork
then goToWork();
if WorkState = timeToLeaveWork
then leaveWork();
Bill
if there exists rb in RentBills such that rb.state = notPaid
then payBill(rb);
eating
if EatingState = eatAtRestaurant
then eatAtRestaurant();
if EatingState = eatAtHome
then eatAtHome();
if EatingState = getGroceries
then getGroceries();
if
money
if MoneyState = low
then withdrawAtBank();
if MoneyState = high
then depositAtBank();
Actions
goToWork() {
WorkState = goingToWork;
DoGoToWork(job.role.buildingLocation);
roles.add(job.role);
role.gui.DoGoToWaitingArea;
msgRemoveRole(this); //or remove itself directly? myPerson.roles.remove(this);
}
leaveWork() {
WorkState = leavingWork;
job.role.gui.”exitBuilding”;
}
payBill(RentBill rb) {
rb.state = payingBill;
DoGoToBank();
roles.add(new BankCustomer); //The bankCustomer role should check if it has any bills to pay?
}
withdrawAtBank() {
MoneyState = processingNewAmount;
DoGoToBank();
roles.add(new BankCustomer); // The bankCustomer role should check its money amount to see how much needs to be withdrawn/deposited. If we do this, then we don’t need the next function - “DepositAtBank()”
}
depositAtBank() {
}
eatAtRestaurant() {
EatingState = headedToRestaurant;
DoGoToRestaurant(currentRestaurantPreference);
roles.add(new RestaurantCustomer);
}
eatAtHome() {
EatingState = headedToHome;
DoGoToHome();
roles.add(new HomeResident);
}
getGroceries() {
EatingState = gettingGroceries;
DoGoToMarket();
roles.add(new MarketCustomer);
}
A v1 design of Person.
public class PersonAgent {
Data:
int currentTime //(ranges from 1-24)
public int accountNumber
Semaphore busyWithTask = new Semaphore(0, false)
double money = 0.0
protected List<Role> roles = new ArrayList<Role>()
public Map<String, Integer> groceryList
public Map<String, Integer> groceryBag
public List<RentBill> rentBills
public boolean checkPersonScheduler = true
PersonGui gui
private LandlordRole landlord
// Locations
public List<Restaurant> restaurants
public Restaurant currentPreference
private int restaurantCounter=0
public List<Market> markets
public Bank bank
private boolean shelter = false
private Home myHome
public Building currentBuilding = spawnPoint
public Building currentDestination = spawnPoint
//States - Currently the states are private. If need be, we can change them to public so our roles can see them
//Preferred Transportation
public enum TransportationState {Walking, Bus, Car}
public TransportationState transportationState = TransportationState.Walking
//Where to eat
public enum EatingState {EatAtHome, HeadedToHome, EatingAtHome, Nowhere, EatAtRestaurant, HeadedtoRestaurant, EatingAtRestaurant}
public EatingState eatingState = EatingState.Nowhere
//When to eat
public enum HungerState {NotHungry, Famished, Hungry, Starving, FeedingHunger}
public int hungerCount = 0
public HungerState hungerState = HungerState.NotHungry
//Going to the market states
public enum MarketState {GetGroceries, GettingGroceries, HaveGroceries, TakeGroceriesHome, TakingGroceriesHome}
public MarketState marketState = MarketState.HaveGroceries
//Keep track of money
public enum MoneyState{Low, High, Neutral}
public MoneyState moneyState = MoneyState.Neutral
//Job
private Job myJob
public enum JobState {
OffWork, GoToWorkSoon, HeadedToWork, AtWork, LeaveWork, LeavingWork
}
public class Job {
public JobState state = JobState.OffWork
int onWork = 8 // 8am
int offWork = 17 // military hours - 17 == 5pm
Role role
String type
Building workplace
// Job Constructor
public Job(Role r, Building w) {
role = r
workplace = w
}
public Job(Role r, String type, Building w) {
role = r
this.type = type
workplace = w
}
public void setJob(Role r, Building w) {
role = r
workplace = w
}
}
// Paying Rent
// When to pay rent
public enum RentState {
Paid, NotPaid, PayingBill
}
public class RentBill {
public RentState state = RentState.NotPaid
public PersonAgent accountHolder
public float amount
public RentBill(PersonAgent p, float a) {
accountHolder = p
amount = a
}
}
Messages:
//Messages from World Clock
public void updateTime(int time) {
currentTime = time
hungerCount++
if(hungerCount > 11 && hungerState != HungerState.Starving &&
hungerState != HungerState.FeedingHunger) {
hungerState = HungerState.Starving
}
else if(hungerCount > 7 && hungerState != HungerState.Hungry &&
hungerState != HungerState.FeedingHunger &&
hungerState != HungerState.Starving) {
hungerState = HungerState.Hungry
}
else if(hungerCount > 3 && hungerState != HungerState.Famished &&
hungerState != HungerState.FeedingHunger &&
hungerState != HungerState.Starving &&
hungerState != HungerState.Hungry) {
hungerState = HungerState.Famished
}
if(myJob != null) {
if(currentTime == myJob.onWork) {
myJob.state = JobState.GoToWorkSoon
}
is atWork
else if (currentTime == myJob.offWork) {
myJob.state = JobState.LeaveWork
checkPersonScheduler = true
}
}
if (money <= low && moneyState != MoneyState.Low) {
moneyState = MoneyState.Low
} else if (money >= high && moneyState != MoneyState.High) {
moneyState = MoneyState.High
moneyState = MoneyState.Neutral
}
stateChanged()
}
public void reachedBuilding() {
currentBuilding = currentDestination
busyWithTask.release()
}
public void leftBuilding(Role role) {
checkPersonScheduler = true
role.setActive(false)
role.getScreen()
gui.getHomeScreen().addGui(gui)
roles.remove(role)
}
public void enteringBuilding(Role role){
roles.add(role)
role.setActive(true)
gui.getHomeScreen().removeGui(gui)
role.getScreen()
role.startBuildingMessaging()
stateChanged()
}
public void eatAtHome() {
if(!shelter) {
eatingState = EatingState.EatAtHome
}
}
public void homeNeedsGroceries(Map<String, Integer> foods) {
groceryList = foods
marketState = MarketState.GetGroceries
}
public void goPayBill(RentBill rb) {
rentBills.add(rb)
}
public void justAte() {
hungerState = HungerState.NotHungry
hungerCount = 0
}
Scheduler:
public boolean pickAndExecuteAnAction() {
if(checkPersonScheduler) {
if(marketState == MarketState.TakeGroceriesHome) {
marketState = MarketState.TakingGroceriesHome
goToHome()
return true
}
if(hungerState == HungerState.Starving && marketState != MarketState.GetGroceries &&
marketState != MarketState.GettingGroceries) {
if(moneyState == MoneyState.Low) {
hungerState = HungerState.FeedingHunger
goToHome()
return true
}
else {
hungerState = HungerState.FeedingHunger
goEatAtRestaurant()
return true
}
}
if(myJob != null) {
if(myJob.state == JobState.GoToWorkSoon){
goToWork()
return true
}
else if(myJob.state == JobState.LeaveWork && myJob.state == JobState.AtWork) {
leaveWork()
return true
}
}
if(hungerState == HungerState.Hungry) {
if(moneyState == MoneyState.Low) {
hungerState = HungerState.FeedingHunger
goToHome()
return true
}
else {
hungerState = HungerState.FeedingHunger
goEatAtRestaurant()
return true
}
}
for(RentBill rb : rentBills) {
if(rb.state == RentState.NotPaid){
goToBank()
return true
}
}
if(eatingState == EatingState.EatAtHome) {
goToHome()
return true
}
else if(eatingState == EatingState.EatAtRestaurant) {
goEatAtRestaurant()
return true
}
if(hungerState == HungerState.Famished) {
if(moneyState == MoneyState.Low) {
hungerState = HungerState.FeedingHunger
goToHome()
return true
}
else {
hungerState = HungerState.FeedingHunger
goEatAtRestaurant()
return true
}
}
if(marketState == MarketState.GetGroceries) {
goGetGroceries()
return true
}
if(moneyState == MoneyState.Low || moneyState == MoneyState.High) {
if(currentBuilding != bank){
goToBank()
return true
}
}
if(currentBuilding != myHome) {
goToHome()
return true
}
}
for(Role r : roles) {
if(r.isActive()) {
if(r.pickAndExecuteAnAction()) {
return true
}
}
}
return false
}
Actions:
goToWork{
gui.DoGoToLocation(myJob.workplace.getEntranceLocation())
roles.add(myJob.role)
myJob.role.setActive(true)
checkPersonScheduler = false
}
private void leaveWork() {
money += 100
roles.remove(myJob.role)
gui.DoGoToLocation(myHome.getEntranceLocation())
}
private void goToHome() {
if(myHome != null) {
if(currentBuilding != myHome) {
gui.DoGoToLocation(myHome.getEntranceLocation())
}
homeTemp = myHome.resident
homeTemp.setActive(true)
currentBuilding = myHome
homeGui = new ResidentGui.get
homeGui.setHomeScreen(ScreenFactory.getMeScreen("Home"))
homeTemp.setGui(homeGui)
homeTemp.setPerson(this)
enteringBuilding(homeTemp)
checkPersonScheduler = false
}
else {
gui.DoGoToLocation(new Location(26, 580, "Default"))
}
}
private void goEatAtRestaurant() {
gui.DoGoToLocation(currentPreference.getEntranceLocation())
eatingState = EatingState.HeadedtoRestaurant
if("Restaurant 1"){
restTemp = RoleFactory.makeMeRole(currentPreference.getCustomerName())
restGui = new Restaurant1CustomerGui((Restaurant1CustomerRole)restTemp, ScreenFactory.getMeScreen(currentPreference.getName()))
}
else if("Restaurant 3") {
restTemp = RoleFactory.makeMeRole(currentPreference.getCustomerName())
restGui = new Restaurant3CustomerGui((Restaurant3CustomerRole)restTemp, ScreenFactory.getMeScreen(currentPreference.getName()))
}
else if ("Restaurant 2") {
restTemp = RoleFactory.makeMeRole(currentPreference.getCustomerName())
restGui = new Restaurant2CustomerGui((Restaurant2CustomerRole)restTemp, ScreenFactory.getMeScreen(currentPreference.getName()))
}
else if(Restaurant 4”) {
restTemp = RoleFactory.makeMeRole(currentPreference.getCustomerName())
restGui = new Restaurant4CustomerGui((Restaurant4CustomerRole)restTemp, ScreenFactory.getMeScreen(currentPreference.getName()))
}
else if(Restaurant 5") {
restTemp = RoleFactory.makeMeRole(currentPreference.getCustomerName())
restGui = new Restaurant5CustomerGui((Restaurant5CustomerRole)restTemp, ScreenFactory.getMeScreen(currentPreference.getName()))
}
restTemp.setPerson(this)
restGui.setHomeScreen(ScreenFactory.getMeScreen(currentPreference.getName()))
checkPersonScheduler = false
restTemp.setGui(restGui)
currentBuilding = currentPreference
enteringBuilding(restTemp)
currentPreference = restaurants.get(restaurantCounter)
restaurantCounter++
if(restaurantCounter >4)
restaurantCounter =0
}
private void goGetGroceries() {
marketState = MarketState.GettingGroceries
for(Market m : markets){
gui.DoGoToLocation(m.getEntranceLocation())
}
marketRoleTemp = RoleFactory.makeMeRole("marketCustomer")
currentBuilding = markets.get(0)
MarketCustomerRole tempMarketCustomerRole = (MarketCustomerRole)marketRoleTemp
marketGui = new MarketCustomerGui((MarketCustomerRole)marketRoleTemp, ScreenFactory.getMeScreen("Market"))
marketRoleTemp.setPerson(this)
marketGui.setHomeScreen(ScreenFactory.getMeScreen("Market"))
activeRole = marketRoleTemp
checkPersonScheduler = false
roles.add(marketRoleTemp)
marketRoleTemp.setGui(marketGui)
enteringBuilding(marketRoleTemp)
}
private void goToBank() {
currentDestination = bank
gui.DoGoToLocation(bank.getEntranceLocation())
currentBuilding = bank
bankRoleTemp = RoleFactory.makeMeRole("bankCustomer")
bankGui = new bankCustomerGui((BankCustomerRole)bankRoleTemp, ScreenFactory.getMeScreen("Bank"))
bankRoleTemp.setPerson(this)
bankGui.setHomeScreen(ScreenFactory.getMeScreen("Bank"))
bankRoleTemp.setGui(bankGui)
enteringBuilding(bankRoleTemp)
checkPersonScheduler = false
}
####Gui Stuff ![Gui_1] (https://raw.github.com/usc-csci201-fall2013/team31/master/docs/Gui_Frames.JPG?token=4757129__eyJzY29wZSI6IlJhd0Jsb2I6dXNjLWNzY2kyMDEtZmFsbDIwMTMvdGVhbTMxL21hc3Rlci9kb2NzL0d1aV9GcmFtZXMuSlBHIiwiZXhwaXJlcyI6MTM4NzMzOTExNH0%3D--965e76d33029a747a52ec1e37fa404791f36ee60) ![Gui_2] (https://raw.github.com/usc-csci201-fall2013/team31/master/docs/Gui_design.JPG?token=4757129__eyJzY29wZSI6IlJhd0Jsb2I6dXNjLWNzY2kyMDEtZmFsbDIwMTMvdGVhbTMxL21hc3Rlci9kb2NzL0d1aV9kZXNpZ24uSlBHIiwiZXhwaXJlcyI6MTM4NzMzOTE3M30%3D--ac83cd60f1a7bd6d0a10cf5f38df1e632e5e7c6f) ![Gui_3] (https://raw.github.com/usc-csci201-fall2013/team31/master/docs/Gui_design_2.JPG?token=4757129__eyJzY29wZSI6IlJhd0Jsb2I6dXNjLWNzY2kyMDEtZmFsbDIwMTMvdGVhbTMxL21hc3Rlci9kb2NzL0d1aV9kZXNpZ25fMi5KUEciLCJleHBpcmVzIjoxMzg3MzM5MjEyfQ%3D%3D--1be646b368538b282eab94b890380e9d2545d443)
All visual represenations of PersonAgents are displayed via using a RoleGui class that contains information about spriting, background color, and movement.
RoleGui
class RoleGui {
int xPos, yPos
int xDestination, yDestination
static int speed = 2 //how many pixels moved at a time
int repeat, repeatBuffer = 10//determines how long to wait before switching image
enum Orientation{North, South, East, West}
Orientation o
ImageIcon current, south1, south2, west1, west2, east1, east2, north1, north2
static final int guiSize = 20
Color myColor
Screen homeScreen
void updatePosition(){
Orientation temp = o
if (xPos < xDestination){
xPos+=speed
o = Orientation.East
}
else if (xPos > xDestination){
xPos-=speed
o = Orientation.West
}
if (yPos < yDestination){
yPos+=speed
o = Orientation.South
}
else if (yPos > yDestination){
yPos-=speed
o = Orientation.North
}
if(!(temp == o)){
repeat = 0
}
updateImage()
}
void updateImage(){
if(o == Orientation.North)
{
if(repeat > repeatBuffer){
if(current == north1){
current = north2
}
else{
current = north1
}
repeat = 0
}
else{
repeat++
}
}
else if(o == Orientation.South)
{
if(repeat > repeatBuffer){
if(current == south1){
current = south2
}
else{
current = south1
}
repeat = 0
}
else{
repeat++
}
}
else if(o == Orientation.East)
{
if(repeat > repeatBuffer){
if(current == east1){
current = east2
}
else{
current = east1
}
repeat = 0
}
else{
repeat++
}
}
else if(o == Orientation.West)
{
if(repeat > repeatBuffer){
if(current == west1){
current = west2
}
else{
current = west1
}
repeat = 0
}
else{
repeat++
}
}
else
}
void draw(Graphics g){
g.setColor(myColor)
g.fillRect(xPos, yPos, guiSize, guiSize)
g.drawImage(current.getImage(), xPos, yPos, null)
}
}
The Screen class contains all of the Gui and background (context) information. A screen factory is used to access Screens throughout the program.
class Screen
{
List<RoleGui> guis = Collections.synchronizedList( new ArrayList<RoleGui>())
String loc = ""
int xCord, yCord
void addGui(RoleGui g1){
synchronized(guis){
guis.add(g1)
}
}
void removeGui(RoleGui g1){
synchronized(guis){
guis.remove(g1)
}
}
void updateAgents(){
synchronized(guis) {
for (int a = 0 a < guis.size() a++) {//RoleGui gui : guis) {
guis.get(a).updatePosition()
}
}
}
void paintAgents(Graphics g){
synchronized(guis) {
for (RoleGui gui : guis) {
gui.draw(g)
}
}
}
void paintBackground(Graphics g)
{
g.setColor(Color.white)
g.fillRect(0,0,1000, 800)
g.setColor(Color.black)
{
g.fillRect(25,50,20,20)//the up one screen button
}
}
String checkSwap(int x, int y){
if((x>25)&&(x<45)&&(y>50)&&(y<70)){
return "City"
}
List<RoleGui> getGuis(){
return guis
}
String printGuiList(){
return guis.toString()
}
}
###Other Design Comments