コード例 #1
0
ファイル: Game.py プロジェクト: rdevis/bomber-berry
def main():
    pygame.init()
    # creamos la ventana y le indicamos un titulo:
    screen = pygame.display.set_mode((320, 240))
    pygame.display.set_caption("BomberPi")
 
    while True:
        game = Game()
        whoWin, timeleft = game.startGame(screen)
        date_end = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
        if not whoWin is None:
            message = "Gano el jugador %s en la fecha %s a falta de %s segundos" % (whoWin, date_end, timeleft)
        else:
            message = "En la fecha %s hubo un empate de los dos jugadores" % (date_end)
        t = threading.Thread(target=Tweet.sendTweet, args=(message, ))
        t.start(); t.join

        #End of game
        scoreBadge=pygame.image.load("scoreframe.png")
        scoreBadge.convert_alpha()
        screen.blit(scoreBadge,(10,10))
        scoreFont=pygame.font.Font(None,52)
        scoreFont2=pygame.font.Font(None,22)
        if whoWin is None:
            statusText=scoreFont.render('Draw game',True,(255,255,255))
            screen.blit(statusText,(66,90))
        else:
            statusText=scoreFont.render('Player '+str(whoWin)+' wins',True,(255,255,255))
            screen.blit(statusText,(44,90))
        statusText2=scoreFont2.render('Press r to restart',True,(255,255,255))
        screen.blit(statusText2,(104,130))
        pygame.display.flip()
        ## Wait for the player to restart
        restart = False
        while not restart:
	    if SERIAL:
        	PlayController = Serial.keysPS()
	    else:
                PlayController = {"PS1_CUADRADO":False, "PS1_TRIANGULO":False, "PS1_CIRCULO":False, "PS1_EQUIS":False, "PS1_ARRIBA":False, "PS1_ABAJO":False, "PS1_IZQUIERDA":False, "PS1_DERECHA":False, "PS1_L1":False, "PS1_R1":False, "PS1_L2":False, "PS1_R2":False, "PS1_L3":False, "PS1_R3":False, "PS1_START":False, "PS1_SELECT":False, "PS1_JLARRIBA":False, "PS1_JLABAJO":False, "PS1_JLIZQUIERDA":False, "PS1_JLDERECHA":False, "PS1_JRARRIBA":False, "PS1_JRABAJO":False, "PS1_JRIZQUIERDA":False, "PS1_JRDERECHA":False, "PS2_CUADRADO":False, "PS2_TRIANGULO":False, "PS2_CIRCULO":False, "PS2_EQUIS":False, "PS2_ARRIBA":False, "PS2_ABAJO":False, "PS2_IZQUIERDA":False, "PS2_DERECHA":False, "PS2_L1":False, "PS2_R1":False, "PS2_L2":False, "PS2_R2":False, "PS2_L3":False, "PS2_R3":False, "PS2_START":False, "PS2_SELECT":False, "PS2_JLARRIBA":False, "PS2_JLABAJO":False, "PS2_JLIZQUIERDA":False, "PS2_JLDERECHA":False, "PS2_JRARRIBA":False, "PS2_JRABAJO":False, "PS2_JRIZQUIERDA":False, "PS2_JRDERECHA":False}

            keys = pygame.key.get_pressed()
            if keys[K_ESCAPE]:
                sys.exit(0)
            if keys[K_r] or PlayController["PS1_START"] or PlayController["PS2_START"]:
                restart = True
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
コード例 #2
0
def budao():
    while True:
        while True:
            time.sleep(1)
            Flag, Position = Base_func.match_template('Battlefinish_sign')
            if Flag:
                break
            Flag, Position = Base_func.match_template('Attack_button')
            if Flag:
                break
        Flag, Position = Base_func.match_template('Attack_button')
        if Flag:
            Serial.touch(960, 510)  #点击attack按钮
            time.sleep(1)
            Card_index = random.sample(range(0, 4), 3)  #随机三张牌
            Serial.touch(115 + (Card_index[0]) * 215, 430)
            Serial.touch(115 + (Card_index[1]) * 215, 430)
            Serial.touch(115 + (Card_index[2]) * 215, 430)
            print(' Card has pressed')
        else:
            break
コード例 #3
0
def serial(posisi):
    ser = Serial('/dev/ttyUSB0',)
    ser.baudrate = 115200
    
    while 1:
        if (posisi == '1'):
            ser.write(str(1).encode())
            print('kiri, 101')
            time.sleep(0.1)
            ser.write(str(0).encode())
            time.sleep(0.1)
            ser.write(str(1).encode())
            
        elif (posisi == '2'):
            print('kiri, nyala 1010 x')
            ser.write(str(1).encode())
            time.sleep(0.1)
            ser.write(str(0).encode())
            ser.write(str(1).encode())
            time.sleep(0.1)
            ser.write(str(0).encode())
            
        elif (posisi == '3'):
            ser.write(str(1).encode())
            time.sleep(0.1)
            ser.write(str(0).encode())
            time.sleep(0.1)
            ser.write(str(1).encode())
            time.sleep(0.1)
            ser.write(str(0).encode())
            time.sleep(0.1)
            ser.write(str(1).encode())
            time.sleep(0.1)
            ser.write(str(0).encode())
            
        
    print(ser.readline())
    return 0
コード例 #4
0
def enter_battle():    
    Current_state.HasBackToMenu()
        #确认已经返回菜单界面,或检测到连续出击按键
    Flag,Position = Base_func.match_template('reenter_battle') 
    if Flag:
        Serial.touch(705,475)       
        print(' ')
        print(' Reenter battle success')    
        return
    
    Flag,Position = Base_func.match_template('LastOrder_sign') 
    if Flag:
        Serial.touch(Position[0]+230,Position[1]+50)       
        print(' ')
        print(' Enter battle success')
    else:
        Serial.touch(791,155)
        print(' ')
        print(' Enter battle by clicking the default position')
コード例 #5
0
"Class that detects a blue led on the screen and sends it coordinates "
"over USB-port"

import cv2
import numpy as np
import Calibrater
import Serial
assert float(cv2.__version__.rsplit('.', 1)[0]) >= 3

ser = Serial.Serial('COM9', 115200)  #initiate the serial communication
img_size = (400, 400)
img_draw = np.ones(img_size) * 255
oldCoordinateX = 0
oldCoordinateY = 0

"Returns the clicked pixel on the image"


def find_pixels(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONUP:
        print("X:", x, "Y:", y)
        global xCoordinate
        global yCoordinate
        xCoordinate = x
        yCoordinate = y


"Correction for the height of camera, "


def heighCorrection2(x, y, ledheight, cameraheight, xStart, ystart, offset):
コード例 #6
0
def find_friend():
    time.sleep(1)
    Flag, Position = Base_func.match_template(
        'F:/FGO_Project/Template/Caster_sign.jpg')
    while bool(1 - Flag):
        time.sleep(1)
        Flag, Position = Base_func.match_template(
            'F:/FGO_Project/Template/Caster_sign.jpg')
    #检测到滚动条说明好友已经刷出
    Flag, Position = Base_func.match_template(
        'F:/FGO_Project/Template/friend_sign.jpg')
    while bool(1 - Flag):
        time.sleep(1)
        Flag, Position = Base_func.match_template(
            'F:/FGO_Project/Template/friend_sign.jpg')

    Flag, Position = Base_func.match_template(
        'F:/FGO_Project/Template/CBA_skill_level.jpg')
    time_limit_flag = 1
    #找310CBA直到找到为止
    while bool(1 - Flag):
        print(' didn\'t find CBA, retry. attempt{}'.format(time_limit_flag))
        if time_limit_flag > 1:
            time.sleep(15)  #如果不是第一次刷新,等待15秒
        #Flag,Position = Base_func.match_template('F:/FGO_Project/Template/Refresh_friend.jpg')
        Serial.send(720, 110)
        Serial.wait_for_flag()

        Flag, Position = Base_func.match_template(
            'F:/FGO_Project/Template/Refresh_decide.jpg')
        Serial.send(Position[0], Position[1])
        Serial.wait_for_flag()

        Flag, Position = Base_func.match_template(
            'F:/FGO_Project/Template/friend_signal.jpg')
        while bool(1 - Flag):
            time.sleep(1)
            Flag, Position = Base_func.match_template(
                'F:/FGO_Project/Template/friend_signal.jpg')

        if time_limit_flag > 4:
            k = input(' 5次刷新未找到CBA,需人工操作,按0退出执行:')
            if k == 0:
                Serial.send(0, 0)
                Serial.wait_for_flag()
                exit()

        Flag, Position = Base_func.match_template(
            'F:/FGO_Project/Template/CBA_skill_level.jpg')
        time_limit_flag += 1

    if Flag:
        print(' success find CBA')
        Serial.send(Position[0], Position[1] - 50)
        Serial.wait_for_flag()
        #识别“开始任务”按钮
        Flag, Position = Base_func.match_template(
            'F:/FGO_Project/Template/Start_button.jpg')
        while bool(1 - Flag):
            time.sleep(1)
            Flag, Position = Base_func.match_template(
                'F:/FGO_Project/Template/Start_button.jpg')
        Serial.send(Position[0], Position[1])
        Serial.wait_for_flag()
        print(' Start battle button pressed')
コード例 #7
0
def main(port_no, times=1, use_commmand=False):
    Serial.port_open(port_no)  #写入通讯的串口号
    FGO_process(times, use_commmand)
    Serial.port_close()
    print(' All done!')
コード例 #8
0
def InfinatePool():
    Serial.port_open('com5')
    Serial.mouse_set_zero()
    Serial.mouse_move((320, 360))
    for i in range(100):
        Serial.mouse_click()
コード例 #9
0
ファイル: main.py プロジェクト: liangzhichao63/YF_Object
def Robot_arm_Rest():
    Serial.Set_Servo_A(80)
    Serial.Set_Servo_B(150)
    Serial.Set_Servo_C(150)
    Serial.Set_Servo_D(150)
コード例 #10
0
#Code used for testning in M3

import cv2
assert float(cv2.__version__.rsplit('.', 1)[0]) >= 3
import numpy as np
import Calibrater
import Serial

ser = Serial.Serial('COM9', 115200)

def find_pixels(event,x,y,flags,param):
    if event == cv2.EVENT_LBUTTONUP:
        print("X:" ,x, "Y:",y)
        global xCoordinate
        global yCoordinate
        xCoordinate = x
        yCoordinate = y


def heighCorrection2(x, y, ledheight, cameraheight, xStart, ystart):
    t = (cameraheight - ledheight)/cameraheight
    vx = x - 200
    vy = 400 - y - 37
    xreal = xStart + t*vx
    yreal = ystart + t*vy
    return [xreal, yreal]
cv2.namedWindow('image')
cv2.setMouseCallback('image', find_pixels)

lower_red = np.array([0,100,100], np.uint8)
upper_red = np.array([10, 255, 255], np.uint8)
コード例 #11
0
ファイル: main.py プロジェクト: liangzhichao63/YF_Object
def Robot_arm_catch():
    Serial.Set_Servo_A(150)
    Serial.Set_Servo_B(220)
    Serial.Set_Servo_C(100)
    Serial.Set_Servo_D(150)
コード例 #12
0
ファイル: main.py プロジェクト: liangzhichao63/YF_Object
def Robot_arm_UP():
    Serial.Set_Servo_A(150)
    Serial.Set_Servo_B(150)
    Serial.Set_Servo_C(150)
    Serial.Set_Servo_D(150)
コード例 #13
0
ファイル: main.py プロジェクト: liangzhichao63/YF_Object
def Robot_arm_GO():
    Serial.Set_Servo_A(80)
    Serial.Set_Servo_B(220)
    Serial.Set_Servo_C(100)
    Serial.Set_Servo_D(150)
コード例 #14
0
ファイル: main.py プロジェクト: liangzhichao63/YF_Object

def Robot_arm_UP():
    Serial.Set_Servo_A(150)
    Serial.Set_Servo_B(150)
    Serial.Set_Servo_C(150)
    Serial.Set_Servo_D(150)


if __name__ == "__main__":
    if (video.Init() == False):
        exit(0)
    # video.Show_Init()
    # video.Show()

    Serial.Set_Speed(0)
    Robot_arm_Rest()
    Serial.Link()
    Ready = 0
    while True:
        frame = video.Read()
        Serial.Link()
        # print(frame.shape)
        target, target_size, frame, inRange_hsv = OD.Object_Recongnition(
            frame, 'green')
        if (target_size != 0):
            target = OD.TF(target)
            Left_Right_Out = target[0] * 50

            if Left_Right_Out > 30:
                Left_Right_Out = 30
コード例 #15
0
def MakeCraftEssenceEXCard():
    Serial.port_open('com5')
    Serial.mouse_set_zero()

    while True:
        Serial.touch(720, 280)
        time.sleep(0.5)
        Serial.mouse_swipe((150, 250), (600, 600), 0.5)
        Serial.touch(990, 570, 3)
        time.sleep(0.5)
        Serial.touch(720, 507, 10)
コード例 #16
0
ファイル: joytest.py プロジェクト: chula-eic/Neo-FRA
                            but_num)
                elif but_num % 2 == 1 and joystick.get_button(but_num) == 1:
                    self.speed -= 50
                    if self.speed < 0:
                        self.speed = 0
                elif but_num % 2 == 0 and joystick.get_button(but_num) == 1:
                    self.speed += 50
                    if self.speed > MAX_SPEED:
                        self.speed = MAX_SPEED
                #self.event['button'][but_num] = int(self.event['button'][but_num])

            hats = joystick.get_numhats()
            self.event['hats'] = {}
            for hat_num in range(hats):
                self.event['hats'][hat_num] = list(joystick.get_hat(hat_num))
                for hat in self.event['hats'][hat_num]:
                    self.event['hats'][hat_num][hat] *= self.speed
                    #self.event['hats'][hat_num][hat] = int(self.event['hats'][hat_num][hat])
            print(joystick.get_axis(2))
            Serial.translation(int(self.event['axes'][0] * 1.5),
                               int(self.event['axes'][1] * 1.5),
                               self.event['axes'][2])


if __name__ == "__main__":
    Serial.setup()
    JoyHandler = JoyHandler()
    while (1):
        JoyHandler.handle_joy()
        #time.sleep(0.1)
コード例 #17
0
ファイル: Game.py プロジェクト: rdevis/bomber-berry
    def checkEvents(self):
        if SERIAL:
            PlayController = Serial.keysPS()
        else:
            PlayController = {"PS1_CUADRADO":False, "PS1_TRIANGULO":False, "PS1_CIRCULO":False, "PS1_EQUIS":False, "PS1_ARRIBA":False, "PS1_ABAJO":False, "PS1_IZQUIERDA":False, "PS1_DERECHA":False, "PS1_L1":False, "PS1_R1":False, "PS1_L2":False, "PS1_R2":False, "PS1_L3":False, "PS1_R3":False, "PS1_START":False, "PS1_SELECT":False, "PS1_JLARRIBA":False, "PS1_JLABAJO":False, "PS1_JLIZQUIERDA":False, "PS1_JLDERECHA":False, "PS1_JRARRIBA":False, "PS1_JRABAJO":False, "PS1_JRIZQUIERDA":False, "PS1_JRDERECHA":False, "PS2_CUADRADO":False, "PS2_TRIANGULO":False, "PS2_CIRCULO":False, "PS2_EQUIS":False, "PS2_ARRIBA":False, "PS2_ABAJO":False, "PS2_IZQUIERDA":False, "PS2_DERECHA":False, "PS2_L1":False, "PS2_R1":False, "PS2_L2":False, "PS2_R2":False, "PS2_L3":False, "PS2_R3":False, "PS2_START":False, "PS2_SELECT":False, "PS2_JLARRIBA":False, "PS2_JLABAJO":False, "PS2_JLIZQUIERDA":False, "PS2_JLDERECHA":False, "PS2_JRARRIBA":False, "PS2_JRABAJO":False, "PS2_JRIZQUIERDA":False, "PS2_JRDERECHA":False}
        keys = pygame.key.get_pressed()
        if keys[K_ESCAPE]:
            sys.exit(0)

        # Player 1 controls
        if (keys[K_DOWN] or keys[K_UP] or keys[K_RIGHT] or keys[K_LEFT] or
            PlayController["PS1_ABAJO"] or PlayController["PS1_JLABAJO"] or
            PlayController["PS1_ARRIBA"] or PlayController["PS1_JLARRIBA"] or
            PlayController["PS1_DERECHA"] or PlayController["PS1_JLDERECHA"] or
            PlayController["PS1_IZQUIERDA"] or PlayController["PS1_JLIZQUIERDA"]):
            self.player.moving=True
        else:
            self.player.moving=False

        if keys[K_DOWN]:
            self.player.direction = DOWN
            self.movePlayer(self.player,0,4*self.player.speed)
        if keys[K_UP]:
            self.player.direction = UP
            self.movePlayer(self.player,0,-4*self.player.speed)
        if keys[K_RIGHT]:
            self.player.direction = RIGHT
            self.movePlayer(self.player,4*self.player.speed,0)
        if keys[K_LEFT]:
            self.player.direction = LEFT
            self.movePlayer(self.player,-4*self.player.speed,0)
        if keys[K_RCTRL]:
            self.putBomb(self.player)
        if keys[K_RSHIFT] and self.player.transport:
            self.transportPlayer(self.player)

        if PlayController["PS1_ABAJO"] or PlayController["PS1_JLABAJO"]:
            self.player.direction = DOWN
            self.movePlayer(self.player,0,4*self.player.speed)
        if PlayController["PS1_ARRIBA"] or PlayController["PS1_JLARRIBA"]:
            self.player.direction = UP
            self.movePlayer(self.player,0,-4*self.player.speed)
        if PlayController["PS1_DERECHA"] or PlayController["PS1_JLDERECHA"]:
            self.player.direction = RIGHT
            self.movePlayer(self.player,4*self.player.speed,0)
        if PlayController["PS1_IZQUIERDA"] or PlayController["PS1_JLIZQUIERDA"]:
            self.player.direction = LEFT
            self.movePlayer(self.player,-4*self.player.speed,0)
        if PlayController["PS1_EQUIS"]:
            self.putBomb(self.player)
        if PlayController["PS1_CIRCULO"] and self.player.transport:
            self.transportPlayer(self.player)

        # Player 2 controls
        if (keys[K_w] or keys[K_s] or keys[K_a] or keys[K_d] or
            PlayController["PS2_ABAJO"] or PlayController["PS2_JLABAJO"] or
            PlayController["PS2_ARRIBA"] or PlayController["PS2_JLARRIBA"] or
            PlayController["PS2_DERECHA"] or PlayController["PS2_JLDERECHA"] or
            PlayController["PS2_IZQUIERDA"] or PlayController["PS2_JLIZQUIERDA"]):
            self.player2.moving=True
        else:
            self.player2.moving=False

        if keys[K_s]:
            self.player2.direction = DOWN
            self.movePlayer(self.player2,0,4*self.player2.speed)
        if keys[K_w]:
            self.player2.direction = UP
            self.movePlayer(self.player2,0,-4*self.player2.speed)
        if keys[K_d]:
            self.player2.direction = RIGHT
            self.movePlayer(self.player2,4*self.player2.speed,0)
        if keys[K_a]:
            self.player2.direction = LEFT
            self.movePlayer(self.player2,-4*self.player2.speed,0)
        if keys[K_LCTRL]:
            self.putBomb(self.player2)
        if keys[K_LSHIFT] and self.player2.transport:
            self.transportPlayer(self.player2)

        if PlayController["PS2_ABAJO"] or PlayController["PS2_JLABAJO"]:
            self.player2.direction = DOWN
            self.movePlayer(self.player2,0,4*self.player2.speed)
        if PlayController["PS2_ARRIBA"] or PlayController["PS2_JLARRIBA"]:
            self.player2.direction = UP
            self.movePlayer(self.player2,0,-4*self.player2.speed)
        if PlayController["PS2_DERECHA"] or PlayController["PS2_JLDERECHA"]:
            self.player2.direction = RIGHT
            self.movePlayer(self.player2,4*self.player2.speed,0)
        if PlayController["PS2_IZQUIERDA"] or PlayController["PS2_JLIZQUIERDA"]:
            self.player2.direction = LEFT
            self.movePlayer(self.player2,-4*self.player2.speed,0)
        if PlayController["PS2_EQUIS"]:
            self.putBomb(self.player2)
        if PlayController["PS2_CIRCULO"] and self.player2.transport:
            self.transportPlayer(self.player2)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit(0)
コード例 #18
0
ファイル: serialTest.py プロジェクト: NikoAlb/tictactobot
import Serial
import time

mySerial = Serial.Serial()

# mySerial needs a few seconds to establish connection
time.sleep(5)

while (1):
    data = raw_input("> ")
    mySerial.write(data)
    time.sleep(0.01)
    #mySerial.read()
    #time.sleep(2)
    response = mySerial.read()
    print(response)
コード例 #19
0
def quit_battle():
    time.sleep(15)
    while True:
        time.sleep(1)
        Flag, Position = Base_func.match_template(
            'F:/FGO_Project/Template/Battlefinish_sign.jpg')
        if Flag:
            break
        Flag, Position = Base_func.match_template(
            'F:/FGO_Project/Template/Master_face.jpg')
        if Flag:
            break
    #检测到战斗结束标志或御主的脸时跳出循环
    Flag, Position = Base_func.match_template(
        'F:/FGO_Project/Template/Master_face.jpg')
    if Flag:
        for i in range(3):
            playsound('F:/FGO_Project/11750.mp3')
        print(' 翻车,需要人工处理')  #翻车检测,系统三声报警
        Serial.send(0, 0)
        Serial.wait_for_flag()
        exit()
    print(' battle finished')
    Flag, Position = Base_func.match_template(
        'F:/FGO_Project/Template/Next_step.jpg')
    Serial.send(936, 571)  #一直点,直到发现“下一步”的按钮
    Serial.wait_for_flag()
    while bool(1 - Flag):
        time.sleep(2)
        Flag, Position = Base_func.match_template(
            'F:/FGO_Project/Template/Next_step.jpg')
        if Flag:
            Serial.send(Position[0], Position[1])
            Serial.wait_for_flag()
        else:
            Serial.send(936, 571)
            Serial.wait_for_flag()
    #time.sleep(7)
    print(' quit success')
コード例 #20
0
def Master_skill(skill_no, para1=3, para2=2):
    Serial.touch(1010, 266)  #御主技能按键
    if skill_no == 1:
        Serial.touch(760, 266)
    elif skill_no == 2:
        Serial.touch(835, 266)
    elif skill_no == 3:  #换人
        Serial.touch(920, 266)
        Serial.touch(630 + (para2 - 1) * 170, 300)  #默认换最后一人与替换区第二人
        Serial.touch(120 + (para1 - 1) * 170, 300)
        Serial.touch(530, 530)
    time.sleep(1)
    Current_state.WaitForBattleStart()
    print(' Master skill{} has pressed'.format(skill_no))
    time.sleep(1)
コード例 #21
0
def Master_skill(skill_no, para1=3, para2=2):
    Serial.send(1000, 266)  #御主技能按键
    Serial.wait_for_flag()
    if skill_no == 1:  #加攻
        Serial.send(760, 266)
        Serial.wait_for_flag()
    elif skill_no == 2:  #眩晕
        Serial.send(835, 266)
        Serial.wait_for_flag()
    elif skill_no == 3:  #换人
        Serial.send(910, 266)
        Serial.wait_for_flag()
        Serial.send(630 + (para2 - 1) * 170, 300)  #默认换最后一人与替换区第二人
        Serial.wait_for_flag()
        Serial.send(120 + (para1 - 1) * 170, 300)
        Serial.wait_for_flag()
        Serial.send(530, 530)
        Serial.wait_for_flag()


#    Flag,Position = Base_func.match_template('F:/FGO_Project/Template/Master_face.jpg')
#    while bool(1-Flag):
#        time.sleep(1)
#        Flag,Position = Base_func.match_template('F:/FGO_Project/Template/Master_face.jpg')
    print(' master skill{} has pressed'.format(skill_no))
コード例 #22
0
class SDevBase:
    def __init__(self, port,baudrate):
        tt = time.strftime("%m-%d_%H.%M",time.localtime(time.time()))
        # get current file absolutely path
        modulepath=os.path.dirname(os.path.realpath(__file__))
        self.log_config(modulpath)

        os_version = sys.platform

        self.baudrate= baudrate
        self.bytesize = 8
        self.parity = 'N'
        self.stopbits = 1
        self.timeout = 1
        self.writeTimeout = 10

        if os_version == 'win32':
            self.port = port
        else:
            self.port = os.path.join('/dev', port)
        self.com = Serial(self.port, baudrate=self.baudrate,
                          bytesize=self.bytesize, parity=self.parity,
                          stopbits=self.stopbits, timeout=self.timeout,
                          writeTimeout=self.writeTimeout)
        # self.open()
    
    def log_config(self,modulpath):
        logpath=os.path.join(modulepath,"_log")
        if not os.path.exists(logpath):
            os.makedirs(logpath)
        log_file = os.path.join(logpath,"%s_%s.log" % (self.__class__.__name__,tt) )
        logging.basicConfig(level=logging.DEBUG,
                format='[%(asctime)s %(filename)s line:%(lineno)d func:%(funcName)s]:  %(message)s',
                datefmt='%d %H:%M:%S',
                filename=log_file,
                filemode='w')
        self.log = logging.getLogger(self.__class__.__name__)

        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        formatter = logging.Formatter('[%(filename)s line:%(lineno)d]:  %(message)s')
        console.setFormatter(formatter)
        # add output log to screen
        self.log.addHandler(console)

    def open(self):
        self.com = serial.Serial()
        self.com.port     = self.port
        self.com.baudrate = 9600
        self.com.timeout  = 1
        try:
            self.com.open()
        except:
            raise Exception('ERROR: Unable to open the COM port %s' % self.port)
            self.com.close()
            sys.exit(-1)

	def read(self):
		n=self.com.InWaiting()
		if n:
			return self.com.read(n)
		return None

	def read_line(self):
        return self.com.readline().strip()

	def write(self,data):
        self.com.write(data)

    def read_data(self):
        n = self.com.inWaiting()
        data = self.com.read(n)
        self.data += data

    def write(self, value, timeout=10):
        self.com.writeTimeout = timeout
        r =  self.com.write(value)
        self.com.flush()
        return r
コード例 #23
0
 def on_enter(self):
     ser.Serial.port = self.textInput.text
     ser.Serial().open_communication()
コード例 #24
0
def enter_battle(template='F:/FGO_Project/Template/LastOrder_sign.jpg'):
    Flag, Position = Base_func.match_template(
        'F:/FGO_Project/Template/Menu_button.jpg')
    while bool(1 - Flag):
        time.sleep(1)
        Flag, Position = Base_func.match_template(
            'F:/FGO_Project/Template/Menu_button.jpg')
        #不停检测菜单按键,确认已经返回菜单界面
    Flag, Position = Base_func.match_template(template)
    if bool(1 - Flag):
        Serial.send(1060, 480)  #如果没有找到,点一下滚动条
        Serial.wait_for_flag()
    i = 1
    while bool(1 - Flag):
        i += 1
        time.sleep(2)
        Flag, Position = Base_func.match_template(template)
        if i > 3:
            k = input('未找到上次执行关卡,需人工操作,按0退出执行:')
            if k == 0:
                Serial.send(0, 0)
                Serial.wait_for_flag()
                exit()
    if Flag:
        Serial.send(Position[0] + 230, Position[1] + 50)  #加一点偏移量,保证点在关卡图标上
        Serial.wait_for_flag()
        Flag, Position = Base_func.match_template(template)
        while Flag:
            time.sleep(2)
            Flag, Position = Base_func.match_template(template)
        print(' ')
        print(' enter battle success')
        return Flag
    else:
        print(' enter battle fail')
        return Flag
コード例 #25
0
 def add_enable_COM(self):
     self.enableCOM = Serial.findEnableCOMPort()
     for ser in self.enableCOM:
         self.COM.addItem(ser)
コード例 #26
0
def card(Baoju_no=1):
    Serial.send(950, 510)  #点击attack按钮
    Serial.wait_for_flag()
    time.sleep(1)
    Flag, Position = Base_func.match_template(
        'F:/FGO_Project/Template/Master_face.jpg')
    i = 0
    while Flag:
        i += 1
        if i > 3:
            print(' 发卡失败,需人工处理')
            Serial.send(0, 0)
            Serial.wait_for_flag()
            exit()
        time.sleep(2)
        Serial.send(950, 510)  #如没有进入选卡界面再次点击attack按钮
        Serial.wait_for_flag()
        Flag, Position = Base_func.match_template(
            'F:/FGO_Project/Template/Master_face.jpg')

    Serial.send(340 + (Baoju_no - 1) * 200, 170)  #打手宝具,参数可选1-3号宝具位
    Serial.wait_for_flag()

    Serial.send(340 + (Baoju_no - 1) * 200, 430)  #随便两张牌,先选宝具下面那张
    Serial.wait_for_flag()

    Serial.send(540, 430)  #默认选中间的牌
    Serial.wait_for_flag()

    print(' Card has pressed')
コード例 #27
0
#Code moved to Positioning!

import Serial

serial = Serial('COM7', 115200)
コード例 #28
0
def apple_feed():
    #喂苹果,先银后金
    Flag, Position = Base_func.match_template(
        'F:/FGO_Project/Template/AP_recover.jpg')
    if Flag:
        Flag, Position = Base_func.match_template(
            'F:/FGO_Project/Template/Silver_apple.jpg')
        if Flag:
            Serial.send(709, Position[1])
            Serial.wait_for_flag()
            Flag, Position = Base_func.match_template(
                'F:/FGO_Project/Template/Feedapple_decide.jpg')
            Serial.send(Position[0], Position[1])
            Serial.wait_for_flag()
            print(' feed silver apple success')
            return Flag
        else:
            Flag, Position = Base_func.match_template(
                'F:/FGO_Project/Template/Gold_apple.jpg')
            if Flag:
                Serial.send(709, Position[1])
                Serial.wait_for_flag()
                Flag, Position = Base_func.match_template(
                    'F:/FGO_Project/Template/Feedapple_decide.jpg')
                Serial.send(Position[0], Position[1])
                Serial.wait_for_flag()
                print(' feed gold apple success')
                return Flag
            else:
                print(' no apple remain')
                Serial.send(0, 0)
                Serial.wait_for_flag()
                exit()
                return Flag
    else:
        print(' no need to feed apple')
コード例 #29
0
# to recieve the input from the ardino to raspberry pi

# AT raspberry pi
import Serial
import RPi.GPIO

scr = serial.Serial('/dev/ttyACM0',9600)

while 1:
	p = scr.read()
	print(p)

# At arduino
 char x; 
void setup(){
	Serial.begin(9600);
}

void loop() {
	digitalWrite('hi');
}

###########################################################

# To recieve data from raspberry pi and glow LED

# At Ardino
char x; 
void setup(){
	
	pinMode(7,OUTPUT);
コード例 #30
0
def main(port_no,times=1,servant='CBA'):
    Serial.port_open(port_no)   #写入通讯的串口号
    Serial.mouse_set_zero()
    FGO_process(times,servant)
    Serial.port_close()
    print(' All done!') 
コード例 #31
0
 def get_serial_port(self):
     ports = Serial.list_available_ports()
     if len(ports) == 0: raise SerialError
     return ports[1] #after trial and error, the correct port is always 2nd
コード例 #32
0
ファイル: RxRxRxPx.py プロジェクト: mrcouts/Nyquist-Attack
from Serial import *

R = Serial("RxRxRxPx", '', Matrix([['x','x','x','0'],['y','y','y','x']]).T)
n_mot = 4
mot = [Motor("mot"+str(i+1),str(R.dof+i+1)) for i in range(n_mot)]

R.StaticBal = solve(R.gh_, R.lg)

R.Mh_sb_ = simplify(R.Mh_.subs(R.StaticBal))
R.vh_sb_ = simplify(R.vh_.subs(R.StaticBal))
R.gh_sb_ = simplify(R.gh_.subs(R.StaticBal))

ph_ = R.ph_
po_ = Matrix([mot[i].p_ for i in range(n_mot)])
p_ = Matrix([ph_,po_])

M_ = R.Mh_sb_
for i in range(n_mot):
	M_ = diag(M_, mot[i].M_)
v_ = Matrix([R.vh_sb_] + [mot[i].v_ for i in range(n_mot)])
g_ = Matrix([R.gh_sb_] + [mot[i].g_ for i in range(n_mot)])

phi_ = po_ - Matrix([R.vw_[0][0]+ph_[1],0,0, R.vw_[0][0]+symbols('beta')*ph_[1],0,0, R.vw_[1][0]+ph_[2],0,0, R.vw_[1][0]+symbols('gamma')*ph_[2],0,0]).subs(R.StaticBal)

Ah_ = phi_.jacobian(ph_)
Ao_ = phi_.jacobian(po_)
C_ = Matrix([eye(R.dof),simplify(-Ao_**-1 * Ah_)])
Mh_ = simplify( (C_.T * M_ * C_) )
vh_ = simplify(  (C_.T * ( M_ * C_.diff(t)*ph_ + v_ ) ))
gh_ = simplify(C_.T *g_)
コード例 #33
0
    exit(0)

image_id = 0
try:
    while True:
        ret, frame = cap.read()
        if frame is None:
            print('--(!) No captured frame -- Break!')
            break
        func.detectAndDisplay(frame, facesCenter, faceGray, face_cascade,
                              eyes_cascade)
        ang = func.pix2ang(facesCenter)
        if ang[0] != -1:
            operation = func.ang2op(ang)
            print('Op: ', ang)
            Serial.write_read('x' + str(operation[0]))
            Serial.write_read('y' + str(operation[1]))

            reshaped = []
            if len(faceGray) > 4:
                faceGray = faceGray[:4]
            for i in range(len(faceGray)):
                reshaped.append(faceGray[i].reshape(32 * 32).astype(
                    np.ubyte).tobytes())
                cv.imwrite('images/' + str(image_id) + '.jpg', faceGray[i])
                image_id += 1

            events = client.sel.select(timeout=1)
            for key, mask in events:
                message = key.data
                try: