예제 #1
0
def listen(sock, client):
    while True:
        n.send(sock, "still here")
        newMessage = unserialize(n.receive(sock))
        newMessageTree = trees.MessageTree(newMessage)
        client.baseMessageTree.append(newMessageTree)
        client.messageTreeOut.put(newMessageTree)
예제 #2
0
def send_data(packet):
    networking.open_connection(args.host, int(args.port))
    networking.send(packet)
    response = networking.recv()
    networking.close_connection()

    if response['status'] != 'success':
        raise Exception(response['message'])

    return True
예제 #3
0
 def poke(self):
     question = DNS(rd=1, qd=DNSQR(qname='twitter.com'))
     if self.sniffer:
         packet = IP(dst=self.dst, src=self.src, id=self.ttl, ttl=self.ttl) / UDP(
             sport=self.sport) / question
         networking.send(packet)
         self.report['PACKETS'].append(('QUESTION', packet))
     else:
         self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
         self.udp_socket.settimeout(0)
         self.udp_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, self.ttl)
         self.udp_socket.bind((self.src, self.sport))
         self.udp_socket.sendto(str(question), (self.dst, self.dport))
예제 #4
0
 def send_syn(self):
     if self.sniffer:
         packet = IP(src=self.src, dst=self.dst, id=self.ttl * 10 + 1, ttl=self.ttl) / TCP(sport=self.sport,
             dport=self.dport, flags='S', seq=0)
         networking.send(packet)
         self.report['PACKETS'].append(('SYN', packet))
     else:
         self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         atexit.register(networking.immediately_close_tcp_socket_so_sport_can_be_reused, self.tcp_socket)
         self.tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         self.tcp_socket.settimeout(2)
         self.tcp_socket.bind((self.src, self.sport)) # if sport change the route going through might change
         self.tcp_socket.connect((self.dst, self.dport))
예제 #5
0
def add_item(item_name, category, subcategory, groups, type, image, user_tag):
    # Protocol 3
    # TODO may want to add a send all or send some function for own stuff after this call
    username = get_username()
    priv_key = get_priv_key()
    item = {
        "Current Owner": username,
        "Permanent Owner": username,
        "Category": category,
        "Subcategory": subcategory,
        "Name": item_name,
        "Groups": [],
        "Type Info": {},
        "Image": image,
        "User Tags": [],
        "Available": true,
    }
    groups = groups.split(" ")
    for i in groups:
        item["Groups"].append(i)
    item["Type Info"] = type
    user_tag = user_tag.split(" ")
    for j in user_tag:
        item["User Tags"].append(j)
    item_key = create_item_key(item)

    header = '@' + username + ':3'
    packet = json.dumps({item_key: item, "private": priv_key})
    message = send([header + ' ' + packet])
    print(message)
    print(header)
    # item_key is returned for testing purposes
    return item_key
예제 #6
0
def delete_friend_test(friend_name, username):
    # Protocol 103
    header = '@' + username + ':103'
    packet = json.dumps({"Target": friend_name})
    message = send([header + ' ' + packet])
    print(message)
    return 'I delete friends'
예제 #7
0
def send_message():
    # Protocol 7
    username = get_username()
    priv_key = get_priv_key()
    header = '@' + username + ':7'
    packet = json.dumps({"Messages": 1, "private": priv_key})
    message = send([header + ' ' + packet])
    message = message.split(":201 ")
    message = message[1]
    message = json.loads(message)
    f = open("./web/db/friends.json", "r")
    friends_list = f.read()
    friends_list = json.loads(friends_list)
    f.close()
    for i in message:
        item = i
        item = str(item)
        item = item.split("@")
        item = item[1]
        item = item.split(":102 ")
        key = item[0]
        info = item[1]
        info = json.loads(info)
        friend_key = info["Key"]
        friends_list[key] = friend_key
        if info["Step"] == 1:
            add_friend(key, 2)
    f = open("./web/db/friends.json", "w")
    friends_list = json.dumps(friends_list)
    f.write(friends_list)
    f.close()

    return 'I get you all of the messages from your "inbox"'
예제 #8
0
def send_pending_friends():
    # Protocol 10
    # TODO need to implement remove friend.
    username = get_username()
    priv_key = get_priv_key()
    header = '@' + username + ':10'
    packet = json.dumps({
        "Friends": 1,
        "private": priv_key,
        "Sender": username
    })
    message = send([header + ' ' + packet])
    print(message)
    message = message.split(":204 ")
    message = message[1]
    message = json.loads(message)
    f = open("./web/db/messages.json", "r")
    message_db = f.read()
    f.close()
    message_db = json.loads(message_db)
    message_db["pending friends"] = message
    message_db = json.dumps(message_db)
    f = open("./web/db/messages.json", "w")
    f.write(message_db)
    f.close()
예제 #9
0
def item_request(item_hash, friend_name):
    # Protocol 100
    username = get_username()
    pub_key = get_pub_key()
    # print(pub_key)
    # pub_key = "pub_key"
    header = '@' + username + ':100'

    borrower_info = {"Public": pub_key, "Username": username}
    f = open("./web/db/friends.json", "r")
    my_friends = f.read()
    f.close()
    my_friends = json.loads(my_friends)
    friend_key = my_friends[friend_name]
    # print(friend_key)
    # friend_key = "friend_key"
    lender_info = {"Public": friend_key, "Username": friend_name}

    packet = {}
    packet["Key"] = item_hash
    packet["Borrower"] = borrower_info
    packet["Lender"] = lender_info
    # print(packet)
    packet = json.dumps(packet)
    message = send([header + ' ' + packet])
    print(message)

    return 'I request items'
예제 #10
0
def clear_messagese():
    # Protocol 9
    username = get_username()
    priv_key = get_priv_key()
    header = '@' + username + ':9'
    packet = json.dumps({"Messages": -1, "private": priv_key})
    message = send([header + ' ' + packet])
    print(message)
예제 #11
0
def friend_request(friend_name):
    # Protocol 101
    username = get_username()
    header = '@' + username + ':101'
    packet = json.dumps({"Target": friend_name})
    message = send([header + ' ' + packet])
    print(message)
    return 'I request friends'
예제 #12
0
def delete_item(item_key):
    # Protocol 2
    username = get_username()
    priv_key = get_priv_key()
    header = '@' + username + ':2'
    packet = json.dumps({"Key": [item_key], "private": priv_key})
    message = send([header + ' ' + packet])
    print(message)
    return 'I delete items from your database'
예제 #13
0
def delete_user():
    # Protocol 1
    username = get_username()
    priv_key = get_priv_key()
    pub_key = get_pub_key()
    header = '@' + username + ':1'
    packet = json.dumps({"Delete": 1, "public": pub_key, "private": priv_key})
    message = send([header + ' ' + packet])
    print(message)
예제 #14
0
def new_user(username):
    # TODO don't let this run if there is already a user on the machine
    # TODO May need to add a nuke user if we run a second new_user
    # Protocol 0
    priv, pub = generate_keys()
    header = '@' + username + ':0'
    priv_key = priv.decode()
    pub_key = pub.decode()
    packet = json.dumps({"private": priv_key, "public": pub_key})
    message = send([header + ' ' + packet])
    print(message)
    if '16' not in message:
        # Save user name
        f = open("username.txt", "w")
        f.write(username)
        f.close()

        # Save private key
        f = open("private.txt", "w")
        f.write(priv_key)
        f.close()

        # Save public key
        f = open("public.txt", "w")
        f.write(pub_key)
        f.close()

        if not os.path.exists('./web/db'):
            os.mkdir('./web/db')

        # Create file to hold future friend keys
        f = open("./web/db/friends.json", "w")
        f.write('{}')
        f.close()

        # Create user item database
        f = open("./web/db/mine.json", "w")
        f.write('{}')
        f.close()

        # Create message database
        f = open("./web/db/messages.json", "w")
        f.write(
            '{"messages":[] ,"exchanges":[], "pending exchanges":[], "pending friends":[]}'
        )
        f.close()

        # Create friends item database
        f = open("./web/db/theirs.json", "w")
        f.write('{}')
        f.close()
        return True

    else:
        print('User name already in use')
        return False
예제 #15
0
def other_add_item(item_name, category, subcategory, user_name, priv_key):
    # Protocol 3
    item = {
        "Current Owner": user_name,
        "Permanent Owner": user_name,
        "Category": category,
        "Subcategory": subcategory,
        "Name": item_name,
        "Groups": [],
        "Type Info": {},
        "Image": 'https://source.unsplash.com/random',
        "User Tags": [],
    }
    item_key = create_item_key(item)
    header = '@' + user_name + ':3'
    packet = json.dumps({item_key: item, "private": priv_key})
    send([header + ' ' + packet])
    # item_key is returned for testing purposes
    return item_key
예제 #16
0
 def send_offending_payload(self):
     if 'DNS' == self.offending_payload_type:
         offending_payload = str(DNS(rd=1, qd=DNSQR(qname="dl.dropbox.com")))
         offending_payload = struct.pack("!H", len(offending_payload)) + offending_payload
     else:
         assert 'HTTP' == self.offending_payload_type
         offending_payload = 'GET / HTTP/1.1\r\nHost: www.facebook.com\r\n\r\n'
     if self.sniffer:
         packet = IP(src=self.src, dst=self.dst, id=self.ttl * 10 + 2, ttl=self.ttl) / TCP(sport=self.sport,
             dport=self.dport, flags='A', seq=1, ack=100) / Raw(offending_payload)
         networking.send(packet)
         self.report['PACKETS'].append(('OFFENDING_PAYLOAD', packet))
     else:
         self.tcp_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, self.ttl)
         try:
             self.tcp_socket.send(offending_payload)
         except socket.error as e:
             if ERROR_CONNECTION_RESET == e[0]:
                 self.report['RST_AFTER_SYN?'] = True
             else:
                 raise
예제 #17
0
def send_all():
    # Protocol 4
    # TODO detect when the received packet is not an id 200
    my_dir = './web/db/'
    username = get_username()
    pub_key = get_pub_key()
    header = '@' + username + ':4'
    packet = json.dumps({"public": pub_key, "Library": 1})
    message = send([header + ' ' + packet])
    # print(message)
    message = message.split(' ', 1)[1]
    f = open(os.path.join(my_dir, "mine.json"), "w")
    f.write(message)
    f.close()

    f = open(os.path.join(my_dir, "theirs.json"), "r")
    friend_library = f.read()
    f.close()
    friend_library = json.loads(friend_library)

    f = open("./web/db/friends.json", "r")
    my_friends = f.read()
    f.close()
    my_friends = json.loads(my_friends)

    for friend in my_friends:
        header = '@' + friend + ':4'
        packet = json.dumps({"public": my_friends[friend], "Library": 1})
        a_friend = send([header + ' ' + packet])
        a_friend = a_friend.split(' ', 1)[1]
        a_friend = json.loads(a_friend)
        for item in a_friend:
            friend_library[item] = a_friend[item]

    f = open(os.path.join(my_dir, "theirs.json"), "w")
    friend_library = json.dumps(friend_library)
    f.write(friend_library)
    f.close()

    return 'I get you all of your stuff and your friends'
예제 #18
0
 def poke(self):
     if self.sniffer:
         syn1 = IP(src=self.src, dst=self.dst, id=self.ttl * 10 + 1, ttl=self.ttl) / TCP(
             sport=self.sport, dport=self.dport, flags='S', seq=0)
         networking.send(syn1)
         self.report['PACKETS'].append(('PACKET_1', syn1))
         syn2 = IP(src=self.src, dst=self.dst, id=self.ttl * 10 + 2, ttl=self.ttl) / TCP(
             sport=self.sport, dport=self.dport, flags='S', seq=0)
         networking.send(syn2)
         self.report['PACKETS'].append(('PACKET_2', syn2))
         syn3 = IP(src=self.src, dst=self.dst, id=self.ttl * 10 + 3, ttl=self.ttl) / TCP(
             sport=self.sport, dport=self.dport, flags='S', seq=0)
         networking.send(syn3)
         self.report['PACKETS'].append(('PACKET_3', syn3))
     else:
         self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         atexit.register(networking.immediately_close_tcp_socket_so_sport_can_be_reused, self.tcp_socket)
         self.tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         self.tcp_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, self.ttl)
         self.tcp_socket.settimeout(2)
         self.tcp_socket.bind((self.src, self.sport)) # if sport change the route going through might change
         try:
             self.tcp_socket.connect((self.dst, self.dport))
             self.report['SYN_ACK?'] = True
         except socket.timeout:
             pass
예제 #19
0
def add_friend(friend_name, step):
    # Protocol 102
    username = get_username()
    pub_key = get_pub_key()
    header = '@' + username + ':102'
    packet = {}
    packet["Target"] = friend_name
    packet["Key"] = pub_key
    packet["Step"] = step
    packet = json.dumps(packet)
    message = send([header + ' ' + packet])
    print(message)
    return 'I accept friend requests'
예제 #20
0
def send_pending_exchanges():
    # Protocol 11
    username = get_username()
    priv_key = get_priv_key()
    header = '@' + username + ':11'
    packet = json.dumps({"Exchanges": 1, "private": priv_key})
    message = send([header + ' ' + packet])
    print("pending ex")
    message = message.split(":203 ")
    message = message[1]
    message = json.loads(message)
    f = open("./web/db/messages.json", "r")
    message_db = f.read()
    message_db = json.loads(message_db)
    f.close()
    message_db["pending exchanges"] = message
    f = open("./web/db/messages.json", "w")
    message_db = json.dumps(message_db)
    f.write(message_db)
    f.close()
예제 #21
0
def add_friend_test(friend_name, friend_key, step, username, pub_key):
    # Protocol 102
    # f = open('frends.json', 'r')
    # friends = f.read()
    # friends = json.loads(friends)
    # f.close()
    # friends[friend_name] = friend_key
    # f = open('frends.json', 'w')
    # friends = json.dumps(friends)
    # f.write(friends)
    # f.close()

    header = '@' + username + ':102'
    packet = {}
    packet["Target"] = friend_name
    packet["Key"] = pub_key
    packet["Step"] = step
    packet = json.dumps(packet)
    message = send([header + ' ' + packet])
    print(message)
    return 'I accept friend requests'
예제 #22
0
    def handle(self):

        # socketType refers to whether the socket is a speaker 
        # or listener from the _client's_ point of view.
        socketType = n.receive(self.request)

        if socketType == "speak":
            server.clientIDLock.acquire()
            clientID = server.clientIDCounter
            server.clientIDCounter += 1
            server.clientIDLock.release()

            # Tell the client its ID.
            n.send(self.request, serialize(clientID))

            print(  "[" + self.client_address[0] + " connected as client "
                  + str(clientID) + ".]")
            # Create a queue corresponding to this client.
            server.messages.append(Queue.Queue())

            while True:
                serializedMessage = n.receive(self.request)
                if serializedMessage:
                    message = unserialize(serializedMessage)
                    print (  "[" + message.__class__.__name__ 
                           + ": " + str(message) + "]")
                    assignID(message)
                    server.distributionQueue.put(message)
                    newMessageTree = trees.MessageTree(message)
                    server.baseMessageTree.append(newMessageTree)
                else:
                    break
                
            print "[Client " + str(clientID) + " quit.]"

        else:
            assert socketType[0:6] == "listen"
            clientID = int(unserialize(socketType[6:]))

            n.send(self.request, serialize(server.baseMessageTree))

            # While the client is still listening...
            while n.receive(self.request) == "still here":
                # ...send a message from the queue 
                # corresponding to this client.
                n.send(self.request, serialize(
                    server.messages[clientID].get()
                    ))
예제 #23
0
    def handle(self):

        # socketType refers to whether the socket is a speaker
        # or listener from the _client's_ point of view.
        socketType = n.receive(self.request)

        if socketType == "speak":
            server.clientIDLock.acquire()
            clientID = server.clientIDCounter
            server.clientIDCounter += 1
            server.clientIDLock.release()

            # Tell the client its ID.
            n.send(self.request, serialize(clientID))

            print("[" + self.client_address[0] + " connected as client " +
                  str(clientID) + ".]")
            # Create a queue corresponding to this client.
            server.messages.append(Queue.Queue())

            while True:
                serializedMessage = n.receive(self.request)
                if serializedMessage:
                    message = unserialize(serializedMessage)
                    print("[" + message.__class__.__name__ + ": " +
                          str(message) + "]")
                    assignID(message)
                    server.distributionQueue.put(message)
                    newMessageTree = trees.MessageTree(message)
                    server.baseMessageTree.append(newMessageTree)
                else:
                    break

            print "[Client " + str(clientID) + " quit.]"

        else:
            assert socketType[0:6] == "listen"
            clientID = int(unserialize(socketType[6:]))

            n.send(self.request, serialize(server.baseMessageTree))

            # While the client is still listening...
            while n.receive(self.request) == "still here":
                # ...send a message from the queue
                # corresponding to this client.
                n.send(self.request,
                       serialize(server.messages[clientID].get()))
예제 #24
0
def send_exchange():
    # Protocol 8
    username = get_username()
    priv_key = get_priv_key()
    header = '@' + username + ':8'
    packet = json.dumps({"Exchanges": 1, "private": priv_key})
    message = send([header + ' ' + packet])
    print("send exchanges")
    print(message)
    message = message.split(":201 ")
    message = message[1]
    message = json.loads(message)
    f = open("./web/db/messages.json", "r")
    message_db = f.read()
    message_db = json.loads(message_db)
    f.close()
    message_db["exchanges"] = message
    f = open("./web/db/messages.json", "w")
    message_db = json.dumps(message_db)
    f.write(message_db)
    f.close()
    return 'I get you all of your exchanges'
예제 #25
0
def change_owner(item_key, friend_name, in_date, out_date):
    # Protocol 6
    # permanent owner agrees to loan item, this protocol is sent
    username = get_username()
    priv_key = get_priv_key()
    f = open("./web/db/friends.json", "r")
    friend_list = f.read()
    f.close()
    friend_list = json.loads(friend_list)

    header = '@' + username + ':6'
    packet = {}
    packet['key'] = item_key
    packet['New Owner'] = friend_name
    packet['public'] = friend_list[friend_name]
    packet['private'] = priv_key
    packet['Schedule']['In'] = in_date
    packet['Schedule']['Out'] = out_date
    packet = json.dumps(packet)

    message = send([header + ' ' + packet])
    print(message)

    return 'I change current owner'
예제 #26
0
 def poke(self):
     question = DNS(rd=1, qd=DNSQR(qname='www.gov.cn'))
     if self.sniffer:
         syn1 = IP(src=self.src, dst=self.dst, id=self.ttl * 10 + 1, ttl=self.ttl) / UDP(
             sport=self.sport, dport=self.dport) / question
         networking.send(syn1)
         self.report['PACKETS'].append(('PACKET_1', syn1))
         syn2 = IP(src=self.src, dst=self.dst, id=self.ttl * 10 + 2, ttl=self.ttl) / UDP(
             sport=self.sport, dport=self.dport) / question
         networking.send(syn2)
         self.report['PACKETS'].append(('PACKET_2', syn2))
         syn3 = IP(src=self.src, dst=self.dst, id=self.ttl * 10 + 3, ttl=self.ttl) / UDP(
             sport=self.sport, dport=self.dport) / question
         networking.send(syn3)
         self.report['PACKETS'].append(('PACKET_3', syn3))
     else:
         self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
         self.udp_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, self.ttl)
         self.udp_socket.settimeout(0)
         self.udp_socket.bind((self.src, self.sport)) # if sport change the route going through might change
         self.udp_socket.sendto(str(question), (self.dst, self.dport))
예제 #27
0
    while True:
        s = f.readframes(sound_frames_per_cicle)
        snd.play(s)

        for effect in effects:
            effect.apply(cicle_number)
        for s in star.stars:
            s.draw(cicle_number)

        cicle_number = cicle_number + 1
        next_frame_time = start_time + (cicle_number /
                                        config_leds.frames_per_second)
        leds_frame_in_audio = cicle_number * sound_frames_per_cicle
        while f.tell() < leds_frame_in_audio:
            time.sleep(0.001)
        networking.send(cicle_number)
"""
else:		
	leds_f = open(fname, "w")
	kdf = None #key down frame
	sssf = None
	grsf = None
	e = None
	egr = []
		
	while True:

		s = f.readframes( sound_frames_per_cicle )
		snd.play( s )
		
		k1 = win32api.GetAsyncKeyState(win32con.VK_NUMPAD1) 
예제 #28
0
def speak(sock, client):
    while True:
        newMessage = client.messageIn.get()
        n.send(sock, serialize(newMessage))
예제 #29
0
def final_setup():
    global start, isHost
    start = random.randint(0, 1)
    net.send(str(start))
    print(net.reciever_ip)
    start = (start + isHost) % 2
예제 #30
0
def join_setup():
    global isHost
    isHost = 0
    net.set_target(input(messages[3]))
    net.send(join_request)
    start = (int(net.rec(1)) + isHost) % 2
예제 #31
0
def place_ships():
    global playerBoard, ships, isHost
    if isHost:
        new_ship("Aircraft Carrier", 5)
        net.send(str(1))

        print(messages[9])
        net.rec(1)
        new_ship("Battleship", 4)
        net.send(str(1))

        print(messages[9])
        net.rec(1)
        new_ship("Destroyer", 3)
        net.send(str(1))

        print(messages[9])
        net.rec(1)
        new_ship("Submarine", 3)
        net.send(str(1))

        print(messages[9])
        net.rec(1)
        new_ship("Patrol Boat", 2)
        net.send(str(1))

        print(messages[9])
        net.rec(1)

    else:
        print(messages[9])
        net.rec(1)
        new_ship("Aircraft Carrier", 5)
        net.send(str(1))

        print(messages[9])
        net.rec(1)
        new_ship("Battleship", 4)
        net.send(str(1))

        print(messages[9])
        net.rec(1)
        new_ship("Destroyer", 3)
        net.send(str(1))

        print(messages[9])
        net.rec(1)
        new_ship("Submarine", 3)
        net.send(str(1))

        print(messages[9])
        net.rec(1)
        new_ship("Patrol Boat", 2)
        net.send(str(1))
예제 #32
0
def main():
    username = input("enter username: "******"connected to server {IP}:{PORT}")

    # send username
    send(client_socket, {'username': username})

    server_data = []

    action = None
    placing = False
    active_game = False

    # main loop
    while True:
        # receive things
        try:
            while True:
                rec = receive(client_socket)
                if rec == False:
                    break
                server_data.append(rec)
        except IOError as e:
            if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
                print('reading error', str(e))
                continue
        except Exception as e:
            print('general error', str(e))

        # process server data
        for rec in server_data:
            if 'game_state' in rec.keys():
                game_state = rec['game_state']
                if not active_game:
                    screen, clock, tile_images, tile_lookup, king_images = start_game(
                        WINDOW_W, WINDOW_H)
                    active_game = True
            if 'message' in rec.keys():
                print(rec['message'])

        # all server data processed, clear the queue
        server_data = []

        # do game stuff
        if active_game:
            # check if closed
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            # check if game over
            if game_state['game_over']:
                active_game = False
                pygame.quit()
                action = None
                continue

            # actions
            if 'action' in game_state.keys() and (
                    game_state['action'][0] == "pick"
                    or game_state['action'][0] == 'place'):
                if game_state['action'][0] == "pick":
                    placing = False

                    # see if the mouse is pressed
                    if pygame.mouse.get_pressed()[0]:
                        if not mouse_was_down:
                            # see if you hit a tile todo dont hard code these, do along with better drawing
                            # get the options
                            pick_options = list(game_state['action'][1])
                            for n, tile in enumerate(
                                    game_state['tiles_to_pick']):
                                if tile[1] is None:
                                    pick_options.append(n)

                            mousePos = pygame.mouse.get_pos()

                            for n, tile in enumerate(
                                    game_state['tiles_to_pick']):
                                tile_x = 300 + 600 + 150
                                tile_y = 0 + 50 + n * 75
                                tile_h = 50
                                tile_w = 100
                                if in_rect(mousePos, tile_x, tile_y, tile_w,
                                           tile_h):
                                    if n in pick_options:  # if the tile has not been picked
                                        print(f"picked tile {n+1}")
                                        send(
                                            client_socket, {
                                                'action': game_state['action'],
                                                "resp": n
                                            })
                                        del game_state['action']
                                        break
                            mouse_was_down = True
                    else:
                        mouse_was_down = False

                elif game_state['action'][0] == "place":
                    for tile in game_state['you']['tiles']:
                        if game_state['action'][1] == tile[0]:
                            print('already have this tile!')

                    if not placing:
                        placing = True
                        placing_number = game_state['action'][1]
                        placing_direction = 'W'
                        dragging = False
                        placing_x = 550
                        placing_y = 700

                        if placing_number is None:
                            print(f"tile duplication glitch")
                            send(client_socket, {
                                'action': game_state['action'],
                                'resp': None
                            })
                            placing = False
                            del game_state['action']
                        elif not can_place(game_state['you']['tiles'],
                                           placing_number, tile_lookup):
                            print(f"impossible to place tile, discarding")
                            send(client_socket, {
                                'action': game_state['action'],
                                'resp': None
                            })
                            placing = False
                            del game_state['action']

                    if pygame.mouse.get_pressed()[0]:  # if mouse down
                        mousePos = pygame.mouse.get_pos()
                        if dragging:  # if currently dragging
                            placing_x = mousePos[0] - dragging_offset_x
                            placing_y = mousePos[1] - dragging_offset_y
                        else:
                            # see if we hit it
                            if placing_direction == 'W' or placing_direction == 'E':
                                w = 50 * 2
                                h = 50
                            else:
                                w = 50
                                h = 50 * 2
                            if in_rect(mousePos, placing_x, placing_y, w, h):
                                # setup dragging
                                dragging_offset_x = mousePos[0] - placing_x
                                dragging_offset_y = mousePos[1] - placing_y
                                dragging = True

                    else:
                        # check if we were dragging
                        if dragging:
                            dragging = False
                            # check if we can place it here
                            grid_coords = get_grid_coords(
                                placing_x + 25, placing_y + 25, 500, 500, 350,
                                150)
                            grid_x = grid_coords[0]
                            grid_y = grid_coords[1]
                            if placing_direction == 'W':
                                pass
                            elif placing_direction == 'N':
                                pass
                            elif placing_direction == 'E':
                                grid_x += 1
                            elif placing_direction == 'S':
                                grid_y += 1

                            if test_new_tile(game_state['you']['tiles'], [
                                    placing_number, grid_x, grid_y,
                                    placing_direction
                            ], tile_lookup):
                                game_state['you']['tiles'].append([
                                    placing_number, grid_x, grid_y,
                                    placing_direction
                                ])
                                send(
                                    client_socket, {
                                        'action':
                                        game_state['action'],
                                        'resp': [
                                            placing_number, grid_x, grid_y,
                                            placing_direction
                                        ]
                                    })
                                placing = False

                                # remove actoin
                                del game_state['action']

                        # check for rotation
                        if pygame.key.get_pressed()[pygame.K_a]:

                            if rotation is None:
                                rotation = 'l'
                            else:
                                rotation = 'held'
                        elif pygame.key.get_pressed()[pygame.K_d]:
                            if rotation is None:
                                rotation = 'r'
                            else:
                                rotation = 'held'
                        elif pygame.key.get_pressed()[pygame.K_LEFT]:
                            if rotation is None:
                                rotation = 'l'
                            else:
                                rotation = 'held'
                        elif pygame.key.get_pressed()[pygame.K_RIGHT]:
                            if rotation is None:
                                rotation = 'r'
                            else:
                                rotation = 'held'
                        else:
                            rotation = None

                        if rotation is not None and rotation != 'held':  # if there is a key down
                            if rotation == 'l':
                                if placing_direction == 'N':
                                    placing_direction = 'W'
                                elif placing_direction == 'W':
                                    placing_direction = 'S'
                                elif placing_direction == 'S':
                                    placing_direction = 'E'
                                elif placing_direction == 'E':
                                    placing_direction = 'N'
                            elif rotation == 'r':
                                if placing_direction == 'N':
                                    placing_direction = 'E'
                                elif placing_direction == 'E':
                                    placing_direction = 'S'
                                elif placing_direction == 'S':
                                    placing_direction = 'W'
                                elif placing_direction == 'W':
                                    placing_direction = 'N'

                else:
                    placing = False

            # draw
            screen.fill((255, 255, 255))

            # draw your board
            draw_board(screen, 500, 500, 350, 150, game_state['you']['tiles'],
                       tile_images, 2, game_state['you']['color'], king_images)

            # draw other boards
            for n, other in enumerate(game_state['others']):
                draw_board(screen, 200, 200, 50, 50 + 250 * n, other['tiles'],
                           tile_images, 1, other['color'], king_images)

            # draw tiles
            # to pick
            for n, tile in enumerate(game_state['tiles_to_pick']):
                if tile[0] is not None:
                    draw_tile(screen, tile[0], 300 + 600 + 150,
                              0 + 50 + n * 75, 50, 'W', tile_images)
                if tile[1] is not None:
                    draw_king(screen, tile[1], 300 + 600 + 50, 0 + 50 + n * 75,
                              50, king_images)
            # picked
            for n, tile in enumerate(game_state['tiles_picked']):
                if tile[0] is not None:
                    draw_tile(screen, tile[0], 300 + 600 + 150,
                              400 + 50 + n * 75, 50, 'W', tile_images)
                if tile[1] is not None:
                    draw_king(screen, tile[1], 300 + 600 + 50,
                              400 + 50 + n * 75, 50, king_images)

            # draw placing tile
            if placing:
                draw_tile(screen, placing_number, placing_x, placing_y, 50,
                          placing_direction, tile_images)

            # update display
            pygame.display.update()

            # limit framerate
            clock.tick(FRAMERATE)
예제 #33
0
def delete_other_user(user_name, priv_key, pub_key):
    header = '@' + user_name + ':1'
    packet = json.dumps({"Delete": 1, "public": pub_key, "private": priv_key})
    send([header + ' ' + packet])
예제 #34
0
    # do the game
    if not active:  # if there is not a game currently
        if len(clients.keys()) >= MIN_PLAYERS:
            if len(clients.keys()) >= 4:
                player_sockets = list(clients.keys())[:4]
            else:
                if game_countdown == -1:  # start countdown if it hasnt been already
                    usernames = []
                    for client_socket in clients.keys():
                        usernames.append(clients[client_socket])

                    for client_socket in clients.keys():
                        send(
                            client_socket, {
                                'message':
                                f"starting {COUNTDOWN_TIME}s countdown for game with {usernames}"
                            })

                    print(
                        f"starting {COUNTDOWN_TIME}s countdown for game with {usernames}"
                    )
                    game_countdown = time.time()

                    continue

                elif time.time(
                ) - game_countdown <= COUNTDOWN_TIME:  # continue if still waiting
                    continue

                player_sockets = list(clients.keys())
예제 #35
0
def speak(sock, client):
    while True:
        newMessage = client.messageIn.get()
        n.send(sock, serialize(newMessage))