/
client.py
303 lines (255 loc) · 8.19 KB
/
client.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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import os
import sys
from socketIO_client import SocketIO, LoggingNamespace
import requests
import json
import threading
import signal
from transitions import Machine
import constants as cs
import click
USER_FILE = './user.txt'
SERVER_IP = None
SERVER_PORT = None
user_name = None
matchId = None
"""
Create a file USER_FILE in the current directory and use it afterwards
"""
# if not os.path.exists(USER_FILE):
def enter_nick():
global user_name
while True:
print('please enter your nick:')
nick = sys.stdin.readline()[:-1]
args = {"name": nick}
res = requests.get(SERVER_ADDR + "/new_user", params=args)
data = json.loads(res.content)
if data['status']:
with open(USER_FILE, 'w') as fobj:
fobj.write(nick)
user_name = nick
break
else:
print data['text']
# else:
# with open(USER_FILE) as fobj:
# user_name = fobj.readline()
# SocketIo for all communications with server
socketIO = None
def get_msg(obj):
"""
The default function used when communicating with server
The obj is a dictionary and is appended to the basic data like user, matchId etc
"""
if not matchId:
user_obj = {
"user": user_name
}
else:
user_obj = {
"user": user_name,
"matchId": matchId
}
return dict(obj, **user_obj)
"""
All interactions with server is designed as a State Machine
The transitions are fairly self-explanatory
"""
class sm(object):
states = [
'dummy',
'init',
'waiting_join',
'playing',
'waiting_play',
'played',
'waiting_rematch',
'opp_exit',
'exit',
'joining']
transitions = [
{'trigger': 'new_match', 'source': 'init', 'dest': 'waiting_join'},
{'trigger': 'join_match', 'source': 'init', 'dest': 'waiting_join'},
{'trigger': 'begin_match', 'source': 'waiting_join', 'dest': 'playing'},
{'trigger': 'sent_value', 'source': 'playing', 'dest': 'waiting_play'},
{'trigger': 'result', 'source': 'waiting_play', 'dest': 'played'},
{'trigger': 'rematch', 'source': 'played', 'dest': 'waiting_rematch'},
{'trigger': 'rematch_reply', 'source': 'waiting_rematch', 'dest': 'playing'},
{'trigger': 'opp_exit', 'source': '*', 'dest': 'opp_exit'},
{'trigger': 'exit', 'source': '*', 'dest': 'exit'}
]
def __init__(self, name):
"""
intializes the state machine with above transitions
"""
self.opponent = None
self.name = name
self.machine = Machine(
model=self,
states=sm.states,
transitions=sm.transitions,
initial='dummy')
self.to_init()
def on_enter_init(self):
"""
Default menu based input.
After this, a confirmation from server will take us to next state
"""
print """
What do you want to do?\n
1. New Match
2. Join Match
3. Exit
"""
c = sys.stdin.readline()[0]
if c == '1':
msg = get_msg({})
socketIO.emit(cs.NEW_MATCH, msg)
elif c == '2':
print 'Please enter matchId'
matchID = sys.stdin.readline()[:-1]
global matchId
matchId = matchID
msg = get_msg({})
socketIO.emit(cs.JOIN_MATCH, msg)
self.join_match()
else:
self.exit()
def on_enter_exit(self):
"""
Before leaving match, make sure you communicate it with server
"""
print 'leaving match!'
socketIO.emit(cs.LEAVE, get_msg({}))
sys.exit(0)
def on_enter_waiting_join(self):
print "Please share this id with your friend", matchId
def on_enter_playing(self):
"""
The basic playing interface. Simple character based r,p,s
"""
print 'Enter your choice Rock(r),Paper(p),Scissor(s)'
choice = sys.stdin.readline()[0]
if choice == 'r' or choice == 'p' or choice == 's':
msg = get_msg({"choice": choice})
socketIO.emit('play', msg)
self.sent_value()
else:
print 'Wrong choice'
self.on_enter_playing()
def on_enter_played(self):
"""
Rematch feature at the end of the game
"""
print ("Do you want a rematch (y/n)?")
ans = sys.stdin.readline()[0]
if ans == 'y':
print 'Waiting for other participant to join'
socketIO.emit('rematch', get_msg({}))
self.rematch()
else:
global matchId
print 'leaving_match'
socketIO.emit(cs.LEAVE, get_msg({}))
matchId = None
self.to_init()
def on_enter_opp_exit(self):
"""
opponent exited. Currently leaving from the game
Might have better implementations
"""
global matchId
print self.opponent + ' has exited!'
socketIO.emit(cs.LEAVE, get_msg({}))
matchId = None
self.to_init()
def sock_match_confirm(self, msg):
"""
Server responded with the matchId. Update the global matchId
"""
if msg:
if msg['status']:
global matchId
matchId = msg['matchId']
self.new_match()
else:
print 'new_match failed'
def sock_begin_match(self, msg):
"""
Another player has joined the game
"""
if msg:
users = msg['users']
print 'Match started between ' + users[0] + " and " + users[1]
self.opponent = users[0] if users[1] == user_name else users[1]
self.begin_match()
def sock_onresult(self, msg):
"""
Match ended.
Calcuate the result and show.
The server sends entire data. Its upto client to find out who won
"""
if msg:
user2 = msg['data'][1] if msg['data'][0][0] == user_name \
else msg['data'][0]
user1 = msg['data'][0] if msg['data'][0][0] == user_name \
else msg['data'][1]
print user2[0] + " has chose " + user2[1]
if msg['result'] == 0:
print 'match drawn'
elif msg['data'][0][0] == user_name and msg['result'] == 1\
or msg['data'][1][0] == user_name and msg['result'] == -1:
print "You've won the match"
else:
print "You've lost"
self.result()
def sock_onjoin_match(self, msg):
"""
When using id to join a new game, server might respond with negative
such as when room is already filled/ id previously used
"""
if msg:
if not msg['status']:
global matchId
print msg['text']
matchId = None
self.to_init()
def sock_onrematch(self, msg):
"""
rematch has been accepted by opponent too
"""
self.rematch_reply()
def sock_onleave(self, msg):
"""
opponent has left
"""
self.opp_exit()
machine = None
def exit_match(signal, frame):
machine.exit()
@click.command()
@click.option('--sip', default="http://127.0.0.1", help='Server Ip')
@click.option('--port', default=5000, help='The defualt port on server.')
def main(sip,port):
global SERVER_IP
global SERVER_PORT
global SERVER_ADDR
global socketIO
global machine
SERVER_IP = sip
SERVER_PORT = port
SERVER_ADDR = SERVER_IP + ":" + str(SERVER_PORT)
socketIO = SocketIO(SERVER_IP, SERVER_PORT, LoggingNamespace)
enter_nick()
machine = sm("Test")
signal.signal(signal.SIGINT, exit_match)
socketIO.on(cs.JOIN_MATCH, machine.sock_onjoin_match)
socketIO.on(cs.NEW_MATCH, machine.sock_match_confirm)
socketIO.on(cs.BEGIN_MATCH, machine.sock_begin_match)
socketIO.on(cs.RESULT, machine.sock_onresult)
socketIO.on(cs.REMATCH, machine.sock_onrematch)
socketIO.on(cs.LEAVE, machine.sock_onleave)
socketIO.wait()
if __name__ == '__main__':
main()