예제 #1
0
파일: gui.py 프로젝트: basilevs/varfill
 def create():
     root=Tk()        
     root.columnconfigure(0, weight=1)
     root.rowconfigure(0, weight=1)
     gui = Gui(mockControl(), root)
     gui.grid(sticky=E+W+S+N)
     return (root, gui)
예제 #2
0
def main():

    # Construct the objects that will run the game.
    courier = Courier()
    world = World(courier)
    gui = Gui(courier, world)

    systems = [courier, world, gui]

    # Connect to the server and wait until the game is ready to begin.
    courier.setup()
    courier.login(world.setup)

    # Open up a window and get ready to start playing.
    clock = pygame.time.Clock()
    frequency = 40

    gui.setup()
    
    # Play the game!
    while world.still_playing():
        time = clock.tick(frequency) / 1000
        for system in systems:
            system.update(time)

    # Exit gracefully.
    for system in systems:
        system.teardown()
예제 #3
0
 def __init__(self, mark_root, mark_travian):
     Gui.__init__(self)
     # tk
     self.root = mark_root
     # frame
     self.frame = Frame(self.root, bd=5, relief=GROOVE)
     # subframes
     self.send = Send(mark_root, mark_travian)
     self.offer = Offer(mark_root, mark_travian)
     # widgets
     self.label = Label(self.frame, text='Marketplace', font='font/Font 16 bold')
     self.margin = self.create_margin(self.frame)
예제 #4
0
 def __init__(self, gui, app):
     Gui.__init__(self)
     # tk
     self.root = gui
     self.travian = app
     # items
     self.news = None
     # frame
     self.frame = Frame(self.root, bd=5, relief=GROOVE)
     # widgets
     self.labels = self.create_labels()
     self.buttons = self.create_buttons()
예제 #5
0
파일: main.py 프로젝트: manna422/pool_sim
def main():
    print 'Simulation started.'

    # Test initial table
    table_data = read_datasheet('../mdata/sample_table.data')
    shot_sequence = read_player_data('../mdata/shots.data', table_data)
    tbl = Table(table_data, shot_sequence)

    spawn(tbl.loop)

    gui = Gui(tbl, 350, 700)
    gui.start()
예제 #6
0
class TPBattStat():
  def __init__(self, mode, forceDelay=None, forceIconSize=None):
    self.mode = mode
    self.forceDelay = forceDelay

    self.prefs = Prefs()
    self.battStatus = BattStatus(self.prefs)
    self.actions = Actions(self.prefs, self.battStatus)
    if self.mode == "gtk" or self.mode == "prefs":
      self.gui = Gui(self.prefs, self.battStatus)
    elif self.mode == "json" or self.mode == "dzen":
      self.guiMarkupPrinter = GuiMarkupPrinter(
        self.prefs, self.battStatus, forceIconSize)
      
  def getGui(self):
    return self.gui
  def startUpdate(self):
    self.curDelay = -1
    self.update()
  def update(self):
    try:
      self.prefs.update()
    except Exception as e:
      print 'ignoring prefs'
      print e.message
    if self.forceDelay != None:
      self.prefs['delay'] = self.forceDelay
    self.battStatus.update(self.prefs)

    self.actions.performActions()
    if self.mode == "gtk":
      self.gui.update()
    elif self.mode == "json" or self.mode == "dzen":
      try:
        if self.mode == "json":
          markup = self.guiMarkupPrinter.getMarkupJson()
        elif self.mode == "dzen":
          markup = self.guiMarkupPrinter.getMarkupDzen()
        print markup
        sys.stdout.flush()
      except IOError, e:
        print >> sys.stderr, "STDOUT is broken, assuming external gui is dead"
        sys.exit(1)

    if self.prefs['delay'] != self.curDelay:
      self.curDelay = self.prefs['delay']
      if self.curDelay <= 0:
        self.curDelay = 1000
      gobject.timeout_add(self.curDelay, self.update)
      return False
    else:
      return True
예제 #7
0
def start():
    while True:
        print "start"
        count = 1
        learnerarray = []
        for i in range(0,5):
            learnerarray.append(LTSBackend(count).getData())
            count = count + 1

        count = 1
        for i in learnerarray:
            Gui.setrow(win,i,count)
            count = count + 1
        sleep(10)
예제 #8
0
파일: __init__.py 프로젝트: xeirxes/pydemic
class Game():
    '''A class containing all major elements of the game engine. GUI, input, draw functions, current state, save/load,
    AI, map functions, as well as settings.'''

    def __init__(self):
        '''Initializes the Game class.'''
        self.clock = pygame.time.Clock()

        # Initialize display, state
        self.display, self.state = Display(), State(self)

        # Initialize GUI and scene
        self.gui, self.scene = Gui(self), Scene(self)

        # Initialize input
        self.input = Input(self)
        self.gui.mainMenu()

    def events(self):
        '''Handles events such as input, but also ingame events which raise dialogs.'''

        # Iterate over new events
        for event in pygame.event.get():

            # Quit
            if event.type == pygame.QUIT:
                sys.exit()
            else:
                self.input.handle(event)

    def update(self):
        '''Goes through updates on the game engine and manages time.

        :return:
        '''
        # Update each sprite group.
        self.gui.widgets.update()
        self.scene.sprites.update()

        # Refresh pygame's event list.
        pygame.event.pump()

        # Keep framerate at 30 fps.
        self.clock.tick(30)

    def draw(self):
        '''Send current sprites to be drawn on the display.'''
        self.display.draw(self.gui.widgets, self.scene.sprites)
예제 #9
0
파일: game.py 프로젝트: MJ-meo-dmt/rollin
 def __init__(self, _main):
     
     self.main = _main
     
     ## PHYSICS HANDLER ##
     self.physics = Physics(self)
     
     ## LEVEL LOADER ##
     self.currentLevelName = None
     self.levelloader = LevelLoader(self)
     self.currentLevelName = "startLevel2-extra"
     
     ## INPUT HANDLER
     self.input = Input(self)
     self.movementOption = '1'
     
     ## HANDLE PLAYER ##
     self.isPlayerActive = False
     self.player = {}
     self.activePlayerName = "player2"
     
     ## Start GuI ##
     self.gui = Gui(self)
     
     self.accept("doStart", self.startGame)
     
     ## GAME STATE VARIABLES ##
     self.isMoving = False
     self.isFloating = False
예제 #10
0
파일: main.py 프로젝트: matanaliz/PyLand
class Game(object):
    def __init__(self, width=1280, height=720, fps=120):
        pygame.init()

        self.width = width
        self.height = height
        self.screen = pygame.display.set_mode((width, height), pygame.DOUBLEBUF)
        self.background = pygame.Surface(self.screen.get_size()).convert()
        self.clock = pygame.time.Clock()
        self.fps = fps
        self.wave = 0

        self.font = pygame.font.Font(None, 30)
        self.score = 0

        self.event_dispatch = EventDispatcher()

        #Init all user interface staff
        self.gui = Gui()
        self.gui.set_event_dispatcher(self.event_dispatch)

        #Init all entities
        self.entities = Entities()
        self.entities.set_event_dispatcher(self.event_dispatch)

    def run(self):
        while True:
            event = pygame.event.poll()

            if event.type == pygame.QUIT:
                break

            self.clock.tick(self.fps)
            self.screen.fill(pygame.Color("#3d863d"))

            self.entities.update()
            self.gui.update()

            pygame.display.flip()

        pygame.quit()

    def display_gameover(self):
        font = pygame.font.Font(None, 72)
        text = font.render("WASTED", 1, (255, 255, 255))
        #TODO: Bad idea. Later: why? Comment more clearly
        self.screen.blit(text, (640, 360))
예제 #11
0
class ClientGame (Engine):
    """ Plays the game. Does not have any game logic. It send player input to
    the server which will eventually tell the client's game what to do. """
    # Constructor {{{1
    def __init__ (self, loop, forum, world):
        print 'C: Begin game engine.'
        Engine.__init__ (self, loop)

        self.forum = forum
        self.world = world
        
        # Set up the relays.
        publisher = self.forum.get_publisher()
        subscriber = self.forum.get_subscriber()

        self.reflex = Reflex(self, subscriber, self.world)
        self.player_relay = PlayerRelay(self, publisher, self.world)

        self.gui = Gui(self.world, self.player_relay)

    def setup (self):
        self.reflex.setup()
        self.player_relay.setup()
        self.gui.setup()

        self.forum.lock()
    
    # Update {{{1
    def update (self, time):
        self.forum.update()
        self.reflex.update(time)
        self.player_relay.update(time)
        self.world.update(time)
        self.gui.update(time)

    # Methods {{{1
    def game_over(self):
        # Called by the Reflex?
        print 'Game over.'
        self.exit_engine()

    def successor (self):
        self.forum.unlock()
        return ClientPostgame(self.loop, self.forum, self.world, self.gui)
    
    def teardown (self):
        time.sleep(1)
예제 #12
0
 def __init__(self, gui, app):
     Gui.__init__(self)
     # tk
     self.root = gui
     self.travian = app
     # frame
     self.frame = Frame(self.root, bd=5, relief=GROOVE)
     # items
     self.news = None
     self.stringvars = self.create_stringvars()
     # widgets
     self.labels = self.create_labels()
     self.buttons = self.create_buttons()
     self.spinboxes = self.create_spinboxes()
     # bools
     self.gather_attack_info = False
     self.flash_bg = False
예제 #13
0
파일: engine.py 프로젝트: copton/spytrain
    def __init__(self):
        self.option = "amount"
        self.options = {"amount":(5,0), "uptime":(20,0), "delay":(20,0), "alphas":self.alphas[self.alpha]}
        self.gui = Gui(self.key_event_handler)

	apply(self.gui.display_option, (), self.options)

        self.rnd = Random()
예제 #14
0
	def __init__(self):
		#self.ws_server = 'users.agh.edu.pl'
		self.ws_server = 'users.dsnet.agh.edu.pl'
		self.ws_port = 10001
		
		self.gui = Gui()
		
		self.tryConnect()
예제 #15
0
파일: pycss.py 프로젝트: ElanMan/PyCSS
 def __init__(self, master):
     self.gui = Gui(master)
     self.encodingerrors = []
     self.fetched_files = []
     self.used = []
     self.unused = []
     self.cssclasses = {}
     self.cssfilesnotfound = {}
     self.css_selectors = {}
예제 #16
0
 def __init__(self, gui, app):
     Gui.__init__(self)
     # tk
     self.root = gui
     self.travian = app
     # frames
     self.frame = Frame(self.root)
     # items
     self.news = None
     self.images = self.create_images()
     self.stringvars = self.create_stringvars()
     self.intvars = self.create_intvars()
     # widgets
     self.buttons = self.create_buttons()
     self.labels = self.create_labels()
     self.opt_menus = self.create_opt_menus()
     self.spin_boxes = self.create_spin_boxes()
     self.check_buttons = self.create_check_buttons()
예제 #17
0
파일: in.py 프로젝트: petryshend/flpy
def main():
    global only_with_photos
    gui = Gui()
    gui.start()
    only_with_photos = Gui.only_with_photos.get()
    while True:
        try:
            print "Start Mailer"
            mailer = Mailer(only_with_photos)
            mailer.start()
            print "Finished Successfully"
        except Exception:
            print "Something went wrong... Restarting..."
            mailer.close_mailer()
            time.sleep(10)
        else:
            print "Finished without exceptions"
            break
예제 #18
0
파일: main.py 프로젝트: soldierkam/pynews
def main():
    socket.setdefaulttimeout(60)
    mainDir = "/run/media/soldier/eea1ee1d-e5c4-4534-9e0b-24308315e271/pynews"
    tweetsDir = os.path.join(mainDir, "stream", "tweets")
    logger.info("Start app")
    model = None
    try:
        gui = Gui()
        mgr = StreamMgr(tweetsDir)
        model = Model(gui, stream=mgr.restore(lastOnly=False), mainDir=mainDir)
    except BaseException:
        logger.exception("Cannot start app")
        if model:
            model.stop()
        sys.exit(1)
        return
    gui.run()
    model.stop()
    logger.info("Exit app")
예제 #19
0
파일: othello.py 프로젝트: rgruener/othello
class Othello:

    def __init__(self):
        self.gui = Gui()
        self.setup_game()

    def read_board_file(self, file_name):
        f = open(file_name)
        lines = [line.strip() for line in f]
        f.close()
        board = np.zeros((8, 8), dtype=np.integer)
        # Read In Board File
        i = 0
        for line in lines[:8]:
            j = 0
            for char in line.split():
                board[i][j] = int(char)
                j += 1
            i += 1
        # Set Current Turn
        if int(lines[8]) == WHITE:
            self.now_playing, self.other_player = self.other_player, self.now_playing

        return board

    def setup_game(self):
        options = self.gui.show_options()
        if options['player_1'] == COMPUTER:
            self.now_playing = player.ComputerPlayer(BLACK, int(options['player_1_time']), self.gui)
        else:
            self.now_playing = player.HumanPlayer(BLACK, gui=self.gui)
        if options['player_2'] == COMPUTER:
            self.other_player = player.ComputerPlayer(WHITE, int(options['player_2_time']), self.gui)
        else:
            self.other_player = player.HumanPlayer(WHITE, gui=self.gui)
        if options.has_key('load_file'):
            self.board = board.Board(self.read_board_file(options['load_file']))
        else:
            self.board = board.Board()

    def run(self):
        self.gui.show_game(self.board)
        while True:
            winner = self.board.game_won()
            if winner is not None:
                break
            self.now_playing.set_current_board(self.board)
            if self.board.get_valid_moves(self.now_playing.color) != []:
                self.board = self.now_playing.get_move()
            self.gui.update(self.board, self.other_player)
            self.now_playing, self.other_player = self.other_player, self.now_playing
        self.gui.show_winner(winner, self.board)
        self.restart()

    def restart(self):
        self.setup_game()
        self.run()
예제 #20
0
def main(numFrames = -1):
    Constants.radius = 10.0
    Constants.numObstacles = 7
    Constants.numCharacters = 5
    Constants.worldDim = (512, 512)
    
    Constants.npcNames = ["Alice", "Bob", "Carol", "Dave"]
    
    # cflewis | 2008-11-02 | It would be nice to have a different colour,
    # but PyGame was only rendering this subset. Pretty annoying.
    Constants.npcColors = ["green", "red", "orange", "#ff00ff"]
    Constants.pcColorName = "blue"
    Constants.flashColorName = "white"
    Constants.backgroundName = "black"
    Constants.obstacleColorName = "white"

    commentator = Commentator()
    gs = commentator.get_observed_game_state(GameState(Constants.worldDim))
    gui = Gui(gs, Constants.backgroundName)

    sim = Simulator(gs)

    kb = Keyboard()

    setupCharacters(gs, gui, kb)

    setupObstacles(gs, gui)

    clock = pygame.time.Clock()

    while True:
        gui.render(gs)
        gs.incFrame()
        kb.processEvents()
        if kb.quit:
            break
        if 0 <= numFrames and numFrames <= gs.frame:
            break
        deltaT = clock.tick(30)/1000.0
        sim.forward(deltaT)

    gui.destroyWindow()
예제 #21
0
def main(argv=argv, cfg_file=cfg_file, update=1):
    """
    The function is the client entry point.
    """

    start_dir = os.getcwd()
    os.chdir(join(start_dir, dirname(argv[0]), dirname(cfg_file)))
    cfg_file = join(os.getcwd(), os.path.basename(cfg_file))
    loadConfiguration(cfg_file)
    os.chdir(start_dir)
    path.append(config['servers']['path'])
    path.append(config['configobj']['path'])

    # this import must stay here, after the appending of configobj path to path
    import storage
    storage.init(config['storage']['path'])

    # this import must stay here, after the appending of configobj path to path
    from gui import Gui
    try:
        app = QApplication([])
        app.setStyle(QStyleFactory.create("Cleanlooks"))

        gui = Gui(cfg_file)
        if not update:
            gui.displayWarning(PROJECT_NAME, gui._text['UpdateFail'])
        gui.show()
        exit(app.exec_())

    except Exception, e:
        print 'Fatal Exception:', e
        info = getExceptionInfo()
        fd = open(join(config['exceptions']['save_path'], 'exception.txt'), 'a+')
        fd.write(info)
        fd.close()

        if config['exceptions']['send_email']:
            try:
                sendMail("DevClient fatal exception: %s" % e, info)
            except Exception, e:
                print 'Error while sending email:', e
예제 #22
0
  def __init__(self, mode, forceDelay=None, forceIconSize=None):
    self.mode = mode
    self.forceDelay = forceDelay

    self.prefs = Prefs()
    self.battStatus = BattStatus(self.prefs)
    self.actions = Actions(self.prefs, self.battStatus)
    if self.mode == "gtk" or self.mode == "prefs":
      self.gui = Gui(self.prefs, self.battStatus)
    elif self.mode == "json" or self.mode == "dzen":
      self.guiMarkupPrinter = GuiMarkupPrinter(
        self.prefs, self.battStatus, forceIconSize)
예제 #23
0
 def __init__(self):
     Thread.__init__(self)
     self.count = 0
     self.voltage = 0
     self.state = "idle"
     self.batNb = int(input("Entrez le numéro de la batterie :"))
     self.fileName = ""
     self.com = BatMon()
     self.com.setPort('COM12')
     self.verrou = Lock()
     self.gui = Gui(self.verrou)
     self.start()
     self.gui.mainloop()
예제 #24
0
파일: guitests.py 프로젝트: michaellin/pong
 def setUp(self):
     self.root = Tk()
     self.gui = Gui(self.root)
     ball = moving.Ball()
     paddleL = moving.PaddleL()
     paddleR = moving.PaddleR()
     self.items = {
         'ball': ball,
         'paddleL': paddleL,
         'paddleR': paddleR,
         }
     for name, item in self.items.items():
         self.gui.addItem(name, item.getCoords())
예제 #25
0
파일: __init__.py 프로젝트: xeirxes/pydemic
    def __init__(self):
        '''Initializes the Game class.'''
        self.clock = pygame.time.Clock()

        # Initialize display, state
        self.display, self.state = Display(), State(self)

        # Initialize GUI and scene
        self.gui, self.scene = Gui(self), Scene(self)

        # Initialize input
        self.input = Input(self)
        self.gui.mainMenu()
예제 #26
0
    def __init__(self, args, **kwargs):
        super().__init__()

        analyzers = dict()

        self.analyzers = []
        self.files = []
        self.indices = []

        self.gui = Gui(**kwargs)
        self.gui.initGui(self)
        self.gui.addEditors(len(args))

        for i in range(len(args)):
            arg = args[i]
            arg = arg.split('@')
            input = arg[0]

            hostname = re.compile("^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?:[0-9]+$", re.IGNORECASE)
            if hostname.match(input):
                host, port = input.split(':')
                port = int(port)
                sock = socket.socket()
                sock.connect((host, port))
                self.files += [sock.makefile(mode="r")]
            else:
                self.files += [open(input, mode="r")]


            if len(arg) > 1:
                analyzer_name = arg[1]
            else:
                analyzer_name = DEFAULT_ANALYZER
            if len(arg) > 2:
                arg = '@'.join(arg[2:])
            else:
                arg = DEFAULT_ANALYZER_ARGS

            print("Analyzing %s by %s(%s)" %(input, analyzer_name, arg))

            if not analyzer_name in analyzers:
                package_name = "analyzers."+analyzer_name.lower()
                class_name = analyzer_name.capitalize()+"Analyzer"
                analyzers[analyzer_name] = getattr(__import__(package_name, fromlist=[class_name]), class_name)

            self.analyzers += [analyzers[analyzer_name](self.files[i].buffer, lambda time, value, i=i: self.gui.add(i, time, value), arg)]

        self.show()
        self.gui.start()
예제 #27
0
class Client:
"""Główna klasa klienta"""
	def __init__(self):
		#self.ws_server = 'users.agh.edu.pl'
		self.ws_server = 'users.dsnet.agh.edu.pl'
		self.ws_port = 10001
		
		self.gui = Gui()
		
		self.tryConnect()
		
	def tryConnect(self):
	"""Połączenie z domyślnym serwerem."""
		try:
			self.gui.display_splash_screen()
			
			print "ws://%s:%s" % (self.ws_server, self.ws_port)
			
			self.ws = create_connection("ws://%s:%s" % (str(self.ws_server), self.ws_port))
			
			self.gui.display_main_form(self)
		except socket.error:
			# jezeli nie mozesz sie polaczyc, to niech wpisze inne dane
			self.gui.display_connection_dialog(self)
	
	def askGoogle(self, topic):
	"""Wysłanie zapytania do serwera"""
		self.ws.send('askGoogle###' + topic)
		
		print "Sent: '%s'\n" % topic
		
		result =  self.ws.recv()
		
		print "Received\n"# % result
		
		# lista linkow w formacie (link, [(ocena, data), ...])
		return pickle.loads(result)
		
	
	def getSections(self):
		linkNo = raw_input("Pokaż tematy dla forum (wybierz numer linka): \n>>> ")
		try:
			int(linkNo)
			
			self.ws.send('getSections###'+linkNo)
			print "Sent: '%s'\n" % linkNo
			
			result =  self.ws.recv()
			
			print "Received: '%s'\n" % result
		except ValueError:
			print "Cza było wybrać numer"
	
	def close(self):
		self.ws.close()
		exit()
예제 #28
0
    def __init__ (self, loop, forum, world):
        print 'C: Begin game engine.'
        Engine.__init__ (self, loop)

        self.forum = forum
        self.world = world
        
        # Set up the relays.
        publisher = self.forum.get_publisher()
        subscriber = self.forum.get_subscriber()

        self.reflex = Reflex(self, subscriber, self.world)
        self.player_relay = PlayerRelay(self, publisher, self.world)

        self.gui = Gui(self.world, self.player_relay)
예제 #29
0
파일: game.py 프로젝트: vhp-jjh/online-tag
def main():
  if len(sys.argv) > 1:
    print(sys.argv[1])
    client = Client(Engine(), sys.argv[1], constants.SERVER_PORT)
  else:
    client = Client(Engine(), constants.SERVER_ADDR, constants.SERVER_PORT)

  gd = client.get_game_start_data()
  field = Gui(gd.width, gd.height, 1.0)
  engine = client.update_engine()
  players = engine.get_players()
  printd("CLIENT: players = {0}".format(players))
  game = Game(players) # TODO: figure out if we want to bother passing this

  # up, down, left, right
  dirs = (0, 0, 0, 0)
  while True:
    start_time = time.time()

    #get input
    dirs = game.get_input(dirs)

    #talk to server
    client.update_player(PlayerUpdate(dirs))    #send my velocity to the server
    engine = client.update_engine()
    game.players = engine.get_players()

    #draw
    field.fill_black()
    for p in game.players:
      field.draw_player(p.get_pos(), p.get_color(), gd.radius, p.is_it())
    pygame.display.flip()

    sleep_time = constants.LOOP_TIME - (time.time() - start_time)
    if sleep_time > 0:
      time.sleep(sleep_time)
예제 #30
0
    def __init__(self, handle):
        Activity.__init__(self, handle)

        # gobject is used for timeing (will be removed when rtp is implemented)
        gobject.threads_init()

        # Set if they started the activity
        self.isServer = not self._shared_activity

        # Let sugar know we only want a 1 to 1 share (limit to 2 people)
        # Note this is not enforced by sugar yet :(
        self.max_participants = 2

        #FIXME: This is a hack to only allow our ip to be sent once.
        #AKA disables others from double streaming
        if self.isServer:
            # server will send out ip twice, first when joinning empty channel
            # second when the user joins
            self.sent_ip = 2
        else:
            self.sent_ip = 1

        # INITIALIZE GUI
        ################
        self.set_title('OpenVideoChat')

        # Setup Gui
        ###########
        self.gui = Gui(self)
        self.gui.show()
        self.set_canvas(self.gui)

        # Setup Network Stack
        #####################
        self.netstack = SugarNetworkStack(self)
        self._sh_hnd = self.connect('shared', self.netstack.shared_cb)
        self._jo_hnd = self.connect('joined', self.netstack.joined_cb)

        # Setup Pipeline
        #################
        self.gststack = GSTStack(self.gui.send_video_to_screen)
        self.gststack.build_incoming_pipeline()
        gobject.idle_add(self.gststack.start_stop_incoming_pipeline, True)

        print "Activity Started"
예제 #31
0
#
#  PHYS 129 final project
#  Poisson's Spot
#  main program
#
#  May 23, 2018 created by Renjie Zhu
#

import sys
from gui import Gui
from info import Info
from PyQt5.QtWidgets import QApplication

app = QApplication(sys.argv)

main_window = Gui(title='Poisson\'s Spot')
main_window.start()
info = Info(title=main_window.INFO_TITLE)
info.info_window(main_window.POISSON_MESSAGE)

sys.exit(app.exec_())
예제 #32
0
class VirxERLU(BaseAgent):
    # Massive thanks to ddthj/GoslingAgent (GitHub repo) for the basis of VirxERLU
    # VirxERLU on VirxEC Showcase -> https://virxerlu.virxcase.dev/
    # Wiki -> https://github.com/VirxEC/VirxERLU/wiki
    def initialize_agent(self):
        self.tournament = False
        self.startup_time = time_ns()

        self.debug = [[], []]
        self.debugging = not self.tournament
        self.debug_lines = True
        self.debug_3d_bool = True
        self.debug_stack_bool = True
        self.debug_2d_bool = False
        self.show_coords = False
        self.debug_ball_path = False
        self.debug_ball_path_precision = 10
        self.disable_driving = False

        if not self.tournament:
            self.gui = Gui(self)
            self.print("Starting the GUI...")
            self.gui.start()

        self.match_comms = None

        self.print("Building game information")

        mutators = self.get_match_settings().MutatorSettings()

        gravity = (Vector(z=-650), Vector(z=-325), Vector(z=-1137.5),
                   Vector(z=-3250))

        base_boost_accel = 991 + (2 / 3)

        boost_accel = (base_boost_accel, base_boost_accel * 1.5,
                       base_boost_accel * 2, base_boost_accel * 10)

        boost_amount = ("default", "unlimited", "slow recharge",
                        "fast recharge", "no boost")

        self.gravity = gravity[mutators.GravityOption()]
        self.boost_accel = boost_accel[mutators.BoostStrengthOption()]
        self.boost_amount = boost_amount[mutators.BoostOption()]

        self.friends = ()
        self.foes = ()
        self.me = car_object(self.index)
        self.ball_to_goal = -1

        self.ball = ball_object()
        self.game = game_object()

        self.boosts = ()

        self.friend_goal = goal_object(self.team)
        self.foe_goal = goal_object(not self.team)

        self.stack = []
        self.time = 0

        self.ready = False

        self.controller = SimpleControllerState()

        self.kickoff_flag = False
        self.kickoff_done = True
        self.shooting = False
        self.best_shot_value = 92
        self.odd_tick = -1

        self.future_ball_location_slice = 180
        self.balL_prediction_struct = None

    def retire(self):
        # Stop the currently running threads
        if not self.tournament:
            self.gui.stop()

        if self.match_comms is not None:
            self.match_comms.stop()

    @staticmethod
    def is_hot_reload_enabled():
        # The tkinter GUI isn't compatible with hot reloading
        # Use the Continue and Spawn option in the GUI instead
        return False

    def get_ready(self, packet):
        field_info = self.get_field_info()
        self.boosts = tuple(
            boost_object(i, boost.location, boost.is_full_boost)
            for i, boost in enumerate(field_info.boost_pads))
        self.refresh_player_lists(packet)
        self.ball.update(packet)

        self.best_shot_value = math.floor((92.75 + self.me.hitbox.width / 2))
        self.print(f"Best shot value: {self.best_shot_value}")

        self.init()

        self.ready = True

        load_time = (time_ns() - self.startup_time) / 1e+6
        print(f"{self.name}: Built game info in {load_time} milliseconds")

    def refresh_player_lists(self, packet):
        # Useful to keep separate from get_ready because humans can join/leave a match
        self.friends = tuple(
            car_object(i, packet) for i in range(packet.num_cars)
            if packet.game_cars[i].team is self.team and i != self.index)
        self.foes = tuple(
            car_object(i, packet) for i in range(packet.num_cars)
            if packet.game_cars[i].team != self.team)
        self.me = car_object(self.index, packet)

        if len(self.friends) > 0 and self.match_comms is None:
            self.match_comms = MatchComms(self)
            self.print("Starting the match communication handler...")
            self.match_comms.start()

    def push(self, routine):
        self.stack.append(routine)

    def pop(self):
        return self.stack.pop()

    def line(self, start, end, color=None):
        if self.debugging and self.debug_lines:
            color = color if color is not None else self.renderer.grey()
            self.renderer.draw_line_3d(
                start.copy(), end.copy(),
                self.renderer.create_color(255, *color)
                if type(color) in {list, tuple} else color)

    def polyline(self, vectors, color=None):
        if self.debugging and self.debug_lines:
            color = color if color is not None else self.renderer.grey()
            vectors = tuple(vector.copy() for vector in vectors)
            self.renderer.draw_polyline_3d(
                vectors,
                self.renderer.create_color(255, *color)
                if type(color) in {list, tuple} else color)

    def print(self, item):
        if not self.tournament:
            print(f"{self.name}: {item}")

    def dbg_3d(self, item):
        self.debug[0].append(str(item))

    def dbg_2d(self, item):
        self.debug[1].append(str(item))

    def clear(self):
        self.shooting = False
        self.stack = []

    def is_clear(self):
        return len(self.stack) < 1

    def preprocess(self, packet):
        if packet.num_cars != len(self.friends) + len(self.foes) + 1:
            self.refresh_player_lists(packet)

        set(map(lambda car: car.update(packet), self.friends))
        set(map(lambda car: car.update(packet), self.foes))
        set(map(lambda pad: pad.update(packet), self.boosts))

        self.ball.update(packet)
        self.me.update(packet)
        self.game.update(self.team, packet)
        self.time = self.game.time
        self.gravity = self.game.gravity

        # When a new kickoff begins we empty the stack
        if not self.kickoff_flag and self.game.round_active and self.game.kickoff:
            self.kickoff_done = False
            self.clear()

        # Tells us when to go for kickoff
        self.kickoff_flag = self.game.round_active and self.game.kickoff
        self.ball_to_goal = self.friend_goal.location.flat_dist(
            self.ball.location)

        self.ball_prediction_struct = self.get_ball_prediction_struct()

        self.odd_tick += 1

        if self.odd_tick > 3:
            self.odd_tick = 0

    def get_output(self, packet):
        try:
            # Reset controller
            self.controller.__init__(use_item=True)

            # Get ready, then preprocess
            if not self.ready:
                self.get_ready(packet)

            self.preprocess(packet)

            if self.me.demolished:
                if not self.is_clear():
                    self.clear()
            elif self.game.round_active:
                try:
                    self.run(
                    )  # Run strategy code; This is a very expensive function to run
                except Exception:
                    print(self.name)
                    print_exc()

                if self.debugging:
                    if self.debug_3d_bool:
                        if self.debug_stack_bool:
                            self.debug[0] = itertools.chain(
                                self.debug[0], ("STACK:", ),
                                (item.__class__.__name__
                                 for item in reversed(self.stack)))

                        self.renderer.draw_string_3d(
                            self.me.location.tuple(), 2, 2,
                            "\n".join(self.debug[0]),
                            self.renderer.team_color(alt_color=True))

                        self.debug[0] = []

                    if self.debug_2d_bool:
                        if self.show_coords:
                            self.debug[1].insert(0,
                                                 str(self.me.location.int()))

                        if not self.is_clear(
                        ) and self.stack[0].__class__.__name__ in {
                                'Aerial', 'jump_shot', 'block_ground_shot',
                                'double_jump'
                        }:
                            self.dbg_2d(
                                round(self.stack[0].intercept_time - self.time,
                                      4))

                        self.renderer.draw_string_2d(
                            20, 300, 2, 2, "\n".join(self.debug[1]),
                            self.renderer.team_color(alt_color=True))
                        self.debug[1] = []

                    if self.debug_ball_path and self.ball_prediction_struct is not None:
                        self.polyline(
                            tuple(
                                Vector(ball_slice.physics.location.x,
                                       ball_slice.physics.location.y,
                                       ball_slice.physics.location.z)
                                for ball_slice in self.ball_prediction_struct.
                                slices[::self.debug_ball_path_precision]))
                else:
                    self.debug = [[], []]

                # run the routine on the end of the stack
                if not self.is_clear():
                    self.stack[-1].run(self)

                if self.is_clear() or self.stack[0].__class__.__name__ not in {
                        'Aerial', 'jump_shot', 'block_ground_shot',
                        'double_jump'
                }:
                    self.shooting = False

            return SimpleControllerState(
            ) if self.disable_driving else self.controller
        except Exception:
            print(self.name)
            print_exc()
            return SimpleControllerState()

    def handle_match_comm(self, msg):
        pass

    def run(self):
        pass

    def handle_quick_chat(self, index, team, quick_chat):
        pass

    def init(self):
        pass
예제 #33
0
import signal

from prodj import ProDj
from gui import Gui

default_loglevel = 0
default_loglevel = logging.DEBUG
#default_loglevel=logging.INFO
#default_loglevel=logging.WARNING

logging.basicConfig(level=default_loglevel,
                    format='%(levelname)s: %(message)s')

prodj = ProDj()
app = QApplication([])
gui = Gui(prodj)

pal = app.palette()
pal.setColor(QPalette.Window, Qt.black)
pal.setColor(QPalette.Base, Qt.black)
pal.setColor(QPalette.Button, Qt.black)
pal.setColor(QPalette.WindowText, Qt.white)
pal.setColor(QPalette.Text, Qt.white)
pal.setColor(QPalette.ButtonText, Qt.white)
pal.setColor(QPalette.Disabled, QPalette.ButtonText, Qt.gray)
app.setPalette(pal)

signal.signal(signal.SIGINT, lambda s, f: app.quit())

prodj.set_client_keepalive_callback(gui.keepalive_callback)
prodj.set_client_change_callback(gui.client_change_callback)
예제 #34
0
파일: client.py 프로젝트: hajdaini/GUI
 def window_input_for_username(self):
     self.gui = Gui(self)
     self.gui.window_config()
     self.gui.widget_for_username()
     self.gui.window.mainloop()
예제 #35
0
# This file keeps our classes seperated from our objects
from gui import Gui

# Starting the GUI
start_gui = Gui()
start_gui.mainloop()
예제 #36
0
def main():
    gui = Gui()
    gui.start()
예제 #37
0
from gui import Gui
from damier import Damier

interface = Gui()
interface.start()

y = input("Longeur ?")
x = input("Largeur ?")

nbgen = input("nb gen ?")

# Je n'arrive pas à importer la class Damier
for i in range(nbgen):
    damier.update()
    interface.updateGrid(damier.grid)

# Tentative de sauvegarde
#def Save (self) :
#Save = input("Sauvegarde ? (0/1)")
#while Save != 0 and Save != 1
#Save = input("Sauvegarde ? (0/1)")
#return Save
예제 #38
0
from config import ConfigStorage, get_config_file
from gui import Gui
from runner import Runner

config_storage = ConfigStorage(get_config_file())
stats_runner = Runner(config_storage.load())
gui = Gui(config_storage, stats_runner)
gui.run()
예제 #39
0
except IndexError:
    role = "sandbox"

# Figure out how to connect to the network.
try:
    host = sys.argv[2]
except IndexError:
    host = "localhost"

# Make sure all the arguments make sense.
if role not in ("host", "client", "sandbox"):
    sys.exit("The first argument must be 'host', 'client', or 'sandbox'.")

try:
    world = World()
    systems = [world, Gui(world), Network(world, role, host)]

    for system in systems:
        system.setup()

    clock = pygame.time.Clock()
    frequency = 40

    while world.is_playing():
        time = clock.tick(frequency) / 1000
        for system in systems:
            system.update(time)

    for system in systems:
        system.teardown()
예제 #40
0
import pickle
import random

from gui import Gui
from network import *
from settings import *

if not LOAD_DATA:
    pop = Population(POP_SIZE,
                     GENERATIONS,
                     LIFESPAN,
                     MUTATION_CHANCE,
                     MUTATION_RATE,
                     network_type=Genetic)

else:
    with open("Networks/" + LOAD_FILE, 'rb') as f:
        nets = pickle.load(f)
        pop = Population(POP_SIZE,
                         GENERATIONS,
                         LIFESPAN,
                         MUTATION_CHANCE,
                         MUTATION_RATE,
                         network_type=Genetic)
        pop.population = nets

# create the game object
g = Gui(pop)
g.new()
g.run()
예제 #41
0
 def __init__(self, scr: CursesWindow) -> None:
     self.delay = 0
     self.gui = Gui(scr)
     self.game = Gameplay(self.gui, self.gui.center)
예제 #42
0
    logging.critical("Uncaught exception",
                     exc_info=(exc_type, exc_value, exc_traceback))


if __name__ == "__main__":
    logging.config.fileConfig('logging.conf')
    sys.excepthook = handle_exception

    config_file = 'config.json'
    if not os.path.isfile(config_file):
        logging.error("Failed to find config file: %s", config_file)
        sys.exit(1)

    config = json.load(open(config_file, 'r'))
    gui = Gui(**config)
    gui.main()

    try:
        config = json.load(open(config_file, 'r'))
        logging.debug(json.dumps(config, indent=2))
    except Exception as err:
        logging.debug(json.dumps(config, indent=2))
        handle_error('no_credentials')

    logging.debug("Creating service...")
    sheet_api = create_service()

    # Aimlab has its data in /AppData/LocalLow/statespace/aimlab_tb/klutch.bytes
    if config["game"] == "Aimlab":
        logging.debug("Game: Aimlab")
예제 #43
0
import pygame
import time
from control import Control
from Snake_class import Snake
from gui import Gui
from food import Food

pygame.mixer.init()

window = pygame.display.set_mode((441, 441))
pygame.display.set_caption("Snake")
control = Control()
snake = Snake()
gui = Gui()
food = Food()

gui.init_field()
food.get_food_position(gui)
#gui.create_image()

while control.flag_game:
    gui.check_win_lose()
    control.control()

    #    head = [x_coord, y_coord]
    window.fill(pygame.Color("Black"))
    if gui.game == "GAME":
        snake.draw_snake(window)
        food.draw_food(window)
        gui.draw_indicator(window)
        gui.draw_level(window)
예제 #44
0
    def initialize_agent(self):
        self.tournament = False
        self.startup_time = time_ns()

        self.debug = [[], []]
        self.debugging = not self.tournament
        self.debug_lines = True
        self.debug_3d_bool = True
        self.debug_stack_bool = True
        self.debug_2d_bool = False
        self.show_coords = False
        self.debug_ball_path = False
        self.debug_ball_path_precision = 10
        self.disable_driving = False

        if not self.tournament:
            self.gui = Gui(self)
            self.print("Starting the GUI...")
            self.gui.start()

        self.match_comms = None

        self.print("Building game information")

        mutators = self.get_match_settings().MutatorSettings()

        gravity = (Vector(z=-650), Vector(z=-325), Vector(z=-1137.5),
                   Vector(z=-3250))

        base_boost_accel = 991 + (2 / 3)

        boost_accel = (base_boost_accel, base_boost_accel * 1.5,
                       base_boost_accel * 2, base_boost_accel * 10)

        boost_amount = ("default", "unlimited", "slow recharge",
                        "fast recharge", "no boost")

        self.gravity = gravity[mutators.GravityOption()]
        self.boost_accel = boost_accel[mutators.BoostStrengthOption()]
        self.boost_amount = boost_amount[mutators.BoostOption()]

        self.friends = ()
        self.foes = ()
        self.me = car_object(self.index)
        self.ball_to_goal = -1

        self.ball = ball_object()
        self.game = game_object()

        self.boosts = ()

        self.friend_goal = goal_object(self.team)
        self.foe_goal = goal_object(not self.team)

        self.stack = []
        self.time = 0

        self.ready = False

        self.controller = SimpleControllerState()

        self.kickoff_flag = False
        self.kickoff_done = True
        self.shooting = False
        self.best_shot_value = 92
        self.odd_tick = -1

        self.future_ball_location_slice = 180
        self.balL_prediction_struct = None
예제 #45
0
from gui import Gui

my_gui = Gui()
my_gui.mainloop()
예제 #46
0
#import the Gui class
from gui import Gui

#create a Gui object
my_gui = Gui()
예제 #47
0
from gui import Gui 

if (__name__ == "__main__"):
    gui = Gui()
    gui.mainloop()
예제 #48
0
파일: main.py 프로젝트: aladmit/ira-utils
    Callback для кнопки "начать" в gui
    """
    # Запретить повторный запуск
    window.disable()

    loop = asyncio.get_event_loop()

    # Добавить задачу на выгрузку данных
    loop.create_task(main(window.api, window.date))


def close_callback():
    """
    Callback для кнопки "закрыть" gui
    :return:
    """
    loop = asyncio.get_event_loop()
    loop.stop()


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)

    loop = asyncio.get_event_loop()

    gui = Gui(run_callback, close_callback)
    # Добавить задачу на работу интерфейса главного окна
    loop.create_task(gui.run())

    loop.run_forever()
예제 #49
0
from gui import Gui

if __name__ == '__main__':
    gui = Gui()
예제 #50
0
#import gui class
from gui import Gui

#create a gui object
mu_gui = Gui()
예제 #51
0
파일: client.py 프로젝트: hajdaini/GUI
class Client:
    IP = 'localhost'
    PORT = 22000

    def __init__(self):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.username = ''
        self.gui = []
        self.is_connected = False

    def window_input_for_username(self):
        self.gui = Gui(self)
        self.gui.window_config()
        self.gui.widget_for_username()
        self.gui.window.mainloop()

    def connection(self):
        try:
            self.client.connect((Client.IP, Client.PORT))
            self.is_connected = True
            return True
        except:
            return False

    def send_username_to_server(self):
        self.client.send(self.username.encode())

    def thread_chatbox_gui_creation(self):
        tk_thread = threading.Thread(target=self.gui.window_creation)
        tk_thread.daemon = True
        tk_thread.start()

    def close(self):
        try:
            self.client.close()
        except:
            print('no socket to close')

    def data_recv_handle(self):
        return_value = True
        try:
            data = pickle.loads(self.client.recv(1024))
        except:
            data = ''
        if not data:
            return_value = False
        else:
            self.gui.display_msg_in_chatbox(data['username'],
                                            data['data'].decode(),
                                            data['color'])

        return return_value

    def run(self):
        self.window_input_for_username()

        if not self.is_connected:
            return None

        self.send_username_to_server()
        self.thread_chatbox_gui_creation()

        while True:
            if not self.data_recv_handle():
                break
예제 #52
0
def main(arg_list):
    """Parse the command line options and arguments specified in arg_list.

    Run either the command line user interface, the graphical user interface,
    or display the usage message.
    """
    usage_message = (
        "Usage:\n"
        "Show help: logsim.py -h\n"
        "Command line user interface: logsim.py -c <file path>\n"
        "Graphical user interface with a blank circuit: logsim.py\n"
        "Graphical user interface with a predefined test circuit: logsim.py -t <circuit_number>\n"
        "Graphical user interface with loading a file: logsim.py <file path>")
    try:
        options, arguments = getopt.getopt(arg_list, "hct:")
    except getopt.GetoptError:
        print("Error: invalid command line arguments\n")
        print(usage_message)
        sys.exit()

    # Initialise instances of the four inner simulator classes
    names = Names()
    devices = Devices(names)
    network = Network(names, devices)
    monitors = Monitors(names, devices, network)
    import app_base as ab
    for option, path in options:
        if option == "-h":  # print the usage message
            print(usage_message)
            sys.exit()
        elif option == "-c":  # use the command line user interface
            scanner = Scanner(path, names)
            parser = Parser(names, devices, network, monitors, scanner)
            if parser.parse_network():
                # Initialise an instance of the userint.UserInterface() class
                userint = UserInterface(names, devices, network, monitors)
                userint.command_interface()
        elif option == "-t":  # manually create the devices, network, and monitors for testing
            if path == "1":
                names, devices, network, monitors = test_1()
            elif path == "2":
                names, devices, network, monitors = test_2()
            elif path == "3":
                names, devices, network, monitors = test_3()
            elif path == "4":
                names, devices, network, monitors = test_4()
            else:
                print("Error: invalid test number.\n")
                sys.exit()

            # Initialise an instance of the gui.Gui() class
            app = wx.App()
            gui = Gui("Logic Simulator", path, names, devices, network,
                      monitors, "en", 0)
            gui.Show(True)
            app.MainLoop()

    if not options:  # no option given, use the graphical user interface

        if len(arguments) == 0:  # Open the blank gui
            # Initialise an instance of the gui.Gui() class
            app = wx.App()
            gui = Gui("Logic Simulator", None, names, devices, network,
                      monitors, "en", 0)
            gui.Show(True)
            app.MainLoop()

        elif len(arguments) == 1:
            [path] = arguments
            scanner = Scanner(path, names)
            parser = Parser(names, devices, network, monitors, scanner)
            if parser.parse_network():
                # Initialise an instance of the gui.Gui() class
                app = wx.App()
                gui = Gui("Logic Simulator", path, names, devices, network,
                          monitors, "en", 0)
                gui.Show(True)
                app.MainLoop()

        else:  # wrong number of arguments
            print("Error: Too many arguments given\n")
            print(usage_message)
            sys.exit()
예제 #53
0
파일: main.py 프로젝트: i-saac/weather
try:
    file = open('address.txt', 'r')
    address = file.read()
    file.close()
except FileNotFoundError:
    address = None

# catch no address error code
if address == 'None':
    address = None

# initialize root
root = tk.Tk()

# create gui object with address
user_interface = Gui(root, address)

# main root loop
root.mainloop()

# create scraper based on last address in user_interface
new_address = user_interface.get_address()
web_scraper = Scraper(new_address)

# write address if there is one, otherwise write none
file = open('address.txt', 'w')
if web_scraper.is_valid_address():
    file.write(new_address)
else:
    file.write('None')
file.close()
예제 #54
0
파일: pycss.py 프로젝트: ElanMan/PyCSS
class PyCSS:
    def __init__(self, master):
        self.gui = Gui(master)
        self.encodingerrors = []
        self.fetched_files = []
        self.used = []
        self.unused = []
        self.cssclasses = {}
        self.cssfilesnotfound = {}
        self.css_selectors = {}

    @staticmethod
    def update_status_bar(*args):
        _css_files.set(())
        selected_file = _file_listbox.get(_file_listbox.curselection())
        if selected_file:
            _status_msg.set(selected_file)

    def show_about_window(self, *args):
        self.gui.show_about_window(*args)

    def show_css_details(self, *args):
        selected_css_file = _css_listbox.get(_css_listbox.curselection())
        if selected_css_file:
            details = [selected_css_file, self.used, self.unused]
            self.gui.show_css_details(_menubar, *details)

    def get_directory(self):
        self.gui.get_directory(_directory)

    def fetch_files(self, recursive_search=True):
        directory = _directory.get()
        if not directory:
            messagebox.showerror('No Directory Selected',
                                 'Please select a directory',
                                 icon='error')
            return
        _files.set(())
        self.fetched_files[:] = []
        for ext in ["shtml", "html", "xhtml"]:

            if recursive_search:
                files = [
                    os.path.join(dirpath, f)
                    for dirpath, dirnames, files in os.walk(directory)
                    for f in files if f.endswith('.' + ext)
                ]
            else:
                files = glob.glob(directory + "*." + ext)

            self.fetched_files += files

        _files.set(self.fetched_files)
        _status_msg.set('Search results for {}'.format(directory) if self.
                        fetched_files else 'No files found')

    def parse_file(self, *args):
        self.css_selectors.clear()
        self.encodingerrors[:] = []
        self.cssclasses.clear()
        self.cssfilesnotfound.clear()

        file = self.fetched_files[_file_listbox.curselection()[0]]
        parser = PyCSSParser(file)

        try:

            with open(file, "r") as handle:

                for linenum, line in enumerate(handle.readlines()):

                    linenum += 1

                    parser.feed(
                        line
                    )  # parser looks for classes and ids in linked css files

                    classes = re.findall(r'class=\"(.+?)\"', line)
                    if classes:
                        for html_class in classes:
                            html_class = "." + html_class
                            self.css_selectors[html_class] = linenum

                    ids = re.findall(r'id=\"(.+?)\"', line)
                    if ids:
                        for html_id in ids:
                            html_id = "#" + html_id
                            self.css_selectors[html_id] = linenum

                handle.close()

        except UnicodeDecodeError:
            if file not in self.encodingerrors:
                self.encodingerrors.append(file)

        self.cssclasses, self.cssfilesnotfound = copy.deepcopy(
            parser.cssclasses), copy.deepcopy(parser.cssfilesnotfound)
        self._link_css_ids_and_classes(file)

    def _link_css_ids_and_classes(self, html_file):
        self.used[:] = []  # reset the class lists
        self.unused[:] = []  # reset the class lists

        if html_file in self.cssclasses:

            for cssfile, css in self.cssclasses[html_file].items():

                # l is the list of line numbers
                for _id, linenumbers in css["ids"].items():

                    if _id in self.css_selectors:
                        self.used.append({_id: linenumbers})
                    else:
                        self.unused.append({_id: linenumbers})

                for _class, linenumbers in css["classes"].items():

                    if _class in self.css_selectors:
                        self.used.append({_class: linenumbers})
                    else:
                        self.unused.append({_class: linenumbers})

                if self.used or self.unused:
                    _css_files.set(cssfile)

                self._output_css_info()
        else:
            print('no linked css files found')

    def _output_css_info(self):

        if self.used:
            for l in self.used:
                for key in l:
                    lines = l[key]
                    print("            ", key, "on line(s)", *lines)

        if self.unused:
            for l in self.unused:
                for key in l:
                    lines = l[key]
                    print("            ", key, "on line(s)", *lines)

        if self.cssfilesnotfound:
            # populate a 'not found tab on interface'
            print("Files not found:")

            for l in self.cssfilesnotfound:
                print("    HTML File: ", l)
                print("        CSS Files Linked From HTML:")
                for file in self.cssfilesnotfound[l]:
                    print("        ", file)

        if self.encodingerrors:
            # populate an 'encoding errors tab in interface'
            print("Files found with encoding errors (not utf-8): ")
            for f in self.encodingerrors:
                print(f)
예제 #55
0
def aStar(gui: Gui, start: Node, end: Node) -> bool:
    """Runs A* algorithm

    One important aspect of A* is f = g + h
    Where:
        f is the total cost of the node.
        g is the distance between the current node and the start node.
        h is the heuristic - estimated distance from the current node to the end node.

    This algorithm expoits the node with the lowest f and its neighbors.

    Reference = [https://medium.com/@nicholas.w.swift/easy-a-star-pathfinding-7e6689c7f7b2]
    Code adapted from = [https://morioh.com/p/cf0c6b11c848?f=5c21fb01c16e2556b555ab32]

    Parameters
    ----------
    nodes : list
        A list of nodes present in the grid
    start : Node
        The starting point
    end : Node
        The ending point

    Returns
    -------
    bool
        True if the ending node was reached, else False
    """
    def h(node1: Node, node2: Node):
        return abs(node1.row - node2.row) + abs(node1.col - node2.col)

    def buildReversePath(came_from: dict, current: Node):
        while current in came_from:
            current = came_from[current]
            current.setState("path")
            gui.updateContents()

    g = 0
    open_set = PriorityQueue(
    )  # tip: A structure that it's always sorted (first f then h...). Method get() gets the first element (lowest f).
    open_set.put((0, g, start))
    came_from = {}
    g_score = {node: float("inf") for node in gui.grid}
    g_score[start] = 0
    f_score = {node: float("inf") for node in gui.grid}
    f_score[start] = h(start, end)

    open_set_hash = {start}

    while not open_set.empty():
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gui.close()

        *_, current = open_set.get()
        open_set_hash.remove(current)

        if current == end:
            buildReversePath(came_from, end)
            end.setState("end point")
            start.setState("start point")
            return True

        for neighbor in current.neighbors:
            temp_g_score = g_score[current] + 1

            if temp_g_score < g_score[neighbor]:
                came_from[neighbor] = current
                g_score[neighbor] = temp_g_score
                f_score[neighbor] = temp_g_score + h(neighbor, end)
                if neighbor not in open_set_hash:
                    g += 1
                    open_set.put((f_score[neighbor], g, neighbor))
                    open_set_hash.add(neighbor)
                    neighbor.setState("watch")
                    gui.updateContents()

        if current != start:
            current.setState("visited")
            gui.updateContents()

    return False
예제 #56
0
파일: main.py 프로젝트: gsauarv/shoppy
from gui import root
from gui import Gui
from db import DbConnection
dbConn = DbConnection()
gui = Gui(root)
예제 #57
0
파일: main.py 프로젝트: PoliPyc/YAPS
def runGui(app):
    root = Tk()
    root.title('YAPS - Yet Another Picture Sorter')
    root.configure(bg=Gui.MAIN_BACKGROUND)
    gui = Gui(root, app)
    root.mainloop()
예제 #58
0
def main():
    gui_fps = 120
    path_finding_fps = 30
    gui = Gui(fps=gui_fps)

    # Mapping the keys that triggers an algorithm initialization
    search_mapping = {
        pygame.K_a: aStar,
        pygame.K_d: depthFirst,
        pygame.K_b: breadthFirstSearch,
    }

    start_node = None
    end_node = None

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gui.close()

            if pygame.mouse.get_pressed()[0]:  # LEFT MOUSE BUTTON
                mouse_xy = pygame.mouse.get_pos()
                start_node, end_node = gui.setNodeColor(
                    mouse_xy, start_node, end_node)

            if pygame.mouse.get_pressed()[2]:  # RIGHT MOUSE BUTTON
                mouse_xy = pygame.mouse.get_pos()
                start_node, end_node = gui.resetNodeColor(
                    mouse_xy, start_node, end_node)

            if event.type == pygame.KEYDOWN:
                # Look for the keys that triggers an algorithm initialization
                if event.key in search_mapping.keys():
                    if start_node and end_node:
                        gui.updateNodeNeighbors()
                        gui.reset(
                            exeptions=["wall", "start point", "end point"])
                        search = search_mapping[event.key]
                        gui.fps = path_finding_fps
                        search(gui, start_node, end_node)
                        gui.fps = gui_fps

                # Look for the keys that resets all blocks
                if event.key == pygame.K_SPACE:
                    start_node, end_node = None, None
                    gui.reset()

                # Look for the keys that resets all blocks except the maze configuration
                if event.key == pygame.K_c:
                    gui.reset(exeptions=["wall", "start point", "end point"])

        gui.updateContents()
예제 #59
0
import argparse

from runner import Runner
from config import ConfigStorage, get_config_file
from gui import Gui

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--no-tray",
                        dest='no_tray',
                        action='store_true',
                        default=False)
    args, _ = parser.parse_known_args()

    config_storage = ConfigStorage(get_config_file())
    if args.no_tray:
        config = config_storage.load()
        aw_runner = Runner(config)
        aw_runner.run_all()
    else:
        stats_runner = Runner(config_storage.load())
        gui = Gui(config_storage, stats_runner)
        gui.run_headless()
예제 #60
0
class Connect4(Connect4Base):
    def __init__(self, config, agent1, agent2):
        super().__init__(config)
        self.agent1 = agent1
        self.agent2 = agent2
        self.agent1.setup(1)
        self.agent2.setup(2)
        self.gui = Gui(config)

    # player 1 - red, player 2 - yellow
    def run(self, step_wait):
        while True:
            board = np.full((config.rows, config.columns), 0, np.int)
            self.gui.draw_board(board)
            self.gui.display(10, 10, RED,
                             "Player 1 - {}".format(self.agent1.name()), True)
            self.gui.display(10, 50, YELLOW,
                             "Player 2 - {}".format(self.agent2.name()), False)
            piece = 1  # starts first
            while True:
                if len(self.valid_moves(board)) == 0:
                    self.gui.display(10, 10, WHITE, "Draw", False)
                    break
                agent = self.agent1 if piece == 1 else self.agent2
                col = agent.move(board)
                board = self.drop_piece(board, col, piece)
                self.gui.draw_board(board)
                if self.check_if_winning(board, piece):
                    self.gui.display(10, 10, RED if piece == 1 else YELLOW,
                                     "Player {} wins".format(piece), True)
                    break
                piece = piece % 2 + 1
                self.gui.wait_for_event(step_wait)
            self.gui.wait_for_event(10000)

    def end(self):
        self.agent1.teardown()
        self.agent2.teardown()