player.py 975 Bytes
Newer Older
1
2
3
from util import *

class Player:
Ralf's avatar
Ralf committed
4
    def __init__(self, game, conn):
5
        self.buffer = b""
Ralf's avatar
Ralf committed
6
        self.game = game
7
8
9
10
11
12
13
        self.conn = conn
    
    # low-level functions
    def send(self, data):
        assert type(data) == str
        send_async(self.conn, (data+"\n").encode('utf-8'))
    
Ralf's avatar
Ralf committed
14
    def close(self): # only to be called by Game - it has to remove us from its list
15
16
17
18
19
20
21
22
23
24
25
26
27
        self.conn.close()
    
    def read(self, conn, mask):
        assert self.conn == conn, "The player's connection changed?"
        data = conn.recv(1024)  # Should be ready
        if data:
            self.buffer += data
            pos = self.buffer.find(b'\n')
            if pos >= 0:
                cmd = self.buffer[:pos]
                self.buffer = self.buffer[pos+1:]
                self.readCmd(cmd.decode('utf-8'))
        else:
Ralf's avatar
Ralf committed
28
            self.game.removePlayer(self)
29
30
31
32
    
    # high(er)-level functions
    def readCmd(self, cmd):
        self.send("Selber "+cmd)