old_gravity/server.py
2020-01-27 16:23:32 +01:00

133 lines
3.5 KiB
Python
Executable File

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 26 17:50:25 2020
@author: suwako
"""
import sys, multiprocessing, socket, time
if sys.platform == 'win32':
import multiprocessing.reduction
from colorama import Fore, Style
import numpy as np
def debug(*s): print("[D ] : " +
str(', '.join(map(str, s))) +
Style.RESET_ALL)
def info(*s): print(Fore.GREEN +
Fore.LIGHTGREEN_EX +
"[I -] : " +
Style.RESET_ALL +
str(', '.join(map(str, s))) +
Style.RESET_ALL)
def warn(*s): print(Fore.MAGENTA +
"[W ~] : " +
Style.RESET_ALL +
str(', '.join(map(str, s))) +
Style.RESET_ALL)
def error(*s): print(Fore.RED +
Fore.LIGHTRED_EX +
"[E !] : " +
Style.RESET_ALL +
str(', '.join(map(str, s))) +
Style.RESET_ALL)
level = 1
for i in range(level):
exec("debug info warn error".split()[i] + "= lambda *x: None")
class Satellite():
def __init__(self, pos=np.array([0., 0.]),
speed=np.array([0., 0.]),
mass=1):
self.pos = pos
self.speed = speed
self.mass = mass
self.G = 0.0000001
def tick(self):
self.pos += self.speed
def apply_gravity(self, elements):
for element in elements:
if element.pos != self.pos:
d = element.pos - self.pos
u = d/np.linalg.norm(d)
norm = self.G * element.mass * (d[0]**2 + d[1]**2)
self.speed += norm*u
class Player():
pass
class Map():
def __init__(self):
self.elements = []
def handle(connection, address):
try:
info("Connected at "+ ':'.join(map(str,address)))
while True:
data = connection.recv(1024)
if data == b"":
info("Socket closed remotely at " + ':'.join(map(str,address)))
break
debug("Received data %r" % data)
connection.sendall(data)
debug("Sent data")
except:
warn("Problem handling request")
connection.close()
raise
finally:
debug("Closing socket with " + ':'.join(map(str,address)))
connection.close()
class Server(object):
def __init__(self, hostname, port):
self.hostname = hostname
self.port = port
def start(self):
debug("listening")
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind((self.hostname, self.port))
self.socket.listen(1)
while True:
conn, address = self.socket.accept()
process = multiprocessing.Process(target=handle,
args=(conn, address))
process.daemon = True
process.start()
if __name__ == "__main__":
server = Server("0.0.0.0", 9000)
try:
info("Listening")
server.start()
except:
error("Unexpected exception")
for process in multiprocessing.active_children():
info("Shutting down process %r", process)
process.terminate()
process.join()
raise
finally:
info("Shutting down")
for process in multiprocessing.active_children():
info("Shutting down process %r", process)
process.terminate()
process.join()
info("All done")