Exemple #1
0
    def initGui(self):
        global gui
        #-----[Gui Init Code Here]-----#
        gui.start(e)

        gui.addButton("Quit", self.surf, (1300,10), "Quit", self.Quit)
        
        gui.addGraph("APM", self.surf, (1250, 10), (25, 25), 200, 0, 10)  #APM: Application Performance Meter
        gui.addGraphChannel("APM", 0, (0, 0,0))
        gui.addValueBox("FPS", self.surf, "FPS", (1125, 10) , size=36)

        gui.addFrame("QTIFrame", self.surf, "QTI Sensors", (10, 10), (200, 200), (0, 0, 255))
        gui.addQTIBWStrip("QTIStrip", self.surf, (20, 40), (180, 36))
        gui.addValueBox("QTIOuterLeftLabel",  self.surf, "QTI Outer Left", (20, 100) , size=24)
        gui.addValueBox("QTIInnerLeftLabel",       self.surf, "QTI Left", (20, 120) , size=24)
        gui.addValueBox("QTIMiddleLabel",     self.surf, "QTI Middle", (20, 140) , size=24)
        gui.addValueBox("QTIInnerRightLabel",      self.surf, "QTI Right", (20, 160) , size=24)
        gui.addValueBox("QTIOuterRightLabel", self.surf, "QTI Outer Right", (20, 180) , size=24)

        gui.addFrame("PingFrame", self.surf, "Ping", (10, 220), (200, 120), (0,0,255))
        gui.addProgressBar("PingL", self.surf, (20, 250), (180, 20), "Left Ping - ")
        gui.addProgressBar("PingM", self.surf, (20, 280), (180, 20), "Middle Ping - ")
        gui.addProgressBar("PingR", self.surf, (20, 310), (180, 20), "Right Ping - ")

        gui.addFrame("CompassFrame", self.surf, "Heading", (10, 350), (200, 200), (0, 0, 255))
        gui.addCompass("Heading", self.surf, (110, 460), 80)

        gui.addFrame("CoreFrame", self.surf, "Cores", (10, 560), (200, 200), (0,0,255))
        gui.addProgressBar("LogicSpeed", self.surf, (20, 590), (180, 20), "Logic - ")
        gui.addProgressBar("Sensor1Speed", self.surf, (20, 620), (180, 20), "Sensor 1 - ")
        gui.addProgressBar("Sensor2Speed", self.surf, (20, 650), (180, 20), "Sensor 2 - ")
        gui.addProgressBar("DebugSpeed", self.surf, (20, 710), (180, 20), "Debug - ")
        gui.addProgressBar("Sensor3Speed", self.surf, (20, 680), (180, 20), "Sensor 3 - ")
        gui.addValueBox("CogsUsed", self.surf, "Cores Used", (20, 733), color=(0,255,0), size=32, value=0)

        gui.addFrame("MotorFrame", self.surf, "Motors", (230, 10), (200, 200), (0,0,255))
        gui.addProgressBar("LeftMotorSpeed", self.surf, (240, 40), (180, 20), "Left Motor - ")
        gui.addProgressBar("ArmMotorSpeed", self.surf, (240, 70), (180, 20), "Arm Motor - ")
        gui.addProgressBar("RightMotorSpeed", self.surf, (240, 100), (180, 20), "Right Motor - ")
        gui.addValueBox("leftDirection", self.surf, "Left Direction", (240, 130), color=(0,255,0), size=20, value="Stopped")
        gui.addValueBox("rightDirection", self.surf, "Right Direction", (240, 145), color=(0,255,0), size=20, value="Stopped")
        gui.addValueBox("armDirection", self.surf, "Arm Direction", (240, 160), color=(0,255,0), size=20, value="Stopped")

        gui.addPictureBox("StatePictureBox", self.surf, "State", (230, 220), (540, 540), (0,0,255), "Seesaw.png")

        #gui.addMap("Map", self.surf, "Map", (650, 10), (400, 400), (0,0,255))

        gui.addFrame("CPALFrame", self.surf, "ColorPAL", (440, 10), (200, 200), (0,0,255))
        gui.addValueBox("LeftCpalRed", self.surf, "Left Red", (450, 40), color=(255, 0,0), size=30, value="0")
        gui.addValueBox("LeftCpalGreen", self.surf, "Left Green", (450, 60), color=(0, 255,0), size=30, value="0")
        gui.addValueBox("LeftCpalBlue", self.surf, "Left Blue", (450, 80), color=(0, 0,255), size=30, value="0")
        gui.addValueBox("RightCpalRed", self.surf, "Right Red", (450, 100), color=(255, 0,0), size=30, value="0")
        gui.addValueBox("RightCpalGreen", self.surf, "Right Green", (450, 120), color=(0, 255,0), size=30, value="0")
        gui.addValueBox("RightCpalBlue", self.surf, "Right Blue", (450, 140), color=(0, 0,255), size=30, value="0")

        gui.addFrame("MiscFrame", self.surf, "Misc. Info", (780, 220), (570, 270), (0,0,255))

        gui.addFrame("Shell", self.surf, "Interactive Console", (780, 500), (570, 260), (0,0,255))
        gui.addTextBox("TextBox1", self.surf, (790, 730), (550, 20), self.executeTextCommand)
        gui.addTextListBox("InteractiveConsole", self.surf, (790, 530), (550, 190), (255,0,0))
Exemple #2
0
def main():
    '''Main Driver Function'''
    global gameState
    initializeNoOfNodes()
    gui.start()
    global newGameFlag
    t.onscreenclick(setNewGameFlag)
    while (newGameFlag == 0):
        t.update()
    newGameFlag = 0
    gui.drawGameBoard()
Exemple #3
0
def main(args):
    try:
        opts, args = getopt.getopt(args, "hs", ["help", "start"])
    except getopt.GetoptError:
        print('Syntax error, try \"start.py -h\" or \"start.py --help\"')
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print(
                "start.py -h or -- help\t\tthis text\nstart.py -s or --start\t\tstart software"
            )
        elif opt in ("-s", "--start"):
            gui.start()
Exemple #4
0
def main(args):
    """
    Starts the migration process

    @param argv The arguments passed to the script
    """
    parser = optparse.OptionParser(usage="migrate1to2 [options] file|dir")
    parser.add_option(
        "-n",
        "--nobackups",
        action="store_true",
        default=False,
        help=
        "Don't write backups for modified files. WARNING: This operation cannot be undone, use with care"
    )
    parser.add_option("-g",
                      "--gui",
                      action="store_true",
                      default=False,
                      help="Starts the GUI")

    options, args = parser.parse_args(args)
    backup = not options.nobackups
    files = get_files(args[0])

    if options.gui:
        retcode = gui.start(args, options)
    else:
        retcode = migrate.run(files, backup)

    # Any clean up code
    return retcode
Exemple #5
0
def main():
    FORMAT = '%(asctime)s %(levelname)s:%(message)s'
    logging.basicConfig(filename='launcher.log',
                        level=logging.INFO,
                        filemode='w',
                        format=FORMAT)
    logging.info("Started logging...")

    args = parser.parse_args()
    if args.temp and args.current:
        TEMP_DIR = args.temp
        CURR_DIR = args.current

        logging.info("Step 5. Delete files in current")
        import os
        import shutil
        for file_name in os.listdir(CURR_DIR):
            file_path = os.path.join(CURR_DIR, file_name)
            try:
                if os.path.isfile(file_path):
                    os.remove(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                logging.error("Failed to delete: {} with error: {}".format(
                    file_path, e))

        logging.info("Step 6. Move Temp Path files to current")
        for file_name in os.listdir(TEMP_DIR):
            src_path = os.path.join(TEMP_DIR, file_name)
            dst_path = os.path.join(CURR_DIR, file_name)
            shutil.move(src_path, dst_path)

        executable = os.path.join(CURR_DIR, sys.argv[0])
        #os.execl(executable, executable, os.path.basename(executable))
        import psutil
        try:
            p = psutil.Process(os.getpid())
            for handler in p.get_open_files() + p.connections():
                os.close(handler.fd)
        except Exception as e:
            logging.error(e)
        os.execl(executable, executable)
        # 7. Launch current/launcher and resume normal operations

    import gui
    gui.start()
Exemple #6
0
def main():
    global max_sample_size

    stream = p.open(format=pyaudio.paFloat32,
                    channels=CHANNELS,
                    rate=RATE,
                    output=True,
                    input=True,
                    stream_callback=delay_callback)

    stream.start_stream()

    while stream.is_active():
        myGui.start()
        stream.stop_stream()
    stream.close()

    p.terminate()
def main():
    arguments = parse_arguments()
    quiet_mode = arguments['quiet_mode']
    app_mode = arguments['app_mode']

    if quiet_mode:
        LOGGER.setLevel(logging.INFO)
    else:
        LOGGER.setLevel(logging.DEBUG)

    if app_mode == 0:
        if gui.is_gui_available():
            gui.start(arguments)
        else:
            app_mode = 1
            LOGGER.error(
                'No PyQt library exists! Continuing to console mode...')

    if app_mode == 1:
        console.start(arguments)
Exemple #8
0
def main(args):
    """
    Starts the migration process

    @param argv The arguments passed to the script
    """
    parser = optparse.OptionParser(usage="migrate1to2 [options] file|dir")
    parser.add_option("-n", "--nobackups", action="store_true", default=False,
                      help="Don't write backups for modified files. WARNING: This operation cannot be undone, use with care")
    parser.add_option("-g", "--gui", action="store_true", default=False,
                      help="Starts the GUI")

    options, args = parser.parse_args(args)
    backup = not options.nobackups
    files = get_files(args[0])

    if options.gui:
        retcode = gui.start(args, options)
    else:
        retcode = migrate.run(files, backup)

    # Any clean up code
    return retcode
Exemple #9
0
    else:
        log.error(f"path is not a file or does not exist {args.config}")
        log.debug("using default config path")

# parse config
if not config_file.is_file():
    log.error(f"cannot read {config_file}")
    sys.exit(1)

log.debug(f"reading config file {config_file}")
config = configparser.ConfigParser()
config.read(config_file)

# runtime data that should NOT be written
config.add_section("runtime_data")
config["runtime_data"]["config_path"] = str(config_file)

# S T A R T

if args.version:
    print(f"""Version {MUDDLE_VERSION}
Muddle Copyright (C) 2020-2021 Nao Pross <*****@*****.**>

This program comes with ABSOLUTELY NO WARRANTY; This is free software, and you
are welcome to redistribute it under certain conditions; see LICENSE.txt for
details. Project repository: https://github.com/NaoPross/Muddle
""")

if args.gui or config.getboolean("muddle", "always_run_gui"):
    gui.start(config)
Exemple #10
0
from gui import start


if __name__ == '__main__':
    start()
Exemple #11
0
def main():
    global root, gopt, glog
    gui.start(glog)
Exemple #12
0
# Getting all the images in the correct interval
trainingImages = np.asfarray(trainingData[:, 1:]) * adjust + 0.01
testImages = np.asfarray(testData[:, 1:]) * adjust + 0.01
# Getting all the labels in the correct order
trainingLabels = np.asfarray(trainingData[:, :1])
testLabels = np.asfarray(testData[:, :1])
# Organising data in a one-hot representation. This will use 0.01s and 0.99 as this is better for calculation
lr = np.arange(numberOfLabels)

trainingLabelsOneHot = (lr == trainingLabels).astype(np.float)
testLabelsOneHot = (lr == testLabels).astype(np.float)
# making sure 0.01s and 0.99s are used
# trainingLabelsOneHot[trainingLabelsOneHot == 0] = 0.01
# trainingLabelsOneHot[trainingLabelsOneHot == 1] = 0.99
# testLabelsOneHot[testLabelsOneHot == 0] = 0.01
# testLabelsOneHot[testLabelsOneHot == 1] = 0.99

timeTaken = datetime.now() - start
print("Time taken:", timeTaken)
# Here we will implement the neural network code and use it to train.
# The second value determines whether the network will be loaded from a file. To make it do a proper training session
# change it to False
neuralNetwork = nn.NeuralNetwork([784, 24, 24, 10], True,
                                 "data/weights[1].txt")
# Loss:0. 017221094251871984 for most trained one
# To edit the learning paces change the values in the learningPace.txt
neuralNetwork.trainNetwork(trainingImages, trainingLabelsOneHot, 100, 0.1,
                           0.017221094251871984)
neuralNetwork.testNetwork(testImages, testLabelsOneHot, 1)
gui.start(neuralNetwork)
Exemple #13
0
        start_sleep = time.clock()
        slep = start_time - time.clock()
        time.sleep(max(0, slep))
        if not max(0, slep):
            print((time.clock() - start_sleep) - slep)


def test(settings, update_func):
    pool2 = Pool(settings.cpucount)
    teststart = time.time() + 1
    results = []
    print("Starting run.")
    stressfunc = timestress if settings.method == 0 else linfreqstress
    for x in range(settings.cpucount):
        results.append(
            pool2.apply_async(stressfunc,
                              ("Process(" + str(x) + ")", teststart, settings,
                               settings.testtime + teststart)))
    while time.time() < teststart + settings.testtime:
        update_func(time.time() - teststart)  # TODO update in between
        time.sleep(0.5)
    for result in results:
        result.get()
    print("Run finished.")


if __name__ == "__main__":
    freeze_support()
    settings = Settings()
    gui.start(settings)
 def run(self):
     import gui
     gui.start(True)
Exemple #15
0
def menu1():
        canvas = pygame.display.set_mode((700,700))

        canvas.fill((0,0,0))

        startButton = pygame.image.load("buttons/start.png").convert_alpha()
        leftArrow = pygame.image.load("buttons/larrow.png").convert_alpha()
        rightArrow = pygame.image.load("buttons/rarrow.png").convert_alpha()
        creditButton = pygame.image.load("buttons/credits.png").convert_alpha()
        closeButton = pygame.image.load("buttons/Exit.png").convert_alpha()
        
        helloWorld = pygame.image.load("menu/VR.png").convert_alpha()
        robot = pygame.image.load("robots/robot.png").convert_alpha()
        robot = pygame.transform.scale(robot,(300,300))

        robot = pygame.transform.scale(robot,(200,200))

        bg = pygame.image.load("menu?wallpaper.jpg")
        bg = pygame.transform.scale(bg,(1107,700))

        soundDisabled = pygame.image.load("buttons/soundoff.png").convert_alpha()
        soundDisabled = pygame.transform.scale(soundDisabled,(35,50))
        soundEnabled = pygame.image.load("buttons/soundon.png").convert_alpha()
        soundEnabled = pygame.transform.scale(soundEnabled,(60,50))

        leftX = 10
        leftY = 300
        rightX = 100
        rightY = 300
        sX = 620
        sY = 640
        rX = 75
        rY = 200
        
        cX = 390
        cY = 400
        startX = 450
        startY = 300
        eX = 500
        eY = 500


        canvas.blit(bg, (0,0))
        canvas.blit(leftArrow, (leftX,leftY))
        canvas.blit(rightArrow, (rightY,rightY))
        canvas.blit(soundDisabled,(sX,sY))
        canvas.blit(robot,(rX,rY))
        canvas.blit(creditButton,(cX,cY))
        canvas.blit(helloWorld,(0,0))
        canvas.blit(startButton,(startX,startY))
        canvas.blit(closeButton,(eX,eY))


        r = startButton.get_rect()
        #print (r.width,r.height,r.x)

        sound = 0

        while True:
                for event in pygame.event.get():
                        if event.type == QUIT:
                                pygame.quit()
                                sys.exit()
                        if event.type == KEYDOWN :
                            if event.key == K_ESCAPE :
                                pygame.quit()
                                sys.exit()
                        pos = pygame.mouse.get_pos()
                        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 :                        
                            if collide(startX,startY,startButton,pos) == 1 :
                                pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)    
                                gui.start(canvas)
                                
                            elif collide(eX,eY,closeButton,pos) :
                                pygame.quit()
                                sys.exit()
                                    
                            elif sound == 0 and collide(sX,sY,soundDisabled,pos) == 1 :
                                sound = 1
                                canvas.blit(bg, (0,0))
                                canvas.blit(leftArrow, (leftX,leftY))
                                canvas.blit(rightArrow, (rightY,rightY))
                                canvas.blit(soundDisabled,(sX,sY))
                                canvas.blit(soundEnabled,(sX,sY))
                                canvas.blit(robot,(rX,rY))
                                canvas.blit(creditButton,(cX,cY))
                                canvas.blit(helloWorld,(0,0))
                                canvas.blit(startButton,(startX,startY))
                                canvas.blit(closeButton,(eX,eY))
                                break

                            elif sound == 1 and collide(sX,sY,soundEnabled,pos) == 1 :
                                sound = 0
                                canvas.blit(bg, (0,0))
                                canvas.blit(leftArrow, (leftX,leftY))
                                canvas.blit(rightArrow, (rightY,rightY))
                                canvas.blit(soundDisabled,(sX,sY))
                                canvas.blit(robot,(rX,rY))
                                canvas.blit(creditButton,(cX,cY))
                                canvas.blit(helloWorld,(0,0))
                                canvas.blit(startButton,(startX,startY))
                                canvas.blit(closeButton,(eX,eY))
                                break
                        
                            elif collide(cX,cY,creditButton,pos) :
                                    pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)
                                    creditMenu(canvas)
                                
                                
                        if collide(startX,startY,startButton,pos) == 1 or collide(cX,cY,creditButton,pos) == 1 or collide(sX,sY,soundDisabled,pos) or collide(eX,eY,closeButton,pos) :
                                pygame.mouse.set_cursor(*cursor.HAND_CURSOR)
                        else :
                                pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)
                        #rX += 1
                        #canvas.blit(robot,(rX,rY))
                pygame.display.update()
        return
Exemple #16
0
def menu1(canvas):
        #this variable is for checking if the start button was clicked
        inStart= 0
        
        #if the settings button was clicked
        inSettings= 0

        
#setting up the coordinates for the images and buttons        
        #left arrow
        leftX = 10
        leftY = 300
        
        #right arrow
        rightX = 280
        rightY = 300
        
        #sound
        sX = 720
        sY = 530
        
        #robot
        rX = 65
        rY = 200
                
        #credit button
        cX = 460
        cY = 370
        
        #start button
        startX = 480
        startY = 185
        
        #leaderboard button
        lX = 380
        lY = 315
        
        #close button
        eX = 500
        eY = 435
        
        #settings
        setX = 445
        setY = 245

#loading all images, buttons
        #robot = image(canvas,(rX,rY),"robots/robot.png")
        #robot.scale(300,300)
        #robot.scale(200,200)
        #transp = image(canvas,(10,140),"menu/transparrent.png")
        helloW = image(canvas,(60,0),"menu/VR.png")
        bgpart = image(canvas,(0,0),"menu/bgpart.png")
        background  = image(canvas,(0,0),"menu/wallpaper.jpg")
        startB = button(canvas,(startX,startY),"buttons/start.png")
        leftB = button(canvas,(leftX,leftY),"buttons/larrow.png")
        rightB = button(canvas,(rightX,rightY),"buttons/rarrow.png")
        soundOffB = button(canvas,(sX,sY),"buttons/soundoff.png")
        soundOffB.scale(35,50)
        soundOnB = button(canvas,(sX,sY),"buttons/soundon.png")
        soundOnB.scale(60,50)
        creditB = button(canvas,(cX,cY),"buttons/credits.png")
        leaderboardB = button(canvas,(lX,lY),"buttons/Leaderboard.png")
        closeB = button(canvas,(eX,eY),"buttons/exit.png")
        single = button(canvas,(73,250),"buttons/Single-Player.png")
        multi = button(canvas,(95,310),"buttons/Multiplayer.png")
        ai = button(canvas,(170,370),"buttons/AI.png")
        singleO = button(canvas,(73,250),"buttons/Single-PlayerO.png")
        multiO = button(canvas,(95,310),"buttons/MultiplayerO.png")
        aiO = button(canvas,(170,370),"buttons/AIO.png")
        settingsB = button(canvas,(setX,setY),"buttons/Settings.png")
        logo=image(canvas,(10,520),'logo/helloWorldStudio.png')

        font = pygame.font.SysFont("calibri",25)
        font1 = pygame.font.SysFont("calibri",15)

        font1.set_bold(1)
        font.set_bold(1)
        
        text = font.render("Receive Emails:",1,(250,250,250))
        text1 = font.render("Enter Email:",1,(250,250,250))
        text2 = font.render("Enter Name:",1,(250,250,250))

        easyTxt = font1.render("Easy",1,(250,250,250))
        medTxt = font1.render("Medium",1,(250,250,250))
        hardTxt = font1.render("Hard",1,(250,250,250))
        difTxt = font.render("AI Difficulty:",1,(250,250,250))

#blitting everything    
        canvas.fill((0,0,0))
        background.blit()
        #transp.blit() 
        leaderboardB.blit()
        creditB.blit()
        helloW.blit()
        closeB.blit()
        #robot.blit()
        startB.blit()
        soundOffB.blit()
        settingsB.blit()
        logo.blit()

#initializing the tickbox and textfields
        emailTickBox = TickBox.tickBox(canvas,(230,330))
        if Config.config["receiveEmail"] ==True:
                print "True"
                emailTickBox.status = 1
        emailTextField = textfield.textField(canvas,(20,270),(280,30),Config.config["email"],20)
        
        nameTextField = textfield.textField(canvas,(20,180),(280,30),Config.config["name"],20)
        
        easyBox = RadioButton.radioButton(canvas,(50,420))
        medBox = RadioButton.radioButton(canvas,(130,420))
        hardBox = RadioButton.radioButton(canvas,(210,420))
        if Config.config["difficulty"]==1:easyBox.status=1
        if Config.config["difficulty"]==2:medBox.status=1
        if Config.config["difficulty"]==3:hardBox.status=1

#no sound when the game run, this var will be set to 1 if the sound button clicked
        sound = 0
        ran = ""

        if sound == 1:
                soundOnB.blit()
                

        while True:
                for event in pygame.event.get():
                        #if user hits x button, window closes
                        if event.type == QUIT:
                                Config.saveConfig()
                                pygame.quit()
                                sys.exit()
                                
                        #if the user presses a key
                        if event.type == KEYDOWN :
                            #if esc key pressed, window closes
                            if event.key == K_ESCAPE :
                                Config.saveConfig()
                                pygame.quit()
                                sys.exit()
                       
                            #if we are in the settings menu
                            if inSettings== 1:
                                    
                                    #if the email textfield was clicked, user will write in it
                                    if emailTextField.isSelected():
                                            emailTextField.handle(event.key)
                                            print event.key
                                            
                                    #if the name textfield was clicked
                                    elif nameTextField.isSelected():
                                            nameTextField.handle(event.key)
                                            print event.key

                                            
                        #getting position of the mouse
                        pos = pygame.mouse.get_pos()
                        #update stored name and email
                        Config.config["email"] = emailTextField.answer
                        Config.config["name"] = nameTextField.answer
                        #if user pressed the left mouse button
                        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 :
                            #play click sound
                            soundFXs = Sounds.Audio(False)    
                            soundFXs.Plysound(False,False,True,False,False)
                            #if we are in the startmenu
                            if inStart== 1:
                                    if multi.clicked():
                                            gui.start(canvas,True,False,False,0,0)
                                    #if singleplayer button was clicked, start in single player mode
                                    if single.clicked():
                                            gui.start(canvas,False,False,False,0,0)
                                    #if ai button was clicked, start in ai mode
                                    elif ai.clicked():
                                            gui.start(canvas,False,False,True,Config.config["numAI"],Config.config["difficulty"])
                            #if we are in the settings menu
                            if inSettings== 1:
                                #if the email tickbox was clicked, untick/tick it
                                if emailTickBox.clicked():
                                        Config.config["receiveEmail"] = not Config.config["receiveEmail"] 

                                if easyBox.clicked():
                                        Config.config["difficulty"] = 1
                                        easyBox.check()
                                        medBox.unCheck()
                                        hardBox.unCheck()
                                        easyBox.blit()
                                        medBox.blit()
                                        hardBox.blit()
                                elif medBox.clicked():
                                        Config.config["difficulty"] = 2
                                        easyBox.unCheck()
                                        medBox.check()
                                        hardBox.unCheck()
                                        easyBox.blit()
                                        medBox.blit()
                                        hardBox.blit()
                                elif hardBox.clicked():
                                        Config.config["difficulty"] = 3
                                        easyBox.unCheck()
                                        medBox.unCheck()
                                        hardBox.check()
                                        easyBox.blit()
                                        medBox.blit()
                                        hardBox.blit()

                            #if email textfield was clicked, select it and unselect the other one
                                elif emailTextField.clicked():
                                            emailTextField.select()
                                            nameTextField.off()
                            #if name textfield clicked
                                elif nameTextField.clicked():
                                            nameTextField.select()
                                            emailTextField.off()
                                elif (easyBox.collide(pos) or
                                    medBox.collide(pos) or
                                    hardBox.collide(pos) or
                                    emailTextField.collide(pos) or
                                    nameTextField.collide(pos) or
                                    emailTickBox.collide(pos)):
                                        pygame.mouse.set_cursor(*cursor.HAND_CURSOR)
                                else :
                                        pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)
                                    


                            #if the start button was clicked
                            if startB.clicked() == 1 :
                                pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)
                                #we are in startmenu
                                inStart = 1
                                #not in settings menu
                                inSettings = 0

                                #reblit everything with the game mode buttons
                                background.blit()
                                #transp.blit()
                                leaderboardB.blit()
                                creditB.blit()
                                helloW.blit()
                                closeB.blit()
                                startB.blit()
                                soundOffB.blit()
                                logo.blit()
                                if sound == 1:
                                        soundOnB.blit()
                                settingsB.blit()
                                single.blit()
                                multi.blit()
                                ai.blit()

                            #if settings button clicked    
                            if settingsB.collide(pos):
                                pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)

                                inStart = 0
                                inSettings = 1
                                background.blit()
                                #transp.blit()
                                leaderboardB.blit()
                                creditB.blit()
                                helloW.blit()
                                closeB.blit()
                                startB.blit()
                                soundOffB.blit()
                                logo.blit()
                                if sound == 1:
                                        soundOnB.blit()
                                settingsB.blit()
                                
                                canvas.blit(text,(30,340))
                                canvas.blit(text1,(30,240))
                                canvas.blit(text2,(30,150))
                                emailTextField.blit()
                                nameTextField.blit()

                                canvas.blit(difTxt,(30,390))
                                emailTickBox.blit()
                                easyBox.blit()
                                medBox.blit()
                                hardBox.blit()

                                canvas.blit(easyTxt,(54,460))
                                canvas.blit(medTxt,(122,460))
                                canvas.blit(hardTxt,(213,460))

                                                                
                        #if close button was clicked, window closes
                            elif closeB.collide(pos) :
                                pygame.quit()
                                sys.exit()
                        #if sound button was clicked and it was off
                            elif sound == 0 and soundOffB.collide(pos) == 1 :
                                pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)
                                inStart= 0
                                sound = 1
                                bgpart.blit()
                                soundOffB.blit()
                                soundOnB.blit()
                                soundFXs.playMusic()       
                        
                        #if it was on
                            elif sound == 1 and soundOnB.collide(pos) == 1 :
                                inStart= 0
                                pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)
                                pygame.mixer.music.stop()
                                pygame.mixer.init(44100, -16,2,2048)
                                sound = 0
                                bgpart.blit()
                                soundOffB.blit()
                        
                            #if credit button clicked        
                            elif creditB.clicked() :
                                    pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)
                                    credit.creditMenu(canvas)

                            #if leaderboard button was clicked    
                            elif leaderboardB.clicked():
                                    pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)
                                    leaderboardMenu.leaderboardMenu(canvas)

                        #if we are in start menu
                        if inStart== 1:
                                #if collision with the game mode buttons, use hand cursor
                                if single.collide(pos):
                                        pygame.mouse.set_cursor(*cursor.HAND_CURSOR)
                                        singleO.blit()
                                elif multi.collide(pos):
                                        pygame.mouse.set_cursor(*cursor.HAND_CURSOR)
                                        multiO.blit()
                                elif ai.collide(pos):
                                        pygame.mouse.set_cursor(*cursor.HAND_CURSOR)
                                        aiO.blit()
                                #else use arrow
                                else :
                                        pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)
                                        single.blit()
                                        multi.blit()
                                        ai.blit()
                        #if collision with buttons, use hand cursor              
                        if (settingsB.collide(pos) == 1 or
                        startB.collide(pos) == 1 or
                        leaderboardB.collide(pos) == 1 or
                        creditB.collide(pos) == 1 or
                        soundOffB.collide(pos) or
                        closeB.collide(pos)):
                                pygame.mouse.set_cursor(*cursor.HAND_CURSOR)
                        else :
                                pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)
               
                        #print emailTickBox.getStatus(
                pygame.display.update()
        return
 def run(self):
     import gui
     gui.start(True)
import gui

gui.start()
a=input()
Exemple #19
0
 def run(self):
     import gui
     gui.set_send_message_callback(send_message)
     gui.start()
Exemple #20
0
def pc_client():
    os.chdir(envpath)
    import gui
    gui.start()
Exemple #21
0
def main():
    '''Main method of Endpoints application'''
    # Get path to the application's root folder
    file_path = inspect.getfile(inspect.currentframe())
    root_path = os.path.realpath(os.path.abspath(os.path.split(file_path)[0]))

    # Initialize logging module
    timestamp = timeutils.get_iso_timestamp()
    timestamp = timestamp.replace(':', '-')

    log_name = 'Log_%s.log' % timestamp
    log_dir = os.path.join(root_path, '.logs')

    try:
        os.makedirs(log_dir)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    log_path = os.path.join(log_dir, log_name)

    logging.basicConfig(filename=log_path,
                        filemode='w',
                        format='%(asctime)s'
                        ' %(levelname)s(%(name)s): %(message)s',
                        datefmt='%m/%d/%Y %H:%M:%S',
                        level=logging.DEBUG)

    logger = logging.getLogger(__name__)  # Retrieve module logger

    # Construct configuration path and load configuration
    config_path = os.path.join(root_path, 'config.json')
    c.Config.load(config_path)

    # Check if this if the first time running the application
    try:
        first_time_user = c.Config.get(c.ConfigEnum.NEW_USER)
    except KeyError:
        first_time_user = True

    if first_time_user:
        # Open window for registering user
        rf.RegistrationFrame.show()

    # Construct host's byte encoding
    try:
        encoding = c.Config.get(c.ConfigEnum.BYTE_ENCODING).strip()
    except KeyError:
        encoding = 'utf-8'  # Set default encoding
        c.Config.set(c.ConfigEnum.BYTE_ENCODING, encoding)  # Write to config

    logger.debug('Encoding: %s', encoding)

    # Construct host's GUID
    missing = False
    try:
        host_guid = c.Config.get(c.ConfigEnum.ENDPOINT_GUID)
    except KeyError:
        missing = True

    if missing or len(str(host_guid)) == 0:
        host_guid = uuid.uuid4().int  # Generate random GUID
        c.Config.set(c.ConfigEnum.ENDPOINT_GUID, host_guid)  # Write to config

    logger.debug('GUID: %s', str(host_guid))

    # Construct machine's NetID
    missing = False
    try:
        ep_name = c.Config.get(c.ConfigEnum.ENDPOINT_NAME).strip()
    except KeyError:
        missing = True

    if missing or len(ep_name) == 0:
        # Use machine name if none specified in configuration
        # Try to get machine name via env vars, fallback to platform.node
        ep_name = os.getenv('HOSTNAME',
                            os.getenv('COMPUTERNAME', platform.node()))

        c.Config.set(c.ConfigEnum.ENDPOINT_NAME, ep_name)

    host_netid = nid.NetID(host_guid, ep_name)
    logger.debug('NetID: %s', host_netid)

    # Retreive port numbers
    try:
        conn_port = c.Config.get(c.ConfigEnum.CONNECTION_PORT)
    except KeyError:
        conn_port = 3435
        c.Config.set(c.ConfigEnum.CONNECTION_PORT, conn_port)

    logger.debug('Connection Port: %d', conn_port)

    try:
        broadcast_port = c.Config.get(c.ConfigEnum.BROADCAST_PORT)
    except KeyError:
        broadcast_port = 3434
        c.Config.set(c.ConfigEnum.BROADCAST_PORT, broadcast_port)

    logger.debug('Broadcast Port: %d', broadcast_port)
    logger.info('Loaded configuration from %s', config_path)

    c.Config.write()  # Write config to disk since it may have been modified

    # Initialize map for tracking connected devices - {GUID: (name, socket)}
    connection_map = sd.SyncedDict()

    # Initialize data passing queues
    connection_bcast_queue = queue.Queue()  # Broadcasted connection requests
    ui_queue = queue.Queue()  # Data -> UI

    # Start data passing layer for getting data to/from the UI
    datapassing.start(ui_queue)

    # Start TCP connection manager
    cm.start(conn_port, host_guid, connection_map)
    logger.info("Connection manager service started")

    # Start UDP listener for connection broadcasts
    bcastl.start(broadcast_port, host_guid, connection_bcast_queue)
    logger.info('Broadcast listener service started')

    # Broadcast discovery message over network adapters
    bcast.execute(broadcast_port, host_guid, host_netid)
    logger.info('Discovery message broadcasting complete')

    # Start up UI in main thread (blocks until UI is exited)
    gui.start(ui_queue)

    # Shutdown
    cm.kill()
    bcastl.kill()
    datapassing.kill()

    # Write configuration back to disk
    c.Config.write()
from processing import multiProcess, singleProcess
import gui

def writeFrames(result, success):
    for frame in result:
        if len(frame) == 0:
            print 'Well it looks like there is an empty image. '+'Frame: '+str(i)
        success.write(frame[1])

if __name__ == '__main__':
    ######## Initialize Constants ########
    # framecount = 0.0;
    i = 0 ## Reads in comparison images
    file="Three_Objects_No_Point_Short.mp4"
    multi_flag=False
    img,file,multi_flag=gui.start()
    print img, file, multi_flag
    img = [cv2.imread(img[0], 0), cv2.imread(img[1],0)]
    videoData = datamani.createVideoData(open('Three_Objects_Raw_Data.txt', 'r')) ## Reads in data file

    capture_temp = cv2.VideoCapture(file)
    fileLen = int((capture_temp).get(cv2.CAP_PROP_FRAME_COUNT))  # opencv3
    fps = capture_temp.get(cv2.CAP_PROP_FPS) ##fps
    # print "fps"+str(fps)
    ret,temp=capture_temp.read(); ## Reads the first frame
    capture_temp.release()
    height, width = temp.shape[:2]
    # print "height"+str(height)
    # print "width"+str(width)
    # print "File length: "+ str(fileLen)
    capSize = (width,height) ## this is the size of my source video
Exemple #23
0
from gui import start

start()
def writeFrames(result, success):
    for frame in result:
        if len(frame) == 0:
            print 'Well it looks like there is an empty image. ' + 'Frame: ' + str(
                i)
        success.write(frame[1])


if __name__ == '__main__':
    ######## Initialize Constants ########
    # framecount = 0.0;
    i = 0  ## Reads in comparison images
    file = "Three_Objects_No_Point_Short.mp4"
    multi_flag = False
    img, file, multi_flag = gui.start()
    print img, file, multi_flag
    img = [cv2.imread(img[0], 0), cv2.imread(img[1], 0)]
    videoData = datamani.createVideoData(
        open('Three_Objects_Raw_Data.txt', 'r'))  ## Reads in data file

    capture_temp = cv2.VideoCapture(file)
    fileLen = int((capture_temp).get(cv2.CAP_PROP_FRAME_COUNT))  # opencv3
    fps = capture_temp.get(cv2.CAP_PROP_FPS)  ##fps
    # print "fps"+str(fps)
    ret, temp = capture_temp.read()
    ## Reads the first frame
    capture_temp.release()
    height, width = temp.shape[:2]
    # print "height"+str(height)
    # print "width"+str(width)
def get_gui():
    gui.start()
Exemple #26
0
def main(players, display_gui):
    if display_gui:
        import gui
        screen = gui.start()
    
    player_names = []
    for player in players:
        player_names.append(player.__file__.split('/')[-1])
    
    print("Starting game.")
    print("Players:", player_names)
    max_turns_per_round = MAX_NUM_TURNS_PER_PLAYER * len(players)
    
    total_scores = [0] * len(players)
    for rnd in range(1, 11): #12): # 11 rounds -> 10 rounds to make it faster
        print("\n\nStarting round " + str(rnd) + " (" + str(rnd+2) + " cards per player)")
        
        deck = get_deck() + get_deck()
        random.shuffle(deck)
        
        # deal cards to each player, removing them from deck
        hands = get_starting_hands(deck, len(players), rnd+2)
        
        stock = deck # rest of cards form deck
        discard_pile = [stock.pop()] # turn up one card from stock
                
        wildcard_rank = rnd   # round 1 = THREE (1); round 2 = FOUR (2), etc.
        
        winning_player = -1
        picked_up_discard_cards = []
        for i in range(len(players)):
            picked_up_discard_cards.append([])

        cur_player = 0
        num_turns_this_round = 0
        while True: # give each person a turn until round ends
            #print("Stock", hand_to_string(stock))
            #print("Discard pile", hand_to_string(discard_pile))
            
            if cur_player == winning_player:
                # play has come back around, so end the round
                print("Round over.")
                break
            elif num_turns_this_round > max_turns_per_round:
                print("Number of turns exceeded limit, ending round due to timeout.")
                break
            
            print("\n\nRound", rnd, "turn", num_turns_this_round, "(wildcard: " + RANKS_STR[wildcard_rank] + ")")
            player_won = player_turn(players[cur_player], player_names[cur_player], cur_player, hands[cur_player], discard_pile, stock, winning_player, picked_up_discard_cards, wildcard_rank, num_turns_this_round)
            #input("End of turn. Press [return] to continue.")
            if display_gui:
                gui.display(screen, hands, discard_pile[-1], total_scores)
            if player_won and winning_player == -1: # player arranged all their cards and no one has gone out yet
                print("Player has gone out. Giving everyone a final turn.")
                hands[cur_player] = []
                winning_player = cur_player # end the game at the winning player's next turn
            
            cur_player = (cur_player + 1) % len(players)
            num_turns_this_round += 1
        
        # round end
        print("\n\nEnd of round " + str(rnd) + ". Arranging everyone's hands.")
        input("Press [return] to continue.")
        
        # arrange players' hands as much as possible
        for cur_player in range(len(players)):
            arrangement = get_arrangement(tuple(sorted(hands[cur_player])), wildcard_rank)
            # remove all arranged cards from their hand
            for seq in arrangement:
                for card in seq:
                    hands[cur_player].remove(card) # removes first matching element
        
        # tally points of non-arranged cards
        round_end(player_names, hands, total_scores) # modifies total scores
        if display_gui:
            gui.display(screen, hands, total_scores)
        else:
            input("Press [return] to continue.")
    
    # determine winner
    winner = calculate_winner(total_scores)
    print("Player", winner, "has won!")
    if display_gui:
        gui.stop()
Exemple #27
0
def capt(driver):
    func.get_captcha(driver)
    guess = func.number()
    driver.find_element_by_id("captcha").clear()
    captcha = driver.find_element_by_id("captcha")
    captcha.send_keys(guess)
    driver.find_element_by_class_name("btn-submit").click()

options = webdriver.ChromeOptions()
options.add_argument("--headless")
#driver = webdriver.Chrome(chrome_options=options, executable_path='./chromedriver')
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://caselearn2.fju.edu.tw/cas/login?service=https%3A//elearn2.fju.edu.tw/login%3Fnext%3D/user/index&locale=zh_TW&ts=1607908465.74927")

ac, pa = gui.start()
login(driver, ac, pa)
capt(driver)

title = driver.title
times = 0
while title == "天主教輔仁大學 - 登入 Tronclass":
    if times <= 2:
        login(driver, ac, pa)
        capt(driver)
    else:
        ac, pa = gui.start()
        login(driver, ac, pa)
        capt(driver)
    title = driver.title
    times += 1
Exemple #28
0
def main():
    gui.start()
def unbind(winframe):
    map(lambda x:winframe.unbind(x),controls)

#Problem 20 - Is the game over or not
def is_game_over(game_board):
    size = len(grid) -1
    truth=True
    for r in range(4):
        for c in range(4):
            val = grid[r][c]
            if val == 0 or (r > 0 and grid[r-1][c] == val) or (c > 0 and grid[r][c-1] == val) or (r < size and grid[r+1][c] == val) or (c < size and grid[r][c+1] == val):
                return False
    if max(max(grid)) >= 2048:
        gui.game_over(game_board,True)
    else: 
        gui.game_over(game_board,False)
    return True
    
if __name__ == '__main__':
    """Your Program will start here"""

    frame, board = gui.setup()
    #Problem 17
    r,c = add_random_number(board)
    r,c = add_random_number(board)
    key = find_identifier(board,r,c)

    bind(frame,board)
    
    gui.start(frame)
Exemple #30
0
import gui
import signal
import thread
from remotehome import clients, event, events, inputs, outputs, gpio, security, cur, con, sensors, sensors_index, nogui, temp_sensors, light_sensors

security = security()
daemonize = False
for i in sys.argv:
    if i == "-nogui":
        nogui = True
    if i == "-D":
        daemonize = True
        nogui = True

if not nogui:
    gui.start()
if daemonize:
    gui.no_output = True

if __name__ == "__main__":
    # Get pins and set them up
    cur.execute("SELECT name, pin FROM outputs")
    data = cur.fetchall()
    for i in data:
        outputs[str(i['pin'])] = gpio(i['pin'], i['name'], "none", 'out')
        
    # Get inputs and set them up
    cur.execute("SELECT name, pin, type FROM inputs")
    data = cur.fetchall()
    for i in data:
        inputs[int(i['pin'])] = gpio(i['pin'], i['name'], i['type'], 'in')
Exemple #31
0
        for i in range(len(name)):
            if i % 2 != 0:
                if parts[i].startswith("$"):
                    entry = functions[parts[i].replace("$", "")]()
                else:
                    entry = random.choice(names[parts[i]])
                name[i] = entry[0]
                for att in entry[1]:
                    if att not in attributes.keys():
                        attributes[att] = entry[1][att]
        return str().join(name), attributes

    return built


if __name__ == '__main__':
    names = loadnames()
    tree = parsegens()
    gui.start(tree, functions)
    """patterns = ["{tulamiden_vor_m} ben {tulamiden_vor_m}", "{tulamiden_vor_m}, Töter von {$Weiden Männlich}"]
    weights = [1, 1]
    ident = "Novadi"
    makenames = genbuilder(patterns, weights, ident)
    patterns = ["{weiden_vor_m} {weiden_nach_pre}{weiden_nach_post}"]
    weights = [1]
    ident = "Weiden Männlich"
    genbuilder(patterns, weights, ident)
    for pr in range(1000):
        name, attrib = makenames()
        print(name, str(attrib).replace("{", "").replace("}", "").replace("'", ""), sep=" \t| ")"""