python multiplayer

Solutions on MaxInterview for python multiplayer by the best coders in the world

showing results for - "python multiplayer"
Carlos
28 Jan 2019
1#some server thingy i found online.
2
3
4
5server = ""
6port = 5555
7
8games = {}
9idCount = 0
10currentPlayer = 0
11
12s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
13
14s.bind((server, port))
15
16s.listen()
17print("Waiting for a connection, Server Started")
18
19class Game:
20    def __init__(self, id):
21        self.connected = False
22
23players = [Player(0), Player(1)]
24
25def threaded_client(conn, player, gameId):
26    global idCount
27    conn.send(pickle.dumps(players[player]))
28    reply = ""
29    while True:
30        try:
31            data = pickle.loads(conn.recv(2048))
32            players[player] = data
33            if gameId in games:
34                game = games[gameId]
35                if not data:
36                    print("Disconnected")
37                    break
38                else:
39                    if player == 1:
40                        reply = players[0]
41                    else:
42                        reply = players[1]
43
44                conn.sendall(pickle.dumps(reply))
45        except:
46            break
47
48    print("Lost connection")
49    try:
50        del games[gameId]
51        print("Closing game", gameId)
52    except:
53        pass
54    idCount -= 1
55    conn.close()
56
57while True:
58    conn, addr = s.accept()
59    print("Connected to:", addr)
60
61    idCount += 1
62    p = 0
63
64    gameId = (idCount - 1) // 2
65
66    if idCount % 2 == 1:
67        games[gameId] = Game(gameId)
68        players[0].connected = True
69        print("Creating a new game")
70        print("Waiting for another player")
71    else:
72        games[gameId].connected = True
73        p = 1
74        players[1].connected = True
75        print("Game is available")
76
77
78
79    start_new_thread(threaded_client, (conn, currentPlayer, gameId))
80    currentPlayer += 1
81
82