Ejemplo n.º 1
0
def game_handler(connection:server.GameConnection,s:'Game State'):
    '''Takes the game state and game connection as arguments and calls the game_play function
       and the board_display function for each players move and returns the winning player
    '''
    print('WELCOME TO CONNECT 4 GAME')
    
    username=read_username()
    server.send(connection,'I32CFSP_HELLO '+username)
    print(server.read_line(connection))
    
    server.send(connection,'AI_GAME ')
    print(server.read_line(connection))
   
    while True:
        if connectfour.winning_player(s)==connectfour.NONE:
            if s.turn==connectfour.RED:
                print('Player ',username)
                s=game_play(s,connection)
                common_file.board_display(s)
            elif s.turn==connectfour.YELLOW:
                print('Player AI')
                s=common_file.game_move(s,server.read(connection))                  
                if s==None:
                    print('Invalid move by Server')
                    server.close(connection)
                    return None
                common_file.board_display(s)                             
        elif connectfour.winning_player(s)==connectfour.RED:
            return username
        elif connectfour.winning_player(s)==connectfour.YELLOW:
            return 'AI'
Ejemplo n.º 2
0
def send_main(args):
    conf = {}
    if args.one:
        conf['ONE'] = True
    if args.password:
        conf['PASSWORD'] = args.password
    server.send(args.file, conf)
Ejemplo n.º 3
0
def msgoab(msg):
    global IRC
    #print msg
    if msg == "PING :tmi.twitch.tv":
        IRC.send("PONG :tmi.twitch.tv\n")
        #print 'ping call'
    elif msg == ":tmi.twitch.tv PONG tmi.twitch.tv :103":
        print 'ping recall'
    else:
        global inroom
        if inroom:
            ss = msg.split(':')[1]
            user = ss.split('!')[0]
            st = msg.split(':')
            text = st[2]
            if len(st) > 3:
                for tm in range(3, len(st)):
                    text += ":" + st[tm]
            global pre_user
            global Nick
            if user == pre_room:
                server.send(
                    "2<img src='setting/owner.png'/><span class='text3'>" +
                    Nick.change(user) + ": " +
                    emo.change(text).encode('utf-8').strip() + "</span>")
            elif Follow.check(user):
                server.send(
                    "2<img src='setting/follow.png'/><span class='text3'>" +
                    Nick.change(user) + ": " +
                    emo.change(text).encode('utf-8').strip() + "</span>")
            else:
                server.send("2" + Nick.change(user) + ": " + text)
            #response for text

            cos.cos_input(text, user, Nick.change(user))

            #server.send(msg)
        else:
            try:
                if msg.split(':')[2] == "End of /NAMES list":
                    inroom = True
                    server.send("1JOIN")
                elif msg.split(':')[2] == "Error logging in":
                    server.send('0Loggin error, please check your password.')
            except:
                pass
Ejemplo n.º 4
0
    def handlePhrasing(self, data):
        speech = data["phrases"][0]["speech"]
        print("updating buffers with", speech)

        cmd_index, remove = self.command_manager.parse_command(speech)
        if cmd_index is not None and remove is not None:
            if remove is True and cmd_index < len(self.stage):
                self.stage.pop(cmd_index)
            elif remove is False and cmd_index < len(self.phrases):
                self.stage.insert(0, self.phrases.pop(cmd_index))
                if len(self.stage) > self.stage_len:
                    self.stage = self.stage[:self.stage_len]
        else:
            self.phrases.insert(0, speech)
            if len(self.phrases) > self.phrases_len:
                self.phrases = self.phrases[:self.stage_len]
        server.send(self.phrases, self.stage)
Ejemplo n.º 5
0
def show_webcam(mirror=False):
    count = 0
    cam = cv2.VideoCapture(0)
    while True:
        ret_val, img = cam.read()
        if mirror: 
            img = cv2.flip(img, 1)
        cv2.imshow('my webcam', img)
        img = cv2.resize(img, (64, 64)).astype(np.float32)
        img = np.expand_dims(img, axis=0)
        res = model.predict(img)
        res = res[0]
        count += 1
        classes = ["Garbage","Fire", "Others"]
        st = classes[res.argmax()]
        if st != "Others" and count % 180 == 0:
            send(st)
        if(cv2.waitKey(1)==27):
            break
    cv2.destroyAllWindows()
Ejemplo n.º 6
0
def msgoab(msg):
  global IRC
  #print msg
  if msg == "PING :tmi.twitch.tv":
    IRC.send("PONG :tmi.twitch.tv\n")
    #print 'ping call'
  elif msg == ":tmi.twitch.tv PONG tmi.twitch.tv :103":
    print 'ping recall'
  else:
    global inroom
    if inroom:
      ss = msg.split(':')[1]
      user = ss.split('!')[0]
      st = msg.split(':')
      text = st[2]
      if len(st) > 3:
        for tm in range(3,len(st)):
          text += ":" + st[tm]
      global pre_user
      global Nick
      if user == pre_room:
      	server.send("2<img src='setting/owner.png'/><span class='text3'>" + Nick.change(user) + ": " + emo.change(text).encode('utf-8').strip() + "</span>")
      elif Follow.check(user):
        server.send("2<img src='setting/follow.png'/><span class='text3'>" + Nick.change(user) + ": " + emo.change(text).encode('utf-8').strip() + "</span>")
      else:
        server.send("2" + Nick.change(user) + ": " + text)
      #response for text

      cos.cos_input(text,user,Nick.change(user))

      #server.send(msg)
    else:
      try:
        if msg.split(':')[2] == "End of /NAMES list":
          inroom = True
          server.send("1JOIN")
        elif msg.split(':')[2] == "Error logging in":
          server.send('0Loggin error, please check your password.')
      except:
        pass
Ejemplo n.º 7
0
def main():
    if not os.path.isfile("data/"):
        os.mkdir("data/")

    port = FindSerial.serial_ports()[0]

    ser = serial.Serial(port=port, baudrate=115200)

    filename = "data/accel_data_running.csv"

    reader = DataReader(filename=filename, serial=ser)
    reader_thread = threading.Thread(target=reader.run)

    sg.theme('DarkGrey4')
    layout = [[sg.Text('Press start to begin data recording and press stop')],
              [sg.Text('to stop recording and send data to server.')],
              [sg.Text('Username'), sg.InputText()],
              [sg.Text('Password'),
               sg.InputText(password_char='*')],
              [sg.Button('Start'), sg.Button('Stop')]]
    window = sg.Window('Strain Sense', layout)

    if '-local' in sys.argv:
        req_url = r'http://localhost:32321/wearables/dashboard'
    else:
        req_url = r'https://ethanvogelsang.com/wearables/dashboard'

    while True:
        event, values = window.read()
        if event == sg.WIN_CLOSED:
            break
        if event == 'Start':
            reader_thread.start()
        if event == 'Stop':
            reader.stop()
            reader_thread.join()
            usr = str(values[0])
            pwd = str(values[1])
            server.send(usr, pwd, filename, req_url)
            break
Ejemplo n.º 8
0
def game_play(s:'GameState',connection:server.GameConnection):
    '''Takes  game state and GameConnection as arguments asks the user to enter their
      move  and returns the game state after the user has made their move and sends the
      move to the server
    '''
    while True:
        User_input=input('Enter (D/P) to drop or pop: ')
        if User_input.strip().upper()=='D':
            move='DROP'
        elif User_input.strip().upper()=='P':
            move='POP'
        else :
            move=' '
        column_number=input('Please Enter Column Number: ')
        column_number=column_number.strip()

        User_message=move+' '+column_number
        g=common_file.game_move(s,User_message)
        if g==None:
            print('Invalid Move')
        else:
            server.send(connection,User_message)
            return g
Ejemplo n.º 9
0
def irc_connect(threadName):
    global Nick, IRC
    global Follow
    global pre_user, pre_room, pre_pass
    global cos, emo
    cos = cosRes.cosRes(IRC, pre_room, server)
    emo = emoticons.emotion()

    cos.load()
    Nick.load()
    Follow.get_follow()
    emo.load()
    while server.wss == []:
        time.sleep(1)

    server.send('1Connecting Twitch server')

    while not IRC.connect():
        time.sleep(5)

    server.send('1Server Connected')
    IRC.send('PASS ' + pre_pass + '\n')
    IRC.send('NICK ' + pre_user + '\n')
    IRC.send('JOIN #' + pre_room + '\n')
    tmp = ""
    while IRC.timed:
        s = IRC.recv()
        tmp += s

        #print tmp
        if tmp.find('\n') != -1:

            ss = tmp.split('\n')
            for ns in range(len(ss) - 1):
                msgoab(ss[ns][0:len(ss[ns]) - 1])
            tmp = ss[len(ss) - 1]
Ejemplo n.º 10
0
def irc_connect(threadName):
  global Nick,IRC
  global Follow
  global pre_user,pre_room,pre_pass
  global cos,emo
  cos = cosRes.cosRes(IRC,pre_room,server)
  emo = emoticons.emotion()

  cos.load()
  Nick.load()
  Follow.get_follow()
  emo.load()
  while server.wss == []:
  	time.sleep(1)

  server.send('1Connecting Twitch server')

  while not IRC.connect():
  	time.sleep(5)

  server.send('1Server Connected')
  IRC.send('PASS ' + pre_pass + '\n')
  IRC.send('NICK ' + pre_user + '\n')
  IRC.send('JOIN #'+ pre_room + '\n')
  tmp = ""
  while IRC.timed:
    s = IRC.recv()
    tmp += s

    #print tmp
    if tmp.find('\n') != -1:
      
      ss = tmp.split('\n')
      for ns in range(len(ss)-1):
        msgoab(ss[ns][0:len(ss[ns])-1])
      tmp = ss[len(ss)-1]
Ejemplo n.º 11
0
    u_s = cv2.getTrackbarPos("U - S", "Trackbars")
    u_v = cv2.getTrackbarPos("U - V", "Trackbars")

    lower_blue = np.array([l_h, l_s, l_v])
    upper_blue = np.array([u_h, u_s, u_v])
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    result = cv2.bitwise_and(frame, frame, mask=mask)
    edged = cv2.Canny(mask, 30, 200)
    contours, hierarchy = cv2.findContours(edged, cv2.RETR_TREE,
                                           cv2.CHAIN_APPROX_SIMPLE)

    for contour in contours:
        cv2.drawContours(frame, contour, -1, (0, 255, 0), 3)
        x, y, w, h = cv2.boundingRect(contour)
        cv2.rectangle(mask, (x, y), (x + w, y + h), (0, 255, 0), 2)
        center = (x, y)
        cx = center[0]
        cy = center[1]
        server.send(message='position', data={'x': cx, 'y': cy})

    cv2.imshow("frame", frame)
    cv2.imshow("mask", mask)
    cv2.imshow("result", result)

    key = cv2.waitKey(1)
    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()
Ejemplo n.º 12
0
                    line_thickness=8)

                ###################
                # funktionen aufrufen die erkannte labels an den server sendet
                ##

                # nur objekte erkennen die mehr als 50% treffergenauigkeit aufweisen
                final_score = np.squeeze(output_dict['detection_scores'])
                count = 0
                for i in range(100):
                    if output_dict['detection_scores'] is None or final_score[i] > 0.5:
                        count = count + 1

                print('number of detected obj: ', count)
                counted_objects = int(count)
                server.send(message='objects', data={'x': counted_objects})

                # schleife um erkannte labels ausgeben
                printcount = 0

                for i in output_dict['detection_classes']:
                    printcount = printcount + 1

                    if count > 0:
                        # neue objekte des aktuellen frames hinzufügen
                        current_object_names.append(category_index[i]['name'])

                        # sortieren
                        current_object_names = sorted(current_object_names, key=str.lower)

                    if count_inference == FRAMES:
Ejemplo n.º 13
0
 while True:
     try:
         message = receive(client_socket)
     except (ConnectionAbortedError, ConnectionResetError):
         exit_client(1, client_socket)
     if message['action'] == 'move':
         answer = input('Will you hand over your partner?. Enter y or n: ')
         while type(answer) != str:
             try:
                 answer = str(answer)
                 if answer != 'y' or answer !='n':
                     raise ValueError()
             except ValueError:
                 answer = input('Invalid input. Try again: ')
         send(client_socket, {
             'answer': answer
         })
         try:
             message = receive(client_socket)
         except (ConnectionAbortedError, ConnectionResetError):
             exit_client(1, client_socket)
         print(f'Your answer: {message["answer"]}. Wait for your turn')
     elif message['action'] == 'end':
         if message['type'] == 'yy':
             print('The game is over! You will go to jail for 2 years')
         elif message['type'] == 'nn':
             print('The game is over! You will go to jail for six months')
         elif message['type'] == 'yn' and answer == 'y':
             print('The game is over! You will be released')
         elif message['type'] == 'yn' and answer == 'n':
             print('The game is over! You will go to jail for 10 years')
Ejemplo n.º 14
0
try:
    while True:
        print("Waiting for a connection...")
        connection = server.acceptConnections(serv)
        
        try:
            print()
            
            while True:
                get = server.receive(connection)
                result = ""
                if get != "":
                    print("> Received             '" + get + "'")
                if get[:4] == "close":
                    print("Client attempted to close server")
                    server.send(connection, "Use: close [password]", False)
                if get == "close" + str(pwd):
                    break
                    exit()
                if get:
                    if get == "SETCALLMETHOD<C++>":
                        if getCodeDisallowement():
                            print("> Denied switch to C++ callmethod")
                            result = "DENIED"
                        else:
                            print("> Set callmethod to C++")
                            callmethod = "c++"
                            result = "OK"
                    elif get == "SETCALLMETHOD<PYTHON>":
                        print("> Set callmethod to native Python")
                        callmethod = "python"
Ejemplo n.º 15
0
        if area > 3000:

            #je kleiner die 0.01 desto genauer der rand
            approx = cv2.approxPolyDP(cnt, 0.01 * cv2.arcLength(cnt, True),
                                      True)
            cv2.drawContours(frame, [approx], 0, (0), 5)
            x = approx.ravel()[0]
            y = approx.ravel()[1]

            form = "Keine Form"

            if 20 < len(approx) < 24:
                cv2.putText(frame, "Elefant", (x, y), font, 1, (0))
                form = "Elefant"

            server.send(message='position', data={'x': form, 'y': form})

    #Rote Formen erkennen
    for cnt in contours_red:
        area = cv2.contourArea(cnt)

        #if bedingung sorgt dafür das nur große sachen erkannt werden
        if area > 3000:

            #je kleiner die 0.01 desto genauer der rand
            approx = cv2.approxPolyDP(cnt, 0.01 * cv2.arcLength(cnt, True),
                                      True)
            cv2.drawContours(frame, [approx], 0, (0), 5)
            x = approx.ravel()[0]
            y = approx.ravel()[1]
Ejemplo n.º 16
0
    try:
        pixels = decompress(recvall(sock, size))
    except:
        pass

    img = pygame.image.fromstring(pixels, (width, height), 'RGB')
    screen.blit(img, (0, 0))
    pygame.display.flip()
    #print("Mouse location" + str(pygame.mouse.get_pos()))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                print("Mouse Left Down")
                server.send(struct.pack('B', 0))
            elif event.button == 3:
                print("Mouse right Down" + str(pygame.mouse.get_pos()))
                server.send(struct.pack('B', 1))
        elif event.type == pygame.MOUSEMOTION:
            loc = pygame.mouse.get_pos()
            print("Mouse Movement" + str(pygame.mouse.get_pos()))
            server.send(struct.pack('Bii', 2, loc[0], loc[1]))
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                print("a")
                server.send(struct.pack('B', 4))
            elif event.key == pygame.K_b:
                print("b")
                server.send(struct.pack('B', 5))
            elif event.key == pygame.K_c:
Ejemplo n.º 17
0
        'chicken.manchuria': 189,
        'egg65': 189,
        'chilli.chicken': 189,
        'chicken.spring.rolls': 189,
        'chillifish': 189,
        'chilli.chicken.dry': 189,
        'aloo65': 189,
        'veg.manchuria': 189,
        'veg65': 189,
        'gobi65': 189,
        'veg.spring.rolls': 189,
        'paneer65': 189,
        'chilli.paneer.dry': 189
    }
    for i in lis:
        print("cost of ", i, "is ", result1[i])
        cost += result1[i]
    print(cost)
    print("to confirm press '4' else to remove items press '2' ")
    bill()


lis = []
menu()
name = input("Enter your name : ")
fp = open('order.txt', 'w')
for i in lis:
    fp.write(i + "," + name + "\n")
fp.close()
server.send('order.txt')
Ejemplo n.º 18
0
def p_send(p):
    """send : SEND"""
    server.send(conn)
    client.receive(client_socket)
Ejemplo n.º 19
0
    # This method checks if the markers coordinates are on a black key
    if (cy < blackBot and cy > blackTop):
        for i in range(0, 20, 2):
            black = blackArray[i]
            v = blackArray[i + 1]
            if (cx < v and cx > black):
                return (i // 2) + 14
    return key


while cap.isOpened():
    # This is the Main loop of the programm. This first part is the countdown, during which the markers are scanned.
    ret, frame = cap.read()
    if (countdown >= -12):
        if countdown >= 0 and (not oneCalibrated):
            server.send(message='countdown1', data={'countdown': countdown})
        if (countdown == 0):
            setFirstMarker(7, 7, frame)
        if countdown >= -11 and countdown < 0:
            server.send(message='countdown2',
                        data={'countdown': countdown + 11})
        if countdown == -12:
            setSecondMarker(7, 7, frame)

            time.sleep(3)
            server.send(message='color1', data={'R': r1, 'G': g1, 'B': b1})
            server.send(message='color2', data={'R': r2, 'G': g2, 'B': b2})

        # Potential marker colors are read from the current camera frame.
        b = (int)(frame[(int)(frameWidth / 2), (int)(frameHeight / 2), 0])
        g = (int)(frame[(int)(frameWidth / 2), (int)(frameHeight / 2), 1])
Ejemplo n.º 20
0
import multiprocessing
from multiprocessing import Pool
import time
import sys

sys.path.append('./')

x = int(input("1 for server  , 2 for client "))
host = input("input the host of the server")

port = int(input("input the port"))

if (x == 1):
    val = int(input("input the interval"))
    server.conn(host, port)
    server.send(str(val))
    val = val / 2

    # multiprocessing
    np = multiprocessing.cpu_count()
    print('You have {0:1d} CPUs'.format(np))
    part_count = [int(val / np) for i in range(np)]
    pool = Pool(processes=np)
    cp = pool.map(getpoint, part_count)
    cp = sum(cp)
    print("locally computed", cp)
    server.send(str(cp))

else:
    val = int(client.recv(host, port).split('.')[0])
    print("interval received", val)