-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredator.py
More file actions
166 lines (138 loc) · 5.6 KB
/
predator.py
File metadata and controls
166 lines (138 loc) · 5.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import json
import random as rd
import socket
import sys
import time
from multiprocessing import Process
import constants
from color import colorString
class Predator(Process):
def __init__(self, duration, log_queue, reproduction_queue):
"""
Predator constructor
"""
super().__init__()
self.duration = duration
self.log_queue = log_queue
self.reprod_queue = reproduction_queue
self.socket = None
self.energy = constants.PREDATOR_INIT_ENERGY
def log(self, color, msg):
if self.log_queue is not None and msg.strip():
self.log_queue.put(colorString(color, msg))
def connect_to_envi(self):
retries = 5
while retries > 0:
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect(("localhost", 8558))
return True
except ConnectionRefusedError:
time.sleep(1.0)
retries -= 1
return False
def form_request(self, request, info):
return json.dumps(
{"pid": self.pid, "type": "predator", "request": request, "info": info}
)
def send_request(self, request_type, info):
if self.socket is None:
self.log(
"red", f"[Predator {self.pid}] Cannot send request: No connection."
)
return
try:
message = self.form_request(request_type, info)
self.socket.sendall(bytes(message, encoding="utf-8"))
reponse = self.socket.recv(2048)
if not reponse:
return None
return json.loads(reponse.decode())
except Exception as e:
self.log("red", f"[Predator {self.pid}] Error sending request: {e}")
def register(self):
response = self.send_request("register", self.energy)
if response is None or response.get("status") != "ok":
self.log("red", f"[Predator {self.pid}] Registration failed.")
def unregister(self):
response = self.send_request("unregister", None)
if response is None or response.get("status") != "ok":
self.log("red", f"[Predator {self.pid}] Unregistration failed.")
# Hunting logic
def kill_prey(self, prey):
succes = self.send_request("mark_dead", {"pid": prey, "type": "prey"})
if succes and succes.get("status") == "ok":
self.log("red", f"[Predator {self.pid}] killed prey {prey}")
self.gain_energy(constants.PREDATOR_PREY_EAT + float(rd.randint(-5, 5)))
def kill_probability(self, n):
# Has 1 chance over n to return true
if rd.random() < 1 / n:
return True
return False
def hunt(self):
response = self.send_request("get_active_preys", None)
if response and response.get("active_preys"):
active_preys = response.get("active_preys")
prey = rd.choice(active_preys)
self.kill_prey(prey)
return True
return False
# Energy management
def lose_energy(self, amount):
self.energy = max(0.0, self.energy - amount)
response = self.send_request("update_energy", self.energy)
if response and response.get("status") == "ok":
self.log(
"blue",
f"[Predator {self.pid}] lost {amount} energy. {self.energy} energy left.",
)
def gain_energy(self, amount):
self.energy = min(100.0, self.energy + amount)
response = self.send_request("update_energy", self.energy)
if response and response.get("status") == "ok":
self.log(
"blue",
f"[Predator {self.pid}] gained {amount} energy. {self.energy} energy left.",
)
def reprod_pred(self):
if self.energy >= constants.PREDATOR_REPRODUCTION_THRESHOLD:
self.lose_energy(30 + float(rd.randint(-5, 20)))
response = self.send_request("update_energy", self.energy)
if response and response.get("status") == "ok":
self.log(
"bright_magenta",
f"[Predator {self.pid}] produced an offspring. {self.energy} energy left.",
)
self.reprod_queue.put("predator")
return True
return False
# Main logic
def run(self):
# Connect to environment
if not self.connect_to_envi():
self.log("red", "Failed to connect to environment")
sys.exit(1)
self.register()
# Wait for processes to load
time.sleep(0.5)
start = time.time()
while time.time() - start < self.duration:
# Check connection
status = self.send_request("check_status", None)
if status is None:
self.log("red", f"[Predator {self.pid}] Connection lost.")
sys.exit(0)
if self.energy <= 0.0:
self.log("red", f"[Predator {self.pid}] has died.")
self.unregister()
sys.exit(0)
time.sleep(rd.uniform(0.0, 2.0))
if self.reprod_pred():
return
self.log("blue", f"[Predator {self.pid}] is on the hunt.")
if self.kill_probability(constants.PREDATOR_KILL_PROBABILITY):
if not self.hunt():
self.log("blue", f"[Predator {self.pid}] killed no prey.")
self.lose_energy(constants.PREDATOR_ENERGY_LOSS + float(rd.randint(-2, 5)))
time.sleep(rd.uniform(4.0, 6.0))
self.log("cyan", f"[Predator {self.pid}] lived peacefully.")