-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient (1).py
More file actions
268 lines (232 loc) · 11.1 KB
/
client (1).py
File metadata and controls
268 lines (232 loc) · 11.1 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# Imports
from socket import *
####################
####################
# functions()
####################
def rockpaperscissors(clientSocket, hostorguest): # socket object and variable for turn order
# hostorguest is to know who should send first, 0 is client called, 1 is server called
print("")
print("Welcome to Rock, Paper, Scissors!")
#start with a
if not hostorguest:
while True:
data = clientSocket.recv(5)
if not data:
print("Error: No Data Received.")
exit(-3)
else:
dataString = data.decode('utf-8')
print("")
print("Received:", dataString)
break
if dataString == "/q":
print("Your opponent has fled the battle, You Win!")
print("")
return
elif dataString == "/rps": # rps = rockpaperscissors = wants to play the game
print("Ready... 3... 2... 1... SHOOT!") # alls good in the hood
else:
print("Received unknown code from opponent.")
exit(-4)
choice = input('"Rock", "Paper", or "Scissors"? It is your time to choose! >')
while True:
if choice == "Rock" or choice == "Paper" or choice == "Scissors":
print("You Selected: ", choice)
break
else:
choice = input("Not a valid choice, try again. >")
sendChoiceBytes = choice.encode('utf-8')
temp = clientSocket.sendall(sendChoiceBytes)
if temp is not None:
print("RPS Error: Sending failed.")
return
while True:
data = clientSocket.recv(10)
if not data:
print("No choice received from opponent.")
# break
else:
dataString = data.decode('utf-8')
print("")
# print("Received:", dataString)
print("Ready... 3... 2... 1... SHOOT!")
break
else:
while True:
data = clientSocket.recv(10)
if not data:
print("No choice received from opponent.")
# break
else:
dataString = data.decode('utf-8')
print("")
#print("Received:", dataString)
print("Ready... 3... 2... 1... SHOOT!")
break
choice = input('"Rock", "Paper", or "Scissors"? It is your time to choose! >')
while True:
if choice == "Rock" or choice == "Paper" or choice == "Scissors":
print("You Selected: ", choice)
break
else:
choice = input("Not a valid choice, try again. >")
sendChoiceBytes = choice.encode('utf-8')
temp = clientSocket.sendall(sendChoiceBytes)
if temp is not None:
print("RPS Error: Sending failed.")
return
# now to see who won
if choice == dataString:
print('It is a tie!, you both chose "', choice, '"')
else:
if choice == "Rock":
if dataString == "Rock":
print("Error 1.")
elif dataString == "Paper":
print('Their "Paper" beats Your "Rock"! You Lose!')
elif dataString == "Scissors":
print('Your "Rock" beats Their "Scissors"! You Win!')
else:
print("Error Desynch")
exit(-6)
elif choice == "Paper":
if dataString == "Rock":
print('Your "Paper" beats Their "Rock"! You Win!')
elif dataString == "Paper":
print('Error 1.')
elif dataString == "Scissors":
print('Their "Scissors" beats Your "Paper"! You Lose!')
else:
print("Error Desynch")
exit(-6)
elif choice == "Scissors":
if dataString == "Rock":
print('Their "Rock" beats Your "Scissors"! You Lose!')
elif dataString == "Paper":
print('Your "Scissors" beats Their "Paper"! You Win!')
elif dataString == "Scissors":
print('Error 1.')
else:
print("Error Desynch")
exit(-6)
pass # exited game loop
####################
####################
# main()
####################
def main():
address = "127.0.0.1"
portNumber = 1024
gameMode = 0 # 0 is chat, 1 is game
with socket(AF_INET, SOCK_STREAM) as clientSocket:
# setup client socket to connect over local network using TCP
# could also set up timeout, not sure if necessary yet + reuse port number
# clientSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
clientSocket.setblocking(True)
clientSocket.connect((address, portNumber)) # 1. The client creates a socket and connects
while True:
connected = True
# now we have a connection
print("Connection to Server successful:", address, "on:", portNumber)
print('Note: Messages limited to 4096 bytes and send only when prompted, or risk unexpected behavior...')
# using ' so " can be literal
print("")
print("Options:")
print("Type and Send a Message. (Enter/Return Key to Send)")
print('Enter: "rockpaperscissors" to play a simple game.')
print('Enter: "/q" to quit.')
#print('Note: Only send messages when prompted, enter "/q" to quit, enter "playgame" to play')
#print('Enter "playgame" to play an ASCII Multiplayer Game.')
while True:
print("")
clientSend = input("Enter Input >") # 2. When connected, the client prompts for a message to send
firstTime = True
while True:
if clientSend == "":
if firstTime:
clientSend = input("Message cannot be empty, try again. >")
firstTime = False
else:
clientSend = input("Message cannot be empty, try again. >")
else:
# for i in range(len(data)):
# print("Data Received From Client: ", data)
clientSendBytes = clientSend.encode('utf-8')
temp = clientSocket.sendall(clientSendBytes) # 3. The client sends the message
if temp is not None:
print("Client Error: Sending failed unexpectedly.")
exit(-5) # not sure what should happen here
# maybe shutdown
if clientSend == "/q":
print("Shutting down and sending EOT to Server.")
# shutdown
clientSocket.shutdown(SHUT_RDWR) # we already sent the EOT, time to exit
connected = False
elif clientSend == "rockpaperscissors":
gameMode = 1
rockpaperscissors(clientSocket, 0)
else:
connected = True
break # if reached end of else then we successfully sent the message
pass # end of sending loop
# first line outside of loop
if connected:
dataFromServer = clientSocket.recv(4096) # 4. The client calls recv to receive data
if not dataFromServer:
print("No Data Received From Server.")
break
else:
# for i in range(len(data)):
dataString = dataFromServer.decode('utf-8')
print("Server:", dataString) # 5. The client prints the data received
if dataString == "/q":
print("EOT Received from Server, shutting down.")
# shutdown
connected = False
clientSocket.shutdown(SHUT_RDWR) # needs a separate shutdown from the one below
break
elif dataString == "rockpaperscissors":
firstTimeConsentLoop = True
while True:
wantToPlay = input('Do you want to play Rock, Paper, Scissors? ("yes", "no") >')
if wantToPlay == "yes" or wantToPlay == "Yes":
acceptance = "/rps"
acceptanceBytes = acceptance.encode('utf-8')
temp = clientSocket.sendall(acceptanceBytes)
if temp is not None:
print("Client Error: Sending failed unexpectedly.")
exit(-5) # not sure what should happen here
# maybe shutdown
rockpaperscissors(clientSocket, 1) # if recv, then we are guest
elif wantToPlay == "no" or wantToPlay == "No":
rejection = "/q"
rejectionBytes = rejection.encode('utf-8')
temp = clientSocket.sendall(rejectionBytes)
if temp is not None:
print("Client Error: Sending failed unexpectedly.")
exit(-5) # not sure what should happen here
# maybe shutdown
else:
if firstTimeConsentLoop:
print("Invalid input, try again. >")
firstTimeConsentLoop = False
# needs to go back to input line again
continue # no break if no valid input
break
else:
connected = True # its just a message
pass #
else:
# shutdowns already set up for both client sending and receiving EOT
# clientSocket.shutdown(SHUT_RDWR) # sends EOT to peer
break
# last steps of each turn loop
pass # 6. Back to step 2(the client prompts for a message to send)
pass # last step in connected loop
if connected:
pass
else:
break
if __name__ == "__main__":
main()