SHARE
TWEET

Untitled

a guest Apr 27th, 2018 44 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import socket
  2. import time
  3. from threading import Thread, Lock
  4. from copy import deepcopy
  5. import queue
  6. from flask import *
  7. import json
  8. import random
  9. from User import User
  10. from Room import Room
  11.  
  12. ip = "0.0.0.0"
  13. port = 8108
  14. cnt_listeners = 100
  15. cards_global = [i for i in range(11, 19)] + [i for i in range(21, 29)] \
  16.                + [i for i in range(31, 39)] + [i for i in range(41, 49)]
  17.  
  18.  
  19. class Gaming(Thread):
  20.     def __init__(self, room):
  21.         Thread.__init__(self)
  22.         self.room = room
  23.         self.position = 1
  24.         self.cards = deepcopy(cards_global)
  25.         self.extra_cards = []
  26.  
  27.     def get_cards(self, count):
  28.         cards = []
  29.         for i in range(count):
  30.             print("self.cards", self.cards)
  31.             x = random.randint(0, len(self.cards) - 1)
  32.             print("x", x)
  33.             item = self.cards[x]
  34.             del self.cards[x]
  35.             cards.append(item)
  36.             print("cards", cards)
  37.         cards.sort()
  38.         return cards
  39.  
  40.     def run(self):
  41.         while True:
  42.             if self.position == 1:
  43.                 players_cards = [self.get_cards(10) for i in range(3)]
  44.                 extra_cards = self.get_cards(2)
  45.                 self.extra_cards = extra_cards
  46.                 for i in range(3):
  47.                     login = self.room.users[i].login
  48.                     data = {
  49.                         "type": "cards",
  50.                         "cards": players_cards[i]
  51.                     }
  52.                     messages.put((json.dumps(data).encode('utf-8'), login_connections[login]))
  53.                 self.position = 2
  54.  
  55.  
  56. class SendingMessage(Thread):
  57.     def __init__(self):
  58.         Thread.__init__(self)
  59.  
  60.     def run(self):
  61.         while True:
  62.             time.sleep(1)
  63.             print("sm")
  64.             print(messages)
  65.             message, address = messages.get()
  66.             print(message, address)
  67.             address.send(message)
  68.  
  69.  
  70. class GettingMessage(Thread):
  71.     def __init__(self, connection):
  72.         Thread.__init__(self)
  73.         self.connection = connection
  74.         self.login = ''
  75.  
  76.     def run(self):
  77.         while True:
  78.             try:
  79.                 data = self.connection.recv(1024)
  80.                 print(data)
  81.                 data = data.decode('utf-8')
  82.                 data = json.loads(data)
  83.                 print(data)
  84.                 if data['type'] == 'connection':
  85.                     login_connections[data['login']] = self.connection
  86.                     print(login_connections)
  87.                     self.login = data['login']
  88.             except ConnectionResetError:
  89.                 connections.remove(self.connection)
  90.                 login_connections.pop(self.login)
  91.                 break
  92.             print(data)
  93.             if not data:
  94.                 print('disconnected')
  95.                 break
  96.  
  97.  
  98. class FindingConnection(Thread):
  99.     def __init__(self):
  100.         Thread.__init__(self)
  101.  
  102.     def run(self):
  103.         while True:
  104.             try:
  105.                 print("fd")
  106.                 connection, address = sock.accept()
  107.                 print(connection, address)
  108.                 with lock:
  109.                     connections.append(connection)
  110.                     gm = GettingMessage(connection)
  111.                     getting.append(gm)
  112.                     gm.start()
  113.             except socket.error:
  114.                 print('something wrong')
  115.  
  116.  
  117. app = Flask(__name__)
  118. login_connections = dict()
  119. rooms = []
  120. users = []
  121. sock = socket.socket()
  122. sock.bind((ip, port + 1))
  123. sock.listen(cnt_listeners)
  124. messages = queue.Queue()
  125. connections = []
  126. lock = Lock()
  127.  
  128. fc = FindingConnection()
  129. fc.start()
  130. sm = SendingMessage()
  131. sm.start()
  132. getting = []
  133. gaming = []
  134.  
  135.  
  136. @app.route('/registration', methods=["POST"])
  137. def registration():
  138.     login = request.values['login']
  139.     name = request.values['name']
  140.     password = request.values['password']
  141.     correct_login = True
  142.     for i in users:
  143.         if i.login == login:
  144.             correct_login = False
  145.     if not correct_login:
  146.         return json.dumps({
  147.             "status": False,
  148.             "error": "Такой логин уже используется"
  149.         })
  150.     users.append(User(login, name, password))
  151.     return json.dumps({
  152.         "status": True
  153.     })
  154.  
  155.  
  156. @app.route('/authorization', methods=['POST'])
  157. def authorization():
  158.     login = request.values['login']
  159.     password = request.values['password']
  160.     is_correct_data = False
  161.     data = ''
  162.     for i in users:
  163.         if i.login == login:
  164.             is_correct_data = True
  165.             if i.password != password:
  166.                 is_correct_data = False
  167.                 data = 'Некорректный пароль'
  168.             else:
  169.                 data = i.name
  170.  
  171.     if not is_correct_data and len(data) == 0:
  172.         data = 'Такого логина не существует'
  173.     if not is_correct_data:
  174.         return json.dumps({
  175.             "status": False,
  176.             "error": data
  177.         })
  178.     return json.dumps({
  179.         "status": True,
  180.         "name": data
  181.     })
  182.  
  183.  
  184. @app.route('/create_room', methods=["POST"])
  185. def create_room():
  186.     room_name = request.values['room_name']
  187.     password = request.values['password']
  188.     login = request.values['login']
  189.     user = None
  190.     for i in users:
  191.         if i.login == login:
  192.             user = i
  193.     work = True
  194.     room_id = 0
  195.     while work:
  196.         room_id = random.randint(1, 10000)
  197.         work = True in list(map(lambda x: x == room_id, [i.room_id for i in rooms]))
  198.     rooms.append(Room(user, room_name, password, room_id))
  199.     return json.dumps({
  200.         "status": True,
  201.         "room_id": room_id
  202.     })
  203.  
  204.  
  205. @app.route('/get_rooms_ids', methods=['GET'])
  206. def get_rooms_ids():
  207.     mas = []
  208.     for i in rooms:
  209.         mas.append(i.room_id)
  210.     return json.dumps({
  211.         "status": True,
  212.         "rooms_ids": mas
  213.     })
  214.  
  215.  
  216. @app.route('/has_password', methods=['GET'])
  217. def has_password():
  218.     room_id = request.values['room_id']
  219.     answer = False
  220.     for i in rooms:
  221.         print(i.room_id, room_id, i.room_id == room_id, int(i.room_id) == int(room_id))
  222.         if int(i.room_id) == int(room_id):
  223.             if len(i.password) > 0:
  224.                 answer = True
  225.     return json.dumps({
  226.         "status": True,
  227.         "has_password": answer
  228.     })
  229.  
  230.  
  231. @app.route('/connect_to_room', methods=['POST'])
  232. def connect_to_room():
  233.     login = request.values['login']
  234.     password = request.values['password']
  235.     room_id = request.values['room_id']
  236.     user = None
  237.     for i in users:
  238.         if i.login == login:
  239.             user = i
  240.     exist = False
  241.     error = ''
  242.     print(rooms)
  243.     for i in rooms:
  244.         print(i.room_id, room_id, int(i.room_id) == int(room_id))
  245.     print(",,,,,,,", room_id)
  246.     for i in rooms:
  247.         if int(i.room_id) == int(room_id):
  248.             if i.password != password:
  249.                 error = 'Неверный пароль'
  250.             elif len(i.users) == 3:
  251.                 error = 'Эта комната заполнена'
  252.             elif login in [local_user.login for local_user in i.users]:
  253.                 error = 'Вы уже состоите в этой комнате'
  254.             else:
  255.                 i.users.append(user)
  256.                 exist = True
  257.  
  258.     if not exist and len(error) == 0:
  259.         error = 'Неверный ID'
  260.     if not exist:
  261.         return json.dumps({
  262.             "status": False,
  263.             "error": error
  264.         })
  265.     return json.dumps({
  266.         "status": True
  267.     })
  268.  
  269.  
  270. @app.route('/get_rooms', methods=["GET"])
  271. def get_rooms():
  272.     return json.dumps({
  273.         "count": len(rooms),
  274.         "rooms": [i.to_json() for i in rooms]
  275.     })
  276.  
  277.  
  278. @app.route('/ready', methods=["GET"])
  279. def ready():
  280.     login = request.values['login']
  281.     for room in rooms:
  282.         print("here1")
  283.         if room.exist(login):
  284.             print("here2")
  285.             room.set_ready(login)
  286.             readies = room.get_readies()
  287.             for i in range(3):
  288.                 print("here3")
  289.                 if room.users[i].login in login_connections:
  290.                     print("here4")
  291.                     left_name = room.prev_name(room.users[i].login)
  292.                     right_name = room.next_name(room.users[i].login)
  293.                     left_login = room.prev_login(room.users[i].login)
  294.                     right_login = room.next_login(room.users[i].login)
  295.                     print(left_name, right_name, left_login, right_login)
  296.                     data = {
  297.                         "type": "connection_info",
  298.                         "left": {
  299.                             "name": left_name,
  300.                             "is_connect": left_login in readies
  301.                         },
  302.                         "right": {
  303.                             "name": right_name,
  304.                             "is_connect": right_login in readies
  305.                         }
  306.                     }
  307.                     messages.put((json.dumps(data).encode('utf-8'), login_connections[room.users[i].login]))
  308.             if len(readies) == 3:
  309.                 g = Gaming(room)
  310.                 gaming.append(g)
  311.                 g.start()
  312.             return json.dumps({
  313.                 "status": True
  314.             })
  315.  
  316.  
  317. @app.route('/room_by_login', methods=['GET'])
  318. def room_by_login():
  319.     login = request.values['login']
  320.     room_id = -1
  321.     for room in rooms:
  322.         for user in room.users:
  323.             if user.login == login:
  324.                 room_id = room.room_id
  325.     return json.dumps({
  326.         "status": True,
  327.         "room_id": room_id
  328.     })
  329.  
  330.  
  331. @app.route('/close', methods=['GET'])
  332. def close():
  333.     fc.join()
  334.     sm.join()
  335.     for i in getting:
  336.         i.join()
  337.     for i in gaming:
  338.         i.join()
  339.     for i in connections:
  340.         i.close()
  341.     sock.close()
  342.  
  343.  
  344. if __name__ == '__main__':
  345.     app.run(host=ip, port=port)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top