-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayerTrading.cs
More file actions
338 lines (305 loc) · 12.5 KB
/
PlayerTrading.cs
File metadata and controls
338 lines (305 loc) · 12.5 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// how trading works:
// 1. A invites his target with CmdTradeRequest()
// -> sets B.tradeInvitationFrom = A;
// 2. B sees a UI window and accepts (= invites A too)
// -> sets A.tradeInvitationFrom = B;
// 3. the TradeStart event is fired, both go to 'TRADING' state
// 4. they lock the trades
// 5. they accept, then items and gold are swapped
using System.Collections.Generic;
using UnityEngine;
using Mirror;
namespace uMMORPG
{
public enum TradingState { Free, Locked, Accepted }
[RequireComponent(typeof(Player))]
[RequireComponent(typeof(PlayerInventory))]
[DisallowMultipleComponent]
public class PlayerTrading : NetworkBehaviour
{
[Header("Components")]
public Player player;
public PlayerInventory inventory;
[Header("Trading")]
[SyncVar, HideInInspector] public string requestFrom = "";
[SyncVar, HideInInspector] public TradingState state = TradingState.Free;
[SyncVar, HideInInspector] public long offerGold = 0;
public readonly SyncList<int> offerItems = new SyncList<int>(); // inventory indices
public override void OnStartServer()
{
// initialize trade item indices
for (int i = 0; i < 6; ++i)
offerItems.Add(-1);
}
// player to player trading ////////////////////////////////////////////////
public bool CanStartTrade()
{
// a player can only trade if he is not trading already and alive
return player.health.current > 0 && player.state != "TRADING";
}
public bool CanStartTradeWith(Entity entity)
{
// can we trade? can the target trade? are we close enough?
return entity != null &&
entity is Player other &&
other != player &&
CanStartTrade() &&
other.trading.CanStartTrade() &&
Utils.ClosestDistance(player, entity) <= player.interactionRange;
}
// request a trade with the target player.
[Command]
public void CmdSendRequest()
{
// validate
if (CanStartTradeWith(player.target))
{
// send a trade request to target
((Player)player.target).trading.requestFrom = name;
Debug.Log(name + " invited " + player.target.name + " to trade");
}
}
// helper function to find the guy who sent us a trade invitation
[Server]
public Player FindPlayerFromInvitation()
{
if (requestFrom != "" &&
Player.onlinePlayers.TryGetValue(requestFrom, out Player sender))
{
return sender;
}
return null;
}
// accept a trade invitation by simply setting 'requestFrom' for the other
// person to self
[Command]
public void CmdAcceptRequest()
{
Player sender = FindPlayerFromInvitation();
if (sender != null)
{
if (CanStartTradeWith(sender))
{
// also send a trade request to the person that invited us
sender.trading.requestFrom = name;
Debug.Log(name + " accepted " + sender.name + "'s trade request");
}
}
}
// decline a trade invitation
[Command]
public void CmdDeclineRequest()
{
requestFrom = "";
}
[Server]
public void Cleanup()
{
// clear all trade related properties
offerGold = 0;
for (int i = 0; i < offerItems.Count; ++i)
offerItems[i] = -1;
state = TradingState.Free;
requestFrom = "";
}
[Command]
public void CmdCancel()
{
// validate
if (player.state == "TRADING")
{
// clear trade request for both guys. the FSM event will do the rest
Player other = FindPlayerFromInvitation();
if (other != null)
other.trading.requestFrom = "";
requestFrom = "";
}
}
[Command]
public void CmdLockOffer()
{
// validate
if (player.state == "TRADING")
state = TradingState.Locked;
}
[Command]
public void CmdOfferGold(long amount)
{
// validate
if (player.state == "TRADING" && state == TradingState.Free &&
0 <= amount && amount <= player.gold)
offerGold = amount;
}
[Command]
public void CmdOfferItem(int inventoryIndex, int offerIndex)
{
// validate
if (player.state == "TRADING" && state == TradingState.Free &&
0 <= offerIndex && offerIndex < offerItems.Count &&
!offerItems.Contains(inventoryIndex) && // only one reference
0 <= inventoryIndex && inventoryIndex < inventory.slots.Count)
{
ItemSlot slot = inventory.slots[inventoryIndex];
if (slot.amount > 0 && slot.item.tradable && !slot.item.summoned)
offerItems[offerIndex] = inventoryIndex;
}
}
[Command]
public void CmdClearOfferItem(int offerIndex)
{
// validate
if (player.state == "TRADING" && state == TradingState.Free &&
0 <= offerIndex && offerIndex < offerItems.Count)
offerItems[offerIndex] = -1;
}
bool IsInventorySlotTradable(int index)
{
return 0 <= index && index < inventory.slots.Count &&
inventory.slots[index].amount > 0 &&
inventory.slots[index].item.tradable;
}
[Server]
bool IsOfferStillValid()
{
// not enough gold? then invalid
if (player.gold < offerGold)
return false;
// all offered items are -1 or valid?
// (avoid Linq because it is HEAVY(!) on GC and performance)
foreach (int index in offerItems)
{
if (index == -1 || IsInventorySlotTradable(index))
{
// good
}
else
{
// invalid item
return false;
}
}
return true;
}
[Server]
int OfferItemSlotAmount()
{
// (avoid Linq because it is HEAVY(!) on GC and performance)
int count = 0;
foreach (int index in offerItems)
if (index != -1)
++count;
return count;
}
[Server]
int InventorySlotsNeededForTrade()
{
// if other guy offers 2 items and we offer 1 item then we only need
// 2-1 = 1 slots. and the other guy would need 1-2 slots and at least 0.
if (player.target != null &&
player.target is Player other)
{
int otherAmount = other.trading.OfferItemSlotAmount();
int myAmount = OfferItemSlotAmount();
return Mathf.Max(otherAmount - myAmount, 0);
}
return 0;
}
[Command]
public void CmdAcceptOffer()
{
// validate
// note: distance check already done when starting the trade
if (player.state == "TRADING" && state == TradingState.Locked &&
player.target != null &&
player.target is Player other)
{
// other has locked?
if (other.trading.state == TradingState.Locked)
{
// simply accept and wait for the other guy to accept too
state = TradingState.Accepted;
Debug.Log("first accept by " + name);
}
// other has accepted already? then both accepted now, start trade.
else if (other.trading.state == TradingState.Accepted)
{
// accept
state = TradingState.Accepted;
Debug.Log("second accept by " + name);
// both offers still valid?
if (IsOfferStillValid() && other.trading.IsOfferStillValid())
{
// both have enough inventory slots?
// note: we don't use InventoryCanAdd here because:
// - current solution works if both have full inventories
// - InventoryCanAdd only checks one slot. here we have
// multiple slots though (it could happen that we can
// not add slot 2 after we did add slot 1's items etc)
if (inventory.SlotsFree() >= InventorySlotsNeededForTrade() &&
other.inventory.SlotsFree() >= other.trading.InventorySlotsNeededForTrade())
{
// exchange the items by first taking them out
// into a temporary list and then putting them
// in. this guarantees that exchanging even
// works with full inventories
// take them out
Queue<ItemSlot> tempMy = new Queue<ItemSlot>();
foreach (int index in offerItems)
{
if (index != -1)
{
ItemSlot slot = inventory.slots[index];
tempMy.Enqueue(slot);
slot.amount = 0;
inventory.slots[index] = slot;
}
}
Queue<ItemSlot> tempOther = new Queue<ItemSlot>();
foreach (int index in other.trading.offerItems)
{
if (index != -1)
{
ItemSlot slot = other.inventory.slots[index];
tempOther.Enqueue(slot);
slot.amount = 0;
other.inventory.slots[index] = slot;
}
}
// put them into the free slots
for (int i = 0; i < inventory.slots.Count; ++i)
if (inventory.slots[i].amount == 0 && tempOther.Count > 0)
inventory.slots[i] = tempOther.Dequeue();
for (int i = 0; i < other.inventory.slots.Count; ++i)
if (other.inventory.slots[i].amount == 0 && tempMy.Count > 0)
other.inventory.slots[i] = tempMy.Dequeue();
// did it all work?
if (tempMy.Count > 0 || tempOther.Count > 0)
Debug.LogWarning("item trade problem");
// exchange the gold
player.gold -= offerGold;
other.gold -= other.trading.offerGold;
player.gold += other.trading.offerGold;
other.gold += offerGold;
}
}
else Debug.Log("trade canceled (invalid offer)");
// clear trade request for both guys. the FSM event will do the
// rest
requestFrom = "";
other.trading.requestFrom = "";
}
}
}
// drag & drop /////////////////////////////////////////////////////////////
void OnDragAndDrop_InventorySlot_TradingSlot(int[] slotIndices)
{
// slotIndices[0] = slotFrom; slotIndices[1] = slotTo
if (inventory.slots[slotIndices[0]].item.tradable)
CmdOfferItem(slotIndices[0], slotIndices[1]);
}
void OnDragAndClear_TradingSlot(int slotIndex)
{
CmdClearOfferItem(slotIndex);
}
}
}