''' (c) 2008 by the GunGame Coding Team
Title: gg_gladiator
Version: 0.0.91
Description: Custom addon.
'''
# ==============================================================================
# IMPORTS
# ==============================================================================
# Python imports
# EventScripts imports
import es
import os
import gamethread
import playerlib
import random
import repeat
import datetime
import popuplib
from sqlite3 import dbapi2 as sqlite
# GunGame imports
import gungamelib
# ==============================================================================
# ADDON REGISTRATION
# ==============================================================================
# Register this addon with EventScripts
info = es.AddonInfo()
info.name = 'Gladiator Addon for GunGame: Python'
info.version = '0.0.91'
info.url = ''
info.basename = 'gungame/custom_addons/gg_gladiator'
info.author = 'Don & Slipknot'
first_t_knifer = 0
first_ct_knifer = 0
bot_start_levels = {}
glad_stats = {}
topten = []
cfg_file = es.ServerVar("eventscripts_gamedir") + "/cfg/gungame5/custom_addon_configs/gg_gladiator.cfg"
botprofile = es.ServerVar("eventscripts_gamedir") + "/botprofile.db"
gg_gladtoptenfile = es.ServerVar("eventscripts_gamedir") + "/addons/eventscripts/gungame/custom_addons/gg_gladiator/gg_glad_topten.csv"
gPlayers = set()
nsPlayers = set()
one_v_one_mode = 0
win_sound = ''
knife_level = 0
one_v_one_only = 0
__version__ = '0.0.91'
es.ServerVar('gg_glad_ver', __version__).makepublic()
class connection(object):
def __init__(self,path):
self.con = sqlite.connect(path)
self.cur = self.con.cursor()
def execute(self,sql):
self.cur.execute(sql)
self.con.commit()
def query(self,sql):
self.cur.execute(sql)
# return self.cur.fetchall()
return convertQuery(self.cur.fetchall())
def close(self):
self.con.close()
# ==============================================================================
# GAME EVENTS
# ==============================================================================
def load():
global knife_level
gg_gladiator = gungamelib.registerAddon('gg_gladiator')
gg_gladiator.setDisplayName('GG Gladiator')
gg_gladiator.loadTranslationFile()
es.stringtable('downloadables', 'sound/gungame/gg_gladiator/gladdiewithhonor.wav')
es.stringtable('downloadables', 'sound/gungame/gg_gladiator/gladkill.wav')
es.stringtable('downloadables', 'sound/gungame/gg_gladiator/gladcrowd1.wav')
es.stringtable('downloadables', 'sound/gungame/gg_gladiator/gladcrowdcheer.wav')
knife_level = gungamelib.getTotalLevels()
load_bot_levels()
db.execute("CREATE TABLE IF NOT EXISTS [UserStats] ([SteamID]VARCHAR(30) UNIQUE NOT NULL,[Name]VARCHAR(30),[Maps]INT,[Glads]INT,[Wins]INT,[Win_Ratio]FLOAT,[LastConnect]VARCHAR(30))")
if not es.exists('saycommand', '!gladstats'):
es.regsaycmd('!gladstats', 'gungame/custom_addons/gg_gladiator/gladstats', 'Say command for displaying the stats')
if not es.exists('saycommand', '!gladranks'):
es.regsaycmd('!gladranks', 'gungame/custom_addons/gg_gladiator/gladranks', 'Say command for displaying the ranks')
stats = db.query("SELECT * FROM UserStats")
for line in stats:
glad_stats[line[0]] = (line[2],line[3],line[4],line[5],line[1],line[6])
repeat.create('crowd', playcrowdsound, ())
reset_game()
def unload():
repeat.delete('crowd')
es.unregisterClientCommandFilter(specfilter)
gungamelib.unregisterAddon('gg_gladiator')
if es.exists('saycommand', '!gladstats'):
es.unregsaycmd('!gladstats')
if es.exists('saycommand', '!gladranks'):
es.unregsaycmd('!gladranks')
db.close()
@es.addons.registerClientCommandFilter
def specfilter(userid, args):
uid = playerlib.uniqueid(userid)
team = args[1] if len(args) >= 2 else 2
team = str(team)
if uid not in gPlayers:
return True
if args[0] == 'jointeam' and team != '1':
gungamelib.msg('gg_gladiator', userid, 'Spectate')
return False
return True
def unload():
gungamelib.unregisterAddon('gg_gladiator')
es.addons.unregisterClientCommandFilter(specfilter)
db = connection(es.ServerVar("eventscripts_gamedir") + '/addons/eventscripts/gungame/custom_addons/gg_gladiator/gladstats.db')
def reset_game():
playerlist = playerlib.getPlayerList('#all')
for player in playerlist:
player_userid = int(player)
reset_player(player_userid)
es.server.cmd("es_set mp_restartgame 1")
def es_map_start(event_var):
repeat.stop('crowd')
global first_t_knifer, first_ct_knifer, one_v_one_mode
first_t_knifer = 0
first_ct_knifer = 0
gPlayers.clear()
nsPlayers.clear()
es.stringtable('downloadables', 'sound/gungame/gg_gladiator/gladdiewithhonor.wav')
es.stringtable('downloadables', 'sound/gungame/gg_gladiator/gladkill.wav')
es.stringtable('downloadables', 'sound/gungame/gg_gladiator/gladcrowd1.wav')
es.stringtable('downloadables', 'sound/gungame/gg_gladiator/gladcrowdcheer.wav')
one_v_one_mode = 0
def player_activate(event_var):
userid = event_var['userid']
reset_player(userid)
if (one_v_one_mode == 1):
uid = playerlib.uniqueid(userid)
gPlayers.add(uid)
def player_death(event_var):
if (one_v_one_mode == 1):
if (int(event_var['attacker']) == 0):
if (int(es.getplayerteam(event_var['userid'])) == 2):
gungamePlayer = gungamelib.getPlayer(first_ct_knifer)
userid = first_ct_knifer
else:
gungamePlayer = gungamelib.getPlayer(first_t_knifer)
userid = first_t_knifer
gungamePlayer.levelup(1, userid, 'kill')
def player_hurt(event_var):
if (one_v_one_mode == 1):
es.emitsound('player', event_var['userid'], 'gungame/gg_gladiator/gladcrowd1.wav', 1, 0)
if (int(event_var['es_userteam']) == 2):
tplayer = playerlib.getPlayer(event_var['userid'])
ctplayer = playerlib.getPlayer(event_var['attacker'])
else:
ctplayer = playerlib.getPlayer(event_var['userid'])
tplayer = playerlib.getPlayer(event_var['attacker'])
gungamelib.msg('gg_gladiator', '#all', 'Health_Message', {'ctName': ctplayer.attributes['name'], 'ctHealth': str(ctplayer.get('health')), 'tName': tplayer.attributes['name'], 'tHealth': str(tplayer.get('health'))})
def player_spawn(event_var):
if (one_v_one_mode == 1):
userid = event_var['userid']
if es.isbot(userid):
gungamePlayer = gungamelib.getPlayer(userid)
if (gungamePlayer['level'] != knife_level):
gungamePlayer.level = knife_level
def gg_levelup(event_var):
global first_t_knifer, first_ct_knifer
if int(event_var['old_level']) != gungamelib.getTotalLevels():
newLevel = int(event_var['new_level'])
if gungamelib.getLevelWeapon(newLevel) == 'knife':
killerteam = int(event_var['es_attackerteam'])
if first_t_knifer == 0 and first_ct_knifer == 0:
if killerteam == 2:
#es.centermsg(event_var['es_attackername'] + " is First T Gladiator")
gungamelib.centermsg('gg_gladiator', '#all', 'First_T_Gladiator', {'tName': event_var['es_attackername']})
gungamelib.msg('gg_gladiator', '#all', 'First_T_Gladiator', {'tName': event_var['es_attackername']})
first_t_knifer = int(event_var['attacker'])
elif killerteam == 3:
es.centermsg(event_var['es_attackername'] + " is First CT Gladiator")
gungamelib.centermsg('gg_gladiator', '#all', 'First_CT_Gladiator', {'ctName': event_var['es_attackername']})
gungamelib.msg('gg_gladiator', '#all', 'First_CT_Gladiator', {'ctName': event_var['es_attackername']})
first_ct_knifer = int(event_var['attacker'])
elif ((first_t_knifer == 0) and (first_ct_knifer > 0) and (killerteam == 2)):
first_t_knifer = int(event_var['attacker'])
gamethread.delayed(.1, do_gladiator, (first_t_knifer, first_ct_knifer))
elif ((first_t_knifer > 0) and (first_ct_knifer == 0) and (killerteam == 3)):
first_ct_knifer = int(event_var['attacker'])
gamethread.delayed(.1, do_gladiator, (first_t_knifer, first_ct_knifer))
def do_gladiator(first_t_knifer, first_ct_knifer):
global gPlayers, one_v_one_mode, win_sound,nsPlayers
if (es.ServerVar('bot_quota') > 0):
if ((es.isbot(first_t_knifer) and not es.isbot(first_ct_knifer)) or not (es.isbot(first_t_knifer) and es.isbot(first_ct_knifer))):
es.server.cmd("es_set bot_quota 1")
elif (not es.isbot(first_t_knifer) and not es.isbot(first_ct_knifer)):
es.server.cmd("es_set bot_quota 0")
elif (es.isbot(first_t_knifer) and es.isbot(first_ct_knifer)):
es.server.cmd("es_set bot_quota 2")
es.server.cmd("es_set bot_join_after_player 0")
es.server.cmd("es_set bot_quota_mode fill")
one_v_one_mode = 1
win_sound = gungamelib.getSound('winner')
tplayer=playerlib.getPlayer(first_t_knifer)
tplayer.set('health', 100)
tplayer.set('armor', 100)
ctplayer=playerlib.getPlayer(first_ct_knifer)
ctplayer.set('health', 100)
ctplayer.set('armor', 100)
gungamelib.msg('gg_gladiator', '#all', 'T_Gladiator', {'tName': tplayer.attributes['name']})
gungamelib.msg('gg_gladiator', '#all', 'CT_Gladiator', {'ctName': ctplayer.attributes['name']})
playerlist = playerlib.getPlayerList('#all')
for player in playerlist:
player_userid = int(player)
uid = playerlib.uniqueid(player_userid)
if player_userid != first_t_knifer and player_userid != first_ct_knifer:
if uid == 'BOT':
playerlib.getPlayer(player_userid).kick('No Bots in 1 vs 1')
for player in playerlist:
player_userid = int(player)
uid = playerlib.uniqueid(player_userid)
gamethread.delayed(1.2, es.playsound, (player_userid,'gungame/gg_gladiator/gladdiewithhonor.wav', 1))
if player_userid != first_t_knifer and player_userid != first_ct_knifer:
gPlayers.add(uid)
if (int(es.getplayerteam(player_userid)) > 1 and uid != 'BOT'):
nsPlayers.add(uid)
es.changeteam(player_userid, 1)
gungamelib.centermsg('gg_gladiator', '#all', 'Glad_Mode')
gungamelib.msg('gg_gladiator', '#all', 'Glad_Mode')
repeat.start('crowd', 6.27, 50)
def gg_win(event_var):
if repeat.status('crowd') > 1:
repeat.stop('crowd')
playerlist = playerlib.getPlayerList('#all')
for player in playerlist:
player_userid = int(player)
steamid = es.getplayersteamid(player_userid)
if (player_userid == int(event_var['winner'])):
winner_steam = steamid
if ((player_userid == first_t_knifer or player_userid == first_ct_knifer) and steamid != 'BOT'):
add_glad(steamid)
if (steamid != 'BOT'):
add_map(steamid)
for steamid in nsPlayers:
add_map(steamid)
if (one_v_one_mode == 1):
gamethread.delayed(.2, play_final, event_var['winner'])
if (winner_steam != 'BOT'):
add_win(winner_steam)
top_ten()
def play_final(winner):
playerlist = playerlib.getPlayerList('#all')
for player in playerlist:
player_userid = int(player)
es.stopsound(player_userid, win_sound)
gamethread.delayed(1.6,es.emitsound, ('player', winner, 'gungame/gg_gladiator/gladkill.wav', 1, 0))
def parse_botprofile():
botlevels = {}
fp = open(xaskins_skinfiles_path + skinnames[i] +".txt")
for line in fp:
line = line.strip("\n")
line = line.strip("\r")
if line[0:1] == '"':
skinfile = line[findsplit(line)+1:len(line)]
skinname = line[0:findsplit(line)]
skinname = skinname.strip('"')
skinmodel = makedownloadable(skinfile,skinnames[i])
skinlist[skinnames[i]][skinname] = skinmodel
def load_bot_levels():
global elite, expert, veryhard, hard, tough, normal, fair, easy
one_v_one_only = es.ServerVar('1_vs_1_only')
elite = int(float(es.ServerVar('gg_glad_elite'))/100 * knife_level)
expert = int(float(es.ServerVar('gg_glad_expert'))/100 * knife_level)
veryhard = int(float(es.ServerVar('gg_veryhard_elite'))/100 * knife_level)
hard = int(float(es.ServerVar('gg_glad_hard'))/100 * knife_level)
tough = int(float(es.ServerVar('gg_glad_tough'))/100 * knife_level)
normal = int(float(es.ServerVar('gg_glad_normal'))/100 * knife_level)
fair = int(float(es.ServerVar('gg_glad_fair'))/100 * knife_level)
easy = int(float(es.ServerVar('gg_glad_easy'))/100 * knife_level)
if (elite == 0): elite = 1
if (expert == 0): expert = 1
if (veryhard == 0): veryhard = 1
if (hard == 0): hard = 1
if (tough == 0): tough = 1
if (normal == 0): normal = 1
if (fair == 0): fair = 1
if (easy == 0): easy = 1
fp = open(botprofile)
for line in fp:
if ("Elite" in line and "Template" not in line):
bot_start_levels[line.split()[1]] = elite
if ("Expert" in line and "Template" not in line):
bot_start_levels[line.split()[1]] = expert
if ("VeryHard" in line and "Template" not in line):
bot_start_levels[line.split()[1]] = veryhard
if ("Hard" in line and "Template" not in line and "VeryHard" not in line):
bot_start_levels[line.split()[1]] = hard
if ("Tough" in line and "Template" not in line):
bot_start_levels[line.split()[1]] = tough
if ("Normal" in line and "Template" not in line):
bot_start_levels[line.split()[1]] = normal
if ("Fair" in line and "Template" not in line):
bot_start_levels[line.split()[1]] = fair
if ("Easy" in line and "Template" not in line):
bot_start_levels[line.split()[1]] = easy
def add_map(steamid):
maps = glad_stats[steamid][0]
maps = int(maps) + 1
glad_stats[steamid] = (maps,glad_stats[steamid][1],glad_stats[steamid][2])
db.execute("UPDATE UserStats SET Maps='%s' WHERE SteamID='%s'" % (maps, steamid))
def add_glad(steamid):
glads = glad_stats[steamid][1]
glads = int(glads) + 1
wins = glad_stats[steamid][2]
win_ratio = float(wins)/float(glads)
glad_stats[steamid] = (glad_stats[steamid][0],glads,glad_stats[steamid][2])
db.execute("UPDATE UserStats SET Glads='%s' WHERE SteamID='%s'" % (glads, steamid))
db.execute("UPDATE UserStats SET Win_Ratio='%s' WHERE SteamID='%s'" % (win_ratio, steamid))
def add_win(steamid):
wins = glad_stats[steamid][2]
glads = glad_stats[steamid][1]
wins = int(wins) + 1
win_ratio = float(wins)/float(glads)
glad_stats[steamid] = (glad_stats[steamid][0],glad_stats[steamid][1],wins)
db.execute("UPDATE UserStats SET Wins='%s' WHERE SteamID='%s'" % (wins, steamid))
db.execute("UPDATE UserStats SET Win_Ratio='%s' WHERE SteamID='%s'" % (win_ratio, steamid))
def playcrowdsound():
playerlist = playerlib.getPlayerList('#human')
for player in playerlist:
player_userid = int(player)
es.playsound(player_userid,'gungame/gg_gladiator/gladcrowdcheer.wav', 0.25)
def reset_player(userid):
steamid = es.getplayersteamid(userid)
name = es.getplayername(userid)
gungamePlayer = gungamelib.getPlayer(userid)
if (steamid != 'BOT'):
gungamelib.msg('gg_gladiator', userid, 'Gladiator_Loaded')
stats = db.query("SELECT * FROM UserStats WHERE SteamID='%s'" % steamid)
if not stats:
db.execute("INSERT INTO UserStats ('SteamID', 'Name', 'Maps', 'Glads', 'Wins', 'Win_Ratio', 'LastConnect') VALUES ('%s', '%s', 0, 0, 0, 0, '%s')" % (steamid, name, datetime.date.today()))
glad_stats[steamid] = (0,0,0,0.0,name,datetime.date.today())
else:
db.execute("UPDATE UserStats SET LastConnect='%s' WHERE SteamID='%s'" % (datetime.date.today(), steamid))
glad_stats[steamid] = (stats[0][2],stats[0][3],stats[0][4],stats[0][5],name,datetime.date.today())
if (one_v_one_only != 1):
if es.isbot(userid):
# The following line removes the Bot Prefix from the Bot's name so we can get their level
bot_name = name
if (es.ServerVar('bot_prefix') != ''):
bot_name = name.split(str(es.ServerVar('bot_prefix')))[1].strip()
newlevel = int(bot_start_levels[bot_name])
gungamePlayer.level = newlevel
myPlayer_level = gungamePlayer['level']
else:
if steamid not in glad_stats.keys():
newlevel = int(knife_level/2)
gungamePlayer.level = newlevel
else:
if (int(glad_stats[steamid][0]) < 1):
stat = 0.0
else:
stat = float(glad_stats[steamid][1]) / float(glad_stats[steamid][0])
gc1 = ((float(knife_level)/2) + 1) - ((float(knife_level)/2) * 2 * stat)
if (gc1 < 1): gc1 = 1
if (float(glad_stats[steamid][1]) != 0):
win_ratio = float(glad_stats[steamid][2]) / float(glad_stats[steamid][1])
else:
win_ratio = 0.0
if (win_ratio > 0.4999999):
gc2 = gc1 + (gc1/1.22 * win_ratio)
else:
gc2 = gc1
newlevel = int(gc2)
gungamePlayer.level = newlevel
gungamelib.msg('gg_gladiator', userid, 'Your_Stats', {'maps': glad_stats[steamid][0], 'glads': glad_stats[steamid][1], 'wins': glad_stats[steamid][2], 'win_ratio': round(win_ratio,3), 'level': newlevel})
def gladranks():
userid = es.getcmduserid()
buildRanksMenu(userid)
popuplib.send('gladRanksMenu', userid)
def gladstats():
userid = es.getcmduserid()
steamid = es.getplayersteamid(userid)
line = db.query("SELECT * FROM UserStats WHERE SteamID='%s'" % steamid)[0]
if (int(glad_stats[steamid][0]) < 1):
stat = 0.0
else:
stat = float(glad_stats[steamid][1]) / float(glad_stats[steamid][0])
gc1 = ((float(knife_level)/2) + 1) - ((float(knife_level)/2) * 2 * stat)
if (gc1 < 1): gc1 = 1
if (float(glad_stats[steamid][1]) != 0):
win_ratio = float(glad_stats[steamid][2]) / float(glad_stats[steamid][1])
else:
win_ratio = 0.0
if (win_ratio > 0.4999999):
gc2 = gc1 + (gc1/1.22 * win_ratio)
else:
gc2 = gc1
newlevel = int(gc2)
gungamelib.msg('gg_gladiator', userid, 'Your_Stats', {'maps': glad_stats[steamid][0], 'glads': glad_stats[steamid][1], 'wins': glad_stats[steamid][2], 'win_ratio': round(win_ratio,3), 'level': newlevel})
def buildRanksMenu(userid):
# Un-send and delete the menu
pname = es.getplayername(userid)
if popuplib.exists('gladRanksMenu'):
popuplib.unsendname('gladRanksMenu', playerlib.getUseridList('#human'))
popuplib.delete('gladRanksMenu')
# Get stats
stats = db.query("SELECT * FROM UserStats ORDER BY Win_Ratio DESC LIMIT 10")
# Create the "gladRanksMenu" popup
gladRanksMenu = popuplib.create('gladRanksMenu')
gladRanksMenu.addline('# Win Ratio Name')
# Add ranks
index = 1
for line in stats:
if pname == line[1]:
gladRanksMenu.addline('->%s %s %s' % (str(index), str(round(line[5],3)), line[1]))
else:
gladRanksMenu.addline('%s %s %s' % (str(index), str(round(line[5],3)), line[1]))
index += 1
# Finish off the menu
gladRanksMenu.addline('----------------------------------------')
gladRanksMenu.addline('0. Exit')
gladRanksMenu.timeout('send', 5)
gladRanksMenu.timeout('view', 5)
# Thanks to GodJonez for this snippet of code to handle UTF-8
def utfcode(value):
""" converts value into utf-8 coded string if it is unicode, otherwise returns the value itself """
if type(value).__name__ == 'unicode':
return value.encode('utf-8')
return value
def convertQuery(result):
""" converts all unicode strings in a full SQLite query result to utf-8 string objects """
newresult = list()
for row in result:
newrow = [utfcode(item) for item in row]
newresult.append(newrow)
return newresult
def top_ten():
global topten
stats = db.query("SELECT * FROM UserStats ORDER BY Win_Ratio DESC LIMIT 10")
topten.append("Steam ID,Name,Maps,Glads,Wins,Win Ratio \n")
for line in stats:
p = str(line[0])+ "," + str(line[1])+ "," + str(line[2])+ "," + str(line[3]) + "," + str(line[4]) + "," + str(line[5]) + "\n"
topten.append(p)
file = open(gg_gladtoptenfile, "w")
b = file.writelines(topten)
file.close()
topten = [][[