Skip to content

Instantly share code, notes, and snippets.

@Axeltherabbit
Last active April 3, 2023 22:31
Show Gist options
  • Save Axeltherabbit/9f905da9aa80dcebd188f61815c6a706 to your computer and use it in GitHub Desktop.
Save Axeltherabbit/9f905da9aa80dcebd188f61815c6a706 to your computer and use it in GitHub Desktop.
2 players game socket example with server as arbiter
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
print(host)
port = 8085 # Reserve a port for your service.
print('Server started!')
print('Waiting for clients...')
s.bind((host, port)) # Bind to the port
s.listen(2) # Now wait for client connection.
players = []
def decode_move(move: str):
return "bf5"
def play(move : str):
# game logic here
# -1 game is not finished, 0 draw, 1 player one win, 2 player 2 win
return -1
while len(players) < 2:
players.append(s.accept()) # Establish connection with client
players[-1][0].send(f"Hello player #{len(players)}\n>".encode())
print('2 players connected', players[0][1], players[1][1])
turn = 0
while True:
current_player_client, addrCP = players[turn%2]
other_player_client, addrOP = players[(turn+1)%2]
msg = current_player_client.recv(1024)
print("received :", msg, "from", addrCP)
try:
move = decode_move(msg)
if play(move) != -1:
break
except ValueError:
# current player invalid move
break
other_player_client.send(f"The other player played {msg}\nYour Turn\n>".encode())
turn += 1
for c, addr in players:
c.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment