0

I made an online connect 4 game that uses the following logic:

  • Player1 sends their move to the server

  • Server sends the move to Player2

  • Player2 receives the move, makes their own move and sends it to the server

  • Server sends the move to Player1

  • Player1 receives the move, makes their own move and sends it to the server

  • (until someone wins or it's a draw)

It works but there is a problem: when player1 takes a while to choose their move and player2 is waiting to receive, player2's pygame window becomes unresponsive since it is stuck in a .recv() call. How can I fix this?

  • 1
    You always need to be handling events to make your operating system happy. You can handle network communication in a separate thread, [here's an example](https://stackoverflow.com/a/65877981/2280890) that uses a thread to connect to a database, and communicates with the main pygame thread via a queue. – import random Aug 12 '21 at 01:20

1 Answers1

2

You need to use threading and events. This way, the pygame window can refresh while another thread waits for any updates from the server.

As soon as the thread receives the update, an event should handle it to the main thread.

I don't remember much about implementation details (i'm a C# developer), but i used this while waiting for a AI to complete in Python.

Ladrillo
  • 79
  • 1
  • 4
  • Should I change the socket to non-blocking? – pythonlover753 Aug 12 '21 at 01:34
  • @pythonlover753 No, you need to create a new thread which will execute the code that handles the socket, while the main thread refreshes the pygame window. It's like having 2 people doing a task! This page: https://www.tutorialspoint.com/python/python_multithreading.htm It contains a good example in which it makes a thread that contains the "run" function which is (as far as i remember) where the socket should be waiting without affecting the main window :) – Ladrillo Aug 12 '21 at 21:44