This repository was archived by the owner on Jun 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
216 lines (173 loc) · 4.91 KB
/
server.py
File metadata and controls
216 lines (173 loc) · 4.91 KB
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# References:
# https://github.com/KyrosDigital/SnakeGame
# https://github.com/engineer-man/youtube/tree/master/015
import socket
import threading
import argparse
import curses
import pickle
import random # import randint
import time
# Global variables
positions = []
SNAKE_LENGTH = 5
snakes_body = []
current_players = 0
BUFFER_SIZE = 1024
def on_new_client(clientsocket, addr,player_num):
print ('Got connection from', addr)
player_num = str(player_num)
clientsocket.send(player_num.encode('utf-8')) # send player number assigned to client
def create_socket(ip_adress, port):
s = socket.socket()
s.bind((ip_adress, port))
s.listen()
print('Server started...')
return s
def joining_players(max_players, mainsocket):
players_threads = []
global current_players
while(current_players < max_players):
c, addr = mainsocket.accept() # Establish connection with client.
thread = threading.Thread(target=on_new_client, args=(c,addr,current_players))
thread.daemon = True
thread.start()
players_threads.append(c)
current_players = current_players + 1
print ("\nAll players connected\nStarting game in 1 second.\n")
time.sleep(1)
return players_threads
def listen_client_moves(player_num, s, players, max_x, max_y):
flag = False
global current_players
while True:
try:
data = s.recv(BUFFER_SIZE)
except socket.error:
break
global positions
check = str(data.decode('utf-8'))
if check == 'Head to body collision detected':
msg = 'Head to body collision detected'
s.send(pickle.dumps(msg))
positions[player_num] = (-1, -1)
current_players -= 1
s.close()
flag = True
break
key = int(data.decode('utf-8'))
temp_x = positions[player_num][0]
temp_y = positions[player_num][1]
if key == curses.KEY_RIGHT:
temp_x = temp_x + 1
elif key == curses.KEY_UP:
temp_y = temp_y - 1
elif key == curses.KEY_LEFT:
temp_x = temp_x - 1
else:
temp_y = temp_y + 1
if (temp_x >= max_x-1) or (temp_x <= 0) or (temp_y >= max_y-1) or (temp_y <= 0):
s.send(pickle.dumps('Out of bounds. '))
positions[player_num] = (-1, -1)
current_players -= 1
s.close()
flag = True
break
new_head = (temp_x, temp_y)
snakes_body[player_num].pop()
snakes_body[player_num].insert(0, new_head)
for i in range(len(positions)):
if i == player_num:
continue
else:
if (temp_x == positions[i][0]) and (temp_y == positions[i][1]):
msg = 'Head to Head collision detected.'
try:
s.send(pickle.dumps(msg))
players[i].send(pickle.dumps(msg))
s.close()
current_players -= 1
except socket.error:
print ('Error on head to head collision')
flag = True
break
if flag == True:
break
if current_players <= 1:
for p in players:
try:
p.send(pickle.dumps('You won!'))
return
except:
pass
try:
positions[player_num] = new_head
data_string = pickle.dumps(positions)
s.send(data_string)
except socket.error:
pass
return
def main():
parser = argparse.ArgumentParser(description='Starts the server. ')
parser.add_argument('ip_adress', nargs=1, default='192.168.10.4')
parser.add_argument('port', type=int, nargs=1, default=9999)
parser.add_argument('players', type=int, nargs=1, default=2)
args = parser.parse_args()
max_players = args.players[0]
players = []
s = create_socket(args.ip_adress[0], args.port[0])
print('Waiting for clients... \n')
stdscr = curses.initscr()
max_y, max_x = stdscr.getmaxyx()
curses.endwin()
max_y = max_y-2
max_x = max_x-2
window_size = (max_y, max_x)
players = joining_players(max_players, s)
for p in players:
msg = 'CREATE_BOARD'
p.send(msg.encode('utf-8'))
data = p.recv(BUFFER_SIZE)
msg = data.decode('utf-8')
if msg == 'STARTED_MAKING_BOARD':
continue
else:
print('Error issuing create_board')
for p in players: # send window size to be created for board
p.send(pickle.dumps(window_size))
data = p.recv(BUFFER_SIZE)
msg = data.decode('utf-8')
if msg == 'SIZE_RECEIVED':
continue
else:
print('Error sending size')
for p in players:
temp_x = random.randint(10, max_x-10)
temp_y = random.randint(10, max_y-10)
temp_tuple = (temp_x, temp_y)
positions.append(temp_tuple)
for p in players:
data_string = pickle.dumps(positions)
p.send(data_string)
for i in range(len(positions)):
temp_snake = []
for j in range(0, -1*SNAKE_LENGTH, -1):
temp_snake.append((positions[i][1], positions[i][0]-j))
snakes_body.append(temp_snake)
listener_threads = []
for i in range(len(players)):
thread = threading.Thread(target=listen_client_moves, args=(i, players[i], players, max_x, max_y))
thread.daemon = True
thread.start()
listener_threads.append(thread)
while True:
flag = False
for thread in listener_threads:
if thread.isAlive():
flag = True
if flag == False:
break
s.close()
print('All players disconnected. \nShutting down server.')
if __name__ == '__main__':
main()