2

I'm trying to make an online game using both pygame and sockets. I'm new to sockets so I'm having some trouble.

For now, each player is just a square that moves around the screen by command. So each player should be able to see the other player's exact position in real time.

What I've come up with so far is this:

#server.py
class Play:
    sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    #sk.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1)

    def __init__(self):
        #players positions
        self.x, self.y = 200, 400
        self.j, self.k = 400, 200
        #wait for client
        self.sk.bind(('', 12345))
        data, self.adr = self.sk.recvfrom(1024)
        #self.sk.setblocking(0)
        self.sk.settimeout(0.05)
        re_th = threading.Thread(target=self.receive)
        re_th.daemon = True
        re_th.start()
        self.run()

run function:

def run(self):
    win = pygame.display.set_mode((width, height))
    clock = pygame.time.Clock()
    while True:
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT] and self.x > 0:
            self.x -= vel
        if keys[pygame.K_RIGHT] and self.x < width - cw:
            self.x += vel
        if keys[pygame.K_UP] and self.y > 0:
            self.y -= vel
        if keys[pygame.K_DOWN] and self.y < height - ch:
            self.y += vel

        self.send()
        #draws on screen both player's squares
        clock.tick(60)

Send and receive functions:

def send(self):
    co = json.dumps((self.x, self.y))
    self.sk.sendto(co.encode('utf-8'), self.adr)

def receive(self):
    while True:
        try:
            data, xadr = self.sk.recvfrom(1024)
            self.j, self.k = (json.loads(data.decode('utf-8')))
        except OSError:
                pass

The client file is very similar.

The run function takes user input to move the square, sends the coordinates to the other player and then draws on screen both players. All at the same time as a thread is receiving the other player's x and y coordinates.

This works well locally, I do notice some delay that I think there shouldn't be since its local, while over the internet its slower.

What am I doing wrong? What could I do better?

Thanks in advance

Jackpy
  • 111
  • 5

0 Answers0