I’ve been working latley on a server-client game that’s very similar to agario (multiplayer game with a server and clients).
The main idea is simple, I run the server code and then the client code for it to connect to the server (if I want to play with multiple cilents I just create another py file with the same code as the other client and run it).
This is the main function of the server:
def handle_client(conn, addr):
global cells, players # Declare cells as a global variable
print(f"[CONNECTION] Connected to {addr}")
# Assign a player ID based on connection order
player_id = uuid.uuid4()
players[player_id] = Player(player_id, 0, 0)
# Send player ID to client
conn.sendall(pickle.dumps(player_id))
# Send cells data to client
conn.sendall(pickle.dumps(cells))
while True:
try:
# Receive player position from client
player_data = conn.recv(4096)
player = pickle.loads(player_data)
#received_player_id, player_x, player_y = player
#print(player_x)
#print(player_y)
# Update player position in the list
players[player_id] = player
conn.sendall(pickle.dumps(players))
cell_data = conn.recv(4096)
cells = pickle.loads(cell_data)
print(cells)
<— The Problematic code
conn.sendall(pickle.dumps(cells))
time.sleep(0.01) # Avoids maxing out CPU
except:
break
print(f"[DISCONNECT] Player {player_id} disconnected")
players.pop(player_id) # Remove player from list
conn.close()
When I Run the server and run 2 clients both of them will have the same cells in the same place, The problem accurs when one of them is trying to “consume” one of the cells (when a player gets in the same location as a cell he consumes it), for the player who consumed the cell, the cell itself disappeares but for the other connected players the cell stays in the same place with no change, only if I use the line “print(cells)” the code will work and the cell will disappear for all players, why is that?
The Game itself (with 2 clients connected)
Electro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.