minor updates to improve the bot tracking players ingame, still a lot left to do probably

This commit is contained in:
jenzur 2020-04-22 00:17:28 +02:00
parent a5f6f6b9c5
commit 1bb64ce55b
8 changed files with 290 additions and 608 deletions

View File

@ -1,100 +1,34 @@
import os import os
import sys
import subprocess import subprocess
import atexit import atexit
from threading import Timer from threading import Timer
import string import string
import random import random
import time import time
import mysql.connector
from mysql.connector import Error
from settings import mysql_connection_ip, mysql_connection_user, mysql_connection_pw, mysql_connection_database
looptestPath = '/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/looptest.cfg' looptestPath = '/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/looptest.cfg'
consolelogPath = '/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log'
clearbool = True
def id_generator(size=6, chars=string.ascii_uppercase + string.digits): def get_connection():
return ''.join(random.choice(chars) for _ in range(size)) return mysql.connector.connect(
host=mysql_connection_ip,
def switchbool(): user=mysql_connection_user,
global clearbool passwd=mysql_connection_pw,
clearbool = True database=mysql_connection_database)
def clearconsolelog():
global clearbool
if clearbool:
clearbool = False
open(consolelogPath, 'w').close()
#print('cleaned console')
connectionTimer = Timer(3.0, switchbool)
#daemon true kills thread instead of deadlock waiting in case program exits
connectionTimer.daemon = True
connectionTimer.start()
def writeCfgInput(Input): def writeCfgInput(Input):
with open(looptestPath, 'w') as f: with open(looptestPath, 'w') as f:
f.write(Input) f.write(Input)
def getconsoleOutputForStatus():
i = 0
while i < 8:
time.sleep(0.25)
randomlygeneratedString = id_generator(11)
str = "status; wait 5; {0}; wait 5;".format(randomlygeneratedString)
writeCfgInput(str)
checkConsoleOutput(randomlygeneratedString)
server_str = ""
player_count = 0
with open(consolelogPath, 'r') as f:
for line in f:
try:
if "udp/ip" in line: server_str = line[9:].strip()
if "players " in line: player_count = int(line[9:].split()[0].strip())
except Exception:
pass
if server_str:
print('server_str: ', server_str, '\nplayer_count: ', player_count)
return (server_str, player_count)
i += 1
return ("None", "None")
def get_output_if_spec():
randomlygeneratedString = id_generator(11)
str = "zspawn; wait 500; {0}; wait 5;".format(randomlygeneratedString)
writeCfgInput(str)
#is sm_team a command to show team?
#maybe instead say !teaminfo, add sourcemod command to autism_bot_info.sp to print team to chat instead
targetstr = "This feature requires that you are on a team."
failurestr = "Unknown command \"zspawn\""
alivestr = "This feature requires that you are dead."
checkConsoleOutput(randomlygeneratedString)
with open(consolelogPath, 'r') as f:
for line in f:
if alivestr in line: return 2
if targetstr in line: return 1
if failurestr in line: return 0
return 0
def checkConsoleOutput(input):
iterations_count = 0
#print('entered checkconsole output')
while iterations_count < 6:
time.sleep(0.5)
with open(consolelogPath, 'r') as f:
for line in f:
if input in line:
iterations_count += 6
break
iterations_count += 1
def resetCfgInputShortWait(): def resetCfgInputShortWait():
#getpos str = "{0}; wait 5;"
randomlygeneratedString = id_generator(11)
#print('randomlygeneratedString: ', randomlygeneratedString)
str = "{0}; wait 5;".format(randomlygeneratedString)
with open(looptestPath, 'w') as f: with open(looptestPath, 'w') as f:
f.write(str) f.write(str)
checkConsoleOutput(randomlygeneratedString) time.sleep(0.5)
def exit_handler(): def exit_handler():
print('reached exithandler') print('reached exithandler')
@ -103,151 +37,132 @@ def exit_handler():
f.write(str) f.write(str)
def joinTeam(): def joinTeam():
randomlygeneratedString = id_generator(11) str = "jointeam 2; wait 2; zspawn; wait 1; {0}; wait 5;"
str = "jointeam 2; wait 2; zspawn; wait 1; {0}; wait 5;".format(randomlygeneratedString)
writeCfgInput(str) writeCfgInput(str)
checkConsoleOutput(randomlygeneratedString) time.sleep(4.5)
print('jointeam func: ')
def checkbotteam(): def checkbotteam():
while True: mysql_check_spectator()
clearconsolelog()
state = get_output_if_spec()
if state == 1:
joinTeam()
break
if state == 2:
break
resetCfgInputShortWait() resetCfgInputShortWait()
connectionTimer = Timer(20.0, checkbotteam) connectionTimer = Timer(20.0, checkbotteam)
connectionTimer.daemon = True connectionTimer.daemon = True
connectionTimer.start() connectionTimer.start()
def checkIfConnected(): def mysql_check_spectator():
randomlygeneratedString = id_generator(11) cnx = get_connection()
server_str, player_count = getconsoleOutputForStatus() cur = cnx.cursor()
connectionTimer = None sql_statement = f"""SELECT spectate from unloze_css_autism_bot.`bot status`"""
if "27015" not in server_str: cur.execute(sql_statement)
str1 = "connect 151.80.230.149:27015; {0}; wait 500;".format(randomlygeneratedString) result = cur.fetchall()[0]
writeCfgInput(str1) spectate = result[0]
checkConsoleOutput(randomlygeneratedString) print('spectate: ', spectate)
elif player_count > 63: if spectate != 0:
#TODO check team differently because zspawn unknown command on zr server joinTeam()
writeCfgInput("connect 151.80.230.149:27016; {0}; wait 5;".format(randomlygeneratedString)) cur.close()
checkConsoleOutput(randomlygeneratedString) cnx.close()
connectionTimer = Timer(60.0 * 15, checkIfConnected)
resetCfgInputShortWait()
if not connectionTimer:
connectionTimer = Timer(60.0 * 2, checkIfConnected)
#daemon true kills thread instead of deadlock waiting in case program exits
connectionTimer.daemon = True
connectionTimer.start()
#print('finished checkIfConnected')
def get_player_info(): def mysql_get_player_info(movement_list):
movement_input = [] #1 = forward, 2 = back, 3 = left, 4 = right
ct_angles = [] #use previous movement instead for evaluation
ct_origin_diff = [] strInput = "-attack; -jump; -duck; +attack; cl_minmodels 1; "
ct_origin_position = [] print('movement_list[0]: ', movement_list[0], '#1 = forward, 2 = back, 3 = left, 4 = right')
ct_distance = 0 print('movement_list[1]: ', movement_list[1], '#1 = forward, 2 = back, 3 = left, 4 = right')
while True: if movement_list[0] == 1:
with open(consolelogPath, 'r') as f: strInput += " -back; wait 5;"
try:
for line in f:
print('line: ', line)
if "movement_input_specific:" in line and len(line) > 26:
movement_input = line.split("movement_input_specific:", 1)[1].split("+")
movement_input = [element.replace("\n", "") for element in movement_input]
#print('movement: ', movement)
if "ct_eye_angles_:" in line:
ct_angles = line.split("ct_eye_angles_:", 1)[1].split("+")
ct_angles = [element.strip() for element in ct_angles]
if "player_origin_diff:" in line:
ct_origin_diff = line.split("player_origin_diff:", 1)[1].split("+")
ct_origin_diff = [element.strip() for element in ct_origin_diff]
ct_origin_diff = [float(element) for element in ct_origin_diff]
if "player_origin_position:" in line:
ct_origin_position = line.split("player_origin_position:", 1)[1].split("+")
ct_origin_position = [element.strip() for element in ct_origin_position]
if "player_lowest_distance:" in line:
ct_distance = line.split("player_lowest_distance:", 1)[1].strip()
ct_distance = float(ct_distance)
if movement_input and ct_angles and ct_origin_diff and ct_origin_position and ct_distance:
return (movement_input, ct_angles, ct_origin_diff, ct_origin_position, ct_distance)
except (UnicodeDecodeError, IndexError):
pass
def getBotOrgin(botOrigin):
#x -> z -> y coordAxis order
botOrigin = [x.strip() for x in botOrigin]
botOrigin = [x.replace(";", "") for x in botOrigin]
#botOrigin = [x.replace(";", "") for x in botOrigin]
botIntorigin0 = float(botOrigin[0])
botIntorigin1 = float(botOrigin[1])
botIntorigin2 = float(botOrigin[2])
#bot coordinates might be usefull?
return [botIntorigin0, botIntorigin1, botIntorigin2]
def getBotOrigin():
while True:
str = "getpos; wait 1; wait 5;"
writeCfgInput(str)
previousStr = ""
with open(consolelogPath, 'r') as f:
for line in f:
if "setpos" in line:
try:
print('found setpos line: ', line)
coords = line.split("setpos")[1].split(";setang")[0].split()
#print('coords: ', coords)
return getBotOrgin(coords)
except IndexError as err:
pass
previousStr = line
def followPlayer(remaining_instructions = [], indexCounter = 0, previousmoment = []):
#setang 0 180 0;
#default_input = "+attack; wait 50; cl_minmodels; wait 50; +right; wait 50; +jump; wait 50; -jump; wait 50; +forward; wait 50; {0}; wait 5;".format(randomlygeneratedString)
#writeCfgInput(default_input)
botOrigin = getBotOrigin()
movement_input, ct_angles, ct_origin_diff, ct_origin_position, ct_distance = get_player_info()
print('movement_input: ', movement_input, '\nct_angles: ', ct_angles, "\nct_origin_diff: ", ct_origin_diff, "\nct_origin_position: ", ct_origin_position, "\nct_distance: ", ct_distance, "\nbotOrigin: ", botOrigin)
randomlygeneratedString = id_generator(11)
remaining_instructions.append([movement_input, ct_angles])
strInput = "-jump; wait 5; +attack; wait 5; cl_minmodels 1; wait 5; setang 0 180 0; wait 5;".format(ct_angles[0], ct_angles[1], ct_angles[2])
#strInput += "-forward; wait 5; -back; wait 5; -moveleft; wait 5; -moveright; wait 5; "
if ct_distance > 250:
remaining_instructions = []
indexCounter = 0
#0 180 0: W = X axis greater minus, S = X axis greater plus, A = Y axis greater minus, D = Y axis greater plus
if botOrigin[0] + 50 > ct_origin_diff[0]:
strInput += "wait 5; +forward;"
elif botOrigin[0] - 50 < ct_origin_diff[0]:
strInput += "wait 5; +back;"
if botOrigin[1] + 50 > ct_origin_diff[1]:
strInput += "wait 5; +moveleft;"
elif botOrigin[1] - 50 < ct_origin_diff[1]:
strInput += "wait 5; +moveright;"
print('ct_distance > 250:')
else: else:
(movement, angles) = remaining_instructions[indexCounter] strInput += " -forward; wait 5;"
if previousmoment != movement: if movement_list[1] == 4:
strInput += "-forward; wait 5; -back; wait 5; -moveleft; wait 5; -moveright; wait 5; " strInput += " -moveleft; wait 5;"
previousmoment = movement else:
strInput = strInput.replace("setang 0 180 0;", "setang {0} {1} {2};".format(angles[0], angles[1], angles[2])) strInput += " -moveright; wait 5;"
for move in movement: #print('strInput movement_list:', strInput)
strInput += "+" cnx = get_connection()
strInput += move cur = cnx.cursor()
strInput += "; " sql_statement = f"""SELECT * from unloze_css_autism_bot.`bot movement input` ORDER BY entry_time LIMIT 1"""
indexCounter += 1 sql_row_count = "SELECT COUNT(*) FROM unloze_css_autism_bot.`bot movement input`"
strInput += " wait 5; {0}; ".format(randomlygeneratedString) cur.execute(sql_statement)
print('strInput: ', strInput) result = cur.fetchall()
writeCfgInput(strInput) cur.execute(sql_row_count)
checkConsoleOutput(randomlygeneratedString) result_count = cur.fetchone()[0]
clearconsolelog() if result:
connectionTimer = Timer(0.2, followPlayer, args=(remaining_instructions, indexCounter)) movement_list = []
result = result[0]
movement_input = result[0]
client_angles = [result[1], result[2], result[3]]
xyz_difference = [result[4], result[5], result[6]]
client_coordinates = [result[7], result[8], result[9]]
lowest_distance = result[10]
print('result_count: ', result_count)
if "+jump;" in movement_input:
strInput += " +jump;"
if "+duck;" in movement_input:
strInput += " +duck;"
#print('xyz_difference: ', xyz_difference)
if xyz_difference[0] > 0:
movement_list.append(1)
strInput += " +forward; wait 5;"
else:
movement_list.append(2)
strInput += " +back; wait 5;"
if xyz_difference[1] < 0:
movement_list.append(4)
strInput += " +moveright; wait 5;"
else:
movement_list.append(3)
strInput += " +moveleft; wait 5;"
strInput += f""" setang 0 180 0; wait 5; """
#print('strInput final:', strInput)
writeCfgInput(strInput)
time.sleep(0.20)
writeCfgInput("wait 5;")
limit = 0
if result_count > 7:
limit = result_count - 2
else:
limit = 1
sql_statement = f"""DELETE FROM unloze_css_autism_bot.`bot movement input` ORDER BY entry_time LIMIT {limit}"""
cur.execute(sql_statement)
cnx.commit()
cur.close()
cnx.close()
connectionTimer = Timer(0.10, mysql_get_player_info, args=[movement_list])
connectionTimer.daemon = True connectionTimer.daemon = True
connectionTimer.start() connectionTimer.start()
def mysql_check_if_connected():
cnx = get_connection()
cur = cnx.cursor()
sql_statement = """SELECT connected, playercount from unloze_css_autism_bot.`bot status`"""
cur.execute(sql_statement)
result = cur.fetchall()[0]
#print('result: ', result, ' result[0]: ', result[0])
connected = result[0]
playercount = result[1]
#playercount might not be updated ingame and auto leave?
print('connected: ', connected)
if connected == 0:
str1 = "connect 151.80.230.149:27015;"
writeCfgInput(str1)
time.sleep(0.5)
writeCfgInput("wait 500;")
time.sleep(15.50)
print('not yet connected')
mysql_check_if_connected()
obsolete = """
elif playercount > 60:
str1 = "connect 151.80.230.149:27016;"
writeCfgInput(str1)
time.sleep(0.5)
writeCfgInput("wait 500;")
time.sleep(15.50)
print('not yet connected')
mysql_check_if_connected() """
connectionTimer = Timer(60.0 * 2, mysql_check_if_connected)
connectionTimer.daemon = True
connectionTimer.start()
cur.close()
cnx.close()
def deadlock(): def deadlock():
try: try:
@ -257,14 +172,17 @@ def deadlock():
if __name__ == '__main__': if __name__ == '__main__':
atexit.register(exit_handler) atexit.register(exit_handler)
clearconsolelog()
resetCfgInputShortWait() resetCfgInputShortWait()
checkIfConnected() mysql_check_if_connected()
checkbotteam() checkbotteam()
print('reached followPlayer') print('reached mysql _get_player_info')
followPlayer() mysql_get_player_info([" +forward;", " +moveright;"])
print('reached deadlock') print('reached deadlock')
deadlock() deadlock()
#autoexec.cfg: #/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/autoexec.cfg:
#alias loop "exec looptest.cfg; wait 5; loop;"; wait 5; loop; #alias loop "exec looptest.cfg; wait 300; loop;"; wait 5; loop;
#-condebug
#cd /home/nonroot/.steam/
#./steam.sh -applaunch 240 -textmode -textmessagedebug -novid -nosound -noipx -nojoy -noshaderapi +exec looptest.cfg

View File

@ -1,191 +0,0 @@
import os
import subprocess
import time, threading
import atexit
from random import randrange, choice
currentmap = ""
#condebug instead of condump, remove all condump entries, instead read from console.log, remove deleteConDump Calls
#perharps instead of opening constantly opening once and somehow updating might be more efficient
def clearconsolelog():
open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log', 'w').close()
def readMapFromConsoleLog():
with open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log', 'r') as f:
for line in f:
#print('line: ', line)
if '[SM] The current map is ' in line:
currentmap = line[line.find('map is ') + len('map is '):line.rfind('.')]
return currentmap
return ""
def writeCfgInput(Input):
with open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/looptest.cfg', 'w') as f:
f.write(Input)
def checkConsoleOutput(input):
bool = False
while not bool:
with open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log', 'r') as f:
for line in f:
if input in line:
#print('line: ', line, ' \ninput: ', input)
bool = True
break
def resetCfgInputShortWait():
str = "wait 1; getpos; wait 1; exec looptest.cfg;"
with open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/looptest.cfg', 'w') as f:
f.write(str)
checkConsoleOutput("setpos")
def findcurrentmap():
currentmap = ""
clearconsolelog()
while not currentmap:
try:
#print("post resetcfg")
writeCfgInput("say currentmap; wait 1; exec looptest.cfg;")
time.sleep(0.02)
currentmap = readMapFromConsoleLog()
except OSError:
#print('failed opening file')
pass
resetCfgInputShortWait()
clearconsolelog()
print("currentmap is: {}".format(currentmap))
return currentmap
def deleteCondump():
[os.remove(os.path.join("/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/",f)) for f in os.listdir("/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/") if f.startswith("condump")]
def joinTeam():
print("reached joinTeam")
str = "jointeam 2; wait 2; zspawn; wait 1; exec looptest.cfg;"
writeCfgInput(str)
checkConsoleOutput("zspawn")
def floatconverter(Array, index):
return float(Array[index].replace('\U00002013', '-').replace(';', ''))
def findClosestCt(originPosition):
PositionArray = originPosition.split()
#print('PositionArray: ', PositionArray)
xAxis = floatconverter(PositionArray, 0)
yAxis = floatconverter(PositionArray, 1)
zAxis = floatconverter(PositionArray, 2)
x = 0.0
y = 0.0
z = 0.0
defaultDistance = 1000000.0
#use CTOrigin to find, input comes from plugin spammed all 3 seconds
checkConsoleOutput("CTOrigin:")
try:
with open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log', 'r') as f:
playerOrigin = [0, 0, 0]
for line in f:
#print('line: ', line)
if 'CTOrigin:' in line:
#print('found origin line: ', line)
playerArray = line[10:].split()
playerArray[2].replace(";", "")
print('playerArray: ', playerArray)
playerOrigin[0] = floatconverter(PositionArray, 0)
playerOrigin[1] = floatconverter(PositionArray, 1)
playerOrigin[2] = floatconverter(PositionArray, 2)
xValue = xAxis - playerOrigin[0]
yValue = yAxis - playerOrigin[1]
zValue = zAxis - playerOrigin[2]
if xValue < 0: xValue * -1
if yValue < 0: yValue * -1
if zValue < 0: zValue * -1
totalDistance = xValue + yValue + zValue
if totalDistance < defaultDistance:
defaultDistance = totalDistance
x = playerOrigin[0]
y = playerOrigin[1]
z = playerOrigin[2]
except OSError:
print('failed opening file readorigin')
return (x, y ,z)
def readOrigin():
originPosition = ""
writeCfgInput("getpos; wait 1; exec looptest.cfg;")
while not originPosition:
try:
with open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log', 'r') as f:
for line in f:
if 'setpos' in line:
originPosition = line[line.find('setpos') + len('setpos'):line.rfind(';setang')]
break
except OSError:
#print('failed opening file readorigin')
pass
return originPosition
def findDirection(x, y, z, originPosition):
directions = ["forward", "back", "moveleft", "moveright"]
PositionArray = originPosition.split()
xAxis = floatconverter(PositionArray, 0)
yAxis = floatconverter(PositionArray, 1)
zAxis = floatconverter(PositionArray, 2)
print('xAxis, yAxis , zAxis', xAxis, yAxis, zAxis)
print('x, y , z', x, y, z)
if x > xAxis + 200 : return directions[1]
elif x < xAxis - 200 : return directions[0]
elif y > yAxis + 200 : return directions[3]
elif y < yAxis - 200 : return directions[2]
return choice(directions)
def followPlayer():
direction = ""
prev_direction = "forward"
default_input = "+attack; wait 1; cl_minmodels 1; wait 5; setang 0 180 0; wait 1;"
while True:
try:
print("start of try")
originPosition = readOrigin()
#print('originPosition: ', originPosition)
CrouchOrJump = "wait 1; -duck; wait 1; +jump; wait 1; -jump;"
if randrange(0, 10) > 8:
CrouchOrJump = "wait 1; +duck;"
x, y, z = findClosestCt(originPosition)
if x != 0.0:
clearconsolelog()
resetCfgInputShortWait()
direction = findDirection(x, y ,z, originPosition)
print('movedirection: ', direction)
str = ""
if direction != prev_direction:
str = "{} -{}; wait 1; +{}; {} wait 1; exec looptest.cfg;".format(default_input, prev_direction, direction, CrouchOrJump)
prev_direction = direction
else:
str = "{} +{}; {} wait 1; exec looptest.cfg;".format(default_input, direction, CrouchOrJump)
writeCfgInput(str)
checkConsoleOutput(str)
except ValueError as err:
print('ValueError occured: ', err)
pass
def exit_handler():
#deleteCondump()
resetCfgInputShortWait()
if __name__ == '__main__':
atexit.register(exit_handler)
resetCfgInputShortWait()
currentmap = findcurrentmap()
joinTeam()
#circlespin()
resetCfgInputShortWait()
followPlayer()
#exploreMap(currentmap)
#loadMapPattern(currentmap)
#final idea: send printchat to bot for movement input from plugin

View File

@ -1,177 +0,0 @@
import os
import subprocess
import time, threading
import os
# COMMENTS
#sm_track_movement jenz
#direct input
#xdotool search --name "Counter-Strike Source - OpenGL" key m
#setxkbmap -layout dk
#xdotool search --name "Counter-Strike Source - OpenGL"
#xdotool windowfocus 10488872 / 31457297 // 67108881
# keydown
# COMMENTS OVER
def processType(type):
subprocess.call(["xdotool", "type", type])
def processKeys(key):
subprocess.call(["xdotool", "key", key])
def findPosOrigin(line):
originPost = line[line.find('setpos ') + len('setpos'):line.rfind(';setang')]
print('originPost: ', originPost)
return originPost
def deleteCondump():
[os.remove(os.path.join("/home/john/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/",f)) for f in os.listdir("/home/john/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/") if f.startswith("condump")]
def processLine(line):
if '[SM] The current map is ' in line:
processType("say")
processKeys("space")
processType("currentmap")
processKeys("space")
processType("is")
processKeys("space")
currentmap = line[line.find('map is ') + len('map is '):line.rfind('.')]
processType(currentmap)
processKeys("Return")
global currentFilename
currentFilename = str(currentmap)
def reachgetDifference(reachpos, getpos):
#print('reachpos: ', reachpos)
#print('getpos: ', getpos)
if getpos[1] == '-':
getpos = getpos[2:]
if reachpos[1] == '-':
reachpos = reachpos[2:]
reachposAxis = float(reachpos[0].strip('"'))
getposAxis = float(getpos[0].strip('"'))
if reachposAxis - 50.0 < getposAxis:
processType("setang")
processKeys("space")
processType("0")
processKeys("space")
processType("180")
processKeys("space")
processType("0")
processKeys("Return")
return True
elif reachposAxis + 50.0 > getposAxis:
processType("setang")
processKeys("space")
processType("0")
processKeys("space")
processType("0")
processKeys("space")
processType("0")
processKeys("Return")
return True
return False
def readmovement(line):
doubleString = "setang "
processphase = 0;
characterString = ""
for index, character in enumerate(line):
#print('character: ', character)
if processphase == 0:
if character.isspace():
continue
if character.isalpha():
if character != characterString:
processKeys("minus")
if character == "w":
characterString = "forward"
elif character == "s":
characterString = "back"
print('characterString: ', characterString)
print('character: ', character)
processType(characterString)
processKeys("Return")
time.sleep(0.5)
processKeys("plus")
if character == "w":
characterString = "forward"
elif character == "s":
characterString = "back"
processType(characterString)
print('characterString2: ', characterString)
processKeys("Return")
characterString = character
processphase += 1
if processphase == 1:
if character.isdigit() or character == '.':
doubleString += character
elif character.isspace() and len(doubleString) > 10:
doubleString += " "
if line[index + 1] == "o":
processType(doubleString)
processKeys("Return")
doubleString = ""
processphase += 1
if processphase == 2:
if not character.isdigit() and not doubleString:
continue
elif character.isdigit() or character == '.':
doubleString += character
elif character.isspace() and doubleString and not line[index + 1].isalpha():
doubleString += " "
else:
reachpos = doubleString.split()
getpos = ["0.0", "0.0", "0.0"]
while reachgetDifference(reachpos, getpos):
processType("clear")
processKeys("Return")
processType("getpos")
processKeys("Return")
time.sleep(2)
processType("condump")
processKeys("Return")
time.sleep(2)
with open('/home/john/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/condump000.txt') as f:
for line in f:
if 'setpos' in line:
getpos = findPosOrigin(line)
break
time.sleep(2)
deleteCondump()
processphase = 0
doubleString = "setang "
def findcurrentmap():
subprocess.call(["xdotool", "search", "--name", "Counter-Strike Source - OpenGL", "windowactivate"])
#clear console field before retrieving info
processKeys("Return")
#clean console prompt
processType("clear")
processKeys("Return")
processType("say")
processKeys("space")
processType("currentmap")
processKeys("Return")
time.sleep(2)
processType("condump")
processKeys("Return")
time.sleep(2)
with open('/home/john/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/condump000.txt') as f:
for line in f:
processLine(line)
time.sleep(2)
deleteCondump()
#subprocess.call(["xdotool", "key", "Escape"])
#subprocess.call(["xdotool", "key", "o"])
def mapmovementpattern():
stringfile = "/home/nonroot/zeeman/maps/%s.txt" % (currentFilename)
with open(stringfile) as f:
for line in f:
readmovement(line)
if __name__ == '__main__':
deleteCondump()
findcurrentmap()
mapmovementpattern()

View File

@ -3,7 +3,7 @@
#glxinfo #glxinfo
#source venv/bin/activate #source venv/bin/activate
export SDL_VIDEO_X11_VISUALID="0x0e5" #0x0e5 export SDL_VIDEO_X11_VISUALID="0x0e5" #0x0e5
python connectServer.py python3.8 connectServer.py
###Nomachine related ###Nomachine related

View File

@ -1,3 +0,0 @@
#!/bin/bash
#source venv/bin/activate
python ingamerunning_2.py

View File

@ -1,3 +0,0 @@
#!/bin/bash
#source venv/bin/activate
python rejoinze.py

View File

@ -1,5 +1,5 @@
#!/bin/bash #!/bin/bash
#source venv/bin/activate #source venv/bin/activate
python ingamefollowct.py python3.8 ingamefollowct.py
#dont need x2go connection for hl2 process or ./steam.sh -textmode, both work with regular ssh if logged in already #dont need x2go connection for hl2 process or ./steam.sh -textmode, both work with regular ssh if logged in already

View File

@ -4,6 +4,7 @@
#define PLUGIN_AUTHOR "jenz" #define PLUGIN_AUTHOR "jenz"
#define PLUGIN_VERSION "1.00" #define PLUGIN_VERSION "1.00"
#define generic_length 256
#include <sourcemod> #include <sourcemod>
#include <sdktools> #include <sdktools>
@ -25,23 +26,51 @@ public Plugin myinfo =
public void OnClientDisconnect(int client) public void OnClientDisconnect(int client)
{ {
if (present == client) if (present == client)
{
present = 0; present = 0;
mysql_enable_disable_connected(0);
}
} }
public void OnPluginStart() public void OnPluginStart()
{ {
//hooks //hooks
HookEvent("round_start", Event_RoundStart, EventHookMode_PostNoCopy); HookEvent("round_start", Event_RoundStart, EventHookMode_PostNoCopy);
HookEvent("player_team", event_playerteam, EventHookMode_PostNoCopy);
//mysql
sql_create_table();
} }
public Action event_playerteam(Event event, const char[] name, bool dontBroadcast)
{
int client = GetClientOfUserId(event.GetInt("userid"));
if (client == present)
{
//PrintToChatAll("called event_playerteam");
int team = event.GetInt("team");
//PrintToChatAll("team: %i", team);
if (team == 2 || team == 3)
mysql_bot_not_spec();
}
}
public void Event_RoundStart(Handle event, const char[] name, bool dontBroadcast) public void Event_RoundStart(Handle event, const char[] name, bool dontBroadcast)
{ {
targethuman = 0; targethuman = 0;
int server_port = GetConVarInt(FindConVar("hostport"));
if (server_port == 27015)
{
mysql_update_playercount();
}
if (present)
mysql_clean_movement_input();
} }
public void OnMapStart() public void OnMapStart()
{ {
CreateTimer(0.3, recursive_pressing, INVALID_HANDLE, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE); sql_create_table();
CreateTimer(1.0, recursive_pressing, INVALID_HANDLE, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE);
} }
public bool TraceEntityFilterPlayer(int entity, int contentsMask) public bool TraceEntityFilterPlayer(int entity, int contentsMask)
@ -52,7 +81,7 @@ public bool TraceEntityFilterPlayer(int entity, int contentsMask)
public Action recursive_pressing(Handle timer, any data) public Action recursive_pressing(Handle timer, any data)
{ {
//PrintToChatAll("present: %N", present); //PrintToChatAll("present: %N", present);
if (present) if (present && IsPlayerAlive(present))
{ {
float client_coord[3]; float client_coord[3];
float xyz[3]; float xyz[3];
@ -85,35 +114,32 @@ public Action recursive_pressing(Handle timer, any data)
float clientangles[3]; float clientangles[3];
GetClientAbsAngles(targethuman, clientangles); GetClientAbsAngles(targethuman, clientangles);
int keys = GetClientButtons(targethuman); int keys = GetClientButtons(targethuman);
char keyinput[256]; char keyinput[generic_length];
if (keys & IN_FORWARD) if (keys & IN_FORWARD)
{ {
StrCat(keyinput, sizeof(keyinput), "forward+"); StrCat(keyinput, sizeof(keyinput), "+forward; ");
} }
if (keys & IN_BACK) if (keys & IN_BACK)
{ {
StrCat(keyinput, sizeof(keyinput), "back+"); StrCat(keyinput, sizeof(keyinput), "+back; ");
} }
if (keys & IN_MOVELEFT) if (keys & IN_MOVELEFT)
{ {
StrCat(keyinput, sizeof(keyinput), "moveleft+"); StrCat(keyinput, sizeof(keyinput), "+moveleft; ");
} }
if (keys & IN_MOVERIGHT) if (keys & IN_MOVERIGHT)
{ {
StrCat(keyinput, sizeof(keyinput), "moveright+"); StrCat(keyinput, sizeof(keyinput), "+moveright; ");
} }
if (keys & IN_JUMP) if (keys & IN_JUMP)
{ {
StrCat(keyinput, sizeof(keyinput), "jump+"); StrCat(keyinput, sizeof(keyinput), "+jump; ");
} }
//PrintToChatAll("keyinput: %s", keyinput); if (keys & IN_DUCK)
//PrintToChatAll("xyz[0], xyz[1], xyz[2]: %f %f %f", xyz[0], xyz[1], xyz[2]); {
//PrintToChatAll("lowest_distance: %f", lowest_distance); StrCat(keyinput, sizeof(keyinput), "+duck; ");
ServerCommand("sm_psay #[U:1:120378081] movement_input_specific:%s", keyinput); }
ServerCommand("sm_psay #[U:1:120378081] ct_eye_angles_:%f+%f+%f", clientangles[0], clientangles[1], clientangles[2]); mysql_send_input(keyinput, clientangles, xyz, client_coord, lowest_distance);
ServerCommand("sm_psay #[U:1:120378081] player_origin_diff:%f+%f+%f", xyz[0], xyz[1], xyz[2]);
ServerCommand("sm_psay #[U:1:120378081] player_origin_position:%f+%f+%f", client_coord[0], client_coord[1], client_coord[2]);
ServerCommand("sm_psay #[U:1:120378081] player_lowest_distance:%f", lowest_distance);
} }
} }
return Plugin_Handled; return Plugin_Handled;
@ -137,7 +163,119 @@ public void OnClientPostAdminCheck(int client)
char auth[50]; char auth[50];
GetClientAuthId(client, AuthId_Engine, auth, sizeof(auth)); GetClientAuthId(client, AuthId_Engine, auth, sizeof(auth));
if (StrEqual("[U:1:120378081]", auth, false)) if (StrEqual("[U:1:120378081]", auth, false))
{
mysql_enable_disable_connected(1);
present = client; present = client;
}
else if (StrEqual("STEAM_0:1:60189040", auth, false)) else if (StrEqual("STEAM_0:1:60189040", auth, false))
{
mysql_enable_disable_connected(1);
present = client; present = client;
}
}
public void sql_create_table()
{
char error_connect[generic_length];
Database database_connection;
if (SQL_CheckConfig("css_autism_bot_info"))
database_connection = SQL_Connect("css_autism_bot_info", true, error_connect, sizeof(error_connect));
if (database_connection == null)
PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!");
//256 not enough
char query_start[generic_length * 2];
Format(query_start, sizeof(query_start), "CREATE TABLE IF NOT EXISTS unloze_css_autism_bot.`bot status` (`connected` BOOL DEFAULT false, `spectate` BOOL DEFAULT true, `ID` INT NOT NULL DEFAULT 1, `playercount` INT DEFAULT 0, PRIMARY KEY (`ID`))");
mysql_exec_prepared_statement(database_connection, query_start);
Format(query_start, sizeof(query_start), "CREATE TABLE IF NOT EXISTS unloze_css_autism_bot.`bot movement input` (`keyinput` text NOT NULL, `clientangles_0` FLOAT DEFAULT 0.0, `clientangles_1` FLOAT DEFAULT 0.0, `clientangles_2` FLOAT DEFAULT 0.0, `xyz_0` FLOAT DEFAULT 0.0, `xyz_1` FLOAT DEFAULT 0.0, `xyz_2` FLOAT DEFAULT 0.0, `client_coord_0` FLOAT DEFAULT 0.0, `client_coord_1` FLOAT DEFAULT 0.0, `client_coord_2` FLOAT DEFAULT 0.0, `lowest_distance` FLOAT DEFAULT 0.0, `entry_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)");
mysql_exec_prepared_statement(database_connection, query_start);
Format(query_start, sizeof(query_start), "INSERT INTO unloze_css_autism_bot.`bot status` (connected, spectate, ID) VALUES (0, 1, 1) ON DUPLICATE KEY UPDATE connected = VALUES(connected), spectate = VALUES(spectate)");
mysql_exec_prepared_statement(database_connection, query_start);
delete database_connection;
}
public void mysql_clean_movement_input()
{
char error_connect[generic_length];
Database database_connection;
if (SQL_CheckConfig("css_autism_bot_info"))
database_connection = SQL_Connect("css_autism_bot_info", true, error_connect, sizeof(error_connect));
if (database_connection == null)
PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!");
char query_start[generic_length];
Format(query_start, sizeof(query_start), "delete from unloze_css_autism_bot.`bot movement input`");
mysql_exec_prepared_statement(database_connection, query_start);
}
public void mysql_update_playercount()
{
char error_connect[generic_length];
Database database_connection;
if (SQL_CheckConfig("css_autism_bot_info"))
database_connection = SQL_Connect("css_autism_bot_info", true, error_connect, sizeof(error_connect));
if (database_connection == null)
PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!");
char query_start[generic_length];
Format(query_start, sizeof(query_start), "INSERT INTO unloze_css_autism_bot.`bot status` (playercount, ID) VALUES (%i, 1) ON DUPLICATE KEY UPDATE playercount = %i", MaxClients, MaxClients);
mysql_exec_prepared_statement(database_connection, query_start);
delete database_connection;
}
public void mysql_bot_not_spec()
{
char error_connect[generic_length];
Database database_connection;
if (SQL_CheckConfig("css_autism_bot_info"))
database_connection = SQL_Connect("css_autism_bot_info", true, error_connect, sizeof(error_connect));
if (database_connection == null)
PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!");
char query_start[generic_length];
Format(query_start, sizeof(query_start), "INSERT INTO unloze_css_autism_bot.`bot status` (connected, spectate, ID) VALUES (1, 0, 1) ON DUPLICATE KEY UPDATE connected = VALUES(connected), spectate = VALUES(spectate)");
mysql_exec_prepared_statement(database_connection, query_start);
}
public void mysql_enable_disable_connected(int state)
{
char error_connect[generic_length];
Database database_connection;
if (SQL_CheckConfig("css_autism_bot_info"))
database_connection = SQL_Connect("css_autism_bot_info", true, error_connect, sizeof(error_connect));
if (database_connection == null)
PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!");
char query_start[generic_length];
if (!state)
Format(query_start, sizeof(query_start), "INSERT INTO unloze_css_autism_bot.`bot status` (connected, spectate, ID) VALUES (0, 1, 1) ON DUPLICATE KEY UPDATE connected = VALUES(connected), spectate = VALUES(spectate)");
else
Format(query_start, sizeof(query_start), "INSERT INTO unloze_css_autism_bot.`bot status` (connected, spectate, ID) VALUES (1, 1, 1) ON DUPLICATE KEY UPDATE connected = VALUES(connected), spectate = VALUES(spectate)");
//PrintToChatAll("query_start: %s", query_start);
mysql_exec_prepared_statement(database_connection, query_start);
delete database_connection;
}
public void mysql_send_input(char []keyinput, float clientangles[3], float xyz[3], float client_coord[3], float lowest_distance)
{
//TODO maybe add autism bot coords too as information
char error_connect[generic_length];
Database database_connection;
if (SQL_CheckConfig("css_autism_bot_info"))
database_connection = SQL_Connect("css_autism_bot_info", true, error_connect, sizeof(error_connect));
if (database_connection == null)
PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!");
char query_start[generic_length];
Format(query_start, sizeof(query_start), "INSERT INTO unloze_css_autism_bot.`bot movement input` VALUES ('%s', %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, NOW())", keyinput, clientangles[0], clientangles[1], clientangles[2], xyz[0], xyz[1], xyz[2], client_coord[0], client_coord[1], client_coord[2], lowest_distance);
mysql_exec_prepared_statement(database_connection, query_start);
//PrintToChatAll("query_start: %s", query_start);
delete database_connection;
}
public void mysql_exec_prepared_statement(Database database_connection, char []query_statement)
{
char error[generic_length];
DBStatement create_statement = SQL_PrepareQuery(database_connection, query_statement, error, sizeof(error));
if (create_statement == INVALID_HANDLE)
{
CloseHandle(create_statement);
return;
}
SQL_Execute(create_statement);
CloseHandle(create_statement);
} }