wooly-vault/solutions/3.py

79 lines
1.7 KiB
Python
Raw Normal View History

2024-09-06 19:55:16 +02:00
from io import TextIOWrapper
import socket
REMOTE = "127.0.0.1"
PORT = 1339
2024-09-06 19:55:16 +02:00
MAX_GUARD = 300
def calc(a: int, b: int, op: str) -> int:
match op:
case '+': return a+b
case '-': return a-b
case '*': return a*b
case '/': return int(a/b)
case _: raise Exception(f"bad op: {op}")
def main() -> int:
response: str = ""
s = socket.socket()
s.connect((REMOTE, PORT))
sf: TextIOWrapper = s.makefile('rw')
guard = 0
res = 0
while guard < MAX_GUARD:
guard += 1
response = recv(sf)
if "What" in response:
parts = response.strip().replace('?',"").split(' ')
print(f"# {parts}")
a = int(parts[2])
op = parts[3]
b = int(parts[4])
print(f"# {a} {op} {b}")
res: int = calc(a,b,op)
_ = send(sf, str(res))
elif "correct" in response:
print(f"# we got one right: {response}")
elif "wrong" in response:
print(f"! our answer was not accepted: '{response}'")
s.close()
return 2
elif "win" in response:
print(f"# We won: '{response}'")
break
2024-09-06 20:01:47 +02:00
elif "slow" in response:
print(f"# We are too slow, it's futile")
break
2024-09-06 19:55:16 +02:00
else:
print(f"! unknown response: '{response}'")
s.close()
return 1
2024-09-06 20:01:47 +02:00
2024-09-06 23:55:31 +02:00
sf.close()
2024-09-06 19:55:16 +02:00
return 0
def send(sf: TextIOWrapper, msg: str) -> int:
print(f"> {msg}")
sent: int = sf.write(f"{msg}\n")
sf.flush()
return sent
def recv(sf: TextIOWrapper) -> str:
response = sf.readline().strip()
print(f"< {response}")
return response
if __name__ == "__main__":
exit(main())