-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
224 lines (194 loc) · 10 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
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
217
218
219
220
221
222
223
224
import socket
import json
from clases.GameSession import GameSession
import random as r
from config import BUFFER_SIZE, IP, PORT, SIZE
import time
PLAYERS = []
SESSIONS = []
SESSION_COUNT = 0
def printMatrix(matrix):
for row in matrix:
print(" ".join(map(str, row)))
def foundSession(ip):
for session in SESSIONS:
if ip == session.player1.ip:
return session.sessionId, session.player1.board, session
elif ip == session.player2.ip:
return session.sessionId, session.player2.board, session
def endGame(UDPServerSocket, ipPlayerLost, ipPlayerWin, bot = False):
sendMessage(UDPServerSocket, ipPlayerLost, "l", 1)
sendMessage(UDPServerSocket, ipPlayerWin, "w", 1)
def sendMessage(UDPServerSocket, address, action ,status,position=[]):
responseData = {
"action": action,
"status": status,
"position": position
}
print("Mensaje enviado: ", responseData, address)
UDPServerSocket.sendto(json.dumps(responseData).encode(), address)
def selectionMode(UDPServerSocket, received_data, address):
global SESSION_COUNT
if(address not in PLAYERS):
PLAYERS.append(address)
selectModeGame = received_data["bot"]
if selectModeGame == 1:
gameSession = GameSession(SESSION_COUNT, address, ("1","1"),1)
SESSION_COUNT += 1
SESSIONS.append(gameSession)
print("Empieza partida contra bot")
gameSession.player2.randomBoard()
printMatrix(gameSession.player2.board)
sendMessage(UDPServerSocket,address, "s",1)
PLAYERS.remove(address)
else:
# Implementa la lógica para esperar a otro jugador.
if len(PLAYERS) % 2 == 0:
gameSession = GameSession(SESSION_COUNT, PLAYERS[0], PLAYERS[1],0)
SESSION_COUNT += 1
SESSIONS.append(gameSession)
print("SESION", gameSession.sessionId, "\nJugador 1:", gameSession.player1.ip, "vs", "Jugador 2:", gameSession.player2.ip)
sendMessage(UDPServerSocket, PLAYERS[0],"s",1)
sendMessage(UDPServerSocket, PLAYERS[0],"b", 1)
sendMessage(UDPServerSocket, PLAYERS[1],"s",1)
sendMessage(UDPServerSocket, PLAYERS[1],"b", 1)
PLAYERS.clear()
# else:
# sendMessage(UDPServerSocket, PLAYERS[0],"s",2)
def takeAction(UDPServerSocket):
global SESSION_COUNT, SESSIONS
bytesAddressPair = UDPServerSocket.recvfrom(BUFFER_SIZE)
message = bytesAddressPair[0]
address = bytesAddressPair[1]
received_data = json.loads(message.decode())
print(received_data)
action = received_data["action"]
# print(SESSIONS)
if action == "c":
print("------------------------------------------------------------")
print("Player connected", address)
sendMessage(UDPServerSocket, address,"c",1)
elif action == "s":
print("------------------------------------------------------------")
print("Player selected mode", address)
selectionMode(UDPServerSocket, received_data, address)
elif action == "a":
idSession, boardFounded, session = foundSession(address)
x, y = received_data["position"]
if (session.bot == 1): #Bot
if(SESSIONS[idSession].player1.ip == address):
hit = SESSIONS[idSession].player2.attackBoard(x, y)
# sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip,"a", hit) # real
sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip,"a", hit, [x,y])
sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip,"t",0)
print("Generando ataque bot...")
##Ataque del bot
x_bot, y_bot = SESSIONS[idSession].player1.botAtack(r.randint(0, SIZE - 1), r.randint(0, SIZE - 1))
print(x_bot, y_bot)
hit = 0
if SESSIONS[idSession].player1.board[x][y] == 2:
hit = 1
# time.sleep(10)
sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip,"a",hit, [x_bot, y_bot])
# time.sleep(10)
sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip,"t",1)
else:
if SESSIONS[idSession].player1.ip == address:
hit = SESSIONS[idSession].player2.attackBoard(x, y)
# sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip,"a",hit) #real
sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip,"a",hit, (x,y))
sendMessage(UDPServerSocket, SESSIONS[idSession].player2.ip, "a",hit,[x,y])
sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip, "t",0)
sendMessage(UDPServerSocket, SESSIONS[idSession].player2.ip, "t",1)
SESSIONS[idSession].player1.printMatrix()
else:
hit = SESSIONS[idSession].player1.attackBoard(x, y)
# sendMessage(UDPServerSocket, SESSIONS[idSession].player2.ip,"a",hit) #real
sendMessage(UDPServerSocket, SESSIONS[idSession].player2.ip, "a",hit,[x,y])
sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip, "a",hit,[x,y])
sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip, "t",1)
sendMessage(UDPServerSocket, SESSIONS[idSession].player2.ip, "t",0)
SESSIONS[idSession].player1.printMatrix()
if SESSIONS[idSession].player1.lost() and not session.bot:
endGame(UDPServerSocket, SESSIONS[idSession].player1.ip, SESSIONS[idSession].player2.ip)
elif SESSIONS[idSession].player2.lost() and not session.bot:
endGame(UDPServerSocket, SESSIONS[idSession].player2.ip, SESSIONS[idSession].player1.ip)
elif SESSIONS[idSession].player1.lost() and session.bot:
sendMessage(UDPServerSocket, address, "l", 1)
elif SESSIONS[idSession].player2.lost() and session.bot:
sendMessage(UDPServerSocket, address, "w", 1)
elif action == "b":
try:
idSession, boardFounded, session = foundSession(address)
ships = received_data["ships"]
print("SHIPS,", ships)
for i in ships:
if i == "p":
boardFounded[ships[i][0]][ships[i][1]] = 1
elif i == "b":
if ships[i][2] == 0:
# print(ships[i][0], ships[i][1])
# print(ships[i][0] + 1, ships[i][1])
boardFounded[ships[i][0]][ships[i][1]] = 1
boardFounded[ships[i][0] + 1][ships[i][1]] = 1
else:
boardFounded[ships[i][0]][ships[i][1]] = 1
boardFounded[ships[i][0]][ships[i][1] + 1] = 1
elif i == "s":
if ships[i][2] == 0:
boardFounded[ships[i][0]][ships[i][1]] = 1
boardFounded[ships[i][0] + 1][ships[i][1]] = 1
boardFounded[ships[i][0] + 2][ships[i][1]] = 1
else:
boardFounded[ships[i][0]][ships[i][1]] = 1
boardFounded[ships[i][0]][ships[i][1] + 1] = 1
boardFounded[ships[i][0]][ships[i][1] + 2] = 1
if SESSIONS[idSession].player1.ip == address:
SESSIONS[idSession].player1.printMatrix()
SESSIONS[idSession].player1.board = boardFounded
SESSIONS[idSession].player1.start = True
sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip, "b",1)
if session.bot == 1:
time.sleep(2)
print("Enviar msj a player para empezar partida")
sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip, "t",1)
# SESSIONS[idSession].player2.start = True
elif(not session.bot):
SESSIONS[idSession].player2.board = boardFounded
sendMessage(UDPServerSocket, SESSIONS[idSession].player2.ip, "b", 1)
SESSIONS[idSession].player2.start = True
SESSIONS[idSession].player2.printMatrix()
if (SESSIONS[idSession].player1.start and SESSIONS[idSession].player2.start):
sendMessage(UDPServerSocket, SESSIONS[idSession].player1.ip, "t",1)
sendMessage(UDPServerSocket, SESSIONS[idSession].player2.ip, "t",0)
except Exception as e:
print("Error", e)
elif action == "d":
try:
idSession, boardFounded, session = foundSession(address)
if(session.player1.ip == address and not session.bot):
# endGame(UDPServerSocket, session.player1, session.player2)
sendMessage(UDPServerSocket, session.player1.ip, "d", 1)
sendMessage(UDPServerSocket, session.player2.ip, "w", 1)
elif (not session.bot):
# endGame(UDPServerSocket, session.player2, session.player1)
sendMessage(UDPServerSocket, session.player2.ip, "d", 1)
sendMessage(UDPServerSocket, session.player1.ip, "w", 1)
else:
sendMessage(UDPServerSocket, session.player1.ip, "d", 1)
SESSIONS.remove(SESSIONS[idSession])
SESSION_COUNT -= 1
except:
print("Error al desconectar")
def main():
# msgFromServer = "Hello UDP Client"
# bytesToSend = str.encode(msgFromServer)
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
UDPServerSocket.bind((IP, PORT))
print("UDP server up and listening")
while True:
takeAction(UDPServerSocket)
# Implementa el temporizador de 10 segundos para desconectar al jugador si no juega.
# UDPServerSocket.sendto(bytesToSend, address)
if __name__ == "__main__":
main()