Advertisement
Guest User

CustomEvents - wcs.py

a guest
May 21st, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 58.24 KB | None | 0 0
  1. # =============================================================================
  2. # >> IMPORTS
  3. # =============================================================================
  4. #Python
  5. from base64 import encodestring as estr, decodestring as dstr
  6. from configobj import ConfigObj
  7. import os
  8. from path import Path
  9. from queue import Empty, Queue
  10. import random
  11. from random import choice
  12. from sqlite3 import dbapi2 as sqlite
  13. import string
  14. import sys
  15. from threading import Thread
  16. import time
  17.  
  18. #SourcePython
  19. from colors import Color
  20. from commands import CommandReturn
  21. from commands.say import SayCommand
  22. from commands.client import ClientCommand
  23. from commands.server import ServerCommand
  24. from contextlib import contextmanager
  25. import core
  26. from core import SOURCE_ENGINE_BRANCH
  27. from cvars import ConVar
  28. from engines.server import execute_server_command, queue_command_string
  29. from entities.helpers import index_from_edict
  30. from events import Event
  31. from events.hooks import PreEvent, EventAction
  32. from filters.players import PlayerIter
  33. from listeners import ListenerManager
  34. from listeners import ListenerManagerDecorator
  35. from listeners import OnTick, OnLevelInit, OnLevelShutdown, OnClientActive
  36. from listeners.tick import Delay, Repeat
  37.  
  38. from messages import HudMsg, SayText2, HintText, KeyHintText
  39. from menus import PagedMenu
  40. from menus import PagedOption
  41. from menus import SimpleMenu
  42. from menus import SimpleOption
  43. from menus import Text
  44. from paths import PLUGIN_PATH
  45. from players.dictionary import PlayerDictionary
  46. from players.entity import Player
  47. from players.helpers import index_from_userid, userid_from_index,userid_from_edict,index_from_steamid
  48. from translations.strings import LangStrings
  49.  
  50. #Eventscripts Emulator
  51. import es
  52.  
  53. #SQL Alchemy
  54. from sqlalchemy import Column, ForeignKey, Integer, String, Index
  55. from sqlalchemy.ext.declarative import declarative_base
  56. from sqlalchemy.sql.expression import insert
  57. from sqlalchemy.orm import sessionmaker
  58. from sqlalchemy import create_engine, desc
  59.  
  60. #Warcraft Source
  61. from wcs import admin
  62. from wcs import changerace
  63. from wcs import commands
  64. from wcs import config
  65. from wcs import downloader
  66. from wcs import effects
  67. import wcs.events
  68. from wcs import firefix
  69. from wcs import ladderfix
  70. from wcs import levelbank
  71. from wcs import logging
  72. from wcs import longjump
  73. from wcs import mana
  74. from wcs import myinfo
  75. from wcs import playerinfo
  76. from wcs import raceinfo
  77. from wcs import randomrace
  78. from wcs import resetskills
  79. from wcs import restrictions
  80. from wcs import savexp
  81. from wcs import setfx
  82. from wcs import shopinfo
  83. from wcs import shopmenu
  84. from wcs import showitems
  85. from wcs import showskills
  86. from wcs import spendskills
  87. from wcs import svar
  88. from wcs import teamrestrictions
  89. from wcs import vip
  90. from wcs import wcs_commands
  91. from wcs import wcsgroup
  92. from wcs import wcshelp
  93. from wcs import wcsmenu
  94. from wcs import wcstop
  95. from wcs import xtell
  96.  
  97. color_codes = ['\x03', '\x04', '\x05', '\x06', '\x07']
  98. raceevents = {}
  99. aliass = {}
  100. item_names = []
  101. player_loaded = {}
  102. output = Queue()
  103. wcsplayers = {}
  104. wcs_rank = {}
  105. player_isdead = {}
  106. gamestarted = 0
  107. saved = 0
  108.  
  109. if os.path.isfile(os.path.join(PLUGIN_PATH, 'wcs/strings', 'strings.ini')):
  110.     strings = LangStrings(os.path.join(PLUGIN_PATH, 'wcs/strings', 'strings'))
  111.    
  112. @contextmanager
  113. def session_scope():
  114.     session = Session()
  115.     try:
  116.         yield session
  117.         session.commit()
  118.     except:
  119.         session.rollback()
  120.         raise
  121.     finally:
  122.         session.close()
  123.    
  124. # =============================================================================
  125. # >> DATABASE
  126. # =============================================================================
  127. Base = declarative_base()
  128. db_method = ConVar('wcs_database_connectstring').get_string()
  129. engine = create_engine(db_method)
  130.  
  131. class Races(Base):
  132.     __tablename__ = 'Races'
  133.     RaceID = Column(Integer, nullable=False, primary_key=True)
  134.     UserID = Column(Integer, nullable=False)
  135.     name = Column(String(50),nullable=False)
  136.     skills = Column(String(50),nullable=False)
  137.     level = Column(Integer,default=0)
  138.     xp = Column(Integer,default=0)
  139.     unused = Column(Integer,default=0)
  140.     Index('racesIndex',UserID)
  141.  
  142. class Players(Base):
  143.     __tablename__ = 'Players'
  144.     UserID = Column(Integer,nullable=False,primary_key=True)
  145.     steamid = Column(String(30),nullable=False)
  146.     currace = Column(String(30),nullable=False)
  147.     name = Column(String(30),nullable=False)
  148.     totallevel = Column(Integer,default=0)
  149.     lastconnect = Column(Integer)
  150.     Index('playersIndex', steamid)
  151.  
  152. if not engine.dialect.has_table(engine, 'Players'):
  153.     Base.metadata.create_all(engine)
  154.    
  155. Session = sessionmaker(bind=engine)
  156.  
  157. # =============================================================================
  158. # >> LOAD
  159. # =============================================================================
  160. def load():
  161.     Thread(target=_load_ranks).start()
  162.     for player in PlayerIter():
  163.         wcsplayers[player.userid] = WarcraftPlayer(player.userid)
  164.         player_isdead[player.userid] = 0
  165.     global curmap
  166.     curmap = ConVar("host_map").get_string().strip('.bsp')
  167.     races = racedb.getAll()
  168.     global aliass
  169.     for race in races:
  170.         for section in races[race]:
  171.             if 'racealias_' in section:
  172.                 if section not in aliass:
  173.                     aliass[section] = str(races[race][section])
  174.  
  175.             if section == 'skillcfg':
  176.                 global raceevents
  177.                 if not race in raceevents:
  178.                     raceevents[race] = {}
  179.  
  180.                 events = races[race]['skillcfg'].split('|')
  181.  
  182.                 for index, cfg in enumerate(events):
  183.                     if not cfg in raceevents[race]:
  184.                         raceevents[race][cfg] = []
  185.  
  186.                     raceevents[race][cfg].append(str(index))
  187.  
  188.             elif section == 'preloadcmd':
  189.                 if races[race]['preloadcmd'] != "":
  190.                     command = races[race]['preloadcmd']
  191.                     command = command.split(";")
  192.                     for com in command:
  193.                         execute_server_command('es', com)
  194.  
  195.             if 'skill' in section:
  196.                 for y in races[race][section]:
  197.                     if 'racealias_' in y:
  198.                         if y not in aliass:
  199.                             aliass[y] = str(races[race][section][y])
  200.  
  201.     items = ini.getItems
  202.     for section in items:
  203.         for item in items[section]:
  204.             for q in items[section][item]:
  205.                 if 'shopalias_' in q:
  206.                     if q not in aliass:
  207.                         aliass[q] = str(items[section][item][q])
  208.     if config.coredata['saving'] == 1:
  209.         repeat_delay = config.coredata['save_time']*60
  210.         repeat = Repeat(do_save)
  211.         repeat.start(repeat_delay)
  212.        
  213. # =============================================================================
  214. # >> UNLOAD
  215. # =============================================================================
  216. def unload():
  217.     aliass.clear()
  218.    
  219. # =============================================================================
  220. # >> INI MANAGER
  221. # =============================================================================
  222. class InI(object):
  223.     def __init__(self):
  224.         if os.path.isfile(os.path.join(PLUGIN_PATH, 'wcs/races', 'races.ini')):
  225.             self.races = os.path.join(PLUGIN_PATH, 'wcs/races', 'races.ini')
  226.         else:
  227.             self.races = None
  228.         if config.coredata['default_races'] == 1:
  229.             self.default_races = os.path.join(PLUGIN_PATH, 'wcs/races', 'default_races.ini')
  230.         else:
  231.             self.default_races = None
  232.         self.items = os.path.join(PLUGIN_PATH, 'wcs/items', 'items.ini')
  233.  
  234.     @property
  235.     def getRaces(self):
  236.         try:
  237.             if self.races != None:
  238.                 user_races = ConfigObj(self.races,encoding="utf-8")
  239.             else:
  240.                 user_races = {}
  241.             if self.default_races != None:
  242.                 def_races = ConfigObj(self.default_races,encoding="utf-8")
  243.             else:
  244.                 def_races = {}
  245.             races_dict = {**def_races,**user_races}
  246.             return ConfigObj(races_dict,encoding="utf-8")
  247.         except:
  248.             sys.excepthook(*sys.exc_info())
  249.             return
  250.  
  251.     @property
  252.     def getItems(self):
  253.         return ConfigObj(self.items,encoding="utf-8")
  254.    
  255.     @property
  256.     def getCats(self):
  257.         return ConfigObj(self.cats,encoding="utf-8")           
  258. ini = InI()
  259.  
  260. # =============================================================================
  261. # >> INI CLASSES
  262. # =============================================================================
  263. #ITEMS DATABASE
  264. class itemDatabase(object):
  265.     def __init__(self):
  266.         self.items = ini.getItems
  267.         self.sectionlist = []
  268.         self.itemlist = []
  269.         self.itemtosection = {}
  270.  
  271.         for section in self.items:
  272.             self.sectionlist.append(section)
  273.             for item in self.items[section]:
  274.                 if item == 'desc':
  275.                     continue
  276.  
  277.                 self.itemlist.append(item)
  278.                 self.itemtosection[item] = section
  279.  
  280.     def __contains__(self, item):
  281.         return item in self.items
  282.  
  283.     def __iter__(self):
  284.         for x in self.items:
  285.             yield x
  286.  
  287.     def __getitem__(self, item):
  288.         return self.items[item]
  289.  
  290.     def keys(self):
  291.         return self.items.keys()
  292.  
  293.     def getSection(self, section):
  294.         return dict(self.items[section])
  295.  
  296.     def getItem(self, item):
  297.         return dict(self.items[self.getSectionFromItem(item)][item])
  298.  
  299.     def getSections(self):
  300.         return list(self.sectionlist)
  301.  
  302.     def getItems(self):
  303.         return list(self.itemlist)
  304.  
  305.     def getSectionFromItem(self, item):
  306.         if item in self.itemtosection:
  307.             return self.itemtosection[item]
  308.  
  309.         return None
  310.  
  311.     def getAll(self):
  312.         return dict(self.items)
  313. itemdb = itemDatabase()
  314.  
  315. #RACE DATABASE
  316. class raceDatabase(object):
  317.     def __init__(self):
  318.         self.races = ini.getRaces
  319.  
  320.     def __contains__(self, race):
  321.         return race in self.races
  322.  
  323.     def __iter__(self):
  324.         for x in self.races:
  325.             yield x
  326.  
  327.     def getRace(self, race):
  328.         return self.races[race]
  329.  
  330.     def getAll(self):
  331.         return self.races
  332.  
  333.     def getAlias(self):
  334.         return aliass
  335.  
  336.     def index(self, race):
  337.         return self.races.keys().index(race)     
  338. racedb = raceDatabase()
  339.  
  340. list_of_str_keys = ["restrictmap","restrictteam","restrictitem","spawncmd","deathcmd","roundstartcmd","roundendcmd","preloadcmd","onchange","allowonly"]
  341. list_of_int_keys = ["teamlimit"]
  342. for race in racedb.getAll():
  343.     for key in list_of_str_keys:
  344.         if key not in racedb.getAll()[race]:
  345.             racedb.getAll()[race][key] = ""
  346.     for key in list_of_int_keys:
  347.         if key not in racedb.getAll()[race]:
  348.             racedb.getAll()[race][key] = 0
  349.  
  350. if len(racedb.getAll()):
  351.     standardrace = racedb.getAll().keys()[0]
  352.     ConVar('wcs_default_race').set_string(standardrace)
  353.    
  354.  
  355. # =============================================================================
  356. # >> PLAYER CLASS
  357. # =============================================================================
  358. class WarcraftPlayer(object):
  359.     def __init__(self,userid):
  360.         self.userid = int(userid)
  361.         self.player_entity = Player.from_userid(self.userid)
  362.         self.index = self.player_entity.index
  363.         self.steamid = self.player_entity.uniqueid
  364.         self.name = self.remove_warnings(self.player_entity.name)
  365.            
  366.         #Dict to check for load status
  367.         player_loaded[self.userid] = False
  368.        
  369.         #Dict to store all the players races:
  370.         self.all_races = {}
  371.            
  372.         #Player data
  373.         self.UserID = -1
  374.         self.currace = ""
  375.         self.totallevel = 0
  376.         self.lastconnect = -1
  377.        
  378.        
  379.         #Race data
  380.         self.RaceID = -1
  381.         self.level = -1
  382.         self.xp = -1
  383.         self.unused = -1
  384.         self.skills = ''
  385.         self.race_name = ''
  386.                
  387.         Thread(target=self._load_from_database).start()
  388.        
  389.     def _load_from_database(self):
  390.         with session_scope() as session:
  391.             #Player data
  392.    
  393.             player = session.query(Players).filter(Players.steamid==self.steamid).one_or_none()
  394.             if player is None:
  395.                 player = Players(steamid=self.steamid,currace=ConVar('wcs_default_race').get_string(),name=self.name,lastconnect=time.time())
  396.                 session.add(player)
  397.                 session.commit()
  398.             self.UserID = player.UserID
  399.             self.currace = player.currace
  400.             self.race_name = self.currace
  401.             self.totallevel = player.totallevel
  402.             self.lastconnect = player.lastconnect
  403.             if self.steamid not in wcs_rank:
  404.                 wcs_rank[self.steamid] = {}
  405.                 wcs_rank[self.steamid]['name'] = self.name
  406.                 wcs_rank[self.steamid]['totallevel'] = self.totallevel
  407.                 wcs_rank[self.steamid]['currace'] = self.currace
  408.                 wcs_rank[self.steamid]['level'] = 0
  409.             #Race data
  410.             try:
  411.                 race = session.query(Races).filter(Races.UserID==self.UserID,Races.name==self.currace).one_or_none()
  412.             except:
  413.                 races = session.query(Races).filter(Races.UserID==self.UserID,Races.name==self.currace).all()
  414.                 session.delete(races[1])
  415.                 session.commit()
  416.                 race = races[0]
  417.             if race is None:
  418.                 if self.skills == '':
  419.                     skills = []
  420.                     for x in range(1,10):
  421.                         skill = 'skill'+str(x)
  422.                         if skill in racedb.races[self.race_name]:
  423.                             skills.append('0')
  424.  
  425.                     self.skills = '|'.join(skills)
  426.                    
  427.                 race = Races(UserID=self.UserID,name=self.race_name,skills=self.skills)
  428.                 session.add(race)
  429.                 session.commit()
  430.             self.RaceID = race.RaceID
  431.             self.level = race.level
  432.             self.xp = race.xp
  433.             self.unused = race.unused
  434.             self.skills = race.skills
  435.             self.race_name = race.name
  436.  
  437.             #Storing all saved races in the all_races dict
  438.             races = session.query(Races).filter(Races.UserID==self.UserID).all()
  439.             if races:
  440.                 for race_ in races:
  441.                     self.all_races[race_.name] = {}
  442.             for race in self.all_races:
  443.                 try:
  444.                     info = session.query(Races).filter(Races.UserID==self.UserID,Races.name==race).one_or_none()
  445.                 except:
  446.                     infos = session.query(Races).filter(Races.UserID==self.UserID,Races.name==race).all()
  447.                     session.delete(infos[1])
  448.                     session.commit()
  449.                     info = infos[0]                
  450.                 self.all_races[race]['level'] = info.level
  451.                 self.all_races[race]['xp'] = info.xp
  452.                 self.all_races[race]['unused'] = info.unused
  453.                 self.all_races[race]['skills'] = info.skills
  454.                 self.all_races[race]['name'] = race
  455.                
  456.         output.put(self._on_finish)
  457.        
  458.     def _on_finish(self):
  459.         if exists(self.userid):
  460.             OnPlayerLoaded.manager.notify(self)
  461.            
  462.     def save(self):
  463.         if exists(self.userid):    
  464.             Thread(target=self._save_player_to_database).start()
  465.        
  466.     def _save_player_to_database(self):
  467.         with session_scope() as session:
  468.             player = session.query(Players).filter(Players.UserID==self.UserID).one_or_none()
  469.             player.steamid = self.steamid
  470.             player.currace = self.currace
  471.             player.name = self.name
  472.             player.totallevel = self.totallevel
  473.             player.lastconnect = self.lastconnect
  474.            
  475.             session.commit()
  476.             for race_ in self.all_races:
  477.                 race = session.query(Races).filter(Races.UserID==self.UserID,Races.name==race_).one_or_none()
  478.                 if not race:
  479.                     race = Races(UserID=self.UserID,name=race_,skills=self.all_races[race_]['skills'])
  480.                     session.add(race)
  481.                     session.commit()
  482.                 race.name = race_
  483.                 race.skills = self.all_races[race_]['skills']
  484.                 race.level = self.all_races[race_]['level']
  485.                 race.xp = self.all_races[race_]['xp']
  486.                 race.unused = self.all_races[race_]['unused']
  487.                 session.commit()
  488.         output.put(self._on_player_saved)
  489.        
  490.     def _on_player_saved(self):
  491.         if exists(self.userid):
  492.             OnPlayerSaved.manager.notify(self)     
  493.        
  494.     def remove_warnings(self, value):
  495.         return str(value).replace("'", "").replace('"', '')
  496.        
  497.     def show_xp(self):
  498.         xp         = self.all_races[self.currace]['xp']
  499.         level      = self.all_races[self.currace]['level']
  500.         if config.cfgdata['experience_system'] == 0:
  501.             needed     = config.cfgdata['interval']*level if level else config.cfgdata['interval']
  502.         elif config.cfgdata['experience_system'] == 1:
  503.             level_string = config.cfgdata['custom_system'].split(',')
  504.             if level < len(level_string):
  505.                 needed = int(level_string[level])
  506.             else:
  507.                 needed = int(level_string[len(level_string)-1])
  508.         race       = self.currace
  509.  
  510.         tell(self.userid, '\x04[WCS] \x04%s \x05 - Level: \x04%s \x05 - XP: \x04%s/%s' % (race, level, xp, needed))
  511.    
  512.     def changerace(self, race, kill=True,who=None,safe=False):
  513.         if safe == False:
  514.             if racedb.races[self.race_name]['onchange']:
  515.                 command = racedb.races[self.race_name]['onchange']
  516.                 command = command.split(";")
  517.                 for com in command:
  518.                     execute_server_command('es', com)
  519.         oldrace = self.currace
  520.  
  521.         self.currace = str(race)
  522.         wcs_rank[self.steamid]['currace'] = str(race)
  523.        
  524.         if self.currace not in self.all_races:
  525.             self.all_races[self.currace] = {}
  526.             self.all_races[self.currace]['level'] = 0
  527.             self.all_races[self.currace]['xp'] = 0
  528.             self.all_races[self.currace]['unused'] = 0
  529.            
  530.             skill_list = []
  531.             for x in range(1,10):
  532.                 skill = 'skill'+str(x)
  533.                 if skill in racedb.races[self.currace]:
  534.                     skill_list.append('0')
  535.             skills = '|'.join(skill_list)
  536.             self.all_races[self.currace]['skills'] = skills
  537.  
  538.         self.level = self.all_races[self.currace]['level']
  539.         self.xp = self.all_races[self.currace]['xp']
  540.         self.unused = self.all_races[self.currace]['unused']
  541.         self.skills = self.all_races[self.currace]['skills']
  542.         if kill:
  543.             self.player_entity.client_command("kill", True)
  544.         if who == None:
  545.             tell(self.player_entity.userid, '\x04[WCS] \x05You changed your race to \x04%s.' % race)
  546.         if who == 'admin':
  547.             tell(self.player_entity.userid,'\x04[WCS] \x05An admin set your race to \x04%s.' % race)
  548.         if config.coredata['race_in_tag'] == 1:
  549.             self.player_entity.clan_tag = race
  550.         event_instance = wcs.events.wcs_changerace(userid=self.userid, oldrace=oldrace, newrace=race)
  551.         event_instance.fire()
  552.        
  553.     def give_xp(self, amount, reason=''):
  554.         amount = int(amount)
  555.         if not amount:
  556.             return
  557.  
  558.         maximumlevel = config.cfgdata['maximum_level']
  559.  
  560.         if 'maximumlevel' in racedb.races[self.currace]: #Tha Pwned
  561.             maximumlevel = int(racedb.races[self.currace]['maximumlevel']) #Tha Pwned
  562.  
  563.         if self.all_races[self.currace]['level'] >= maximumlevel: #Tha Pwned
  564.             return #Tha Pwned
  565.  
  566.         current_xp = self.all_races[self.currace]['xp'] + amount
  567.  
  568.         amount_of_levels = 0
  569.        
  570.        
  571.         if config.cfgdata['experience_system'] == 0:
  572.             next_level_xp = config.cfgdata['interval']*self.all_races[self.currace]['level'] if self.all_races[self.currace]['level'] else config.cfgdata['interval']
  573.         elif config.cfgdata['experience_system'] == 1:
  574.             level_string = config.cfgdata['custom_system'].split(',')
  575.             if self.all_races[self.currace]['level'] < len(level_string):
  576.                 next_level_xp = int(level_string[self.all_races[self.currace]['level']])
  577.             else:
  578.                 next_level_xp = int(level_string[len(level_string)-1])
  579.                
  580.                
  581.         if config.cfgdata['experience_system'] == 0:
  582.             while current_xp >= next_level_xp:
  583.                 amount_of_levels += 1
  584.                 current_xp -= next_level_xp
  585.                 next_level_xp += config.cfgdata['interval']
  586.         elif config.cfgdata['experience_system'] == 1:
  587.             x = 0
  588.             level_string = config.cfgdata['custom_system'].split(',')
  589.             while current_xp >=next_level_xp:
  590.                 amount_of_levels += 1
  591.                 current_xp -= next_level_xp
  592.                 if self.all_races[self.currace]['level']+x < len(level_string):
  593.                     next_level_xp = int(level_string[self.all_races[self.currace]['level']+x])
  594.                 else:
  595.                     next_level_xp = int(level_string[len(level_string)-1])
  596.                 x += 1
  597.         self.all_races[self.currace]['xp'] = current_xp
  598.         if not reason:
  599.             tell(self.userid, '\x04[WCS] \x05You have gained \x04%s XP.' % amount)
  600.         else:
  601.             tell(self.userid, '\x04[WCS] \x05You have gained \x04%s XP %s' % (amount, reason))
  602.  
  603.         if amount_of_levels+self.all_races[self.currace]['level'] >= maximumlevel: #Tha Pwned
  604.             amount_of_levels = maximumlevel-self.all_races[self.currace]['level'] #Tha Pwned
  605.            
  606.         if amount_of_levels:
  607.             self.give_level(amount_of_levels)
  608.  
  609.         event_instance = wcs.events.wcs_gainxp(userid=self.userid, amount=amount, levels=amount_of_levels, currentxp=self.xp,reason=reason)
  610.         event_instance.fire()      
  611.        
  612.         return current_xp
  613.        
  614.     def give_level(self, amount):
  615.         amount = int(amount)
  616.         if not amount:
  617.             return
  618.            
  619.         maximumlevel = config.cfgdata['maximum_level']
  620.  
  621.         if 'maximumlevel' in racedb.races[self.currace]: #Tha Pwned
  622.             maximumlevel = int(racedb.races[self.currace]['maximumlevel']) #Tha Pwned
  623.  
  624.         if self.all_races[self.currace]['level'] >= maximumlevel: #Tha Pwned
  625.             return #Tha Pwned
  626.  
  627.         if amount+self.all_races[self.currace]['level'] >= maximumlevel: #Tha Pwned
  628.             amount = maximumlevel-self.all_races[self.currace]['level'] #Tha Pwned
  629.            
  630.         self.all_races[self.currace]['level'] += amount
  631.         self.all_races[self.currace]['unused'] += amount
  632.         self.totallevel += amount
  633.         wcs_rank[self.steamid]['totallevel'] += amount
  634.  
  635.         if 'BOT' in self.steamid:
  636.             nol = racedb.races[self.currace]['numberoflevels']
  637.             nos = racedb.races[self.currace]['numberofskills']
  638.             if '|' in nol:
  639.                 nol = nol.split('|')
  640.                 nol = [int(x) for x in nol]
  641.             else:
  642.                 nos = int(racedb.races[self.currace]['numberofskills'])
  643.                 nol_tmp = int(racedb.races[self.currace]['numberoflevels'])
  644.                 nol = []
  645.                 x = 0
  646.                 while x < nos:
  647.                     nol.append(nol_tmp)
  648.                     x += 1
  649.  
  650.             while True:
  651.                 if not self.all_races[self.currace]['unused']:
  652.                     break
  653.  
  654.                 possible_choices = []
  655.                 skills = self.all_races[self.currace]['skills'].split('|')
  656.  
  657.                 for skill, level in enumerate(skills):
  658.                     if int(skills[skill]) < nol[skill]:
  659.                         possible_choices.append(str(skill+1))
  660.  
  661.                 if not len(possible_choices):
  662.                     break
  663.  
  664.                 choice = random.choice(possible_choices)
  665.                 self.add_point(choice)
  666.  
  667.         else:
  668.             if config.cfgdata['experience_system'] == 0:
  669.                 needed = config.cfgdata['interval']*self.all_races[self.currace]['level']
  670.             elif config.cfgdata['experience_system'] == 1:
  671.                 level_string = config.cfgdata['custom_system'].split(',')
  672.                 if self.all_races[self.currace]['level'] < len(level_string):
  673.                     needed = int(level_string[self.all_races[self.currace]['level']])
  674.                 else:
  675.                     needed = int(level_string[len(level_string)-1])
  676.             tell(self.userid, '\x04[WCS] \x05You are on level \x04%s\x05 XP: \x04%s/%s' % (self.all_races[self.currace]['level'], self.all_races[self.currace]['xp'], needed))
  677.             Delay(2.0, spendskills.doCommand, (self.userid,))
  678.             return
  679.         oldlevel = self.all_races[self.currace]['level'] - amount
  680.         event_instance = wcs.events.wcs_levelup(userid=self.userid, race=self.name, oldlevel=oldlevel, newlevel=self.all_races[self.currace]['level'],amount=amount)
  681.         event_instance.fire()  
  682.  
  683.         return self.all_races[self.currace]['level']
  684.        
  685.  
  686.     def add_point(self, skill):
  687.         skills = self.all_races[self.currace]['skills'].split('|')
  688.         index = int(skill)-1
  689.         level = int(skills[index])
  690.  
  691.         if self.all_races[self.currace]['unused']:
  692.             skills.pop(index)
  693.             skills.insert(index, str(level+1))
  694.  
  695.             self.all_races[self.currace]['skills'] = '|'.join(skills)
  696.  
  697.             self.all_races[self.currace]['unused'] -= 1
  698.  
  699.             return level+1
  700.            
  701.     def get_rank(self):
  702.         rank_list = wcs_rank.values()
  703.         rank_list = sorted(wcs_rank, key=lambda x: wcs_rank[x]['totallevel'],reverse=True)
  704.         i = 0
  705.         for x in rank_list:
  706.             i+=1
  707.             if self.steamid == x:
  708.                 rank = i
  709.                 break
  710.         return (i,len(rank_list))
  711.        
  712.     def show_rank(self):
  713.         rank,total = self.get_rank()
  714.         if config.cfgdata['experience_system'] == 0:
  715.             needed     = config.cfgdata['interval']*self.level if self.level else config.cfgdata['interval']
  716.         elif config.cfgdata['experience_system'] == 1:
  717.             level_string = config.cfgdata['custom_system'].split(',')
  718.             if self.level < len(level_string):
  719.                 needed = int(level_string[self.level])
  720.             else:
  721.                 needed = int(level_string[len(level_string)-1])
  722.         unused     = self.unused
  723.         for player in PlayerIter('all'):
  724.             tell(player.userid, "\x04[WCS] \x05%s \x04is on race \x05%s \x04level\x05 %s\x04, ranked \x05%s/%s \x04with\x05 %s/%s \x04XP and \x05%s \x04Unused." % (self.name, self.currace, self.all_races[self.currace]['level'], rank, total, self.all_races[self.currace]['xp'], needed, self.all_races[self.currace]['unused']))
  725.        
  726.     def delete_race(self):
  727.         Thread(target=self._delete_race).start()
  728.  
  729.     def _delete_race(self):
  730.         with session_scope() as session:
  731.             delete = session.query(Races).filter(Races.UserID==self.UserID,Races.name==self.currace).one_or_none()
  732.             if delete != None:
  733.                 session.delete(delete)
  734.                 session.commit()
  735.             else:
  736.                 self.totallevel -= self.all_races[self.currace]['level']
  737.                 self.all_races[self.currace] = {}
  738.                 self.all_races[self.currace]['level'] = 0
  739.                 self.all_races[self.currace]['xp'] = 0
  740.                 self.all_races[self.currace]['unused'] = 0
  741.                
  742.                 skill_list = []
  743.                 for x in range(1,10):
  744.                     skill = 'skill'+str(x)
  745.                     if skill in racedb.races[self.currace]:
  746.                         skill_list.append('0')
  747.                 skills = '|'.join(skill_list)
  748.                 self.all_races[self.currace]['skills'] = skills
  749.                
  750.                
  751.         output.put(self._on_race_deleted)
  752.    
  753.     def _on_race_deleted(self):
  754.         if exists(self.userid):
  755.             OnRaceDeleted.manager.notify(self.index,self.currace)
  756.        
  757.     def delete_player(self):
  758.         wcsplayers.pop(self.userid)
  759.         Thread(target=self._delete_player).start()
  760.        
  761.     def _delete_player(self):
  762.         with session_scope() as session:
  763.             delete_races = session.query(Races).filter(Races.UserID==self.UserID).all()
  764.             delete = session.query(Players).filter(Players.UserID==self.UserID).one_or_none()
  765.             for x in delete_races:
  766.                 session.delete(x)
  767.             session.delete(delete)
  768.             session.commit()
  769.         output.put(self._on_player_deleted)
  770.        
  771.     def _on_player_deleted(self):
  772.         if exists(self.userid):
  773.             OnPlayerDeleted.manager.notify(self.index) 
  774.            
  775.        
  776.        
  777. for player in PlayerIter('all'):
  778.     wcsplayers[player.userid] = WarcraftPlayer(player.userid)
  779.        
  780. @Repeat
  781. def repeat():
  782.     try:
  783.         callback = output.get_nowait()
  784.     except Empty:
  785.         pass
  786.     else:
  787.         callback()
  788. repeat.start(0.1)
  789.            
  790. # =============================================================================
  791. # >> PLAYER COMMANDS
  792. # =============================================================================
  793. @SayCommand(config.ultimate_list)
  794. @ClientCommand(config.ultimate_list)
  795. def _ultimate_command(command, index, team=None):
  796.     userid = userid_from_index(index)
  797.     player_entity = Player(index)
  798.     if int(player_entity.team) > 1 and not int(player_entity.dead):
  799.         returned = checkEvent1(userid, 'player_ultimate')
  800.         if returned is not None:
  801.             if returned is False:
  802.                 tell(userid, 'You cannot activate your ultimate now.')
  803.             elif len(returned) == 3 and not returned[0]:
  804.                 tell(userid, '\x04[WCS] \x05You cannot use your \x04ultimate! \x05Cooldown time is \x04'+str(returned[1])+' \x05seconds, \x04'+str(returned[1]-returned[2])+' \x05left!')
  805.     return CommandReturn.BLOCK
  806.    
  807.        
  808. @SayCommand(config.ability_list)
  809. @ClientCommand(config.ability_list)
  810. def _ultimate_command(command, index, team=None):
  811.     userid = userid_from_index(index)
  812.     player_entity = Player(index)
  813.     if int(player_entity.team) > 1 and not int(player_entity.dead):
  814.         value = wcsgroup.getUser(userid, 'ability')
  815.         if value == "None":
  816.             returned = checkEvent1(userid, 'player_ability')
  817.             if returned is not None:
  818.                 if returned is False:
  819.                     tell(userid, '\x04[WCS] \x05You cannot activate your ability now.')
  820.                 elif len(returned) == 3 and not returned[0]:
  821.                     tell(userid, '\x04[WCS] \x05You cannot use your \x04ability! \x05Cooldown time is \x04'+str(returned[1])+' \x05seconds, \x04'+str(returned[1]-returned[2])+' \x05left!')
  822.         else:
  823.             if gamestarted == 1:
  824.                 es.ServerVar('wcs_userid').set(userid)
  825.                 es.doblock('wcs/tools/abilities/'+str(value)+'/'+str(value))
  826.             else:
  827.                 tell(userid, '\x04[WCS] \x05You cannot activate your ability now.')
  828.     return CommandReturn.BLOCK
  829.    
  830. @SayCommand(config.wcsrank_list)
  831. @ClientCommand(config.wcsrank_list)
  832. def _wcs_rank_command(command, index, team=None):
  833.     userid = userid_from_index(index)
  834.     wcstop.wcsRank(userid)
  835.     return CommandReturn.BLOCK
  836.    
  837. @SayCommand(config.wcstop_list)
  838. @ClientCommand(config.wcstop_list)
  839. def _wcs_top_command(command, index, team=None):
  840.     userid = userid_from_index(index)
  841.     wcstop.doCommand(userid)
  842.     return CommandReturn.BLOCK
  843.  
  844. @SayCommand(config.showxp_list)
  845. @ClientCommand(config.showxp_list)
  846. def _showxp_command(command, index, team=None):
  847.         userid = userid_from_index(index)
  848.         wcsplayers[userid].show_xp()
  849.         return CommandReturn.BLOCK
  850.  
  851. @SayCommand(config.wcsmenu_list)
  852. @ClientCommand(config.wcsmenu_list)
  853. def _wcsmenu_command(command, index, team=None):
  854.     userid = userid_from_index(index)
  855.     wcsmenu.doCommand(userid)
  856.     return CommandReturn.BLOCK
  857.        
  858. @SayCommand(config.raceinfo_list)
  859. @ClientCommand(config.raceinfo_list)
  860. def _raceinfo_command(command, index, team= None):
  861.     userid = userid_from_index(index)
  862.     raceinfo.doCommand(userid)
  863.     return CommandReturn.BLOCK
  864.    
  865. @SayCommand(config.shopinfo_list)
  866. @ClientCommand(config.shopinfo_list)
  867. def _shopinfo_command(command, index, team= None):
  868.     userid = userid_from_index(index)
  869.     shopinfo.doCommand(userid)
  870.     return CommandReturn.BLOCK
  871.        
  872. @SayCommand(config.spendskills_list)
  873. @ClientCommand(config.spendskills_list)
  874. def _spendskills_command(command, index, team= None):
  875.     userid = userid_from_index(index)
  876.     spendskills.doCommand(userid)
  877.     return CommandReturn.BLOCK
  878.  
  879. @SayCommand(config.changerace_list)
  880. @ClientCommand(config.changerace_list)
  881. def _changerace_command(command, index, team=None):
  882.     userid = userid_from_index(index)
  883.     if not command.arg_string:
  884.         changerace.HowChange(userid)
  885.     else:
  886.         changerace.HowChange(userid,command.arg_string)
  887.     return CommandReturn.BLOCK
  888.    
  889. @SayCommand(config.resetskills_list)
  890. @ClientCommand(config.resetskills_list)
  891. def _resetskills_command(command, index, team=None):
  892.     userid = userid_from_index(index)
  893.     resetskills.doCommand(userid)
  894.     return CommandReturn.BLOCK
  895.  
  896. @SayCommand(config.savexp_list)
  897. @ClientCommand(config.savexp_list)
  898. def _savexp_command(command, index, team=None):
  899.     userid = userid_from_index(index)
  900.     savexp.doCommand(userid)
  901.     return CommandReturn.BLOCK
  902.    
  903. @SayCommand(config.showskills_list)
  904. @ClientCommand(config.showskills_list)
  905. def _showskills_command(command, index, team=None):
  906.     userid = userid_from_index(index)
  907.     showskills.doCommand(userid)
  908.     return CommandReturn.BLOCK
  909.  
  910. @SayCommand(config.wcshelp_list)
  911. @ClientCommand(config.wcshelp_list)
  912. def _wcshlep_command(command, index, team=None):
  913.     userid = userid_from_index(index)
  914.     wcshelp.doCommand(userid)
  915.     return CommandReturn.BLOCK
  916.    
  917. @SayCommand(config.shopmenu_list)
  918. @ClientCommand(config.shopmenu_list)
  919. def _shopmenu_command(command, index, team=None):
  920.     userid = userid_from_index(index)
  921.     shopmenu.doCommand(userid)
  922.     return CommandReturn.BLOCK
  923.    
  924. @SayCommand(config.playerinfo_list)
  925. @ClientCommand(config.playerinfo_list)
  926. def _playerinfo_command(command, index, team=None):
  927.     userid = userid_from_index(index)
  928.     playerinfo.doCommand(userid)
  929.     return CommandReturn.BLOCK
  930.        
  931. def buyitem_menu_select(menu, index, choice):
  932.     userid = userid_from_index(index)
  933.     shopmenu.addItem(userid, choice.value, pay=True, tell=True,close_menu=True)
  934.        
  935. @SayCommand(config.wcsbuyitem_list)
  936. @ClientCommand(config.wcsbuyitem_list)
  937. def wcs_buy_item(command,index,team=None):
  938.     userid = userid_from_index(index)
  939.     if len(command) < 2:
  940.         return
  941.     if len(command) > 2:
  942.         item = command[1]
  943.         for x in command:
  944.             if x != "wcsbuyitem" and x != command[1]:
  945.                 item = item+" "+x
  946.     else:
  947.         item = str(command[1])
  948.     items = find_items(item)
  949.     if items != -1:
  950.         if len(items) == 1:
  951.             shopmenu.addItem(userid, items[0], pay=True, tell=True,close_menu=True)
  952.         if len(items) > 1:
  953.             buyitem_menu = PagedMenu(title='Choose item',select_callback=buyitem_menu_select,fill=False)
  954.             buyitem_menu.clear()
  955.             for i in items:
  956.                 iteminfo = itemdb.getItem(i)
  957.                 option = PagedOption('%s - %s$' % (str(iteminfo['name']), str(iteminfo['cost'])), i)
  958.                 buyitem_menu.append(option)
  959.             buyitem_menu.send(index)
  960.     return CommandReturn.BLOCK
  961.    
  962. # =============================================================================
  963. # >> SERVER COMMANDS
  964. # =============================================================================    
  965. @ServerCommand('wcs_changerace')
  966. def _wcs_changerace(command):
  967.     userid = int(command[1])
  968.     if len(command) > 3:
  969.         race = command[2]
  970.         for x in command:
  971.             if x != "wcs_changerace" and not is_number(x) and x != command[2]:
  972.                 race = race+" "+x
  973.     else:
  974.         race = str(command[2])
  975.     wcsplayers[userid].changerace(race)
  976.    
  977.    
  978. @ServerCommand('wcs_reload')
  979. def _wcs_reload_command(command):
  980.     load_races()
  981.    
  982. @ServerCommand('wcs_givexp')
  983. def _wcs_give_xp_command(command):
  984.     userid = int(command[1])
  985.     amount = int(command[2])
  986.     wcsplayers[userid].give_xp(amount)
  987.  
  988. @ServerCommand('wcs_givelevel')
  989. def _wcs_givelevel_command(command):
  990.     userid = int(command[1])
  991.     amount = int(command[2])
  992.     wcsplayers[userid].give_level(amount)
  993.    
  994. @ServerCommand('wcs_xalias')
  995. def _wcs_xalias_command(command):
  996.     alias = str(command[1])
  997.     if len(command) == 2:
  998.         if alias in aliass:
  999.             todo = aliass[alias].split(";")
  1000.             for com in todo:
  1001.                 execute_server_command('es', com)
  1002.     elif len(command) == 3:
  1003.         aliass[alias] = str(command[2])
  1004.    
  1005. @ServerCommand('wcs_reload_races')
  1006. def _wcs_reload_races_command(command):
  1007.     if not 'reload' in time:
  1008.         time['reload'] = time.time()
  1009.  
  1010.     if time.time()-time['reload'] <= 180:
  1011.         racedb.races = ini.getRaces
  1012.         time['reload'] = time.time()
  1013.     load_races()
  1014.    
  1015.    
  1016. @ServerCommand('wcs_get_skill_level')
  1017. def get_skill_level(command):
  1018.     userid = str(command[1])
  1019.     var = str(command[2])
  1020.     skillnum = int(command[3])
  1021.    
  1022.     skills = wcsplayers[userid].all_races[race]['skills'].split('|')
  1023.     if skillnum <= len(skills):
  1024.         ConVar(var).set_string(skills[skillnum-1])
  1025.        
  1026.    
  1027. @ServerCommand('wcs_getinfo')
  1028. def getInfoRegister(command):
  1029.     if len(command) == 5:
  1030.         userid = int(command[1])
  1031.         var = str(command[2])
  1032.         info = str(command[3])
  1033.         where = str(command[4])
  1034.         race = wcsplayers[userid].currace
  1035.  
  1036.         if where == 'race':
  1037.             if info in wcsplayers[userid].all_races[race]:
  1038.                 returned = wcsplayers[userid].all_races[race][info]
  1039.                 ConVar(var).set_string(str(returned))
  1040.  
  1041.         elif where == 'player':
  1042.             if hasattr(wcsplayers[userid], info):
  1043.                 returned = getattr(wcsplayers[userid], info)
  1044.                 ConVar(var).set_string(str(returned))
  1045.         else:
  1046.             if not where in racedb:
  1047.                 return
  1048.  
  1049.             if info in wcsplayers[userid].all_races[where]:
  1050.                 returned = wcsplayers[userid].all_races[where][info]
  1051.                 ConVar(var).set_string(str(returned))
  1052.    
  1053. # =============================================================================
  1054. # >> EVENTS
  1055. # =============================================================================
  1056. @Event('player_activate')  
  1057. def _player_activate(event):
  1058.     userid = int(event['userid'])
  1059.     player_entity = Player(index_from_userid(userid))
  1060.     wcsplayers[userid].name = wcsplayers[userid].remove_warnings(player_entity.name)
  1061.  
  1062.     if not player_entity.steamid == 'BOT':
  1063.         Delay(10.0, tell, (userid, '\x04[WCS] \x05Welcome to this \x04WCS server\x05. Try \x04"wcshelp" \x05and bind mouse3 ultimate'))
  1064.     race = wcsplayers[userid].currace
  1065.     if player_loaded[userid] == True:
  1066.         raceinfo = racedb.races[race]
  1067.         if raceinfo['allowonly'] != "":
  1068.             if not player_entity.steamid in raceinfo['allowonly']:
  1069.                 rand_race = get_random_race(int(userid))
  1070.                 player.changerace(rand_race)
  1071.         player_entity.clan_tag = race
  1072.     wcsgroup.addUser(userid)
  1073.     if SOURCE_ENGINE_BRANCH == 'csgo':
  1074.         delay = ConVar('mp_force_pick_time').get_int()
  1075.         Delay(float(delay),set_team,(event['userid'],))
  1076.  
  1077. @Event('round_freeze_end')
  1078. def _event_freeze(ev):
  1079.     global gamestarted
  1080.     gamestarted = 1
  1081.  
  1082. @Event('player_disconnect')
  1083. def player_disconnect(ev):
  1084.     userid = ev.get_int('userid')
  1085.     player_entity = Player(index_from_userid(userid))
  1086.    
  1087.     wcsplayers[ev['userid']].save()
  1088.     if userid in wcsplayers:
  1089.         wcsplayers[ev['userid']].lastconnect = time.time()
  1090.         wcsplayers[ev['userid']].name = wcsplayers[ev['userid']].remove_warnings(player_entity.name)
  1091.         wcsplayers[ev['userid']].save()
  1092.  
  1093.     wcsgroup.delUser(userid)
  1094.  
  1095. @Event('round_start')
  1096. def round_start(event):
  1097.     freezetime = ConVar('mp_freezetime').get_int()
  1098.     if freezetime == 0:
  1099.         global gamestarted
  1100.         gamestarted = 1
  1101.     for player in PlayerIter():
  1102.         userid = player.userid
  1103.         if player.team >= 2:
  1104.             race = wcsplayers[userid].currace
  1105.             if race != '':
  1106.                 raceinfo = racedb.races[race]
  1107.                 if raceinfo['roundstartcmd']:
  1108.                     command = raceinfo['roundstartcmd']
  1109.                     command = command.split(";")
  1110.                     ConVar("wcs_userid").set_int(userid)
  1111.                     for com in command:
  1112.                         execute_server_command('es', com)
  1113.     round_count = ConVar('wcs_roundcounter').get_int()
  1114.     round_count += 1
  1115.     ConVar('wcs_roundcounter').set_int(round_count)
  1116.    
  1117. @Event('round_end')
  1118. def round_end(event):
  1119.     global gamestarted
  1120.     gamestarted = 0
  1121.     for player in PlayerIter():
  1122.         userid = player.userid
  1123.         if player_loaded[userid] == True:
  1124.             if player.team >= 2:
  1125.                 race = wcsplayers[userid].currace
  1126.                 raceinfo = racedb.getRace(race)
  1127.                 if raceinfo['roundendcmd']:
  1128.                     command = raceinfo['roundendcmd']
  1129.                     command = command.split(";")
  1130.                     for com in command:
  1131.                         execute_server_command('es', com)
  1132.                
  1133.     xpsaver = config.coredata['xpsaver']
  1134.     if xpsaver:
  1135.         global saved
  1136.         if xpsaver <= saved:
  1137.             for user in wcsplayers:
  1138.                 wcsplayers[user].save()
  1139.             saved = 0
  1140.  
  1141.         else:
  1142.             saved += 1
  1143.            
  1144.     if int(event['winner']) == 3:
  1145.         team = 'ct'
  1146.         other = ['t','alive']
  1147.     if int(event['winner']) == 2:
  1148.         team = 't'
  1149.         other = ['ct','alive']
  1150.     if str(event['winner']) not in "2;3":
  1151.         return
  1152.     for player in PlayerIter(team):
  1153.         if player.steamid == 'BOT':
  1154.             winxp = config.cfgdata['bot_roundwxp']
  1155.         else:
  1156.             winxp = config.cfgdata['player_roundwxp']
  1157.         Delay(1, wcsplayers[player.userid].give_xp, (winxp, 'for winning the round'))
  1158.     for player in PlayerIter(other):
  1159.         if player.steamid == 'BOT':
  1160.             surxp = config.cfgdata['bot_roundsxp']
  1161.         else:
  1162.             surxp = config.cfgdata['player_roundsxp']      
  1163.         Delay(1,  wcsplayers[player.userid].give_xp, (surxp, 'for surviving the round'))
  1164.  
  1165. @PreEvent('player_death')
  1166. def pre_death(event):
  1167.     userid = int(event['userid'])
  1168.     if player_isdead[userid] == 0:
  1169.         player_isdead[userid] = 1
  1170.         attacker = Player.from_userid(int(event['attacker']))
  1171.     elif player_isdead[userid] == 1:
  1172.         return EventAction.BLOCK
  1173.  
  1174. @Event('player_death')         
  1175. def player_death(event):
  1176.     #player_death variables
  1177.     victim = event.get_int('userid')
  1178.     attacker = event.get_int('attacker')
  1179.     if SOURCE_ENGINE_BRANCH == 'csgo':
  1180.         assister = event.get_int('assister')
  1181.     else:
  1182.         assister = 0
  1183.     headshot = event.get_int('headshot')
  1184.     weapon = event.get_string('weapon')
  1185.     queue_command_string('es wcsgroup set regeneration_active %s 0' % victim)
  1186.     #player_death execution
  1187.     victim_entity = Player(index_from_userid(victim))
  1188.     if attacker:
  1189.         attacker_entity = Player(index_from_userid(attacker))
  1190.     if attacker and victim:
  1191.  
  1192.         if not victim == attacker:
  1193.             if not victim_entity.team == attacker_entity.team:
  1194.                 bonus = 0
  1195.                 if wcsplayers[attacker_entity.userid].level <  wcsplayers[victim_entity.userid].level:
  1196.                     diffience = wcsplayers[victim_entity.userid].level - wcsplayers[attacker_entity.userid].level
  1197.                     #Bonus XP
  1198.                     if attacker_entity.steamid == 'BOT':
  1199.                         limit = config.cfgdata['bot_levellimit']
  1200.                         if limit:
  1201.                             if diffience > limit:
  1202.                                 diffience = limit
  1203.                         bonus = config.cfgdata['bot_difxp']*diffience
  1204.                     else:
  1205.                         limit = config.cfgdata['player_levellimit']
  1206.                         if limit:
  1207.                             if diffience > limit:
  1208.                                 diffience = limit
  1209.                         bonus = config.cfgdata['player_difxp']*diffience
  1210.                 #Normal XP Gain
  1211.                 if victim_entity.steamid == 'BOT':
  1212.                     killxp = config.cfgdata['bot_killxp']
  1213.                     headshotxp = config.cfgdata['bot_headshotxp']
  1214.                     knifexp = config.cfgdata['bot_knifexp']
  1215.                     hexp = config.cfgdata['bot_hexp']
  1216.                     flashxp = config.cfgdata['bot_flashxp']
  1217.                     smokexp = config.cfgdata['bot_smokexp']
  1218.                     if SOURCE_ENGINE_BRANCH == 'csgo':
  1219.                         molotovxp = config.cfgdata['bot_molotovxp']
  1220.                 else:
  1221.                     killxp = config.cfgdata['player_killxp']
  1222.                     headshotxp = config.cfgdata['player_headshotxp']
  1223.                     knifexp = config.cfgdata['player_knifexp']
  1224.                     hexp = config.cfgdata['player_hexp']
  1225.                     flashxp = config.cfgdata['player_flashxp']
  1226.                     smokexp = config.cfgdata['player_smokexp']
  1227.                     if SOURCE_ENGINE_BRANCH == 'csgo':
  1228.                         molotovxp = config.cfgdata['player_molotovxp']
  1229.                 if bonus:
  1230.                     Delay(1, wcsplayers[attacker_entity.userid].give_xp, (killxp+bonus, 'for killing a higher-level enemy. (\x04%s level difference bonus xp!)' % diffience))
  1231.                 else:
  1232.                     Delay(1, wcsplayers[attacker_entity.userid].give_xp, (killxp, 'for making a kill'))
  1233.  
  1234.                 if headshot == 1:
  1235.                     Delay(1, wcsplayers[attacker_entity.userid].give_xp, (headshotxp, 'for making a headshot'))
  1236.                    
  1237.                 elif 'knife' in weapon:
  1238.                     Delay(1, wcsplayers[attacker_entity.userid].give_xp, (knifexp, 'for making a knife kill'))
  1239.                 elif weapon == 'hegrenade':
  1240.                     Delay(1, wcsplayers[attacker_entity.userid].give_xp, (hexp, 'for making a explosive grenade kill'))
  1241.                 elif weapon == 'smokegrenade':
  1242.                     Delay(1, wcsplayers[attacker_entity.userid].give_xp, (smokexp, 'for making a smoke grenade kill'))
  1243.                 elif weapon == 'flashbang':
  1244.                     Delay(1, wcsplayers[attacker_entity.userid].give_xp, (flashbangxp, 'for making a flashbang grenade kill'))
  1245.                 elif weapon == 'inferno':
  1246.                     Delay(1, wcsplayers[attacker_entity.userid].give_xp, (molotovxp, 'for making a fire kill'))
  1247.            
  1248.  
  1249.             checkEvent(victim,  'player_death')
  1250.             checkEvent(attacker, 'player_kill')
  1251.  
  1252.         race = wcsplayers[attacker].currace
  1253.         if racedb.races[race]['deathcmd']:
  1254.             command = racedb.races[race]['deathcmd']
  1255.             command = command.split(";")
  1256.             for com in command:
  1257.                 execute_server_command('es', com)
  1258.     if (victim and not attacker) or (victim == attacker):
  1259.         checkEvent(victim,  'player_death')
  1260.     if assister:
  1261.         assist_player = Player.from_userid(int(assister))
  1262.         if assist_player.steamid == 'BOT':
  1263.             assistxp = config.cfgdata['bot_assistxp']
  1264.         else:
  1265.             assistxp = config.cfgdata['player_assistxp']
  1266.         Delay(1, wcsplayers[assister].give_xp, (assistxp, 'for assisting in a kill'))
  1267.         checkEvent(assister,'player_assister')
  1268.        
  1269.  
  1270. @Event('player_hurt')
  1271. def _player_hurt(event):
  1272.     victim = event.get_int('userid')
  1273.     attacker = event.get_int('attacker')
  1274.     weapon = event.get_string('weapon')
  1275.     health = event.get_int('health')
  1276.    
  1277.     if victim:
  1278.         victim_entity = Player(index_from_userid(victim))
  1279.     if attacker:
  1280.         attacker_entity = Player(index_from_userid(attacker))
  1281.     if attacker and victim and not weapon.lower() in ('point_hurt') and not weapon.lower() in ('worldspawn'):
  1282.         if not victim == attacker:
  1283.             if not victim_entity.team == attacker_entity.team:
  1284.                 checkEvent(victim, 'player_victim')
  1285.                 if health > 0:
  1286.                     checkEvent(attacker, 'player_attacker')
  1287.                
  1288.             checkEvent(victim, 'player_hurt')
  1289.             if health > 0:
  1290.                 checkEvent(attacker, 'player_hurt')
  1291.                
  1292. @Event('bomb_planted')
  1293. def bomb_planted(event):
  1294.     userid = int(event['userid'])
  1295.     player = Player.from_userid(userid)
  1296.     if player.steamid == 'BOT':
  1297.         plantxp = config.cfgdata['bot_plantxp']
  1298.     else:
  1299.         plantxp = config.cfgdata['player_plantxp']
  1300.     Delay(1, wcsplayers[userid].give_xp, (plantxp, 'for planting the bomb!'))
  1301.        
  1302. @Event('bomb_defused')
  1303. def bomb_planted(event):
  1304.     userid = int(event['userid'])
  1305.     player = Player.from_userid(userid)
  1306.     if player.steamid == 'BOT':
  1307.         defusexp = config.cfgdata['bot_defusexp']
  1308.     else:
  1309.         defusexp = config.cfgdata['player_defusexp']
  1310.     Delay(1, wcsplayers[userid].give_xp, (defusexp, 'for defusing the bomb!'))
  1311.  
  1312. @Event('bomb_exploded')
  1313. def bomb_exploded(event):
  1314.     userid = int(event['userid'])
  1315.     player = Player.from_userid(userid)
  1316.     if player.steamid == 'BOT':
  1317.         explodexp = config.cfgdata['bot_explodexp']
  1318.     else:
  1319.         explodexp = config.cfgdata['player_explodexp']
  1320.     Delay(1, wcsplayers[userid].give_xp, (explodexp, 'for letting the bomb explode!'))
  1321.  
  1322. @Event('hostage_rescued')
  1323. def hostage_rescued(event):
  1324.     userid = int(event['userid'])
  1325.     player = Player.from_userid(userid)
  1326.     if player.steamid == 'BOT':
  1327.         rescuexp = config.cfgdata['bot_rescuexp']
  1328.     else:
  1329.         rescuexp = config.cfgdata['player_rescuexp']
  1330.     Delay(1, wcsplayers[userid].give_xp, (rescuexp, 'for rescuing a hostage!'))    
  1331.  
  1332.            
  1333. @Event('player_spawn')         
  1334. def _player_spawn(event):
  1335.     userid = event.get_int('userid')
  1336.     player_isdead[userid] = 0
  1337.     player = Player.from_userid(userid)
  1338.     player.color = Color(255,255,255,255)
  1339.     player.gravity = 1.0
  1340.     player.speed = 1.0
  1341.     queue_command_string('es wcsgroup set regeneration_active %s 0' % userid)
  1342.     if player_loaded[userid] == True:
  1343.         event_instance = wcs.events.wcs_player_spawn(userid=userid)
  1344.         event_instance.fire()
  1345.     else:
  1346.         return
  1347.        
  1348. @Event('wcs_player_spawn')
  1349. def _wcs_player_spawn(event):
  1350.     userid = event.get_int('userid')
  1351.     index = index_from_userid(userid)
  1352.     players = PlayerDictionary()
  1353.     if userid not in wcsplayers:
  1354.         wcsplayers[userid] = WarcraftPlayer(userid)
  1355.     race = wcsplayers[userid].currace
  1356.     allraces = racedb.getAll()
  1357.     if race not in allraces:
  1358.         race = ConVar('wcs_default_race').get_string()
  1359.         wcsplayers[userid].changerace(ConVar('wcs_default_race').get_string(), kill=False,who='silent',safe=True)
  1360.     players[index].clan_tag = race
  1361.     if userid and players[index].team >= 2:
  1362.         for i, v in {'gravity':1.0,'speed':1.0,'longjump':1.0}.items():
  1363.             wcsgroup.setUser(userid, i, v)
  1364.  
  1365.         players[index].gravity = 1.0
  1366.         players[index].color = Color(255,255,255,255)
  1367.         wcsgroup.setUser(userid,'ability',None)
  1368.  
  1369.  
  1370.         wcsgroup.addUser(userid)
  1371.  
  1372.         wcsplayers[userid].show_xp()
  1373.  
  1374.         checkEvent(userid, 'player_spawn')
  1375.  
  1376.         raceinfo = racedb.getRace(race)
  1377.         if int(raceinfo['restrictteam']) and not players[index].steamid == 'BOT':
  1378.             if players[index].team == int(raceinfo['restrictteam']) and players[index].team >= 2 and not players[index].steamid == 'BOT':
  1379.                 players[index].team = 1
  1380.                 changerace.HowChange(userid)
  1381.  
  1382.         elif 'teamlimit' in raceinfo and not players[index].steamid == 'BOT':
  1383.             q = int(raceinfo['teamlimit'])
  1384.             if q:
  1385.                 v = wcsgroup.getUser({2:'T',3:'CT'}[players[index].team], 'restricted')
  1386.                 if v == None:
  1387.                     v = 0
  1388.                 if v > q:
  1389.                     players[index].team = 1
  1390.                     changerace.HowChange(userid)
  1391.  
  1392.         elif curmap in raceinfo['restrictmap'].split('|'):
  1393.             if not players[index].steamid == 'BOT':
  1394.                     players[index].team = 1
  1395.                     changerace.HowChange(userid)
  1396.  
  1397.         if raceinfo['spawncmd'] != "":
  1398.             command = raceinfo['spawncmd']
  1399.             command = command.split(";")
  1400.             for com in command:
  1401.                 execute_server_command('es', com)
  1402.  
  1403. @Event('player_say')           
  1404. def player_say(event):
  1405.     userid = event.get_int('userid')
  1406.     checkEvent(userid, 'player_say')
  1407. # =============================================================================
  1408. # >> LISTENERS
  1409. # =============================================================================
  1410. class OnPlayerSaved(ListenerManagerDecorator):
  1411.     manager = ListenerManager()
  1412.    
  1413. class OnPlayerLoaded(ListenerManagerDecorator):
  1414.     manager = ListenerManager()
  1415.    
  1416. class OnPlayerDeleted(ListenerManagerDecorator):
  1417.     manager = ListenerManager()
  1418.    
  1419. class OnRaceDeleted(ListenerManagerDecorator):
  1420.     manager = ListenerManager()
  1421.    
  1422. @OnPlayerLoaded
  1423. def on_loaded(wcsplayer):
  1424.     player_loaded[wcsplayer.userid] = True
  1425.     player = Player.from_userid(int(wcsplayer.userid))
  1426.     if player.dead == 0:
  1427.         event_instance = wcs.events.wcs_player_spawn(userid=wcsplayer.userid)
  1428.         event_instance.fire()
  1429.    
  1430. @OnClientActive
  1431. def on_client_active(index):
  1432.     wcsplayers[Player(index).userid] = WarcraftPlayer(Player(index).userid)
  1433.     race = wcsplayers[Player(index).userid].currace
  1434.     Player(index).clan_tag = race
  1435.    
  1436. @OnPlayerDeleted
  1437. def on_player_deleted(index):
  1438.     userid = userid_from_index(index)
  1439.     if userid not in wcsplayers:
  1440.         wcsplayers[userid] = WarcraftPlayer(userid)
  1441.        
  1442. @ServerCommand('changelevel')
  1443. def _changelevel_hook(command):
  1444.     for user in wcsplayers:
  1445.         wcsplayers[user].save()
  1446.     return CommandReturn.CONTINUE
  1447.        
  1448.  
  1449. @OnLevelShutdown
  1450. def level_shutdown_listener():
  1451.     for player in PlayerIter():
  1452.         userid = player.userid
  1453.         savexp.doCommand(userid)
  1454.    
  1455.     for user in wcsplayers:
  1456.         wcsplayers[user].save()
  1457.  
  1458. @OnLevelInit
  1459. def level_init_listener(mapname):
  1460.     allow_alpha = ConVar('sv_disable_immunity_alpha')
  1461.     allow_alpha.set_int(1)
  1462.     autokick = ConVar('mp_autokick')
  1463.     autokick.set_int(0)
  1464.     queue_command_string('sp reload wcs')
  1465.     global curmap
  1466.     if ".bsp" in mapname:
  1467.         mapname = mapname.strip('.bsp')
  1468.     curmap = mapname
  1469.     if config.coredata['saving'] == 1:
  1470.         repeat_delay = float(config.coredata['save_time'])*60.0
  1471.         repeat = Repeat(do_save)
  1472.         repeat.start(repeat_delay)
  1473.        
  1474. @OnTick
  1475. def on_tick():
  1476.     if config.coredata['keyinfo'] == 1:
  1477.         for player in PlayerIter('all'):
  1478.             if not player.is_bot():
  1479.                 user_queue = PagedMenu.get_user_queue(player.index)
  1480.                 if user_queue.active_menu is None:
  1481.                     userid = player.userid
  1482.                     race = wcsplayers[userid].currace
  1483.                     if race in wcsplayers[userid].all_races:
  1484.                         totallevel = wcsplayers[userid].totallevel
  1485.                         if 'level' in wcsplayers[userid].all_races[race]:
  1486.                             level = wcsplayers[userid].all_races[race]['level']
  1487.                             xp = wcsplayers[userid].all_races[race]['xp']
  1488.                             if config.cfgdata['experience_system'] == 0:
  1489.                                 needed = config.cfgdata['interval']*level if level else config.cfgdata['interval']
  1490.                             elif config.cfgdata['experience_system'] == 1:
  1491.                                 level_string = config.cfgdata['custom_system'].split(',')
  1492.                                 if level < len(level_string):
  1493.                                     needed = int(level_string[level])
  1494.                                 else:
  1495.                                     needed = int(level_string[len(level_string)-1])
  1496.                             steamid = player.uniqueid
  1497.                             rank,total = wcsplayers[player.userid].get_rank()
  1498.                             text = str(race)+'\n--------------------\nTotallevel: '+str(totallevel)+'\nLevel: '+str(level)+'\nXp: '+str(xp)+'/'+str(needed)+'\n--------------------\nWCS rank: '+str(rank)+'/'+str(total)
  1499.                             if SOURCE_ENGINE_BRANCH == "css":
  1500.                                 KeyHintText(text).send(player.index)
  1501.                             else:
  1502.                                 HudMsg(text, 0.025, 0.4,hold_time=0.2).send(player.index)
  1503.                
  1504.                
  1505. # =============================================================================
  1506. # >> Functions
  1507. # =============================================================================
  1508.  
  1509. def _load_ranks():
  1510.     with session_scope() as session:
  1511.         query = session.query(Players, Races).filter(Players.UserID == Races.UserID).filter(Players.currace == Races.name).all()
  1512.         if query != None:
  1513.             for (user, race) in query:
  1514.                 wcs_rank[user.steamid] = {}
  1515.                 wcs_rank[user.steamid]['name'] = user.name
  1516.                 wcs_rank[user.steamid]['totallevel'] = user.totallevel
  1517.                 wcs_rank[user.steamid]['currace'] = user.currace
  1518.                 wcs_rank[user.steamid]['level'] = race.level
  1519.                
  1520.    
  1521. def centertell(userid,message):
  1522.     index = index_from_userid(userid)
  1523.     if SOURCE_ENGINE_BRANCH == "css":
  1524.         queue_command_string("es_centertell %s %s" %(userid,message))
  1525.     else:
  1526.         HudMsg(message, -1, 0.35,hold_time=5.0).send(index)
  1527.  
  1528. def checkEvent(userid, event, other_userid=0, health=0, armor=0, weapon='', dmg_health=0, dmg_armor=0, hitgroup=0,assister=0,headshot=0):
  1529.     if userid is not None:
  1530.         player_entity = Player(index_from_userid(userid))
  1531.         if int(player_entity.team) > 1:
  1532.             race = wcsplayers[userid].currace
  1533.             race1 = racedb.races[race]
  1534.             if event in raceevents[race]:
  1535.                 skills = wcsplayers[userid].all_races[race]['skills'].split('|')
  1536.                 for index in raceevents[race][event]:
  1537.                     try:
  1538.                         level = int(skills[int(index)])
  1539.                     except IndexError:
  1540.                         level = None
  1541.                     if level:
  1542.                         wcs_dice = ConVar('wcs_dice')
  1543.                         wcs_dice.set_int(random.randint(0, 100))
  1544.                         for x in range(1, 9):
  1545.                             wcs_dice = ConVar('wcs_dice'+str(x))
  1546.                             wcs_dice.set_int(random.randint(0,100))
  1547.                         skill = 'skill'+str(int(index)+1)
  1548.  
  1549.                         try:
  1550.                             if race1[skill]['setting'].split('|')[level-1]:
  1551.                                 settings = race1[skill]['setting'].split('|')[level-1]
  1552.                                 if ';' in settings:
  1553.                                     sub_settings = settings.split(';')
  1554.                                     for com in sub_settings:
  1555.                                         execute_server_command('es', com)
  1556.                                 else:
  1557.                                     execute_server_command('es', settings)
  1558.                         except IndexError:
  1559.                             continue
  1560.                         if 'cmd' in race1[skill]:
  1561.                             if race1[skill]['cmd']:
  1562.                                 command = race1[skill]['cmd']
  1563.                                 command = command.split(";")
  1564.                                 for com in command:
  1565.                                     execute_server_command('es', com)                  
  1566.                         else:
  1567.                             continue
  1568.                         if 'sfx' in race1[skill]:
  1569.                             if race1[skill]['sfx']:
  1570.                                 command = race1[skill]['sfx']
  1571.                                 command = command.split(";")
  1572.                                 for com in command:
  1573.                                     execute_server_command('es', com)  
  1574.  
  1575. def checkEvent1(userid, event):
  1576.     if userid is not None:
  1577.         player_entity = Player(index_from_userid(userid))
  1578.         if int(player_entity.team) > 1:
  1579.             race = wcsplayers[userid].currace
  1580.             race1 = racedb.races[race]
  1581.             if event in raceevents[race]:
  1582.                 skills = wcsplayers[userid].all_races[race]['skills'].split('|')
  1583.                 index = raceevents[race][event][0]
  1584.  
  1585.                 try:
  1586.                     level = int(skills[int(index)])
  1587.                 except IndexError:
  1588.                     level = None
  1589.                 if level:
  1590.                     if gamestarted:
  1591.                         wcs_dice = ConVar('wcs_dice')
  1592.                         wcs_dice.set_int(random.randint(0, 100))
  1593.                         for x in range(1, 9):
  1594.                             wcs_dice = ConVar('wcs_dice'+str(x))
  1595.                             wcs_dice.set_int(random.randint(0,100))
  1596.                         skill = 'skill'+str(int(index)+1)
  1597.                         skill_names = race1['skillnames'].split('|')
  1598.                         ulti_name = skill_names[int(index)]
  1599.                         cooldown = wcsgroup.getUser(userid, event+'_cooldown')
  1600.                         if cooldown is None:
  1601.                             cooldown = 0
  1602.                         cooldown = int(cooldown)
  1603.                         wcsgroup.setUser(userid, event+'_pre_cooldown', cooldown)
  1604.                         timed = int(float(time.time()))
  1605.                         downtime = str(race1[skill]['cooldown']).split('|')
  1606.                         nol = race1['numberoflevels']
  1607.                         if '|' in nol:
  1608.                             nol = nol.split('|')
  1609.                             nol = [int(x) for x in nol]
  1610.                         else:
  1611.                             nos = int(race1['numberofskills'])
  1612.                             nol_tmp = int(race1['numberoflevels'])
  1613.                             nol = []
  1614.                             x = 0
  1615.                             while x < nos:
  1616.                                 nol.append(nol_tmp)
  1617.                                 x += 1
  1618.                        
  1619.                         if len(downtime) == int(nol[int(index)]):
  1620.                             downtime = int(downtime[level-1])
  1621.                         else:
  1622.                             downtime = int(downtime[0])
  1623.  
  1624.                         if not downtime or (timed - cooldown >= downtime):
  1625.                             if race1[skill]['setting']:
  1626.                                 try:
  1627.                                     if race1[skill]['setting'].split('|')[level-1]:
  1628.                                         settings = race1[skill]['setting'].split('|')[level-1]
  1629.                                         if ';' in settings:
  1630.                                             sub_settings = settings.split(';')
  1631.                                             for com in sub_settings:
  1632.                                                 execute_server_command('es', com)
  1633.                                         else:
  1634.                                             execute_server_command('es', settings)
  1635.                                 except IndexError:
  1636.                                     return
  1637.  
  1638.                             if 'cmd' in race1[skill]:
  1639.                                 ConVar("wcs_userid").set_int(userid)
  1640.                                 if race1[skill]['cmd']:
  1641.                                     command = race1[skill]['cmd']
  1642.                                     command = command.split(";")
  1643.                                     for com in command:
  1644.                                         execute_server_command('es', com)
  1645.                             else:
  1646.                                 return
  1647.                             if 'sfx' in race1[skill]:
  1648.                                 ConVar("wcs_userid").set_int(userid)
  1649.                                 if race1[skill]['sfx']:
  1650.                                     command = race1[skill]['sfx']
  1651.                                     command = command.split(";")
  1652.                                     for com in command:
  1653.                                         execute_server_command('es', com)
  1654.  
  1655.                             wcsgroup.setUser(userid, event+'_cooldown', timed)
  1656.                             #Success
  1657.                             return (1, downtime, timed-cooldown)
  1658.                         #Cooldown
  1659.                         return (0, downtime, timed-cooldown)
  1660.                     #Game has not started
  1661.                     return False
  1662.     return None
  1663.  
  1664. def do_save():
  1665.     for x in wcsplayers:
  1666.         wcsplayers[x].save()
  1667.        
  1668. def exists(userid):
  1669.     try:
  1670.         index_from_userid(userid)
  1671.     except ValueError:
  1672.         return False
  1673.     return True
  1674.  
  1675. def find_items(name):
  1676.     item_list = []
  1677.     items_all = wcs.wcs.ini.getItems
  1678.     items_all.walk(gather_subsection)
  1679.     for item in item_names:
  1680.         item_sec = itemdb.getSectionFromItem(item)
  1681.         iteminfo = itemdb.getItem(item)
  1682.         if name.lower() in iteminfo['name'].lower():
  1683.             item_list.append(item)
  1684.     if len(item_list):
  1685.         return item_list
  1686.     else:
  1687.         return -1
  1688.  
  1689. def format_message(message):
  1690.     for color in color_codes:
  1691.         if color in message:
  1692.             message = message.replace(color, '')
  1693.     return message
  1694.    
  1695. def gather_subsection(section, key):
  1696.     if section.depth > 1:
  1697.         if section.name not in item_names:
  1698.             item_names.append(section.name)
  1699.            
  1700. def get_cooldown(userid):
  1701.     race = wcsplayers[userid].currace
  1702.     race1 = racedb.races[race]
  1703.     if 'player_ultimate' in raceevents[race]:
  1704.         skills = wcsplayers[userid].all_races[race]['skills'].split('|')
  1705.         index = raceevents[race]['player_ultimate'][0]
  1706.         skill = 'skill'+str(int(index)+1)
  1707.         try:
  1708.             level = int(skills[int(index)])
  1709.         except IndexError:
  1710.             level = None
  1711.         if level:
  1712.             downtime = str(race1[skill]['cooldown']).split('|')
  1713.             nol = race1['numberoflevels']
  1714.             if '|' in nol:
  1715.                 nol = nol.split('|')
  1716.                 nol = [int(x) for x in nol]
  1717.             else:
  1718.                 nos = int(race1['numberofskills'])
  1719.                 nol_tmp = int(race1['numberoflevels'])
  1720.                 nol = []
  1721.                 x = 0
  1722.                 while x < nos:
  1723.                     nol.append(nol_tmp)
  1724.                     x += 1
  1725.             if len(downtime) == nol[int(index)]:
  1726.                 downtime = int(downtime[level-1])
  1727.                 if not downtime:
  1728.                     downtime = str(race1[skill]['cooldown']).split('|')
  1729.                     downtime = int(downtime[0])
  1730.                 return downtime
  1731.             else:
  1732.                 return int(downtime[len(downtime)-1])  
  1733.        
  1734. def get_random_race(userid):
  1735.     race_list = []
  1736.     races = racedb.getAll()
  1737.     allraces = races.keys()
  1738.     for number, race in enumerate(allraces):
  1739.         v = changerace.canUse(userid,race)
  1740.         if not v:
  1741.             race_list.append(race)
  1742.     if len(race_list):
  1743.         chosen = str(choice(race_list))
  1744.         return chosen
  1745.     else:
  1746.         return -1
  1747.  
  1748. def is_number(s):
  1749.     try:
  1750.         float(s)
  1751.         return True
  1752.     except ValueError:
  1753.         return False   
  1754.        
  1755. def load_races():
  1756.     races = racedb.getAll()
  1757.     for race in races:
  1758.         for section in races[race]:
  1759.             if section == 'skillcfg':
  1760.                 global raceevents
  1761.                 raceevents = {}
  1762.                 if not race in raceevents:
  1763.                     raceevents[race] = {}
  1764.  
  1765.                 events = races[race]['skillcfg'].split('|')
  1766.  
  1767.                 for index, cfg in enumerate(events):
  1768.                     if not cfg in raceevents[race]:
  1769.                         raceevents[race][cfg] = []
  1770.  
  1771.                     raceevents[race][cfg].append(str(index))
  1772.  
  1773.             elif section == 'preloadcmd':
  1774.                 if races[race]['preloadcmd'] != "":
  1775.                     command = races[race]['preloadcmd']
  1776.                     command = command.split(";")
  1777.                     for com in command:
  1778.                         execute_server_command('es', com)
  1779. def remove_effects():
  1780.     for player in PlayerIter():
  1781.         userid = player.userid
  1782.         queue_command_string('wcs_color %s 255 255 255 255' % userid)
  1783.         queue_command_string('wcs_setgravity %s 1.0' % userid)
  1784.         queue_command_string('es playerset speed %s 1.0' % userid)
  1785.         queue_command_string('es wcsgroup set regeneration_active %s 0' % userid)
  1786.    
  1787. def set_team(userid):
  1788.     if exists(userid):
  1789.         player = Player.from_userid(userid)
  1790.         if player.team == 0:
  1791.             Player.from_userid(userid).team = 1
  1792.    
  1793. def tell(userid, message):
  1794.     text_message = 1
  1795.     index = index_from_userid(userid)
  1796.     if text_message == 1:
  1797.         if SOURCE_ENGINE_BRANCH == "css":
  1798.             message = message.replace('\x05','\x03')
  1799.         SayText2(message).send(index)
  1800.     if text_message == 2:
  1801.         message = format_message(message)
  1802.         HintText(message).send(index)
  1803.  
  1804. @ServerCommand("wcs_giveprivate")
  1805. def _give_private_race(command):
  1806.     userid = int(command[1])
  1807.     race_name = str(command[2])
  1808.     steamid = Player.from_userid(userid).uniqueid
  1809.     race_dict = ConfigObj(ini.races,encoding="utf-8")
  1810.     allowonly = race_dict[race_name]['allowonly']
  1811.     if steamid not in allowonly:
  1812.         if allowonly != "":
  1813.             new_only = str(allowonly)+"|"+str(steamid)
  1814.         else:
  1815.             new_only = str(steamid)
  1816.         race_dict[race_name]['allowonly'] = new_only
  1817.         race_dict.write()
  1818.         ini.races = os.path.join(PLUGIN_PATH, 'wcs/races', 'races.ini')
  1819.         racedb.races = ini.getRaces
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement