-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
executable file
·124 lines (107 loc) · 3.38 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#!/usr/bin/python3
import socket
import sys
import signal
import threading
from functools import partial
from board import Board
import random
WHITE = 0
BLACK = 1
EMPTY = 2
# PIECE[WHITE] = "X"
# PIECE[BLACK] = "O"
# PIECE[EMPTY] = "."
PIECE=["X", "O", "."]
class Serve(threading.Thread):
def __init__(self, connection, address):
threading.Thread.__init__(self)
self.connection = connection
self.address = address
self.board = ""
def run(self):
print("[INFO] Got connection form", self.address)
# Send acknowledgement for connecting
msg="Welcome to Reversi\n\nChoose a color:\n0. White\n1. Black"
self.connection.send(msg.encode("ascii"))
# Wait for handshake packet
handshakePacket = self.connection.recv(1024)
packet=list(handshakePacket.decode("ascii").split(" "))
if packet[0] == "initiate":
print("[INFO] Opponent wants to play with", packet[1])
if packet[1] == "white":
myColor = BLACK
elif packet[1] == "black":
myColor = WHITE
self.board = Board(myColor)
gameInitialized = True
self.board.printBoard()
validMoves = self.board.legalMoves()
while not(self.board.isBoardFull()) and len(validMoves) > 0:
# Black makes the first move
if gameInitialized and self.board.myColor == BLACK:
print("[DEBUG] Valid Moves:", validMoves)
ij = validMoves[random.randint(0, len(validMoves) - 1)]
self.board.updateBoard(ij, self.board.myColor)
self.connection.send(ij.encode("ascii"))
print("[DEBUG] You chose i:", ij[:1], "j:", ij[1:])
self.board.printBoard()
gameInitialized = False
ij = self.connection.recv(1024).decode("ascii")
if ij == "close":
print("[INFO] Opponent left")
self.board.printBoard()
self.board.getFinalScore()
break
else:
self.board.updateBoard(ij, self.board.opponentColor)
print("[DEBUG] Opponent chose i:", ij[:1], "j:", ij[1:])
self.board.printBoard()
validMoves = self.board.legalMoves()
if self.board.isBoardFull() or len(validMoves) == 0:
break
print("[DEBUG] Valid Moves:", validMoves)
ij = validMoves[random.randint(0, len(validMoves) - 1)]
self.board.updateBoard(ij, self.board.myColor)
self.connection.send(ij.encode("ascii"))
print("[DEBUG] You chose i:", ij[:1], "j:", ij[1:])
self.board.printBoard()
print("\n[INFO] Fetching final score...")
self.board.getFinalScore()
self.connection.close()
class Server():
def __init__(self, port):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.host = socket.gethostname()
self.port = port
def run(self):
try:
self.s.bind((self.host, self.port))
except Exception as e:
print("[ERROR] Cannot bind the address")
exit()
# Will listen to 1 simultaneous connection
self.s.listen(1)
print("[INFO] Server running at port", self.port)
while True:
self.connection, self.address = self.s.accept()
self.serve = Serve(self.connection, self.address);
# Start a serving thread
self.serve.start()
def terminate(server, signum, frame):
print("\n[INFO] Shutting down the server...")
server.s.close()
exit()
def main():
try:
port = int(sys.argv[1])
except Exception as e:
print("[ERROR] Usage:", sys.argv[0], "port")
exit()
server = Server(port)
# Terminates the server gracefully
interruptHandler = signal.signal(signal.SIGINT, partial(terminate, server))
server.run()
if __name__ == '__main__':
main()