Commit 070c2e4a authored by Ralf's avatar Ralf

introduce a game class

parent 4d38b80e
from player import Player
import selectors
import socket
class Game:
def __init__(self):
self.players = []
self.sock = socket.socket()
self.sock.bind(('0.0.0.0', 1234))
self.sock.listen(100)
self.sel = selectors.DefaultSelector()
self.sel.register(self.sock, selectors.EVENT_READ, self.accept)
def accept(self, sock, mask):
assert sock == self.sock
conn, addr = sock.accept() # Should be ready
player = Player(self, conn)
self.players.append(player)
self.sel.register(conn, selectors.EVENT_READ, player.read)
def removePlayer(self, player):
assert player in self.players
player.close()
self.players.remove(player)
assert player not in self.players # this ensure the player was in only once
def close(self):
for player in self.players:
player.close()
self.players.clear()
self.sock.close()
def run(self):
while True:
events = self.sel.select()
for key, mask in events:
callback = key.data
callback(key.fileobj, mask)
#!/usr/bin/python3
from game import Game
import selectors
import socket
import atexit
from player import Player
sel = selectors.DefaultSelector()
players = []
def accept(sock, mask):
conn, addr = sock.accept() # Should be ready
player = Player(sel, conn)
players.append(player)
sel.register(conn, selectors.EVENT_READ, player.read)
sock = socket.socket()
sock.bind(('0.0.0.0', 1234))
sock.listen(100)
sel.register(sock, selectors.EVENT_READ, accept)
game = Game()
try:
while True:
events = sel.select()
for key, mask in events:
callback = key.data
callback(key.fileobj, mask)
game.run()
finally:
sock.close()
for player in players:
player.close()
game.close()
from util import *
class Player:
def __init__(self, sel, conn):
def __init__(self, game, conn):
self.buffer = b""
self.sel = sel
self.game = game
self.conn = conn
# low-level functions
......@@ -11,7 +11,7 @@ class Player:
assert type(data) == str
send_async(self.conn, (data+"\n").encode('utf-8'))
def close(self):
def close(self): # only to be called by Game - it has to remove us from its list
self.conn.close()
def read(self, conn, mask):
......@@ -25,9 +25,7 @@ class Player:
self.buffer = self.buffer[pos+1:]
self.readCmd(cmd.decode('utf-8'))
else:
log_stdout('closing', conn)
self.sel.unregister(conn)
conn.close()
self.game.removePlayer(self)
# high(er)-level functions
def readCmd(self, cmd):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment