From 614de777f3b9104eeae246c589d72cd0860cef44 Mon Sep 17 00:00:00 2001
From: jenz <unlozehq@gmail.com>
Date: Thu, 14 Jul 2022 21:23:19 +0200
Subject: [PATCH] updated autism bot plugin and python script to make movement
 hopefully less annoying to players

---
 AutismBotIngame/python/ingamefollowct.py     |  43 ++--
 AutismBotIngame/python/pyhoca_display.py     |  14 +-
 AutismBotIngame/scripting/autism_bot_info.sp | 243 +++++++++++--------
 3 files changed, 171 insertions(+), 129 deletions(-)

diff --git a/AutismBotIngame/python/ingamefollowct.py b/AutismBotIngame/python/ingamefollowct.py
index 80749879..797dd0fd 100644
--- a/AutismBotIngame/python/ingamefollowct.py
+++ b/AutismBotIngame/python/ingamefollowct.py
@@ -33,34 +33,41 @@ def exit_handler():
     kill_owned_process("pidof xterm")
 
 def bot_process_movement(input_line):
-    dist_target = input_line[input_line.index("dist_target:") + len("dist_target:"):input_line.index("targethuman:")]
-    targethuman = input_line[input_line.index("targethuman:") + len("targethuman:"):input_line.index("enemy_distance:")]
+    dist_target = input_line[input_line.index("dist_target:") + len("dist_target:"):input_line.index("enemy_distance")]
     enemy_distance = input_line[input_line.index("enemy_distance:") + len("enemy_distance:"):input_line.index("targeteam:")]
-    targeteam = input_line[input_line.index("targeteam:") + len("targeteam:"):input_line.index("target_enemy:")]
-    target_enemy = input_line[input_line.index("target_enemy:") + len("target_enemy:"):]
+    targeteam = input_line[input_line.index("targeteam:") + len("targeteam:"):input_line.index("state:")]
+    state = input_line[input_line.index("state:") + len("state:"):]
+
+    state = int(state.strip())
     dist_target = float(dist_target)
     enemy_distance = float(enemy_distance)
     targeteam = int(targeteam)
-    min_distance_target_human = 10.0
-    strInput = "-attack; wait 2; -use; wait 5; +attack; wait 5; cl_minmodels 1; wait 2; +use; +forward; wait 2; "
-    if dist_target > min_distance_target_human:
-        strInput += "use weapon_elite; wait 3; "
-    elif targeteam == 3:
-        strInput += "use weapon_p90; wait 3; "
-    elif targeteam == 2:
-        strInput += "use weapon_knife; wait 5; "
-    print('dist_target: ', dist_target, ' enemy distance: ', enemy_distance) 
-    strInput = strinput_append(strInput, 2)
+    strInput = "-attack; wait 2; -use; wait 5; +attack; wait 5; cl_minmodels 1; wait 2; +use; wait 5; "
+    #python has no switches and such
+    if state in [5, 7]:
+        strInput += "-forward; wait 2; use weapon_knife; wait 5;"
+    elif state >= 3:
+        strInput += "use weapon_knife; wait 5; +forward; wait 2;"
+    elif state == 0:
+        strInput += "use weapon_p90; wait 2; -forward; wait 2;"
+    elif state == 1:
+        strInput += "wait 2; use weapon_elite; wait 3; +forward; wait 2;"
+    elif state == 2: 
+        strInput += "-forward; wait 2; use weapon_elite; wait 3;"
+
+    print('dist_target: ', dist_target, ' enemy distance: ', enemy_distance, ' targetteam: ', targeteam, ' state:', state)
+    if state not in [0, 2, 5, 7, 8]:
+        strInput = strinput_append(strInput, 2)
     #print('strInput final:', strInput)
     writeCfgInput(strInput)
 
 def strinput_append(strInput, nth):
-    for _ in range(10 * nth):
+    for _ in range(3 * nth):
         boolean_val = random.choice([True, False])
         if boolean_val:
-            strInput += "+moveleft; wait 15; -moveleft; "
+            strInput += " +moveleft; wait 15; -moveleft; "
         else:
-            strInput += "+moveright; wait 15; -moveright; "
+            strInput += " +moveright; wait 15; -moveright; "
     return strInput
 
 def kill_user_owned_pid(pid):
@@ -187,8 +194,6 @@ if __name__ == '__main__':
                     kill_owned_process("pidof hl2_linux")
                     print('exiting')
                     sys.exit(1)
-
-		
                 if not connected_to_other or "connect to ze" == data:
                     print('data: ', data)
                     connection_issue_counter += 1
diff --git a/AutismBotIngame/python/pyhoca_display.py b/AutismBotIngame/python/pyhoca_display.py
index 4ff2f473..7e789248 100644
--- a/AutismBotIngame/python/pyhoca_display.py
+++ b/AutismBotIngame/python/pyhoca_display.py
@@ -4,14 +4,14 @@ import subprocess
 
 whoami = subprocess.getoutput(["whoami"])
 with open(f'/home/{whoami}/ze_runner/config.json') as jsonfile:
-        data_ports = json.load(jsonfile)
+	data_ports = json.load(jsonfile)
 
+#enter screen to enter password
 def main():
-        with Display() as disp:
-                d = subprocess.getoutput(["echo $DISPLAY"])
-                print(d)
-                subprocess.getoutput([f"pyhoca-cli --server localhost -N --password {data_ports['x2go_pw']}"])
-
+	with Display() as disp:
+		d = subprocess.getoutput(["echo $DISPLAY"])
+		print(d)
+		subprocess.getoutput([f"pyhoca-cli --server localhost -N --password {data_ports['x2go_pw']}"])
 
 if __name__ == '__main__':
-        main()
+	main()
diff --git a/AutismBotIngame/scripting/autism_bot_info.sp b/AutismBotIngame/scripting/autism_bot_info.sp
index 7c3d601a..02c07224 100644
--- a/AutismBotIngame/scripting/autism_bot_info.sp
+++ b/AutismBotIngame/scripting/autism_bot_info.sp
@@ -25,13 +25,13 @@ float client_old_coords[MAXPLAYERS + 1][3];
 float targethuman_self_teleported[MAXPLAYERS + 1][3];
 bool chat_cooldown = false;
 
-//admins & vips
-bool admins[MAXPLAYERS + 1];
-bool vips[MAXPLAYERS + 1];
-
 //socket for bot input
 Handle global_socket;
 
+//timer handle
+Handle g_hTimer_pressing = null;
+Handle g_hTimer_bot_connect = null;
+
 public Plugin myinfo = 
 {
 	name = "coordinates for the bot",
@@ -43,20 +43,35 @@ public Plugin myinfo =
 
 public void OnPluginStart()
 {
-	for (int i = 1; i <= MaxClients; i++)
+    for (int i = 1; i <= MaxClients; i++)
         if (IsValidClient(i))
-		{
-			target_friend[i] = 0;
-			target_enemy[i] = 0;
-			OnClientPostAdminCheck(i);
-		}
-	//talking
-	RegConsoleCmd("sm_autism", cmd_talk, "talking to the bot through java application");
-	RegConsoleCmd("sm_botrtv", cmd_botrtv, "making bots rtv");
-	
-	//UDP connection
-	connect_socket();
-	chat_cooldown = false;
+        {
+            target_friend[i] = 0;
+            target_enemy[i] = 0;
+            OnClientPostAdminCheck(i);
+        }
+    //talking
+    RegConsoleCmd("sm_autism", cmd_talk, "talking to the bot through java application");
+    RegConsoleCmd("sm_botrtv", cmd_botrtv, "making bots rtv");
+
+    //UDP connection
+    connect_socket();
+    chat_cooldown = false;
+    
+    g_hTimer_bot_connect = CreateTimer(15.0, bot_check_connect, _, TIMER_REPEAT);
+    g_hTimer_pressing = CreateTimer(0.30, recursive_pressing, _, TIMER_REPEAT);
+}
+
+public void OnPluginEnd()
+{
+    if (g_hTimer_pressing != null)
+    {
+        delete g_hTimer_pressing;
+    }
+    if (g_hTimer_bot_connect != null)
+    {
+        delete g_hTimer_bot_connect;
+    }
 }
 
 public void reset_target_tp(int client)
@@ -136,8 +151,8 @@ public bool is_autism_bot4(int client)
 
 public Action cmd_botrtv(int client, int args)
 {
-	if (vips[client] || admins[client])
-        {
+    if ((CheckCommandAccess(client, "sm_kick", ADMFLAG_KICK)) || (CheckCommandAccess(client, "sm_reserved", ADMFLAG_RESERVATION)))
+    {
 		for (int i = 1; i <= MaxClients; i++)
 		{
 			if (IsValidClient(i) && !IsFakeClient(i))
@@ -162,57 +177,59 @@ public Action cmd_botrtv(int client, int args)
 				}
 			}
 		}
-        }
-	return Plugin_Handled;
+    }
+    return Plugin_Handled;
 }
 
 public Action cmd_talk(int client, int args)
-{	
-	char info[generic_length];
-	GetCmdArgString(info, sizeof(info));
-	
-	if (strlen(info) == 0)
-	{
-		PrintToChat(client, "Add a message to the command if autism bot is ingame and running on discord");
-		return Plugin_Handled;
-	}
-	if (is_bot_player(client))
-	{
-		return Plugin_Handled;
-	}
-	if (chat_cooldown)
-	{
-		PrintToChat(client, "spamming bot too much, applying cooldown");
-		return Plugin_Handled;
-	}
-	bool bot_found = false;
-	for (int i = 1; i <= MaxClients; i++)
-		if (IsValidClient(i) && !IsFakeClient(i))
-                {
-			if (is_autism_bot1(i))
-			{
-				cmd_talk_help(ports[0], client, info);
-				bot_found = true;
-			}
-			if (is_autism_bot2(i))
-			{
-				cmd_talk_help(ports[1], client, info);
-				bot_found = true;
-			}
-			if (is_autism_bot3(i))
-                        {
-				cmd_talk_help(ports[2], client, info);
-                                bot_found = true;
-                        }
-			if (is_autism_bot4(i))
-                        {
-				cmd_talk_help(ports[3], client, info);
-                                bot_found = true;
-                        }
-	}
-	if (!bot_found)
-		PrintToChat(client, "bot not connected to server");
-	return Plugin_Handled;
+{
+    char info[generic_length];
+    GetCmdArgString(info, sizeof(info));
+
+    if (strlen(info) == 0)
+    {
+        PrintToChat(client, "Add a message to the command if autism bot is ingame and running on discord");
+        return Plugin_Handled;
+    }
+    if (is_bot_player(client))
+    {
+        return Plugin_Handled;
+    }
+    if (chat_cooldown)
+    {
+        PrintToChat(client, "spamming bot too much, applying cooldown");
+        return Plugin_Handled;
+    }
+    bool bot_found = false;
+    for (int i = 1; i <= MaxClients; i++)
+    {
+        if (IsValidClient(i) && !IsFakeClient(i))
+        {
+            if (is_autism_bot1(i))
+            {
+                cmd_talk_help(ports[0], client, info);
+                bot_found = true;
+            }
+            if (is_autism_bot2(i))
+            {
+                cmd_talk_help(ports[1], client, info);
+                bot_found = true;
+            }
+            if (is_autism_bot3(i))
+            {
+                cmd_talk_help(ports[2], client, info);
+                bot_found = true;
+            }
+            if (is_autism_bot4(i))
+            {
+                cmd_talk_help(ports[3], client, info);
+                bot_found = true;
+            }
+        }
+    }
+    if (!bot_found)
+        PrintToChat(client, "bot not connected to server");
+    return Plugin_Handled;
 }
 
 public Action bot_chat_cooldown(Handle timer, any data)
@@ -236,10 +253,7 @@ public void did_target_tp(int client, int bot_client)
 
 public void OnMapStart()
 {
-	//0.2 too spammmy, 1.5 too slow
 	chat_cooldown = false;
-	CreateTimer(0.30, recursive_pressing, INVALID_HANDLE, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE);
-	CreateTimer(15.0, bot_check_connect, INVALID_HANDLE, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE);
 }
 
 public void send_socket_msg(char[] query_msg, int len, int port)
@@ -550,29 +564,62 @@ public Action recursive_pressing(Handle timer, any data)
                     GetEntPropVector(target_enemy[client], Prop_Send, "m_vecOrigin", pos);
                     enemy_distance = get_power_distance(client, pos);
                 }
-                float max_range_dist = 500.0;
-                if (0 < dist_target < max_range_dist && IsValidClient(target_enemy[client]))
+                float max_range_dist = 150.0;
+                int state = -1;
+                if (GetEntityMoveType(client) == MOVETYPE_LADDER)
                 {
-                    face_call(target_enemy[client], client);
+                    state = 8;
                 }
-                else if (IsValidClient(target_friend[client]))
-                    face_call(target_friend[client], client);
-                else if (IsValidClient(target_enemy[client]) && !admins[target_enemy[client]] && !vips[target_enemy[client]])
+                //if bot is ct: is close enough to friend, can stop following friend and focus on shooting zombies
+                else if (targeteam == 3 && 0 < dist_target < max_range_dist && IsValidClient(target_enemy[client]))
                 {
                     face_call(target_enemy[client], client);
+                    state = 0;
+                }
+                //if bot is ct: if bot is not close enough to friend follow him
+                else if (targeteam == 3 && dist_target > max_range_dist)
+                {
+                    face_call(target_friend[client], client);
+                    state = 1;
+                }
+                //if bot is ct and close enough to friend then just do nothing in case of there being no enemy to shoot at
+                else if (targeteam == 3)
+                {
+                    state = 2;
+                }
+                //if bot is zm follow enemy sometimes
+                else if (targeteam == 2 && 0 < enemy_distance < max_range_dist * 5 && IsValidClient(target_enemy[client]))
+                {
+                    face_call(target_enemy[client], client);
+                    state = 3;
+                }
+                //if bot is zm just follow the closest friend zm, but not constantly when too close because people start bitching then
+                else if (targeteam == 2 && dist_target > max_range_dist / 2)
+                {
+                    face_call(target_friend[client], client);
+                    state = 4;
+                }
+                //if bot is zm and no close enemies and no friends far away enough to follow then check if friend is close, if its the case then do nothing
+                else if (targeteam == 2 && 0 < dist_target < max_range_dist / 2)
+                {
+                    face_call(target_friend[client], client);
+                    state = 5;
+                }
+                //if bot is zm and there are no friends close or far away but there is also no enemy close check if there is an enemy far away
+                else if (targeteam == 2 && IsValidClient(target_enemy[client]))
+                {
+                    face_call(target_enemy[client], client);
+                    state = 6;
+                }
+                //else nothing to do as zm
+                else if (targeteam == 2)
+                {
+                    state = 7;
                 }
                 if (GetEntProp(client, Prop_Data, "m_nWaterLevel") <= 2 && GetEntityMoveType(client) != MOVETYPE_LADDER)
                     trace_hulling_bot(client);
                 char message[generic_length * 7];
-                if (IsValidClient(target_friend[client]))
-                    Format(message, sizeof(message), "dist_target: %f targethuman: %N enemy_distance: %f targeteam: %i", dist_target, target_friend[client], enemy_distance, targeteam);
-                else
-                    Format(message, sizeof(message), "dist_target: %f targethuman: none enemy_distance: %f targeteam: %i", dist_target, enemy_distance, targeteam);
-                if (IsValidClient(target_enemy[client]))
-                    Format(message, sizeof(message), "%s target_enemy: %N", message, target_enemy[client]);
-			    else
-                    Format(message, sizeof(message), "%s target_enemy: none", message);
-
+                Format(message, sizeof(message), "dist_target: %f enemy_distance: %f targeteam: %i state: %i", dist_target, enemy_distance, targeteam, state);
                 if (is_autism_bot1(client))
                 {
                     send_socket_msg(message, strlen(message), ports[0]);
@@ -826,12 +873,10 @@ public int GetClosestClient_option1(bool finding_friend, int client)
 {
 	float nearestdistance = -1.0;
 	int nearest = -1;
-	if (GetEntityMoveType(client) == MOVETYPE_LADDER)
-		return nearest;
 	for (int i = 1; i <= MaxClients; i++)
 	if (IsValidClient(i) && IsPlayerAlive(i) && i != client && !is_bot_player(i))
 	{
-		if (!IsAbleToSee(client, i) || is_client_stuck_or_afk(client, i) || admins[i])
+		if (!IsAbleToSee(client, i) || is_client_stuck_or_afk(client, i))
 		{
 			continue; 
 		}
@@ -842,8 +887,9 @@ public int GetClosestClient_option1(bool finding_friend, int client)
 		{
 			continue;
 		}
-		if ((admins[i] || vips[i] || i == target_friend[client]))
-		    dist_target /= 5;
+        /*
+		if (i == target_friend[client])
+		    dist_target /= 5; */
 		if (nearestdistance < 0 || dist_target < nearestdistance)
 		{
 		    nearest = i;
@@ -888,10 +934,6 @@ public void OnClientPostAdminCheck(int client)
 	{
 		send_socket_msg(msg, strlen(msg), ports[3]);
 	}
-	if (CheckCommandAccess(client, "sm_kick", ADMFLAG_KICK))
-		admins[client] = true;
-	else if (CheckCommandAccess(client, "sm_reserved", ADMFLAG_RESERVATION))
-		vips[client] = true;
 	client_old_coords[client][0] = 0.0;
 	client_old_coords[client][1] = 0.0;
 	client_old_coords[client][2] = 0.0;
@@ -926,20 +968,15 @@ stock void connect_socket()
 
 public void OnClientDisconnect(int client)
 {
-	if (CheckCommandAccess(client, "sm_kick", ADMFLAG_KICK))
-                admins[client] = false;
-        else if (CheckCommandAccess(client, "sm_reserved", ADMFLAG_RESERVATION))
-		vips[client] = false;
-
 	bot_avoid_edge[client] = -1;
 	client_old_coords[client][0] = 0.0;
 	client_old_coords[client][1] = 0.0;
 	client_old_coords[client][2] = 0.0;
 	for (int i = 1; i <= MaxClients; i++)
-        {
-                if (IsValidClient(i) && is_bot_player(i) && i != client)
-                        target_friend_afk_counter[i][client] = 0;
-        }
+    {
+        if (IsValidClient(i) && is_bot_player(i) && i != client)
+            target_friend_afk_counter[i][client] = 0;
+    }
 	reset_target_tp(client);
 }