Пример #1
0
    def test_login(self):
        driver = self.driver
        driver.get(self.base_url+'/tmpl/member/login.html')
        sleep(Config.STIME)
        username = [15000000006, 13717648820]
        pwd = [111112, 111111]

        for i in range(len(username)):
            driver.get(self.base_url+'/tmpl/member/login.html')
            user_textfield = driver.find_element_by_id('username')
            pwd_textfield = driver.find_element_by_id('userpwd')
            login_btn = driver.find_element_by_id('loginbtn')
            for j in range(len(pwd)):
                user_textfield.send_keys(username[i])
                sleep(Config.STIME)
                pwd_textfield.send_keys(pwd[j])
                sleep(Config.STIME)
                login_btn.click()
                sleep(Config.STIME)
                current_url = driver.current_url
                if current_url == self.base_url+'/tmpl/member/member.html':
                    print 'login seccessed'
                    sleep(Config.STIME)
                    # s = driver.get_cookies()
                    print s
                    sleep(Config.STIME+10)
                else:
                    screen(driver, 'login_err')
                    sleep(Config.STIME)
                    print 'login failed'
                    user_textfield.clear()
                    pwd_textfield.clear()
                    sleep(Config.STIME)
Пример #2
0
    def __init__(self):
        # These have to stay at 30 so they move to each square properly
        self.personStep = 30
        self.enemyStep = 30
        self.bulletStep = 30

        # Starting positions
        self.personWidth = 210
        self.personHeight = 420
        self.enemyWidth = 210
        self.enemyHeight = 30

        # Some stats
        self.enemyHealth = 10
        self.bulletPower = 10
        self.personScore = 0

        # The speed, lower number is faster (has to do with modulous).
        # Min: 1 (Super fast), Max: 100 (Super slow), Default: 5 / 3
        self.aiSpeed = 5
        self.bulletSpeed = 3

        # The bullet fire rate.  This value is time in seconds (can be float)
        #  between each shot that can be taken.
        self.bulletFireRate = 0.3

        # The current time to calculate the fire rate time
        self.currentBulletFireRate = time.time()

        # (Frequency modulus/% xxxSpeed) to control the speed of bullets
        self.bulletFrequency = 1

        # (Frequency modulus/% xxxSpeed) to control the speed of ai
        self.aiFrequency = 1

        # The max depth that the computer looks down to determine his move
        # Default: 3  -Anything above 4 or 5 and the computer can't handle it.
        self.maxDepth = 1

        # The offset from the person/enemy is to where the bullet is.
        # For collision detection. Do not touch this.
        self.offsetWidth = 10
        self.offsetHeight = 10

        # Enemy List and object initialization
        self.enemyList = []

        # Initialization of bullet list of person
        self.personBulletList = []

        # Object   filename.classname
        self.menuScreenObj = screen.screen()
        self.gameScreenObj = screen.screen()
        self.personObj = person.person(self.personStep, self.personWidth,
                                       self.personHeight, True)

        # Start the menu
        self.menu()
Пример #3
0
    def test_instalment(self):
        self.login()
        driver = self.driver
        driver.get(self.base_url+'/')
        sleep(Config.STIME)

    # 全额购买商品

        # 点击商品
        driver.find_element_by_xpath('//*[@id="main-container2"]/div[4]/ul/li[4]/a/div/img').click()
        sleep(Config.STIME)

        # 第一次点击立即购买按钮
        # driver.find_element_by_xpath('//*[@id="product_detail_html"]/div[2]/div[9]/div/a').click() #线上环境
        driver.find_element_by_xpath('//*[@id="product_detail_html"]/div[2]/div[10]/div/a').click()#测试环境
        sleep(2)

        # 选择分期支付
        driver.find_element_by_xpath('//*[@id="product_detail_spec_html"]/div[2]/div[4]/div[2]/dl/dt/div[2]').click()
        sleep(Config.STIME)

        # 第二次点击立即购买按钮
        driver.find_element_by_id('buy-now').click()
        sleep(2)
        self.assertEqual(self.base_url+'/tmpl/order/buy_step1.html?goods_id=100115&buynum=1&credit_id=2', driver.current_url) #测试环境

        # 提交订单
        credit_able = driver.find_element_by_id('credit_able').text
        goods_price = driver.find_element_by_xpath('//*[@id="deposit"]/div/ul/li/div[2]/span/em').text
        # 额度足够
        if credit_able >= goods_price:
            # 点击提交订单按钮
            driver.find_element_by_id('ToBuyStep2').click()
            sleep(Config.STIME)
            # 跳转到确认支付页面
            self.assertEqual('http://fqlm2test.i.hrbbwx.com/fenqipay/index#!/order', driver.current_url)
            # 点击确认按钮
            driver.find_element_by_xpath('//*[@id="app"]/div[1]/a[1]').click()
            sleep(Config.STIME)
            # 跳转到输入支付密码页面
            self.assertEqual('http://fqlm2test.i.hrbbwx.com/fenqipay/index#!/defrayal', driver.current_url)
            # 输入支付密码
            driver.find_element_by_name('pwd').send_keys(111111)
            sleep(Config.STIME)
            driver.find_element_by_xpath('//*[@id="app"]/div[1]/a[1]').click()
            sleep(Config.STIME)
            driver.find_element_by_xpath('//*[@id="modal-btn-right"]').click()
            sleep(Config.STIME)
            self.assertEqual('http://test.fenqiman.com/wap/tmpl/member/order_list.html?backHome=1', driver.current_url)
        else:
            driver.find_element_by_id('ToBuyStep2').click()
            screen(driver, 'limit')
Пример #4
0
    def test_regist_user_exist(self):
        driver = self.driver
        driver.get(self.base_url+'/tmpl/member/register.html')
        sleep(1)
        # 分别是手机号已注册,手机号格式正确且未注册
        username = [13717648820, 15000000005]
        sleep(2)
        # 遍历手机号
        for i in range(len(username)):
            user_mobile = driver.find_element_by_id('usermobile')
            user_mobile.send_keys(username[i])
            sleep(1)
            checkbox = driver.find_element_by_id('checkbox')
            if checkbox.is_selected():
                print 'checkbox is enabled'
            else:
                checkbox.click()

            register_mobile_btn = driver.find_element_by_id('refister_mobile_btn')
            sleep(2)
            register_mobile_btn.click()
            screen(driver, 'register_mobile')
            sleep(1)
            # 设置短信验证码固定为:111111
            driver.find_element_by_id('mobilecode').send_keys(111111)
            sleep(3)
            driver.find_element_by_id('register_mobile_password').click()
            sleep(1)
            screen(driver, 'security_code')
            url1 = driver.current_url
            print self.base_url+'a '+str(username[i])
            sleep(1)
            if url1 == self.base_url+'/tmpl/member/register_mobile_password.html?mobile='+str(username[i])+'&captcha=111111&invitation=undefined':
                # 获取完验证码后,设置密码
                driver.find_element_by_id('password').send_keys('111111')
                sleep(2)
                # 点击注册完成
                driver.find_element_by_id('completebtn').click()
                sleep(2)
                # 跳转至首页
                self.assertEqual('http://test.fenqiman.com/wap/index.html', driver.current_url)
                sleep(2)
            else:
                driver.find_element_by_xpath('//*[@id="header"]/div/div[1]/a/i').click()
                sleep(2)
                user_mobile2 = driver.find_element_by_id('usermobile')
                user_mobile2.clear()
                sleep(3)
                # driver.clear()
                # invitation_box.clear()
                print 'failure'
Пример #5
0
    def __init__(self):
        #intantiate classes
        self.config = self.getConfigs()
        self.database = database(
            os.path.join(self.getConfigPath(), 'database.db3'))
        self.screen = screen(self.config)
        self.rssworker = rss()

        self.screen.setWindowTitle("SimpleRSS")

        moveUpKeys = [KEY_UP, ord('k')]
        moveDownKeys = [KEY_DOWN, ord('j')]
        feedListReturnKeys = [
            ord('q'),
            ord('h'),
            ord('r'),
            ord('R'),
            ord('a'),
            ord('A'),
            ord('u'),
            ord('U'), 10,
            ord('l'),
            ord('?')
        ]
        articleListReturnKeys = feedListReturnKeys + [ord('o')]

        try:
            self.mainloop(moveUpKeys, moveDownKeys, feedListReturnKeys,
                          articleListReturnKeys)
        except Exception as e:
            self.screen.close()
            print("simpleRSS crashed:")
            traceback.print_exc()
        return
Пример #6
0
    def __init__(self,debug = False):
        self.title = "SimpleRSS {0}".format(VERSION)
        #instantiate classes
        if (debug == True):
            self.logwriter = logWriter()
        else:
            self.logwriter = logWriter("/dev/null")

        self.config = self.getConfigs()
        self.database = database(os.path.join(self.getConfigPath(),'database.db3'), VERSION)
        self.screen = screen(self.config)
        self.rssworker = rss()

        self.screen.setWindowTitle(self.title);

        self.moveUpKeys = [KEY_UP,ord('k')]
        self.moveDownKeys = [KEY_DOWN,ord('j')]

        try:
            self.showFirstPage()
        except Exception as e:
            self.screen.close()
            print("simpleRSS crashed:")
            traceback.print_exc()

        self.screen.close()
        return
Пример #7
0
    def test_fill(self):
        s = screen.screen(10, 10)
        s.fill_region(10, 1, 1, 10, 'X')
        s.fill_region(2, 2, 9, 9, 'O')
        s.fill_region(8, 8, 3, 3, ':')
        s.fill_region(4, 7, 7, 4, 'o')
        s.fill_region(6, 5, 5, 6, '.')
        assert str(s) == fill1_target

        s = screen.screen(11, 11)
        s.fill_region(1, 1, 11, 11, 'X')
        s.fill_region(2, 2, 10, 10, 'O')
        s.fill_region(9, 9, 3, 3, ':')
        s.fill_region(4, 8, 8, 4, 'o')
        s.fill_region(7, 5, 5, 7, '.')
        s.fill_region(6, 6, 6, 6, '+')
        assert str(s) == fill2_target
Пример #8
0
    def test_fill (self):
        s = screen.screen (10,10)
        s.fill_region (10,1,1,10,'X')
        s.fill_region (2,2,9,9,'O')
        s.fill_region (8,8,3,3,':')
        s.fill_region (4,7,7,4,'o')
        s.fill_region (6,5,5,6,'.')
        assert str(s) == fill1_target

        s = screen.screen (11,11)
        s.fill_region (1,1,11,11,'X')
        s.fill_region (2,2,10,10,'O')
        s.fill_region (9,9,3,3,':')
        s.fill_region (4,8,8,4,'o')
        s.fill_region (7,5,5,7,'.')
        s.fill_region (6,6,6,6,'+')
        assert str(s) == fill2_target
Пример #9
0
 def __init__(self, mode, param={}):
     param.update({
         'hwnds':
         self._get_hwnds(param.get('window_class'),
                         param.get('window_name'))
     })
     self._m = mouse(mode, param)
     self._s = screen(mode, param)
     return
Пример #10
0
def main():

	file = open('Tetris.gb', 'r')
	tetris = file.read()

	gb_memory = processor.memory(0xFFFF, tetris)
	
	gb_screen = screen.screen(gb_memory)
	gb_processor = processor.processor(tetris, gb_screen, gb_memory)
	
	gb_screen.start()
	gb_processor.power_on()
Пример #11
0
def main():

    pygame.init()
    window = screen.screen(pygame)
    input_h = input_handler.input_handler(pygame, sys)
    grid_p = grid_processor.grid_processor([window.SIZE_X, window.SIZE_Y] )
    s_algo = search_algorithm.search_algorithm()

    game_states={}

    game_states['pixel_p_mode'] = 0
    game_states['process_state'] = False
    game_states['color_theme'] = 0
    game_states['draw_mouse'] = False
    game_states['search_algorithm'] = 0
    game_states['selected_creature'] = 0
    game_states['mouse_pos'] = [0,0]
    game_states['status'] = ''
    game_states['fullscreen'] = False



    while(True):

        #Draw the grid panel
        window.draw_game_board(grid_p.grid)
        #Draw the status panel
        window.draw_game_status_panel(game_states)

        #Draw Search Algorithm
        window.draw_search_path(s_algo, game_states)
        #Run the PROCESSING
        if game_states['process_state']:
            grid_p.process(window, game_states)
        #Run the Searching
        if game_states['search_algorithm'] == 2:
            search_state = s_algo.step_search_dfs(grid_p.grid, window)
            if search_state:
                game_states['search_algorithm'] = 3
                game_states['status'] = 'Solution Found'


            elif search_state == False:
                game_states['search_algorithm'] = 3
                game_states['status'] = 'Solution not Found'

        #Handle User input events
        input_h.handle_event(grid_p, window, s_algo,game_states)

        window.update_screen()
Пример #12
0
    def __init__(self):
        self.default_color = (255, 255, 0)
        self.default_s_color = (127, 127, 0)
        self.a_color = (255, 255, 0)
        self.a_s_color = (127, 0, 0)
        self.b_color = (0, 0, 0)
        self.default_font = 'data/Roboto-Light.ttf'

        self.clock = pygame.time.Clock()
        self.screen = screen()
        pygame.mouse.set_visible(False)

        #self.font = pygame.font.Font('segoeui.ttf', 126)
        self.font = pygame.font.Font(self.default_font, 190)
        self.dateFont = pygame.font.Font(self.default_font, 36)

        os.putenv('SDL_MOUSEDRV', 'TSLIB')
        os.putenv('SDL_MOUSEDEV', '/dev/input/touchscreen')
Пример #13
0
    def __init__(self):
        #intantiate classes
        self.config = self.getConfigs()
        self.database = database(os.path.join(self.getConfigPath(),'database.db3'))
        self.screen = screen(self.config)
        self.rssworker = rss()
        
        self.screen.setWindowTitle("SimpleRSS");
        
        moveUpKeys = [KEY_UP,ord('k')]
        moveDownKeys = [KEY_DOWN,ord('j')]
        feedListReturnKeys = [ord('q'), ord('h'), ord('r'), ord('R'), ord('a'), ord('A'), ord('u'), ord('U'), 10, ord('l'), ord('?')]
        articleListReturnKeys = feedListReturnKeys + [ord('o')]

        try:
            self.mainloop(moveUpKeys, moveDownKeys, feedListReturnKeys, articleListReturnKeys)
        except Exception as e:
            self.screen.close()
            print("simpleRSS crashed:")
            traceback.print_exc()
        return
Пример #14
0
    def end_batch(self, end_req):
        response = udf_pb2.Response()
        #send back a begin batch to kapacitor
        response.begin.CopyFrom(self.begin_req)
        self.agent.write_response(response)

        self.matrix = np.array(self.matrix)

        start_time = datetime.now()
        results = screen.screen(self.matrix, self.timestamps, 0.1, -0.1, 300)
        end_time = datetime.now()
        t = (end_time - start_time).total_seconds()
        response = udf_pb2.Response()
        response.point.fieldsDouble["Screentime"] = t
        #seting timestamp for screen time
        response.point.time = int(
            (datetime.now() - datetime(1970, 1, 1)).total_seconds() *
            1000000000)
        self.agent.write_response(response)

        #29 feb for screeen
        time = 1583000000000000000
        for v in results:
            time = time + 10000000000
            response = udf_pb2.Response()
            response.point.time = time
            for i in range(len(v)):
                response.point.fieldsDouble["dim" + str(i)] = v[i]
            self.agent.write_response(response)

        response = udf_pb2.Response()
        response.end.CopyFrom(end_req)
        self.agent.write_response(response)
        logger.info("end batch")
        self.final_time = datetime.now()

        output_file = open("<output_file>", "a")
        output_file.write(
            str(self.matrix.shape) + " -- " +
            str((self.final_time - self.initial_time).total_seconds()) + "\n")
Пример #15
0
 def make_screen_with_put(self):
     s = screen.screen(10, 10)
     s.fill('.')
     for r in range(1, s.rows + 1):
         if r % 2:
             s.put_abs(r, 1, str(r))
         else:
             s.put_abs(r, s.cols, str(r))
     for c in range(1, s.cols + 1):
         if c % 2:
             s.put_abs(1, c, str(c))
         else:
             s.put_abs(s.rows, c, str(c))
     s.put_abs(1, 1, '\\')
     s.put_abs(1, s.cols, '/')
     s.put_abs(s.rows, 1, '/')
     s.put_abs(s.rows, s.cols, '\\')
     s.put_abs(5, 5, '\\')
     s.put_abs(5, 6, '/')
     s.put_abs(6, 5, '/')
     s.put_abs(6, 6, '\\')
     return s
Пример #16
0
 def make_screen_with_put (self):
     s = screen.screen(10,10)
     s.fill ('.')
     for r in range (1,s.rows + 1):
         if r % 2:
             s.put_abs (r, 1, str(r))
         else:
             s.put_abs (r, s.cols, str(r))
     for c in range (1,s.cols + 1):
         if c % 2:
             s.put_abs (1, c, str(c))
         else:
             s.put_abs (s.rows, c, str(c))
     s.put_abs(1,1, '\\')
     s.put_abs(1,s.cols, '/')
     s.put_abs(s.rows,1,'/')
     s.put_abs(s.rows, s.cols, '\\')
     s.put_abs(5,5,'\\')
     s.put_abs(5,6,'/')
     s.put_abs(6,5,'/')
     s.put_abs(6,6,'\\')
     return s
Пример #17
0
import os
import pygame
import time
import random
import math
from time import strftime, localtime
from screen import screen
import Queue
import imgthread as imgthread

queue = Queue.Queue()

screen = screen()
pygame.mouse.set_visible(0)
font = pygame.font.Font('segoeui.ttf', 90)
dateFont = pygame.font.Font('segoeui.ttf', 35)
lastTime = ""
currentImg = None
lastImg = None
imgt = imgthread.imgthread(queue)
imgt.setDaemon(True)
imgt.start()
fade = 0
while 1:
    if(not queue.empty()):
        lastImg = currentImg
        currentImg = queue.get()
        fade = 0
    if(currentImg != None):
        if(fade < 255 and lastImg != None):
            currentImg.surface.set_alpha(fade)
Пример #18
0
    5, 15, 85, 11, 72, 33, 85, 30, 59, 6, 84, 29, 51, 77, 99, 43, 95, 44, 83,
    95, 89, 27, 54, 16, 85, 90, 82, 34, 98, 59, 87, 12, 73, 25, 74, 29, 95, 82,
    51, 5, 81, 46, 51, 0, 0, 21, 21, 1, 10, 1, 0, 0, 0, 0, 0, 0
]

#defines
memorySize = 5000
#bad algorithm but run few times may give proper answer
answer = 9999
sx = 25
sy = 25
bw = 50
bl = 50
# main
itr = 0
scr = screen.screen(bw, bl)
cpu = computer.compu(inputProgram, [])
rb = repBot.repairBot(sx, sy, bw, bl)
scr.inp([sx, sy, 4])
process = True
cpuBuf = list()
aiBuf = list()
vidBuf = list()
road = list()
#find place
while process:
    vidBuf, aiBuf = rb.process(cpuBuf)
    if (len(aiBuf) == 0):
        process = False
    cpu.addInput(aiBuf)
    status, cpuBuf = cpu.ProcessProgram()
Пример #19
0
def main():
    inf = None
    fd_log = None
    ana = None
    dbc = None
    remove_time = 1.2
    uncolor_time = 1.2
    # initialize
    parser, args = parse_args()
    if args.version:
        print(__version__)
        return
    elif args.canusb_dev:
        inf = interface.canusb(args.canusb_dev)
        if inf is None:
            print("interface intialize error %s" % (args.canusb_dev))
            return
        if args.logging_name:
            fd_log = open(args.logging_name, "w")
    elif args.pythoncan_dev:
        inf = interface.pythoncan(args.pythoncan_dev)
        if inf is None:
            print("interface intialize error %s" % (args.pythoncan_dev))
            return
        if args.logging_name:
            fd_log = open(args.logging_name, "w")
    elif args.usb2can_dev:
        inf = interface.usb2can()
        if inf is None:
            print("interface intialize error usb2can_dev")
            return
        if args.logging_name:
            fd_log = open(args.logging_name, "w")
    elif args.candump_log:
        inf = interface.candump(args.candump_log)
        if inf is None:
            print("interface intialize error %s" % (args.candump_log))
            return
    elif args.candump_log_nots:
        remove_time = 100
        inf = interface.candump_nots(args.candump_log_nots)
        if inf is None:
            print("interface intialize error %s" % (args.candump_log_nots))
            return
    elif args.vehiclespy_csv:
        remove_time = 0.02
        uncolor_time = 0.002
        inf = interface.vehiclespy(args.vehiclespy_csv)
        if inf is None:
            print("interface intialize error %s" % (args.vehiclespy_csv))
            return
    else:
        parser.print_help()
        return
    # diff mode
    if args.diff:
        main_diff(inf)
        return
    # initialize filter/find
    if args.filter_by_ids:
        filter_by_ids = [int(i, 16) for i in args.filter_by_ids.split(",")]
    else:
        filter_by_ids = None
    find_string_ids = []
    # initialize library
    scn = screen.screen()
    scn.color("", "w")
    if args.analyze:
        ana_level = 1
        ana = analyzer.analyzer(ana_level)
    if args.dbc:
        dbc = cantools.database.load_file(args.dbc)
    # main loop
    msgs_latest = {}
    view_line_num_latest = 0
    scn.clear()
    for msg in inf.recv():
        # recv new msg
        ts, dev_name, msg_id, msg_size, msg_dat = msg.timestamp, msg.channel, msg.arbitration_id, msg.dlc, msg.data.hex(
        )
        # filter by id
        if filter_by_ids and msg_id not in filter_by_ids:
            continue
        # logging
        if fd_log:
            fd_log.write("(%f) %s %03X#%s\x0a" %
                         (ts, dev_name, msg_id, msg_dat))
            continue
        # analyze
        if ana:
            ana.analyze(msg)
        # find string
        if ana and args.find_string:
            if msg_id in find_string_ids:
                pass
            elif args.find_string in ana.get_msg_ascii(msg_id):
                find_string_ids.append(msg_id)
            else:
                continue
        # view msg
        if args.not_view_msg:
            # not view msg
            pass
        elif args.sniffer:
            # sniffer view mode (only latest msg each msg_id)
            scn.move(0, 0)
            view_line_num_latest = view_msg(msg, msgs_latest, scn, ana,
                                            view_line_num_latest, remove_time,
                                            uncolor_time)
        else:
            # flow view mode
            view_line_num_latest = view_msg(
                msg, {msg_id: msgs_latest.get(msg_id, msg)}, scn, ana,
                view_line_num_latest, remove_time, uncolor_time)
            if dbc:
                try:
                    for k, v in dbc.decode_message(msg.arbitration_id,
                                                   msg.data).items():
                        print(k, v)
                except:
                    pass
        # set latest msg
        msgs_latest[msg_id] = msg
    # view byte/bit range
    view_range(msgs_latest, ana, args.analyze_range)
    if fd_log:
        fd_log.close()
    inf.close()
    return
Пример #20
0
import usercollection
import user
import screen


if __name__ == "__main__":

    s = screen.screen()

    while 1:
        if s.logged_in_user == None:
            s.mainScreen()








Пример #21
0
def read():
    screen.screen(0, 0, 1920, 1080, temp)
    return baiduOcr.getString(temp)
state = dType.ConnectDobot(api, "", 115200)[0]
print("Etat de la connexion / Connect status : {}] \n".format(CON_STR[state]))

if (state == dType.DobotConnect.DobotConnect_NoError):

    # Run camera in order to retrieve the position of the green dot and the size of the region delimited by the red dots
    result, target, screen_size = Cfonct.run()

    # Initialize robot
    Dfonct.Init(api)
    # Get the height of the screen's plane
    z_min = Dfonct.Calc_Z_Min(api)
    Dfonct.Touch(api, z_min)

    # Launch robot calibration
    ecran = screen.screen(api, screen_size[0], screen_size[1])

    # Convert the coordinates of the green dot to the robot's basis
    # Largeur
    x = target[1]
    # Longueur
    y = target[0]
    [xf, yf] = ecran.Calc_Coordinates(x, y)
    print('xf : {}'.format(xf))
    print('yf : {}'.format(yf))

    # Move to the green dot and touch it.
    Dfonct.Movement(api, xf, yf, z_min + 20)
    Dfonct.Touch(api, z_min)

#Disconnect Dobot
Пример #23
0
def acquire_images(cam, nodemap, nodemap_tldevice, api):
    """
    This function shows images from a device.

    :param cam: Camera to acquire images from.
    :param nodemap: Device nodemap.
    :param nodemap_tldevice: Transport layer device nodemap.
    :type cam: CameraPtr
    :type nodemap: INodeMap
    :type nodemap_tldevice: INodeMap
    :return: True if successful, False otherwise.
    :rtype: bool
    """

    print('*** IMAGE ACQUISITION ***\n')
    try:

        result = True
        centroids = None
        centroidsTouches = None
        stats = None
        screen_size = [0, 0]
        ecran = None
        z_min = None
        cum = None
        current = None
        previous = None

        # Set acquisition mode to continuous
        #
        #  Retrieve enumeration node from nodemap

        # In order to access the node entries, they have to be casted to a pointer type (CEnumerationPtr here)
        node_acquisition_mode = PySpin.CEnumerationPtr(
            nodemap.GetNode('AcquisitionMode'))
        if not PySpin.IsAvailable(
                node_acquisition_mode) or not PySpin.IsWritable(
                    node_acquisition_mode):
            print(
                'Unable to set acquisition mode to continuous (enum retrieval). Aborting...'
            )
            return False, centroidsTouches, screen_size

        # Retrieve entry node from enumeration node
        node_acquisition_mode_continuous = node_acquisition_mode.GetEntryByName(
            'Continuous')
        if not PySpin.IsAvailable(
                node_acquisition_mode_continuous) or not PySpin.IsReadable(
                    node_acquisition_mode_continuous):
            print(
                'Unable to set acquisition mode to continuous (entry retrieval). Aborting...'
            )
            return False, centroidsTouches, screen_size

        # Retrieve integer value from entry node
        acquisition_mode_continuous = node_acquisition_mode_continuous.GetValue(
        )

        # Set integer value from entry node as new value of enumeration node
        node_acquisition_mode.SetIntValue(acquisition_mode_continuous)

        print('Acquisition mode set to continuous...')

        #  Begin acquiring images
        cam.BeginAcquisition()

        print('Acquiring images...')

        #  Retrieve device serial number
        device_serial_number = ''
        node_device_serial_number = PySpin.CStringPtr(
            nodemap_tldevice.GetNode('DeviceSerialNumber'))
        if PySpin.IsAvailable(node_device_serial_number) and PySpin.IsReadable(
                node_device_serial_number):
            device_serial_number = node_device_serial_number.GetValue()
            print('Device serial number retrieved as %s...' %
                  device_serial_number)

        # Retrieve, convert, and show images
        cv2.namedWindow('im', cv2.WINDOW_NORMAL)
        print(
            "Please ensure you have calibration screen image downloaded. Then put it in full screen to get started."
        )
        print(
            "Please use keyboard :\n\t- press c to calibrate\n\t- press y to extract screen after calibration\n\t- press e to segment the screen after extracted\n\t- press q when you are done (with a correct segmentation).\nYou can extract a new screen (y) and segment it (e) as long as you are not satisfied with the result. Playing with screen brightness and camera focus may help."
        )
        while (1):
            try:

                #  Retrieve next received image
                image_result = cam.GetNextImage()

                #  Ensure image completion
                if image_result.IsIncomplete():
                    print('Image incomplete with image status %d ...' %
                          image_result.GetImageStatus())

                else:
                    # Retrieve image width and height
                    width = image_result.GetWidth()
                    height = image_result.GetHeight()

                    # Convert image to uint8 numpy array
                    row_bytes = float(len(image_result.GetData())) / width
                    rawFrame = np.array(image_result.GetData(),
                                        dtype="uint8").reshape(height, width)
                    # Convert image to BGR
                    im = cv2.cvtColor(rawFrame, cv2.COLOR_BAYER_BG2BGR)

                    # Display image in window 'im'
                    cv2.imshow('im', im)
                    k = cv2.waitKey(10) & 0xFF
                    if k == ord('q'):  # Press 'q' to exit
                        cv2.destroyAllWindows()
                        break
                    elif k == ord('c'):
                        print(
                            "Processing... Please wait... This will take less than a minute..."
                        )
                        # Denoise image
                        dst = cv2.fastNlMeansDenoisingColored(
                            im, None, 10, 10, 7, 21)
                        # Calibrate camera
                        centroids = CamCalibrate(dst)

                        if len(centroids ==
                               3):  # if camera calibration went well
                            # Retrieve screen size
                            screen_size = size(centroids)
                            # Destroy all OpenCV windows
                            cv2.destroyAllWindows()

                            # Initialize robot
                            Dfonct.Init(api)
                            # Get the height of the screen's plane
                            z_min = Dfonct.Calc_Z_Min(api)
                            Dfonct.Touch(api, z_min)
                            # Launch robot calibration
                            ecran = screen.screen(api, screen_size[0],
                                                  screen_size[1])
                            Dfonct.Touch(api, z_min)
                            # Move robot offscreen
                            [xf, yf] = ecran.Calc_Coordinates(-50, -10)
                            Dfonct.Movement(api, xf, yf, z_min + 20)

                    elif k == ord('y') and centroids is not None:
                        # If a previous image of the screen was taken, it is copied to 'previous'
                        if current is not None:
                            previous = np.copy(current)
                        # Extract image of the screen, assign it to 'current' and display it
                        im2 = resizeScreen(im, centroids)
                        cv2.imshow('resized', im2)
                        current = np.copy(im2)

                    elif k == ord('e') and im2 is not None:

                        mask = None

                        # If a 'previous' image exists, compare it to 'current'. If new objects appeared, the resulting mask will hide everything but them. Otherwise returned mask will be None (ie if 'current' screen is unchanged or completely different).
                        if previous is not None:
                            mask = imcp.compareImages(previous, current)
                            # Display mask in case it is not None
                            if mask is not None:
                                cv2.imshow("mask", mask)

                        # Segment 'current' image with mask. If mask is None no mask is applied to 'current'.
                        markers, stats, centroidsTouches = segmentation(
                            im2, mask)
                        # Display resulting object markers
                        cv2.imshow('segmentation', markers)
                        # Select what are most likely graphical objects beyond those detected by segmentation and display their centroids
                        centroidsTouches = getOnlyTouches(
                            stats, centroidsTouches)
                        showObjects(im2, centroidsTouches)
                        cv2.imshow('touches', im2)
                        # Convert the object's coordinates to the red dot's basis.
                        centroidsTouches = TouchCoordinates(
                            centroidsTouches, centroids)

                    elif k == ord('r') and centroids is not None:

                        if centroidsTouches is not None:
                            # Pick a random object beyond those detected, and touch it.
                            i = random.randint(0, len(centroidsTouches) - 1)

                            touche = centroidsTouches[i]
                            x = touche[1]
                            y = touche[0]
                            [xf, yf] = ecran.Calc_Coordinates(x, y)
                            Dfonct.Movement(api, xf, yf, z_min + 20)
                            Dfonct.Touch(api, z_min)
                            # Move offscreen.
                            [xf, yf] = ecran.Calc_Coordinates(-50, -10)
                            Dfonct.Movement(api, xf, yf, z_min + 20)

                    #  Release image
                    image_result.Release()

            except PySpin.SpinnakerException as ex:
                print('Error: %s' % ex)
                return False, centroidsTouches, screen_size

        #  End acquisition
        cam.EndAcquisition()

    except PySpin.SpinnakerException as ex:
        print('Error: %s' % ex)
        return False, centroidsTouches, screen_size

    return result, centroidsTouches, screen_size
Пример #24
0
def titlescreen():
    global loaded, savefile
    loaded = False
    savefile = ''

    screename = ''

    stars = f'''  *    .  *       .             *    {screen.color.blink}*{screen.color.end}
                           *   .        *       .      .       *    .     *   .     .         {screen.color.blink}*{screen.color.end}       .                .        ..  *       .    {screen.color.blink}*{screen.color.end}                     *           .     .  *        {screen.color.blink}*{screen.color.end}.       .                .        ..  {screen.color.blink}*{screen.color.end}           *           .         {screen.color.blink}*{screen.color.end}     .    .     .               .                             .  .  *       .             *                .         {screen.color.blink}*{screen.color.end} *   .        *       .       .       * *   .        {screen.color.blink}*{screen.color.end}       .       .       *'''

    logo = '''     _______.___________. _______   ______   .______          ___      
    /       |           ||   ____| /  __  \  |   _  \        /   \     
   |   (----`---|  |----`|  |__   |  |  |  | |  |_)  |      /  ^  \    
 ___\   \       |  |     |   __|  |  |  |  | |      /______/  /_\  \   
.----)   |      |  |     |  |____ |  `--´  | |  |\  \----./  _____  \  
|_______/       |__|     |_______| \______/  | _| `._____/__/     \__\ '''

    text = screen.color.lightcyan + logo + screen.color.end + stars

    optiontitle = ''

    options = '................1)PLAY........................2)SETTINGS...................\n' \
             '...........................................................................\n' \
             '................3)HELP........................4)ABOUT......................\n' \
             '...............................5)QUIT......................................'

    screen.screen(screename, text, optiontitle, options)

    if screen.inpt is '1':
        screename = ''

        text = screen.color.lightcyan + logo + screen.color.end + stars

        optiontitle = 'PLAY'

        options = '...........................................................................\n' \
                 '................1)NEW GAME....................2)LOAD GAME..................\n' \
                 '............................ENTER TO GO BACK...............................\n' \
                 '...........................................................................'

        screen.screen(screename, text, optiontitle, options)

        if screen.inpt is '1':

            screename = f'INTRO'

            text = f"The year is 5733. Many civilizations of Steora - as the galaxy is called - had advanced significantly after the flourish of quasi-dimensional technology, allowing a movement that astrohistorians named galaticalization. The almost instantaneous quasi-dimensional communication served well for the strengthen of interracial diplomatic relationship, which culminated in the sign of the Karsov's Pact.    The Karsov's Pact is sign by the 12 races that has a status of permanent chair in the League of Steora. In this pact, it was guaranteed that the deep space, beyond the domains of a stellar system, should remain as autonomous region. The treaty also approved the construction of the Karsov's Base, a huge installation that orbits the supermassive black hole in the center of the galaxy, it's function is not only to be a safeport for interstellar travel, but also to harvest the energy from the black hole to the members of the League"

            optiontitle = ''

            options = '...........................................................................\n' \
                     '............................ENTER TO CONTINUE..............................\n' \
                     '...........................................................................\n' \
                     '...........................................................................'

            screen.screen(screename, text, optiontitle, options)

            text = f"As the Karsov's Pact stopped any attempt to establish a galactic government dictatorship, also stopped any race from legislate in space. Several groups faced that as an opportunity for space piracy, attacking cargo spaceships and hiding in remote planets and desert moons.                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀The consequence was the urge of bounty hunters across the galaxy, looking for personal gain and aiming to capture those who had a bounty on their head.                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀But, the deep space didn't became just a lawless land, several space explorers venture into the edges of Steora, looking for undiscovered worlds that may or may not present biological activity."

            screen.screen(screename, text, optiontitle, options)

            text = f"Space exploration is strongly encouraged by the League, aiming to reinforce the principle of the Knowledge Universalization established in the Pact, in such way to make the Unified System Catalogue (USC) accessible to all.                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Another measure taken with the Karsov's Pact is the formation of a single galactic economical block, facilitating and stimulating the trading between members of the League and adopting a common currency named Quain and symbolized by {screen.color.stroke}Q{screen.color.end}.                             ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀    ⠀⠀⠀And in this context that you're in! But, what is your name?                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀(The name you choose will be used to load your game later!)"

            options = '...........................................................................\n' \
                     '..............................TYPE YOUR NAME...............................\n' \
                     '...........................................................................\n' \
                     '...........................................................................'

            screen.screen(screename, text, optiontitle, options)
            while screen.inpt is '':
                optiontitle = 'INVALID NAME!'
                screen.screen(screename, text, optiontitle, options)
            global playername
            playername = screen.inpt

            def racechoice():
                text = f"{playername}! Right... And which race you'll choose? Each race has a bonus in certain attribute and starts in a different planet!                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Races with bonus in Agility: Humans, Kal-shon, Zayolin                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Races with bonus in Dexterity: Alnits, Droides, Zorahtos                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Races with bonus in Intelligence: Kaitos, Lattuns, Ophidianos                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Races with bonus in Luck: Destanis, Nephinos, Svastos                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Choose a race to know more, don't worry, you can come back to here later!"

                optiontitle = ''
                options = '.....1)HUMANS..................2)KAL-SHON..................3)ZAYOLIN.......\n' \
                         '.....4)ALNITS..................5)DROIDES...................6)ZORAHTOS......\n' \
                         '.....7)KAITOS..................8)LATTUNS...................9)OPHIDIANOS....\n' \
                         '.....10)DESTANIS...............11)NEPHINOS.................12)SVASTOS......'
                screen.screen(screename, text, optiontitle, options)
                global playerrace
                playerrace = screen.inpt

                while screen.inpt not in [
                        '1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
                        '11', '12'
                ]:
                    optiontitle = 'INVALID OPTION'
                    screen.screen(screename, text, optiontitle, options)
                    playerrace = screen.inpt

                def racechoice2(playerrace):
                    screename = f'{races.races[playerrace]["name"]}'

                    text = f'The {races.races[playerrace]["name"]} are original inhabitants of the planet {races.races[playerrace]["planet"]} in the {races.races[playerrace]["system"]} System. Physically {races.races[playerrace]["description"]}. The bonus of this race is {races.races[playerrace]["bonus"]} points in {races.races[playerrace]["attribute"]} and the innate skills: {races.races[playerrace]["skills"]}'

                    optiontitle = 'CONFIRM RACE?'

                    options = '..........1)CONFIRM.....................3)CULTURAL INFORMATION.............\n' \
                             '...........................................................................\n' \
                             '..........2)SKILLS INFORMATION.........................0)BACK..............\n' \
                             '...........................................................................'
                    screen.screen(screename, text, optiontitle, options)
                    global playersplanet
                    global playerssystem
                    global playerscity
                    global choosenrace
                    if screen.inpt is '1':
                        playerscity = (races.races[playerrace]["city"]).upper()
                        playersplanet = (
                            races.races[playerrace]["planet"]).upper()
                        playerssystem = (
                            races.races[playerrace]["system"]).upper()
                        choosenrace = races.races[playerrace]["singularname"]

                    elif screen.inpt is '2':
                        screename = f'{races.races[playerrace]["name"]}: SKILLS'

                        text = f'WIP'

                        optiontitle = 'CONFIRM RACE?'

                        options = '...........................................................................\n' \
                                 '...........1)CONFIRM....................................0)BACK.............\n' \
                                 '...........................................................................\n' \
                                 '...........................................................................'
                        screen.screen(screename, text, optiontitle, options)
                        if screen.inpt is '1':
                            playerscity = (
                                races.races[playerrace]["city"]).upper()
                            playersplanet = races.races[playerrace]["planet"]
                            playerssystem = races.races[playerrace]["system"]
                            choosenrace = races.races[playerrace][
                                "singularname"]

                        else:
                            racechoice2(playerrace)
                    elif screen.inpt is '3':
                        screename = f'{races.races[playerrace]["name"]}: CULTURE'

                        text = f'The {races.races[playerrace]["name"]} {races.races[playerrace]["culture"]}'

                        optiontitle = 'CONFIRM RACE?'

                        options = '...........................................................................\n' \
                                 '...........1)CONFIRM....................................0)BACK.............\n' \
                                 '...........................................................................\n' \
                                 '...........................................................................'
                        screen.screen(screename, text, optiontitle, options)
                        if screen.inpt is '1':
                            playerscity = (
                                races.races[playerrace]["city"]).upper()
                            playersplanet = races.races[playerrace]["planet"]
                            playerssystem = races.races[playerrace]["system"]
                            choosenrace = races.races[playerrace][
                                "singularname"]

                        else:
                            racechoice2(playerrace)
                    else:
                        racechoice()

                racechoice2(playerrace)

            racechoice()

        elif screen.inpt is '2':
            screename = f'STEORA'
            text = f'What is your name?'
            optiontitle = 'LOAD GAME'
            options = '...........................................................................\n' \
                     '..............................TYPE YOUR NAME...............................\n' \
                     '...........................................................................\n' \
                     '...........................................................................'

            screen.screen(screename, text, optiontitle, options)
            while screen.inpt is '':
                optiontitle = 'INVALID NAME!'
                screen.screen(screename, text, optiontitle, options)
            if os.path.exists(screen.inpt.lower() + '.p'):
                loaded = True
                savefile = f'{screen.inpt.lower()}.p'
            else:
                titlescreen()
        else:
            titlescreen()
    elif screen.inpt is '2':
        setting()
    elif screen.inpt is '3':
        screename = 'HELP'
        text= 'STEORA RPG its a text based game with the goal of space exploration,' \
               ' the options of action will appear bellow the main text.'
        optiontitle = ''
        options = '...........................................................................\n' \
                 '.............................ENTER TO GO BACK..............................\n' \
                 '...........................................................................\n' \
                 '...........................................................................'
        screen.screen(screename, text, optiontitle, options)
        titlescreen()
    elif screen.inpt is '4':
        screename = 'ABOUT'
        text = 'This is a working in progress project.'
        optiontitle = ''
        options = '...........................................................................\n' \
                 '.............................ENTER TO GO BACK;.............................\n' \
                 '...........................................................................\n' \
                 '...........................................................................'
        screen.screen(screename, text, optiontitle, options)
        titlescreen()
    elif screen.inpt is '5':
        sys.exit()
    elif screen.inpt is '9':
        return
    else:
        titlescreen()
Пример #25
0
import usercollection
import user
import screen

if __name__ == "__main__":

    s = screen.screen()

    while 1:
        if s.logged_in_user == None:
            s.mainScreen()
Пример #26
0
                def racechoice2(playerrace):
                    screename = f'{races.races[playerrace]["name"]}'

                    text = f'The {races.races[playerrace]["name"]} are original inhabitants of the planet {races.races[playerrace]["planet"]} in the {races.races[playerrace]["system"]} System. Physically {races.races[playerrace]["description"]}. The bonus of this race is {races.races[playerrace]["bonus"]} points in {races.races[playerrace]["attribute"]} and the innate skills: {races.races[playerrace]["skills"]}'

                    optiontitle = 'CONFIRM RACE?'

                    options = '..........1)CONFIRM.....................3)CULTURAL INFORMATION.............\n' \
                             '...........................................................................\n' \
                             '..........2)SKILLS INFORMATION.........................0)BACK..............\n' \
                             '...........................................................................'
                    screen.screen(screename, text, optiontitle, options)
                    global playersplanet
                    global playerssystem
                    global playerscity
                    global choosenrace
                    if screen.inpt is '1':
                        playerscity = (races.races[playerrace]["city"]).upper()
                        playersplanet = (
                            races.races[playerrace]["planet"]).upper()
                        playerssystem = (
                            races.races[playerrace]["system"]).upper()
                        choosenrace = races.races[playerrace]["singularname"]

                    elif screen.inpt is '2':
                        screename = f'{races.races[playerrace]["name"]}: SKILLS'

                        text = f'WIP'

                        optiontitle = 'CONFIRM RACE?'

                        options = '...........................................................................\n' \
                                 '...........1)CONFIRM....................................0)BACK.............\n' \
                                 '...........................................................................\n' \
                                 '...........................................................................'
                        screen.screen(screename, text, optiontitle, options)
                        if screen.inpt is '1':
                            playerscity = (
                                races.races[playerrace]["city"]).upper()
                            playersplanet = races.races[playerrace]["planet"]
                            playerssystem = races.races[playerrace]["system"]
                            choosenrace = races.races[playerrace][
                                "singularname"]

                        else:
                            racechoice2(playerrace)
                    elif screen.inpt is '3':
                        screename = f'{races.races[playerrace]["name"]}: CULTURE'

                        text = f'The {races.races[playerrace]["name"]} {races.races[playerrace]["culture"]}'

                        optiontitle = 'CONFIRM RACE?'

                        options = '...........................................................................\n' \
                                 '...........1)CONFIRM....................................0)BACK.............\n' \
                                 '...........................................................................\n' \
                                 '...........................................................................'
                        screen.screen(screename, text, optiontitle, options)
                        if screen.inpt is '1':
                            playerscity = (
                                races.races[playerrace]["city"]).upper()
                            playersplanet = races.races[playerrace]["planet"]
                            playerssystem = races.races[playerrace]["system"]
                            choosenrace = races.races[playerrace][
                                "singularname"]

                        else:
                            racechoice2(playerrace)
                    else:
                        racechoice()
Пример #27
0
            def racechoice():
                text = f"{playername}! Right... And which race you'll choose? Each race has a bonus in certain attribute and starts in a different planet!                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Races with bonus in Agility: Humans, Kal-shon, Zayolin                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Races with bonus in Dexterity: Alnits, Droides, Zorahtos                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Races with bonus in Intelligence: Kaitos, Lattuns, Ophidianos                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Races with bonus in Luck: Destanis, Nephinos, Svastos                            ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Choose a race to know more, don't worry, you can come back to here later!"

                optiontitle = ''
                options = '.....1)HUMANS..................2)KAL-SHON..................3)ZAYOLIN.......\n' \
                         '.....4)ALNITS..................5)DROIDES...................6)ZORAHTOS......\n' \
                         '.....7)KAITOS..................8)LATTUNS...................9)OPHIDIANOS....\n' \
                         '.....10)DESTANIS...............11)NEPHINOS.................12)SVASTOS......'
                screen.screen(screename, text, optiontitle, options)
                global playerrace
                playerrace = screen.inpt

                while screen.inpt not in [
                        '1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
                        '11', '12'
                ]:
                    optiontitle = 'INVALID OPTION'
                    screen.screen(screename, text, optiontitle, options)
                    playerrace = screen.inpt

                def racechoice2(playerrace):
                    screename = f'{races.races[playerrace]["name"]}'

                    text = f'The {races.races[playerrace]["name"]} are original inhabitants of the planet {races.races[playerrace]["planet"]} in the {races.races[playerrace]["system"]} System. Physically {races.races[playerrace]["description"]}. The bonus of this race is {races.races[playerrace]["bonus"]} points in {races.races[playerrace]["attribute"]} and the innate skills: {races.races[playerrace]["skills"]}'

                    optiontitle = 'CONFIRM RACE?'

                    options = '..........1)CONFIRM.....................3)CULTURAL INFORMATION.............\n' \
                             '...........................................................................\n' \
                             '..........2)SKILLS INFORMATION.........................0)BACK..............\n' \
                             '...........................................................................'
                    screen.screen(screename, text, optiontitle, options)
                    global playersplanet
                    global playerssystem
                    global playerscity
                    global choosenrace
                    if screen.inpt is '1':
                        playerscity = (races.races[playerrace]["city"]).upper()
                        playersplanet = (
                            races.races[playerrace]["planet"]).upper()
                        playerssystem = (
                            races.races[playerrace]["system"]).upper()
                        choosenrace = races.races[playerrace]["singularname"]

                    elif screen.inpt is '2':
                        screename = f'{races.races[playerrace]["name"]}: SKILLS'

                        text = f'WIP'

                        optiontitle = 'CONFIRM RACE?'

                        options = '...........................................................................\n' \
                                 '...........1)CONFIRM....................................0)BACK.............\n' \
                                 '...........................................................................\n' \
                                 '...........................................................................'
                        screen.screen(screename, text, optiontitle, options)
                        if screen.inpt is '1':
                            playerscity = (
                                races.races[playerrace]["city"]).upper()
                            playersplanet = races.races[playerrace]["planet"]
                            playerssystem = races.races[playerrace]["system"]
                            choosenrace = races.races[playerrace][
                                "singularname"]

                        else:
                            racechoice2(playerrace)
                    elif screen.inpt is '3':
                        screename = f'{races.races[playerrace]["name"]}: CULTURE'

                        text = f'The {races.races[playerrace]["name"]} {races.races[playerrace]["culture"]}'

                        optiontitle = 'CONFIRM RACE?'

                        options = '...........................................................................\n' \
                                 '...........1)CONFIRM....................................0)BACK.............\n' \
                                 '...........................................................................\n' \
                                 '...........................................................................'
                        screen.screen(screename, text, optiontitle, options)
                        if screen.inpt is '1':
                            playerscity = (
                                races.races[playerrace]["city"]).upper()
                            playersplanet = races.races[playerrace]["planet"]
                            playerssystem = races.races[playerrace]["system"]
                            choosenrace = races.races[playerrace][
                                "singularname"]

                        else:
                            racechoice2(playerrace)
                    else:
                        racechoice()

                racechoice2(playerrace)
Пример #28
0
 def run(self):
     # Si on est en Wi-Fi, on se connecte au telephone
     if self.fenetre.choixconnection.get() == 2:
         self.fenetre.setInstruction("Connection au telephone.")
         adb.Connect(self.fenetre.IPvalue.get())
     # pour informer l'utilisateur
     self.fenetre.setInstruction("Démarrage de l'oscilloscope.")
     # on demarre l'oscilloscope
     if int(self.choixOscillo) == 2:
         if platform.system() != "Windows":
             Mesure = MM.Monsoon()
         else:
             self.fenetre.setInstruction("Le Monsoon n'est actuellement pas supporte par Windows")
             return
     else:
         Mesure = OEC.OscilloscopeEnergyCollector(self.valeurfrequence, self.fenetre)
     # Si on choisi le robot pour effectuer le test
     if self.choixRobot == 1:
         # Creation de la pile d'actions du robot
         api = dType.load()
         # Connection au  Dobot
         state = dType.ConnectDobot(api, "", 115200)[0]
         # si le robot est dans le bon etat
         if (state == dType.DobotConnect.DobotConnect_NotFound):
             self.fenetre.setInstruction(
                 "Veuillez brancher le Dobot Magician ou installez les\ndrivers correspondants.")
             return
         elif (state == dType.DobotConnect.DobotConnect_Occupied):
             self.fenetre.setInstruction("Veuillez liberer le port USB du robot et Reessayer.")
             return
         else:
             self.fenetre.setInstruction("Dobot Magician bien connecte. Demarrage du test.")
             # on initialise le robot
             Dfonct.SpeedInit(api)
             Dfonct.Init(api)
             # on demande au robot la valeur minimum de Z
             Z_min = Dfonct.Calc_Z_Min(api, self.fenetre)
             # on entre les données de notre écran
             ecran = screen.screen(api, self.largueur, self.longueur, self.fenetre)
     else:
         self.fenetre.setInstruction("Mode sans robot. Demarrage du test.")
     # on regarde si nous faisons le test sur un ou plusieurs scénarios
     Filelist = []
     if self.tousScenarios == 1:
         for fichier in sorted(os.listdir('scenarios/')):
             Filelist.append(fichier)
     else:
         Filelist.append(self.scenar + ".sim")
     # on test le nombre de scénarios souhaités
     num_scenar = -1
     for scenars in Filelist:
         num_test = 0
         num_scenar += 1
         if alreadydone(scenars, int(self.repetition)):
             continue
         # recuperer les valeurs utiles du scénarios
         apk, package, occurenceInit, languageinit, language = DecoupageScenarios(scenars)
         # on recupere le chemin absolu de l'apk
         try:
             if self.choixDebug == 0:
                 chemin = os.path.abspath("./apk/nodebug/" + apk + ".apk")
             else:
                 chemin = os.path.abspath("./apk/debug/" + apk + ".apk")
         except:
             self.fenetre.setInstruction(
                 "l'apk specifie en ligne 1 dans le dossier scenario \nn'est pas presente dans le dossier apk. \nVeuillez l'ajouter ou modifier son nom.")
             return
         if self.powertran == 1:
             self.fenetre.setInstruction("installation de l'apk PowerTran...")
             adb.installApk("./ressources/powertran/powertran.apk")
         self.fenetre.setInstruction("installation de l'apk...")
         if self.choixRobot == 1:
             adb.installApk(chemin)
         else:
             adb.installApk("./apk/debug/" + apk + ".apk")
             adb.installApk("./apk/robotium/" + apk + ".apk")
         # on fait tourner l'application une premiere fois
         self.fenetre.setInstruction("test preliminaire de l'apk...")
         if self.choixRobot == 1:
             for j in range(0, int(occurenceInit)):
                 # on démarre l'application
                 adb.startApk(apk, package)
                 time.sleep(5)
                 # on supprime les evenements exceptionnels
                 robot.Robot(api, ecran, self.fenetre, Z_min, languageinit).action()
                 time.sleep(5)
                 # On ferme l'application
                 adb.closeApk(apk)
         else:
             # on démarre l'application
             adb.startApk(apk, package)
             time.sleep(10)
             # On ferme l'application
             adb.closeApk(apk)
         self.fenetre.setInstruction("test de l'application...")
         # On demarre le test de l'application
         for i in range(1, int(self.repetition) + 1):
             num_test += 1
             # On regarde si le fichier existe deja
             if os.path.exists("./results/" + apk + "-" + str(i) + ".csv"):
                 continue
             # on tient au courant l'utilisateur
             self.fenetre.setInstruction("etape " + str(i) + "/" + str(int(self.repetition)) + " : En cours")
             if self.powertran == 1:
                 adb.startApk("powertran", "powertran.start")
                 robot.Robot(api, ecran, self.fenetre, Z_min, "").action()
                 adb.closeApk("powertran")
             # on recupere la temperature et frequence du processeur avant test
             temp1 = 1
             freq1 = 1
             # on force la luminosité au minimum pour l'homogeneïté des tests
             adb.Luminosity(0)
             # on place le robot en position (pour toujours commencer au même endroit)
             if self.choixRobot == 1:
                 robot.Robot(api, ecran, self.fenetre, Z_min, "mov(" + str(int(ecran.pixelwidth) / 2) + "," + str(
                     int(ecran.pixelheight) / 2) + ")").action()
             # On démarre l'oscilloscope sélectionné
             Mesure.start("./results/" + apk + "-" + str(i) + ".csv")
             # si on utilise le robot
             if self.choixRobot == 1:
                 # on démarre l'application
                 adb.startApk(apk, package)
                 # temps de pause par sécurité
                 time.sleep(1)
                 # On execute notre scénario complet
                 robot.Robot(api, ecran, self.fenetre, Z_min, language).action()
                 # On ferme l'application
                 adb.closeApk(apk)
             # si on utilise pas le robot
             else:
                 if self.choixDebug == 0:
                     adb.RobotiumTest(False, apk)
                 else:
                     adb.RobotiumTest(True, apk)
             # On tient au courant l'utilisateur
             self.fenetre.setInstruction("etape " + str(i) + "/" + str(int(self.repetition)) + " : Enregistrement")
             # On arrete et sauvegarde la mesure d'energie
             Mesure.stop(True, temp1, freq1, 1, 1)
             # on met à jour la barre de chargement
             self.fenetre.setpourcent(100.*(num_scenar+(num_test/float(self.repetition)))/len(Filelist))
         # Si on utilise la methode powertran
         if self.powertran == 1:
             self.fenetre.setInstruction("desinstallation de l'apk PowerTran...")
             adb.uninstallApk("powertran")
         # On tient au courant l'utilisateur
         self.fenetre.setInstruction("desinstallation de l'apk...")
         # Une fois que tout est fait, on désinstalle l'application
         if self.choixRobot == 0:
             adb.uninstallApk(apk + ".test")
             adb.uninstallApk(apk)
         else:
             adb.uninstallApk(apk)
     # On tient au courant l'utilisateur
     self.fenetre.setInstruction("Les mesures ont ete enregistrees dans\nle dossier results.")
     # on deconnecte le robot
     if self.choixRobot == 1:
         dType.DisconnectDobot(api)
Пример #29
0
def main(count=6):
    db = SQL(count)
    device = screen()
    loop(db,device)
    device.cleanup()
def acquire_images(cam, nodemap, nodemap_tldevice, api):
    """
    This function shows images from a device.

    :param cam: Camera to acquire images from.
    :param nodemap: Device nodemap.
    :param nodemap_tldevice: Transport layer device nodemap.
    :type cam: CameraPtr
    :type nodemap: INodeMap
    :type nodemap_tldevice: INodeMap
    :return: True if successful, False otherwise.
    :rtype: bool
    """

    print('*** IMAGE ACQUISITION ***\n')
    try:

        result = True
        centroids = None
        centroidsTouches = None
        stats = None
        screen_size = [0, 0]
        ecran = None
        z_min = None
        M = None
        hello_im = None

        keyboard = cv2.imread('./clavier.jpg')
        keyboard = cv2.cvtColor(keyboard, cv2.COLOR_BGR2GRAY)

        # Set acquisition mode to continuous
        #
        #  Retrieve enumeration node from nodemap

        # In order to access the node entries, they have to be casted to a pointer type (CEnumerationPtr here)
        node_acquisition_mode = PySpin.CEnumerationPtr(
            nodemap.GetNode('AcquisitionMode'))
        if not PySpin.IsAvailable(
                node_acquisition_mode) or not PySpin.IsWritable(
                    node_acquisition_mode):
            print(
                'Unable to set acquisition mode to continuous (enum retrieval). Aborting...'
            )
            return False, hello_im, z_min, ecran

        # Retrieve entry node from enumeration node
        node_acquisition_mode_continuous = node_acquisition_mode.GetEntryByName(
            'Continuous')
        if not PySpin.IsAvailable(
                node_acquisition_mode_continuous) or not PySpin.IsReadable(
                    node_acquisition_mode_continuous):
            print(
                'Unable to set acquisition mode to continuous (entry retrieval). Aborting...'
            )
            return False, hello_im, z_min, ecran

        # Retrieve integer value from entry node
        acquisition_mode_continuous = node_acquisition_mode_continuous.GetValue(
        )

        # Set integer value from entry node as new value of enumeration node
        node_acquisition_mode.SetIntValue(acquisition_mode_continuous)

        print('Acquisition mode set to continuous...')

        #  Begin acquiring images
        cam.BeginAcquisition()

        print('Acquiring images...')

        #  Retrieve device serial number
        device_serial_number = ''
        node_device_serial_number = PySpin.CStringPtr(
            nodemap_tldevice.GetNode('DeviceSerialNumber'))
        if PySpin.IsAvailable(node_device_serial_number) and PySpin.IsReadable(
                node_device_serial_number):
            device_serial_number = node_device_serial_number.GetValue()
            print('Device serial number retrieved as %s...' %
                  device_serial_number)

        # Retrieve, convert, and show images
        cv2.namedWindow('im', cv2.WINDOW_NORMAL)
        print(
            "Please ensure you have calibration screen image downloaded. Then put it in full screen to get started."
        )
        print(
            "Please use keyboard :\n\t- press c to calibrate\n\t- press y to extract screen after calibration\n\t- press e to segment the screen after extracted\n\t- press q when you are done (with a correct segmentation).\nYou can extract a new screen (y) and segment it (e) as long as you are not satisfied with the result. Playing with screen brightness and camera focus may help."
        )
        while (1):
            try:

                #  Retrieve next received image
                image_result = cam.GetNextImage()

                #  Ensure image completion
                if image_result.IsIncomplete():
                    print('Image incomplete with image status %d ...' %
                          image_result.GetImageStatus())

                else:
                    # Retrieve image width and height
                    width = image_result.GetWidth()
                    height = image_result.GetHeight()

                    # Convert image to uint8 numpy array
                    row_bytes = float(len(image_result.GetData())) / width
                    rawFrame = np.array(image_result.GetData(),
                                        dtype="uint8").reshape(height, width)
                    # Convert image to BGR
                    im = cv2.cvtColor(rawFrame, cv2.COLOR_BAYER_BG2BGR)

                    # Display image in window 'im'
                    cv2.imshow('im', im)
                    k = cv2.waitKey(10) & 0xFF
                    if k == ord('q'):  # Press 'q' to exit
                        cv2.destroyAllWindows()
                        break
                    elif k == ord('c'):
                        print(
                            "Processing... Please wait... This will take less than a minute..."
                        )
                        # Denoise image
                        dst = cv2.fastNlMeansDenoisingColored(
                            im, None, 10, 10, 7, 21)
                        # Calibrate camera
                        centroids = CamCalibrate(dst)
                        # Retrieve screen size
                        screen_size = size(centroids)
                        # Initialize robot
                        Dfonct.Init(api)
                        # Get the height of the screen's plane
                        z_min = Dfonct.Calc_Z_Min(api)
                        Dfonct.Touch(api, z_min)
                        # Launch robot calibration
                        ecran = screen.screen(api, screen_size[0],
                                              screen_size[1])
                        Dfonct.Touch(api, z_min)

                    elif k == ord('y') and centroids is not None:
                        # Extract image of the screen
                        im2 = resizeScreen(im, centroids)
                        # Search keyboard in screen image
                        im3, M = findKeyboard(im2, keyboard)
                        if M is not None:
                            # Show position of the keyboard
                            cv2.imshow('keyboard detection', im3)
                            # Get the positions to press to type 'hello world' on the screen
                            hello_im = helloCoord(M, centroids)

                    #  Release image
                    image_result.Release()

            except PySpin.SpinnakerException as ex:
                print('Error: %s' % ex)
                return False, hello_im, z_min, ecran

        #  End acquisition
        cam.EndAcquisition()

    except PySpin.SpinnakerException as ex:
        print('Error: %s' % ex)
        return False, hello_im, z_min, ecran

    return result, hello_im, z_min, ecran