00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include <algorithm>
00023
00024 #include "game-server/buysell.hpp"
00025
00026 #include "defines.h"
00027 #include "game-server/character.hpp"
00028 #include "game-server/gamehandler.hpp"
00029 #include "game-server/inventory.hpp"
00030 #include "net/messageout.hpp"
00031
00032 BuySell::BuySell(Character *c, bool sell):
00033 mChar(c), mSell(sell)
00034 {
00035 c->setBuySell(this);
00036 }
00037
00038 BuySell::~BuySell()
00039 {
00040 mChar->setBuySell(NULL);
00041 }
00042
00043 void BuySell::cancel()
00044 {
00045 delete this;
00046 }
00047
00048 void BuySell::registerItem(int id, int amount, int cost)
00049 {
00050 if (mSell)
00051 {
00052 int nb = Inventory(mChar).count(id);
00053 if (nb == 0)
00054 return;
00055 if (!amount || nb < amount)
00056 amount = nb;
00057 }
00058
00059 TradedItem it = { id, amount, cost };
00060 mItems.push_back(it);
00061 }
00062
00063 void BuySell::start(Actor *actor)
00064 {
00065 if (mItems.empty())
00066 {
00067 cancel();
00068 return;
00069 }
00070
00071 MessageOut msg(mSell ? GPMSG_NPC_SELL : GPMSG_NPC_BUY);
00072 msg.writeShort(actor->getPublicID());
00073 for (TradedItems::const_iterator i = mItems.begin(),
00074 i_end = mItems.end(); i != i_end; ++i)
00075 {
00076 msg.writeShort(i->itemId);
00077 msg.writeShort(i->amount);
00078 msg.writeShort(i->cost);
00079 }
00080 mChar->getClient()->send(msg);
00081 }
00082
00083 void BuySell::perform(int id, int amount)
00084 {
00085 Inventory inv(mChar);
00086 for (TradedItems::iterator i = mItems.begin(),
00087 i_end = mItems.end(); i != i_end; ++i)
00088 {
00089 if (i->itemId != id) continue;
00090 if (i->amount && i->amount <= amount) amount = i->amount;
00091 if (mSell)
00092 {
00093 amount -= inv.remove(id, amount);
00094 inv.changeMoney(amount * i->cost);
00095 }
00096 else
00097 {
00098 amount = std::min(amount, mChar->getPossessions().money / i->cost);
00099 amount -= inv.insert(id, amount);
00100 inv.changeMoney(-amount * i->cost);
00101 }
00102 if (i->amount)
00103 {
00104 i->amount -= amount;
00105 if (!i->amount)
00106 {
00107 mItems.erase(i);
00108 }
00109 }
00110 return;
00111 }
00112 }