File size: 14,971 Bytes
4c75d73 |
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 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
"""
Trading System Plugin for MMORPG
Adds player-to-player trading and marketplace functionality
"""
from src.interfaces.plugin_interfaces import IEconomyPlugin, PluginMetadata, PluginType
from typing import Dict, List, Any, Optional
import time
import uuid
class TradingSystemPlugin(IEconomyPlugin):
"""Plugin that adds comprehensive trading and marketplace features."""
def __init__(self):
self._metadata = PluginMetadata(
id="trading_system",
name="Trading System",
version="1.1.0",
author="MMORPG Dev Team",
description="Adds player trading, marketplace, and auction features",
plugin_type=PluginType.SERVICE,
dependencies=["enhanced_chat"], # Depends on chat for trade messages
config={
"enable_direct_trading": True,
"enable_marketplace": True,
"trade_tax_rate": 0.05,
"max_trade_distance": 100
}
)
self._enabled = False
self._active_trades = {} # Trade sessions
self._marketplace_listings = {} # Marketplace items
self._trade_history = []
# Sample items for trading
self._tradeable_items = {
"health_potion": {"name": "Health Potion", "base_value": 10, "stackable": True},
"mana_potion": {"name": "Mana Potion", "base_value": 15, "stackable": True},
"iron_sword": {"name": "Iron Sword", "base_value": 50, "stackable": False},
"wooden_shield": {"name": "Wooden Shield", "base_value": 30, "stackable": False},
"magic_scroll": {"name": "Magic Scroll", "base_value": 25, "stackable": True},
"gold_coin": {"name": "Gold Coin", "base_value": 1, "stackable": True} }
@property
def metadata(self) -> PluginMetadata:
return self._metadata
def initialize(self, context: Dict[str, Any]) -> bool:
"""Initialize the trading system plugin."""
try:
self._config = self._metadata.config
self._enabled = True
print(f"🏪 Trading System Plugin initialized with {len(self._tradeable_items)} tradeable items")
return True
except Exception as e:
print(f"🏪 Failed to initialize Trading System Plugin: {e}")
return False
def cleanup(self) -> None:
"""Clean up trading system resources."""
# Cancel all active trades
for trade_id in list(self._active_trades.keys()):
self.cancel_trade(trade_id)
self._enabled = False
print("💰 Trading System Plugin cleaned up")
def is_enabled(self) -> bool:
return self._enabled
def initiate_trade(self, player1_id: str, player2_id: str, player1_pos: tuple, player2_pos: tuple) -> Dict[str, Any]:
"""Initiate a trade between two players."""
if not self._enabled or not self._config.get("enable_direct_trading", True):
return {"success": False, "error": "Trading is disabled"}
# Check distance
max_distance = self._config.get("max_trade_distance", 100)
distance = ((player1_pos[0] - player2_pos[0]) ** 2 + (player1_pos[1] - player2_pos[1]) ** 2) ** 0.5
if distance > max_distance:
return {"success": False, "error": "Players are too far apart to trade"}
# Create trade session
trade_id = str(uuid.uuid4())
trade_session = {
"id": trade_id,
"player1": player1_id,
"player2": player2_id,
"player1_items": {},
"player2_items": {},
"player1_gold": 0,
"player2_gold": 0,
"player1_accepted": False,
"player2_accepted": False,
"status": "active",
"created_at": time.time()
}
self._active_trades[trade_id] = trade_session
return {
"success": True,
"trade_id": trade_id,
"message": f"Trade initiated between players {player1_id} and {player2_id}"
}
def add_item_to_trade(self, trade_id: str, player_id: str, item_id: str, quantity: int = 1) -> Dict[str, Any]:
"""Add an item to a trade."""
if trade_id not in self._active_trades:
return {"success": False, "error": "Trade not found"}
trade = self._active_trades[trade_id]
if trade["status"] != "active":
return {"success": False, "error": "Trade is not active"}
# Determine which player
if player_id == trade["player1"]:
items_dict = trade["player1_items"]
elif player_id == trade["player2"]:
items_dict = trade["player2_items"]
else:
return {"success": False, "error": "Player not part of this trade"}
# Add item
if item_id not in items_dict:
items_dict[item_id] = 0
items_dict[item_id] += quantity
# Reset acceptance status
trade["player1_accepted"] = False
trade["player2_accepted"] = False
return {
"success": True,
"message": f"Added {quantity}x {self._tradeable_items.get(item_id, {}).get('name', item_id)} to trade"
}
def add_gold_to_trade(self, trade_id: str, player_id: str, amount: int) -> Dict[str, Any]:
"""Add gold to a trade."""
if trade_id not in self._active_trades:
return {"success": False, "error": "Trade not found"}
trade = self._active_trades[trade_id]
if trade["status"] != "active":
return {"success": False, "error": "Trade is not active"}
# Determine which player and update gold
if player_id == trade["player1"]:
trade["player1_gold"] += amount
elif player_id == trade["player2"]:
trade["player2_gold"] += amount
else:
return {"success": False, "error": "Player not part of this trade"}
# Reset acceptance status
trade["player1_accepted"] = False
trade["player2_accepted"] = False
return {"success": True, "message": f"Added {amount} gold to trade"}
def accept_trade(self, trade_id: str, player_id: str) -> Dict[str, Any]:
"""Accept a trade."""
if trade_id not in self._active_trades:
return {"success": False, "error": "Trade not found"}
trade = self._active_trades[trade_id]
if trade["status"] != "active":
return {"success": False, "error": "Trade is not active"}
# Mark player as accepted
if player_id == trade["player1"]:
trade["player1_accepted"] = True
elif player_id == trade["player2"]:
trade["player2_accepted"] = True
else:
return {"success": False, "error": "Player not part of this trade"}
# Check if both players accepted
if trade["player1_accepted"] and trade["player2_accepted"]:
return self._complete_trade(trade_id)
return {"success": True, "message": "Trade accepted, waiting for other player"}
def cancel_trade(self, trade_id: str) -> Dict[str, Any]:
"""Cancel a trade."""
if trade_id not in self._active_trades:
return {"success": False, "error": "Trade not found"}
trade = self._active_trades[trade_id]
trade["status"] = "cancelled"
del self._active_trades[trade_id]
return {"success": True, "message": "Trade cancelled"}
def get_trade_status(self, trade_id: str) -> Dict[str, Any]:
"""Get the status of a trade."""
if trade_id not in self._active_trades:
return {"success": False, "error": "Trade not found"}
trade = self._active_trades[trade_id]
return {
"success": True,
"trade": {
"id": trade["id"],
"status": trade["status"],
"player1": trade["player1"],
"player2": trade["player2"],
"player1_items": trade["player1_items"],
"player2_items": trade["player2_items"],
"player1_gold": trade["player1_gold"],
"player2_gold": trade["player2_gold"],
"player1_accepted": trade["player1_accepted"],
"player2_accepted": trade["player2_accepted"]
}
}
def create_marketplace_listing(self, player_id: str, item_id: str, quantity: int, price: int) -> Dict[str, Any]:
"""Create a marketplace listing."""
if not self._enabled or not self._config.get("enable_marketplace", True):
return {"success": False, "error": "Marketplace is disabled"}
listing_id = str(uuid.uuid4())
listing = {
"id": listing_id,
"seller_id": player_id,
"item_id": item_id,
"quantity": quantity,
"price": price,
"created_at": time.time(),
"status": "active"
}
self._marketplace_listings[listing_id] = listing
item_name = self._tradeable_items.get(item_id, {}).get("name", item_id)
return {
"success": True,
"listing_id": listing_id,
"message": f"Listed {quantity}x {item_name} for {price} gold"
}
def get_marketplace_listings(self, item_filter: Optional[str] = None) -> List[Dict[str, Any]]:
"""Get marketplace listings."""
if not self._enabled or not self._config.get("enable_marketplace", True):
return []
listings = []
for listing in self._marketplace_listings.values():
if listing["status"] != "active":
continue
if item_filter and listing["item_id"] != item_filter:
continue
item_info = self._tradeable_items.get(listing["item_id"], {})
listing_info = {
"id": listing["id"],
"seller_id": listing["seller_id"],
"item_id": listing["item_id"],
"item_name": item_info.get("name", listing["item_id"]),
"quantity": listing["quantity"],
"price": listing["price"],
"price_per_unit": listing["price"] / listing["quantity"],
"created_at": listing["created_at"]
}
listings.append(listing_info)
# Sort by price per unit
listings.sort(key=lambda x: x["price_per_unit"])
return listings
def purchase_from_marketplace(self, buyer_id: str, listing_id: str) -> Dict[str, Any]:
"""Purchase an item from the marketplace."""
if listing_id not in self._marketplace_listings:
return {"success": False, "error": "Listing not found"}
listing = self._marketplace_listings[listing_id]
if listing["status"] != "active":
return {"success": False, "error": "Listing is no longer active"}
if listing["seller_id"] == buyer_id:
return {"success": False, "error": "Cannot buy your own listing"}
# Calculate tax
tax_rate = self._config.get("trade_tax_rate", 0.05)
tax_amount = int(listing["price"] * tax_rate)
seller_receives = listing["price"] - tax_amount
# Mark listing as sold
listing["status"] = "sold"
listing["buyer_id"] = buyer_id
listing["sold_at"] = time.time()
# Add to trade history
trade_record = {
"type": "marketplace",
"seller_id": listing["seller_id"],
"buyer_id": buyer_id,
"item_id": listing["item_id"],
"quantity": listing["quantity"],
"price": listing["price"],
"tax_amount": tax_amount,
"timestamp": time.time()
}
self._trade_history.append(trade_record)
item_name = self._tradeable_items.get(listing["item_id"], {}).get("name", listing["item_id"])
return {
"success": True,
"message": f"Purchased {listing['quantity']}x {item_name} for {listing['price']} gold",
"seller_receives": seller_receives,
"tax_paid": tax_amount
}
def get_tradeable_items(self) -> Dict[str, Dict[str, Any]]:
"""Get list of tradeable items."""
return self._tradeable_items.copy()
def _complete_trade(self, trade_id: str) -> Dict[str, Any]:
"""Complete a trade between two players."""
trade = self._active_trades[trade_id]
# Mark trade as completed
trade["status"] = "completed"
trade["completed_at"] = time.time()
# Add to trade history
trade_record = {
"type": "direct_trade",
"player1": trade["player1"],
"player2": trade["player2"],
"player1_items": trade["player1_items"],
"player2_items": trade["player2_items"],
"player1_gold": trade["player1_gold"],
"player2_gold": trade["player2_gold"],
"timestamp": time.time()
}
self._trade_history.append(trade_record)
# Remove from active trades
del self._active_trades[trade_id]
return {
"success": True,
"message": "Trade completed successfully!",
"trade_summary": trade_record
}
def get_status(self) -> Dict[str, Any]:
"""Get trading system status."""
return {
"enabled": self._enabled,
"active_trades": len(self._active_trades),
"marketplace_listings": len(self._marketplace_listings),
"total_items": len(self._tradeable_items),
"trade_history_count": len(self._trade_history)
}
def shutdown(self) -> bool:
"""Shutdown the trading system."""
try:
self.cleanup()
return True
except Exception as e:
print(f"🏪 Error shutting down Trading System Plugin: {e}")
return False
# Plugin entry point
def create_plugin():
"""Factory function to create the plugin instance."""
return TradingSystemPlugin()
|