|
@@ -0,0 +1,96 @@
|
|
|
+import json
|
|
|
+import select
|
|
|
+import socket
|
|
|
+import sys
|
|
|
+import time
|
|
|
+
|
|
|
+HOST = 'localhost'
|
|
|
+PORT = 6546
|
|
|
+
|
|
|
+ssock = None
|
|
|
+
|
|
|
+def listen():
|
|
|
+ global ssock
|
|
|
+ ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
+ #ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
|
+ ssock.connect((HOST, PORT))
|
|
|
+ print('connected:', ssock)
|
|
|
+ send_msg(set_name('BOT_select_first'))
|
|
|
+ while True:
|
|
|
+ bmsg = ssock.recv(1024)
|
|
|
+ if len(bmsg) <= 0:
|
|
|
+ print('read 0; hangup')
|
|
|
+ exit(3)
|
|
|
+ msg = str(bmsg, 'utf-8').strip()
|
|
|
+ jmsg = json.loads(msg)
|
|
|
+ msg_type = parse_server_message(jmsg)
|
|
|
+ print('parsed msg_type:', msg_type)
|
|
|
+ if msg_type == 'query':
|
|
|
+ action = get_action(jmsg)
|
|
|
+ print('parsed action:', action)
|
|
|
+ if action == 'give_card':
|
|
|
+ bot_give_card(jmsg)
|
|
|
+ elif action == 'select_row':
|
|
|
+ bot_select_row(jmsg)
|
|
|
+ else:
|
|
|
+ print('unknown message action:', action)
|
|
|
+ else:
|
|
|
+ print('unknown message type:', msg_type)
|
|
|
+
|
|
|
+def bot_give_card(msg):
|
|
|
+ print('about to give card')
|
|
|
+ hand = msg.get('hand')
|
|
|
+ print(hand, '->', hand[0])
|
|
|
+ msg = give_card(hand[0])
|
|
|
+ send_msg(msg)
|
|
|
+ return hand[0]
|
|
|
+
|
|
|
+def bot_select_row(msg):
|
|
|
+ print('about to select row')
|
|
|
+ msg = choose_row(0)
|
|
|
+ send_msg(msg)
|
|
|
+ return 0
|
|
|
+
|
|
|
+def get_action(jmsg):
|
|
|
+ try:
|
|
|
+ action = jmsg.get('action')
|
|
|
+ except:
|
|
|
+ print('unable to get action')
|
|
|
+ exit(8)
|
|
|
+ return action
|
|
|
+
|
|
|
+def parse_server_message(jmsg):
|
|
|
+ try:
|
|
|
+ typ = jmsg.get('type')
|
|
|
+ except:
|
|
|
+ print('unable to get type')
|
|
|
+ exit(8)
|
|
|
+ return typ
|
|
|
+
|
|
|
+def send_msg(msg):
|
|
|
+ jmsg = json.dumps(msg)
|
|
|
+ print('msg to send:', jmsg)
|
|
|
+ ssock.send(bytes(jmsg, 'utf-8'))
|
|
|
+
|
|
|
+def build_action(action, rest = {}):
|
|
|
+ ret = { 'action': action}
|
|
|
+ ret = ret | rest
|
|
|
+ return ret
|
|
|
+
|
|
|
+def choose_row(row_index):
|
|
|
+ return build_action('select_row', { 'i': row_index })
|
|
|
+
|
|
|
+def give_card(card):
|
|
|
+ return build_action('give_card', { 'card': card })
|
|
|
+
|
|
|
+def set_name(name):
|
|
|
+ return build_action('set_name', { 'name': name })
|
|
|
+
|
|
|
+if __name__ == '__main__':
|
|
|
+ try:
|
|
|
+ while True:
|
|
|
+ listen()
|
|
|
+ except KeyboardInterrupt:
|
|
|
+ print('interrupt - exiting')
|
|
|
+ #TODO: close
|
|
|
+ exit(9)
|