from io import TextIOWrapper import socket import time REMOTE = "127.0.0.1" PORT = 1337 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 elif "slow" in response: print(f"# We are too slow, it's futile") break else: print(f"! unknown response: '{response}'") s.close() return 1 sf.close() 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())