예제 #1
0
 def __init__(self, style=STYLE_DEFAULT, fixed_size=None):
     View.__init__(self)
     self._window = self
     self._first_responder = None
     self._title = None
     self._style = style
     self._resizable = fixed_size is None
     self._application = Application.shared_application()
     self._min_size = None
     self._max_size = None
     self._zoomed = False
     self._key_window = False
     self._main_window = False
     if fixed_size is None:
         # normal window
         self._pyglet = PygletWindow(self, 
                                     style=style, 
                                     resizable=True)
     else:
         # fixed size window
         self._pyglet = PygletWindow(self, 
                                     style=style, 
                                     resizable=False, 
                                     width=fixed_size.width, 
                                     height=fixed_size.height)
     x, y = self._pyglet.get_location()
     width, height = self._pyglet.get_size()
     View.set_frame(self, Rect(x, y, width, height))
     self._application._add_window(self)
예제 #2
0
 def export_print_page(self, event):
     """Export a print page using a JSON file"""
     event.Skip()
     if self.view.image is not None:
         # We don't require an RMAP file, just rect data that we can generate
         dlg = wx.FileDialog(self, "Choose a JSON file to load", "", "", "", wx.SAVE)
         if dlg.ShowModal() == wx.ID_OK:
             filename = dlg.GetFilename()
             dirname = dlg.GetDirectory()
             dlg.Destroy()
         else:
             self.SetStatusText(Preferences.failedToOpen)
             return False
         rmap_data = self.view.rects
         try:
             with open(join(dirname, filename), "r") as f:
                 json_data = loads(f.read())
         except Exception as e:
             self.SetStatusText(Preferences.failedToExport)
             return False
         fd = self.img.split(".")
         fd.pop()
         fname = ".".join(fd)
         rmap_data = View.filter_list(rmap_data)
         rmap_data = View.clean_list(rmap_data)
         rmap_data = View.generate_data(rmap_data)
         self.write_html_printpage(self.filename, fname, rmap_data, json_data)
     else:
         self.SetStatusText(Preferences.noImageLoaded)
예제 #3
0
 def set_frame(self, rect):
     if (    self._resizable == False
         and (rect.size.width != None or rect.size.height != None)):
         raise ValueError(u'Window is not resizable')
     View.set_frame(self, rect)
     self._pyglet.set_location(self._frame.origin.x, self._frame.origin.y)
     self._pyglet.set_size(self._frame.size.width, self._frame.size.height)
예제 #4
0
 def __init__(self):
     View.__init__(self)
     self._state = Control.STATE_NORMAL
     self._attrs = {}
     for k, v in ControlState:
         self._attrs[k] = None
     self._actions = {}
예제 #5
0
 def __init__(self, controller, parentXYView):
   View.__init__(self, controller)
   self._mplAxes = None
   self._mplLines = None
   self._isHighlighted = False
   self._initialLineWidth = None
   self._parentXYView = parentXYView
   
   self._marker = None
   self._color = None
   self._lineStyle = None
 def __init__( self, controller) :
     """ Constructor """
     View.__init__( self, controller)
     CurveTreeDockWidget.__init__(self)
     self._noUpdate = False
     
     treeWidget = self.getTreeWidget()
     treeWidget.itemSelectionChanged.connect(self.onItemSelectionChanged)
     treeWidget.itemDoubleClicked.connect(self.onItemDoubleCliked)
     treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
     treeWidget.customContextMenuRequested.connect(self.openMenu)
예제 #7
0
def main(args) :
	"""Fonction principal qui va nous lancer notre annuaire"""	
	#bdd = sqlite3.connect('Bdd/patron.db')
	
	app=QApplication(args)
	control = Control()
	model = Model(control)
	fenetre = View(control);
	fenetre.show();
	
	#bdd.close()
	return app.exec_()
 def __init__(self, path):
     self.myModel = Model()
     if path != "" or path is not None:
         self.load_data(path)
     self.myView = View(self)
     self.myModel.data_handler.load_pickle_data()
     self.myView.cmdloop()
예제 #9
0
 def __init__(self, path):
     self.myModel = Model(Filer(), Validator())
     if path != "" or path is not None:
         self.load_data(path)
     self.myView = View(self)
     self.myModel.pickle_data()
     self.myView.cmdloop()
예제 #10
0
 def __init__(self):
     self.model = Model()
     self.view = View()
     self.firstTime = True
     self.result = 0.0
     self.a = 0.0
     self.b = 0.0
     self.usePrev = 0
예제 #11
0
class Controller(object):
  def __init__(self):
    self.model = Model()
    self.view = View()

  def run(self):
    name = self.view.welcome()
    if name == 'Ken':
      print(self.model.say_hello(name))
    else:
      print(self.model.say_bye())
예제 #12
0
class Game:
    def __init__(self):
        self.board = Board()
        self.evaluation = Evaluation(self.board)
        self.view = View(self.board)

    def __finish(self, computerPlayer):
        if self.evaluation.winner() == computerPlayer:
            print "Computer player wins"
        elif self.evaluation.isTie():
            print "Tie game"
        else:
            print "Human player wins"

    def run(self):
        startPlayer = self.view.inputStartPlayer()
        computerPlayer = 'X' if startPlayer == 2 else 'O'
        ai = AI(computerPlayer, self.board)
        while self.evaluation.winner() == None and not self.evaluation.isTie():
            self.view.displayBoard()
            if self.board.getPlayer() == computerPlayer:
                ai.makeMove()
            else:
                move = self.view.inputMove()
                self.board.move(move)
        self.view.displayBoard()
        self.__finish(computerPlayer)
예제 #13
0
class Controller:
    def __init__(self, path):
        self.myModel = Model(Filer(), Validator())
        if path != "" or path is not None:
            self.load_data(path)
        self.myView = View(self)
        self.myModel.pickle_data()
        self.myView.cmdloop()

    def delete_data(self):
        self.myModel.del_data()

    def wash_data(self):
        self.myModel.wash_data()
        self.myModel.toDataSet()

    def get_data(self):
        return self.myModel.get_data()

    def get_weight_data(self):
        return self.myModel.get_weight()

    def get_sales_data(self):
        return self.myModel.get_sales()

    def get_gender_data(self):
        return self.myModel.get_gender()

    def load_data(self, path):
        try:
            file = open(path)
            file.read()
        except FileNotFoundError:
            print("File Does Not Exist")
            return
        self.myModel.read(path)
        self.wash_data()

    def save_data(self):
        self.myModel.save_data()
    def update_manager(self):
        if self.model.show_user != []:
            View.print_user(self.model.show_user[0])
        choice = -1
        params_to_upd = dict()
        while choice != 0:
            View.update_user_menu()
            try:
                choice = int(input("Your choice: "))

                if choice == 1:
                    params_to_upd['productName'] = str(input("New name: "))
                elif choice == 2:
                    params_to_upd['age'] = int(input("New age: "))
                elif choice == 3:
                    params_to_upd['height'] = str(input("New height: "))
                elif choice == 4:
                    params_to_upd['weight'] = str(input("New weight: "))
                elif choice == 5:
                    params_to_upd['gender'] = str(input("New gender: "))
                elif choice == 6:
                    params_to_upd['activity'] = str(input("New activity: "))

            except ValueError:
                View.wrong_input()
                choice = -1

        try:
            self.model.update_user_param(params_to_upd)
        except Exception as e:
            print(e)
예제 #15
0
class Controller(object):
    ''' A class for controlling a graph-analyser. '''
    def __init__(self, master, graph_img=None):
        ''' A class for managing a GUI graph-analyser.

        Users select an image of a graph, then identify three points with well-
            defined locations, then add as many points as desired to the graph.
            The selected points are saveable in a csv format, and the graph
            image is saveable as a PNG image.

        Could be expanded to include zooming, logarithmic axis scaling,
            automatic line detection, saving of state (to reopen where you left
            off), or full automation with automatic axis detection and line
            detection combined.

        Constructor: Controller(tk.Tk, *str)

        '''
        # initialise data storage
        self._model = Model()

        # initialise display and event bindings
        self._root = master  # overarching 'main' window for the application
        self._view = View(self._root, graph_img)
        self._add_bind_functions()

    def _add_bind_functions(self):
        ''' Link the Model functionality to View binding functions.

        self._add_bind_functions() -> None

        '''
        self._view.add_binding_funcs(
            save_data=self._model.save_data,
            clear_data=self._model.clear_data,
            clear_stored_pts=self._model.clear_stored_points,
            set_def_pts=self._model.set_defining_points,
            new_point=self._model.add_stored_point,
            del_point=self._model.remove_stored_point,
        )
예제 #16
0
    def run(self):

        self.rows,self.lines = View.GreatingMessage()

        self.NamesOfPlayers,View.NumberOfPlayers = View.NamesOfPlayers() # intial Players from View

        for name in self.NamesOfPlayers:
            player = Controller.Player(name)
            self.Players.append(player)







        self.Turner  = Controller.Turner(self.Players)

        View.Symbols = View.GenerateSymbols(View.NumberOfPlayers)
        View.tablePrint(self.rows,self.lines,[])

        Win = False

        while not Win:
            CurentPlayer = self.Turner.getNext()
            print "Hello ", CurentPlayer.getName()
            x,y = View.InputMessage()

            if not self.ValidCoordinate((x,y)):
                print "continue"
                self.Turner.CurentState = self.Turner.CurentState - 1
                continue
            self.Model.setCordinate(CurentPlayer,(x,y))
            mapp = self.Model.getMappingNotLinear()
            View.tablePrint(self.lines,self.rows,mapp)

            Win = self.is_win(CurentPlayer,(x,y))
        
            pass
        View.WinMessage(Winner=self.Winner)
예제 #17
0
    def play_rounds(self, tournament, p):
        for i in range(tournament.current_round(), int(tournament.rounds)):
            if i == 0:
                p.order_by_rank()
                player_pairs = p.matchmaking_round1()
            else:
                p.order_by_score()
                player_pairs = p.matchmaking_over_rounds(tournament)
            for player in p.list:
                View.display_player_infos(player.first_name, player.name,
                                          str(player.rank), str(player.score))

            matches = Matches()
            for pair in player_pairs:
                matches.add_match(Match(pair[0], pair[1]))
            View.print_matches(matches)

            for match in matches.list:
                match.winner = View.ask_winner(match)
                if match.winner is None:
                    match.white_player.draw_match()
                    match.black_player.draw_match()
                else:
                    match.winner.won_match()

            tournament.add_round(matches)
            tournament_in_db = Query()
            self.tournaments_db.update(tournament.to_dict(),
                                       tournament_in_db.id == tournament.id)

            continue_choice = View.ask_to_continue()
            if continue_choice == 0:
                return
예제 #18
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.__view = View()
        self.__inventory_label = QLabel()
        self.__inventory_label.setPixmap(
            QPixmap("image/Inventory.png").scaled(
                self.__view.width * self.__view.tile_size * 120 / 196 *
                (7 / self.__view.width),
                self.__view.height * self.__view.tile_size *
                (7 / self.__view.height)))  # 120 196
        # self.hp_bar = QLabel()  # this code for test

        self.__main_layout = QGridLayout()
        self.__main_layout.setSpacing(0)
        self.__main_layout.addLayout(self.__view.layout, 0, 0)
        self.__main_layout.addWidget(self.__inventory_label, 0, 1)
        # self.__main_layout.addWidget(self.hp_bar, 1, 0)  # this code for test

        self.setStyleSheet("background-color: #B7A284;")
        # container.setStyleSheet("background-color:black;")
        self.setLayout(self.__main_layout)
예제 #19
0
    def __init__(self):
        # ウィンドウを作成
        self.window = tk.Tk()
        self.window.resizable(width=False, height=False)
        # 描画領域を作成
        self.canvas = tk.Canvas(self.window,
                                width=FIELD_WIDTH,
                                height=FIELD_HEIGHT)
        self.keyinput = KeyInput(self.window)
        self.autokeyinput = AutoKeyInput(self.window)
        self.cm = ClientModel(self.window, self.autokeyinput, 0, 200,
                              200)  #canvasを渡すことに注意.詳しくはView.py
        self.bm = BulletManager(self.window)

        self.data = {}
        self.init_data()
        self.view = View(self.canvas, self.data)

        # 最初の1回(update内で再帰的にupdateが呼ばれてループとなる)
        self.update_model()
        self.update_view()
        self.window.mainloop()
예제 #20
0
파일: __init__.py 프로젝트: agnsal/HTTPyS
class Controller:
    __cssFilesRoot = None
    __jsFilesRoot = None
    __jsonFilesRoot = None
    __imgFilesRoot = None
    __View = None

    def __init__(self):
        assert path.isdir(cssFilesRoot)
        assert path.isdir(jsFilesRoot)
        assert path.isdir(jsonFilesRoot)
        assert path.isdir(imgFilesRoot)
        self.__cssFilesRoot = cssFilesRoot
        self.__jsFilesRoot = jsFilesRoot
        self.__jsonFilesRoot = jsonFilesRoot
        self.__imgFilesRoot = imgFilesRoot
        self.__View = View()

    def manageGET(self, reqPath=""):
        reqPath = str(reqPath)
        fileName = str(reqPath).split("/")[-1].split("?")[0]
        if ".css" in fileName:
            ct = "text/css"
            resource = self.takeResourceFile(root=self.__cssFilesRoot, fileName=fileName, mode="rb")
        elif ".json" in fileName:
            ct = "application/javascript"
            resource = self.takeResourceFile(root=self.__jsonFilesRoot, fileName=fileName, mode="rb")
        elif ".js" in fileName:
            ct = "application/javascript"
            resource = self.takeResourceFile(root=self.__jsFilesRoot, fileName=fileName, mode="rb")
        elif ".ico" in fileName or ".png" in fileName or ".jpeg" in fileName:
            ct = "image/x-icon"
            resource = self.takeResourceFile(root=self.__imgFilesRoot, fileName=fileName, mode="rb")
        else:
            ct = "text/html"
            resource = self.__View.takeView(fileName)
        return {"Content-type": ct, "resource": resource}

    def takeResourceFile(self, root="", fileName="", mode="rb"):
        resourcePath = root + fileName
        if path.isfile(resourcePath):
            resFile = open(resourcePath, mode)
            resource = resFile.read()
            resFile.close()
            return resource
        else:
            return None

    def managePOST(self, receivedObj):
        # Put here your code to manage post data
        '''
class Controller:
    def __init__(self, path):
        self.myModel = Model()
        if path != "" or path is not None:
            self.load_data(path)
        self.myView = View(self)
        self.myModel.data_handler.load_pickle_data()
        self.myView.cmdloop()

    def delete_data(self):
        self.myModel.data_handler.del_data()

    def wash_data(self):
        self.myModel.wash_data()

    def get_data(self):
        return self.myModel.data_handler.get_data()

    def get_weight_data(self):
        return self.myModel.get_weight()

    def get_sales_data(self):
        return self.myModel.get_sales()

    def get_gender_data(self):
        return self.myModel.get_gender()

    def load_data(self, path):
        try:
            file = open(path)
            file.read()
        except FileNotFoundError:
            print("File Does Not Exist")
            return
        self.myModel.data_handler.read_in(path)

    def save_data(self):
        self.myModel.data_handler.save_pickle_data()
    def show_stat_manager(self):
        View.statisics_menu()
        try:
            choice = int(input("Your choice: "))
            if choice not in range(1, 5):
                raise ValueError
        except ValueError:
            View.wrong_input()
            return

        if choice == 1:
            try:
                today = datetime.datetime.now()
                total = self.model.total(dict((("year", today.year),\
                      ("month", today.month), ("day", today.day))))
            except Exception as e:
                print(e)
                return
        elif choice == 2:
            try:
                year = int(input("Year: "))
                month = int(input("Month: "))
                day = int(input("Day: "))
                total = self.model.total(
                    dict((("year", year), ("month", month), ("day", day))))
            except Exception:
                View.wrong_input()
                return
        elif choice == 3:
            try:
                year = int(input("Year: "))
                month = int(input("Month: "))
                total = self.model.total(
                    dict((("year", year), ("month", month))))
            except Exception as e:
                print(e)
                #View.wrong_input()
                return
        elif choice == 4:
            try:
                year = int(input("Year: "))
                total = self.model.total({"year": year})
            except ValueError as e:
                #View.wrong_input()
                print(e)
                return

        View.print_stat(total, self.model.should_consume())
예제 #23
0
    def baslat():
        while True:
            View.viewbaslat()
            print("Lütfen yapmak istediğiniz işlemi seçin : ")
            giris = input()
            if giris not in ["0", "1", "2", "3", "4", "5"]:
                print("Hatalı giriş !!!")
            elif giris == "0":
                print("Çıkış seçildi")
                exit(0)
            elif giris == "1":
                return Controller.kisiekleme()
            elif giris == "2":
                return Controller.kisiarama()
            elif giris == "3":
                return Controller.kisiguncelle()
            elif giris == "4":
                return Controller.kisisilme()
            elif giris == "5":
                return Controller.kisilistele()

            else:
                print("yanlış bir giris yaptınız ")
예제 #24
0
class Play():
    def __init__(self, song):
        self.audio = Audio()
        self.audio.preOpen()
        self.detect = Detect()
        pygame.init()
        self.audio.open()
        self.song = LoadSong(song).song
        pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption('DanceDanceCV')
        screen = pygame.display.get_surface()
        self.view = View(screen, self.detect, self.song)

    def run(self):
        playing = True
        while playing:
            for events in pygame.event.get():
                if events.type == QUIT:
                    return 'quit'
            self.detect.run()
            self.view.run()
            pygame.display.update()
        pygame.quit()
예제 #25
0
파일: Model.py 프로젝트: mal1k/db-lab3
 def Update():
     num = View.attribute_list(1)
     value = input('Attribute value to update = ')
     value2 = input('New attribute value = ')
     if num == 1:
         session.query(Owner).filter(Owner.owner_id == value).update(
             {Owner.owner_id: value2})
     elif num == 2:
         session.query(Owner).filter(Owner.owner_name == value).update(
             {Owner.owner_name: value2})
     elif num == 3:
         session.query(Owner).filter(Owner.owner_surname == value).update(
             {Owner.owner_surname: value2})
     session.commit()
예제 #26
0
class Controller(object):
    def __init__(self):
        self.model = Model()
        self.view = View()
        self.velkommen_text = ''

    def intro_screen(self):
        color = self.model.make_color(255, 255, 255)
        screen = self.model.get_screen()
        self.view.fill(color, screen)

        text = self.model.make_text('Velkommen til Card Game!', 40)
        text2 = self.model.make_text('Trykk enter for å starte', 20)
        self.view.update(text, 60, 50, screen)
        self.view.update(text2, 200, 200, screen)
        self.view.flip()
예제 #27
0
def main():
    gameMatrix = MapMatrix(DIMENSION)
    view = View()
    view.draw(gameMatrix.matrix)
    ai = MinMaxStrategy(gameMatrix)
    view.draw(gameMatrix.matrix)
    while True:
        i = pygame.event.wait()
        if i.type == pygame.QUIT:
            sys.exit(0)

        if pygame.mouse.get_pressed()[LEFT_MOUSE]:
            pos = pygame.mouse.get_pos()
            wsp_x = int(pos[POS_X] / (SMALL_BOX_LENGTH + SPACE_LENGTH))
            wsp_y = int(pos[POS_Y] / (SMALL_BOX_LENGTH + SPACE_LENGTH))
            if pos[POS_X] > BOX_LENGTH or pos[POS_X] < 0 or pos[
                    POS_Y] > BOX_LENGTH or pos[POS_Y] < 0 or gameMatrix.matrix[
                        wsp_y][wsp_x] != EMPTY:
                continue
            else:
                gameMatrix.markCrossOn(Coordinates(wsp_y, wsp_x))
                view.draw(gameMatrix.matrix)
                SoundService.playCrossSound()

                if ai.hasWon(CROSS):
                    sys.exit("Wygrales!")
                elif (not ai.hasWon(CROSS)) and gameMatrix.checkIfMapFull():
                    sys.exit("Remis!")

                ai.doBestMove(gameMatrix)
                view.draw(gameMatrix.matrix)
                SoundService.playCircleSound()

                if ai.hasWon(CIRCLE):
                    sys.exit("Przegrales!")
                elif (not ai.hasWon(CIRCLE)) and gameMatrix.checkIfMapFull():
                    sys.exit("Remis!")
예제 #28
0
    def generateMap(self):
        self.ant = Ants(8, 6)  #ants class

        for x in range(Globals.mapwidth):
            for y in range(Globals.mapheight):
                if (y <= Globals.mapheight / 2):
                    if randint(0, 10) > 8:
                        self.tiles[x][y] = choice(self.foliageTiles)
                    else:
                        self.tiles[x][y] = choice(self.groundTiles)
                else:
                    self.tiles[x][y] = choice(
                        self.undergroundTiles)  #underground map

        return View(self.tiles[:, :])  #tiles[every x, every y]
예제 #29
0
파일: XYView.py 프로젝트: Sunqia/salome-gui
    def __init__(self, controller):
        View.__init__(self, controller)
        self._eventHandler = EventHandler()

        self._curveViews = {}  # key: curve (model) ID, value: CurveView
        self._salomeViewID = None
        self._mplFigure = None
        self._mplAxes = None
        self._mplCanvas = None
        self._plotWidget = None
        self._sgPyQt = self._controller._sgPyQt
        self._toolbar = None
        self._mplNavigationActions = {}
        self._toobarMPL = None
        self._grid = None
        self._currCrv = None  # current curve selected in the view

        self._legend = None
        self._legendLoc = "right"  # "right" or "bottom"

        self._fitArea = False
        self._zoomPan = False
        self._dragOnDrop = False
        self._move = False

        self._patch = None
        self._xdata = None
        self._ydata = None
        self._defaultLineStyle = None
        self._last_point = None
        self._lastMarkerID = -1
        self._blockLogSignal = False

        self._axisXSciNotation = False
        self._axisYSciNotation = False
        self._prevTitle = None
예제 #30
0
    def main(self):
        print("starting new game")
        bd = BattleData()
        bd.loadBattleData()
        view = View()
        view.sendOutput("Loaded all fighter data. Count: " + str(bd.getFighterCount()))
        for i in range(bd.getFighterCount()):
            bd.getFighter(i).sendToView(view)

        tournament = TournamentController()
        tournament.start(bd, view)

        view.sendOutput('Tournament is over')
        view.sendOutput('display all fighters stats')

        for i in range(bd.getFighterCount()):
            bd.getFighter(i).sendToView(view)
예제 #31
0
 def __init__(self, controller):
   View.__init__(self, controller)
   self._eventHandler = EventHandler()
   
   self._curveViews = {}    # key: curve (model) ID, value: CurveView
   self._salomeViewID = None
   self._mplFigure = None
   self._mplAxes = None
   self._mplCanvas = None
   self._plotWidget = None
   self._sgPyQt = self._controller._sgPyQt
   self._toolbar = None
   self._mplNavigationActions = {}
   self._toobarMPL = None
   self._grid = None
   self._currCrv = None   # current curve selected in the view
   
   self._legend = None
   self._legendLoc = "right"  # "right" or "bottom"
   
   self._fitArea = False
   self._zoomPan = False
   self._dragOnDrop = False
   self._move = False
   
   self._patch = None
   self._xdata = None
   self._ydata = None
   self._defaultLineStyle = None
   self._last_point = None
   self._lastMarkerID = -1
   self._blockLogSignal = False
   
   self._axisXSciNotation = False
   self._axisYSciNotation = False
   self._prevTitle = None
class Controller:
    def __init__(self):
        self.view = View()
        self.model = Model(self.view)
        self.player = ""

    def play(self):
        while True:
            self.playAGame()

            # ask if user wants to play another game
            # if no, break

    def playAGame(self):
        self.view.reset()
        self.player = "X"
        # update message in View to say it's X's turn
        self.view.startText("X\'s turn0")

        while True:
            # get click/cellNum
            self.view.getClick(cellNum)
            # loop until have vaild cellNum
            # valid: 0 >= cellNum <= 8 AND v.model.isEmpty(cellNum) returns True
            # provide message if click was not in valid cell
            # self.model.turn(cellNum, self.player) - model updates data and tells you to draw player
            # answer = self.model.isDone() - return "X" or "O" or "Draw" or "Continue"
            # if answer is "X" or "O"
            # self.view.startText("winner is" answer)
            # break
            # if answer is "draw"
            # self.view.startText("Game was a draw")
            # break

            # switches to other player
            if self.player == "X":
                self.player = "O"
            else:
                self.player = "X"
            self.view.startText(self.player + "\s turn")
            pass

    def ControllerTest():
        c = Controller()

        input()
예제 #33
0
    def test_view(self):
        global g
        g = Graph(port_mates=port_mates)
        v = g.add_node(View(NodeCriterion(nodeclass=Number, tagclass=Avail)))
        dv = g.datum(v)
        n5 = g.add_node(Number(5))
        g.add_tag(Avail, n5)
        n6 = g.add_node(Number(6)) # not tagged Avail
        g.do_touches()

        self.assertCountEqual(dv.viewing(), [n5.id])

        g.remove_tag(n5, Avail)  # Removing the tag should remove it from View
        g.do_touches()

        self.assertCountEqual(dv.viewing(), [])
def preprocess_views(views, max_views):
    # sort by size
    views_sorted = sorted(views, key=lambda x: x.area(), reverse=True)
    # how many views we want in this iteration
    rand_int = randint(2, min(max_views, len(views_sorted)))

    views_to_be_drawn = []
    views_to_be_drawn.append(
        View(-999, 0, 0, config.screen_width, config.screen_height))
    for view in views_sorted:
        if view.width == config.screen_width and view.height == config.screen_height:
            continue
        if len(views_to_be_drawn) >= rand_int:
            break
        views_to_be_drawn.append(view)
    return views_to_be_drawn
예제 #35
0
파일: Model.py 프로젝트: mal1k/db-lab3
 def Update():
     num = View.attribute_list(4)
     value = input('Attribute value to update = ')
     value2 = input('New attribute value = ')
     if num == 1:
         session.query(HeadCoach).filter(
             HeadCoach.coach_id == value).update(
                 {HeadCoach.coach_id: value2})
     elif num == 2:
         session.query(HeadCoach).filter(
             HeadCoach.coach_name == value).update(
                 {HeadCoach.coach_name: value2})
     elif num == 3:
         session.query(HeadCoach).filter(
             HeadCoach.coach_surname == value).update(
                 {HeadCoach.coach_surname: value2})
예제 #36
0
class Controller:
    """ a 'middleman' between the View (visual aspects) and the Model (information) of the application.
        It ensures decoupling between both.
    """

    def __init__(self, app):
        # initialize the model and view
        # * The model handles all the data, and signal-related operations
        # * The view handles all the data visualization
        self.model = Model()
        self.view = View()

        # subscribe to messages sent by the view
        pub.subscribe(self.parse_file, "FILE PATH CHANGED")
        pub.subscribe(self.reprocess_fft, "FFT CONTROLS CHANGED")

        # subscribe to messages sent by the model
        pub.subscribe(self.signal_changed, "SIGNAL CHANGED")
        pub.subscribe(self.signal_changed, "FFT CHANGED")

        self.view.Show()

    def parse_file(self, message):
        """
        Handles "FILE PATH CHANGED" messages, send by the View. It tells the model to parse a new file.
        message.data should contain the path of the new file
        """
        try:
            self.model.parse_file(message.data)

        except Exception as exception:
            self.view.show_exception(
                "Error reading file", "The following error happened while reading the file:\n%s" % str(exception)
            )

    def reprocess_fft(self, message):
        """
        Handler "FFT CONTROLS CHANGED" messages from the View. It tells the model to re-process the fft.
        message.data should contain the array [window, slices, max_peaks]
        """
        self.model.reprocess_fft(*message.data)

    def signal_changed(self, message):
        """
        Handles "SIGNAL CHANGED" messages sent by the model. Tells the view to update itself.
        message is ignored
        """
        self.view.signal_changed(self.model)

    def fft_changed(self, message):
        """
        Handles "FFT CHANGED" messages sent by the model. Tells the view to update itself.
        message is ignored
        """
        self.view.fft_changed(self.model)
예제 #37
0
    def __init__(self, app):
        # initialize the model and view
        # * The model handles all the data, and signal-related operations
        # * The view handles all the data visualization
        self.model = Model()
        self.view = View()

        # subscribe to messages sent by the view
        pub.subscribe(self.parse_file, "FILE PATH CHANGED")
        pub.subscribe(self.reprocess_fft, "FFT CONTROLS CHANGED")

        # subscribe to messages sent by the model
        pub.subscribe(self.signal_changed, "SIGNAL CHANGED")
        pub.subscribe(self.signal_changed, "FFT CHANGED")

        self.view.Show()
예제 #38
0
파일: Model.py 프로젝트: mal1k/db-lab3
 def Update():
     num = View.attribute_list(7)
     value = input('Attribute value to update = ')
     value2 = input('New attribute value = ')
     if num == 1:
         session.query(Contract).filter(
             Contract.contract_id == value).update(
                 {Contract.contract_id: value2})
     elif num == 2:
         session.query(Contract).filter(Contract.fc_id == value).update(
             {Contract.fc_id: value2})
     elif num == 3:
         session.query(Contract).filter(
             Contract.partner_id == value).update(
                 {Contract.partner_id: value2})
     session.commit()
예제 #39
0
def ModelTest():
    v = View()
    m = Model(v)
    for i in range(9):
        if m.Empty(v.Click()) == 1:
            m.ControlX()
            print(m.Empty(v.Click()))
        else:
            v.Message(1, "Illegal Move!")
        v.Click()
        m.ControlO()
        if m.isWinner() is 1:
            v.Message(1, "You Win!")
        elif m.isWinner() is 2:
            v.Message(1, "Draw!")
        print(m.grid)

    input()
예제 #40
0
파일: __init__.py 프로젝트: koen92/etstat
def main():
    app = QtGui.QApplication(sys.argv)

    w = View()
    m = Model()
    c = Controller(w, m)
    w.initUI(c)
    w.show()
    c.loadServers()

    sys.exit(app.exec_())
예제 #41
0
파일: Model.py 프로젝트: mal1k/db-lab3
def show_table(number):
    flag = 0
    table = 0
    while flag == 0:
        if number == 1:
            table = View.list()
            flag = 1
        elif number == 2:
            table += 1
            if table == 7:
                flag = 1
        if table == 1:
            print("table: Owner")
            for row in session.query(Owner):
                print(row.print())
            print("\n")
        elif table == 2:
            print("table: Football Club")
            for row in session.query(FootballClub):
                print(row.print())
            print("\n")
        elif table == 3:
            print("table: Player")
            for row in session.query(Player):
                print(row.print())
            print("\n")
        elif table == 4:
            print("table: Head Coach")
            for row in session.query(HeadCoach):
                print(row.print())
            print("\n")
        elif table == 5:
            print("table: Partner")
            for row in session.query(Partner):
                print(row.print())
            print("\n")
        elif table == 6:
            print("table: Assistant")
            for row in session.query(Assistant):
                print(row.print())
            print("\n")
        elif table == 7:
            print("table: Contract")
            for row in session.query(Contract):
                print(row.print())
            print("\n")
예제 #42
0
    def generateMap(self):
        for x in range(Globals.mapwidth):
            for y in range(Globals.mapheight * 2):
                if (y <= Globals.mapheight):
                    if randint(0, 10) > 8:
                        self.tiles[x][y] = choice(self.foliageTiles)
                    else:
                        self.tiles[x][y] = choice(self.groundTiles)
                else:
                    self.tiles[x][y] = choice(
                        self.undergroundTiles)  #underground map

        # Starts in a tunnel underground
        self.tiles[0][33] = Tile(
            Globals.datadir + 'images/underground/underground2.png', True)

        return View(self.tiles[:, :])  #tiles[every x, every y]
예제 #43
0
class Controller:
   def __init__(self,root):
      self.root = root
      self.model = Model()
      self.view = View(self.root)
      self.view.calculateButton.bind('<Button>',self.calculate)
      
   def calculate(self,event):
      
      self.view.clearCalcSolution()

      try:
         firstNumber = self.view.getFirstNumber()
         secondNumber = self.view.getSecondNumber()
         self.model.addTwoNumbers(firstNumber,secondNumber )
         solution = self.model.getCalculatorValue()
         self.view.setCalcSolution(solution)
      except:
         self.view.displayErroMessage()
예제 #44
0
def show_scores(runs, screen, controller):
    """
    draws and displays the scores

    :param runs: int
    :param screen: pygame screen
    :param controller: Controller
    :return:
    """
    screen.fill((0, 0, 0))
    c = Controller(Model(), View())
    c.get_and_draw_scores(screen)
    pygame.display.update()
    while c.model.game_run:
        user_input = pygame.event.get()
        for game_event in user_input:
            c.scores_event(game_event, screen, runs, controller)
    pygame.quit()
예제 #45
0
def play_game(runs, screen, controller):
    """
    main game function
    :param runs:
    :param screen:
    :param controller:
    :return:
    """
    fps_clock = pygame.time.Clock()
    c = Controller(Model(), View())
    # initialize deck
    c.init_cards(controller.model.difficulty)

    # Load card-back image for all cards at first, and have matches slowly unveiled
    c.model.set_visible_deck()

    # Shows cards for the first time
    c.initial_draw(controller.model.display_time, controller.model.difficulty)
    max_amount_of_matches = controller.model.difficulty * 10
    if controller.model.difficulty == 1:
        max_amount_of_matches += 2
    while c.model.game_run:
        user_input = pygame.event.get()
        pressed_key = pygame.key.get_pressed()
        # Retrieves all user input
        for game_event in user_input:
            c.update(game_event, runs, screen, controller)

        # checks how many cards were flipped
        c.tick(controller.model.difficulty)
        # This comes before quitting to avoid video errors
        pygame.display.flip()
        fps_clock.tick(DESIRED_FPS)

        if len(c.model.get_found()) == max_amount_of_matches:
            # print score and asks for another round
            runs = c.done()

        # if game finished checks for user input
        c.game_finished_check_for_rematch(screen, runs, pressed_key,
                                          controller)

    pygame.quit()
예제 #46
0
 def kisiekleme():
     ad = input("Kaydı yapılacak yeni kişinin adı? ")
     soyad = input("Kaydı yapılacak yeni kişinin soyadı? ")
     babaad = input("Kaydı yapılacak yeni kişinin baba adı? ")
     annead = input("Kaydı yapılacak yeni kişinin anne adı? ")
     dogumyer = input("Kaydı yapılacak yeni kişinin doğum yeri? ")
     medenidurum = input(
         "Kaydı yapılacak yeni kişinin medeni durumu? (Bekar/Evli) ")
     kangrup = input("Kaydı yapılacak yeni kişinin adı? (örn. A rH +) ")
     kutukil = input("Kaydı yapılacak yeni kişinin kütük şehri? ")
     kutukilc = input("Kaydı yapılacak yeni kişinin kütük ilçesi? ")
     ikametil = input(
         "Kaydı yapılacak yeni kişinin ikametgah ettiği şehir? ")
     ikametilc = input(
         "Kaydı yapılacak yeni kişinin ikametgah ettiği ilçe? ")
     Kisiekle = Model()
     Kisiekle.kayitgir(ad, soyad, babaad, annead, dogumyer, medenidurum,
                       kangrup, kutukil, kutukilc, ikametil, ikametilc)
     return View.viewkisiekle(ad, soyad)
예제 #47
0
    def take_return_book_helper(self, book_list):
        '''Helper methods for take and return manage.
		Made because of similiar organization.'''
        View.print_books(book_list)
        book_number = -1
        try:
            book_number = int(input("Enter book number: "))
        except ValueError:
            View.wrong_input()

        if (book_number not in range(1, len(book_list) + 1)):
            View.wrong_input()
            return
        return book_number - 1
예제 #48
0
파일: Model.py 프로젝트: mal1k/db-lab3
 def Update():
     num = View.attribute_list(6)
     value = input('Attribute value to update = ')
     value2 = input('New attribute value = ')
     if num == 1:
         session.query(Assistant).filter(
             Assistant.assistant_id == value).update(
                 {Assistant.assistant_id: value2})
     elif num == 2:
         session.query(Assistant).filter(
             Assistant.assistant_name == value).update(
                 {Assistant.assistant_name: value2})
     elif num == 3:
         session.query(Assistant).filter(
             Assistant.assistant_surname == value).update(
                 {Assistant.assistant_surname: value2})
     elif num == 4:
         session.query(Assistant).filter(Assistant.head_id == value).update(
             {Assistant.head_id: value2})
     session.commit()
예제 #49
0
 def on_resize(self, width, height):
     pyglet.window.Window.on_resize(self, width, height)
     View.set_frame(self._window, Rect(width=width, height=height))
예제 #50
0
 def __init__(self,root):
    self.root = root
    self.model = Model()
    self.view = View(self.root)
    self.view.calculateButton.bind('<Button>',self.calculate)
예제 #51
0
	def __init__(self):
		View.__init__(self)
예제 #52
0
    def __init__(self, config = None):
        """
        Constructor.

        @param config:  L{Config} instance for settings
        """

        if not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")
        tickrate     = self.config.get("engine", "tickrate")
        Engine.__init__(self, fps = fps, tickrate = tickrate)

        pygame.init()

        self.title             = _("Frets on Fire")
        self.restartRequested  = False
        self.handlingException = False
        self.video             = Video(self.title)
        self.audio             = Audio()

        Log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")

        self.audio.pre_open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)
        pygame.init()
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        Log.debug("Initializing video.")
        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)

        # Enable the high priority timer if configured
        if self.config.get("engine", "highpriority"):
            Log.debug("Enabling high priority timer.")
            self.timer.highPriority = True

        viewport = glGetIntegerv(GL_VIEWPORT)
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.img = ImgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.server    = None
        self.sessions  = []
        self.mainloop  = self.loading

        # Load game modifications
        Mod.init(self)
        theme = Config.load(self.resource.fileName("theme.ini"))
        Theme.open(theme)

        # Make sure we are using the new upload URL
        if self.config.get("game", "uploadurl").startswith("http://kempele.fi"):
            self.config.set("game", "uploadurl", "http://fretsonfire.sourceforge.net/play")

        self.addTask(self.audio, synchronized = False)
        self.addTask(self.input, synchronized = False)
        self.addTask(self.view)
        self.addTask(self.resource, synchronized = False)
        self.data = Data(self.resource, self.img)

        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False

        Log.debug("Ready.")
예제 #53
0
class GameEngine(Engine):
    """The main game engine."""
    def __init__(self, config = None):
        """
        Constructor.

        @param config:  L{Config} instance for settings
        """

        if not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")
        tickrate     = self.config.get("engine", "tickrate")
        Engine.__init__(self, fps = fps, tickrate = tickrate)

        pygame.init()

        self.title             = _("Frets on Fire")
        self.restartRequested  = False
        self.handlingException = False
        self.video             = Video(self.title)
        self.audio             = Audio()

        Log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")

        self.audio.pre_open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)
        pygame.init()
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        Log.debug("Initializing video.")
        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)

        # Enable the high priority timer if configured
        if self.config.get("engine", "highpriority"):
            Log.debug("Enabling high priority timer.")
            self.timer.highPriority = True

        viewport = glGetIntegerv(GL_VIEWPORT)
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.img = ImgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.server    = None
        self.sessions  = []
        self.mainloop  = self.loading

        # Load game modifications
        Mod.init(self)
        theme = Config.load(self.resource.fileName("theme.ini"))
        Theme.open(theme)

        # Make sure we are using the new upload URL
        if self.config.get("game", "uploadurl").startswith("http://kempele.fi"):
            self.config.set("game", "uploadurl", "http://fretsonfire.sourceforge.net/play")

        self.addTask(self.audio, synchronized = False)
        self.addTask(self.input, synchronized = False)
        self.addTask(self.view)
        self.addTask(self.resource, synchronized = False)
        self.data = Data(self.resource, self.img)

        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False

        Log.debug("Ready.")

    def setStartupLayer(self, startupLayer):
        """
        Set the L{Layer} that will be shown when the all
        the resources have been loaded. See L{Data}

        @param startupLayer:    Startup L{Layer}
        """
        self.startupLayer = startupLayer

    def isDebugModeEnabled(self):
        return bool(self.debugLayer)

    def setDebugModeEnabled(self, enabled):
        """
        Show or hide the debug layer.

        @type enabled: bool
        """
        if enabled:
            self.debugLayer = DebugLayer(self)
        else:
            self.debugLayer = None

    def toggleFullscreen(self):
        """
        Toggle between fullscreen and windowed mode.

        @return: True on success
        """
        if not self.video.toggleFullscreen():
            # on windows, the fullscreen toggle kills our textures, se we must restart the whole game
            self.input.broadcastSystemEvent("restartRequested")
            self.config.set("video", "fullscreen", not self.video.fullscreen)
            return True
        self.config.set("video", "fullscreen", self.video.fullscreen)
        return True

    def restart(self):
        """Restart the game."""
        if not self.restartRequested:
            self.restartRequested = True
            self.input.broadcastSystemEvent("restartRequested")
        else:
                # evilynux - With self.audio.close(), calling self.quit() results in
                #            a crash. Calling the parent directly as a workaround.
            Engine.quit(self)

    def quit(self):
        self.audio.close()
        Engine.quit(self)

    def resizeScreen(self, width, height):
        """
        Resize the game screen.

        @param width:   New width in pixels
        @param height:  New height in pixels
        """
        self.view.setGeometry((0, 0, width, height))
        self.img.setGeometry((0, 0, width, height))

    def isServerRunning(self):
        return bool(self.server)

    def startServer(self):
        """Start the game server."""
        if not self.server:
            Log.debug("Starting server.")
            self.server = Server(self)
            self.addTask(self.server, synchronized = False)

    def connect(self, host):
        """
        Connect to a game server.

        @param host:  Name of host to connect to
        @return:      L{Session} connected to remote server
        """
        Log.debug("Connecting to host %s." % host)
        session = ClientSession(self)
        session.connect(host)
        self.addTask(session, synchronized = False)
        self.sessions.append(session)
        return session

    def stopServer(self):
        """Stop the game server."""
        if self.server:
            Log.debug("Stopping server.")
            self.removeTask(self.server)
            self.server = None

    def disconnect(self, session):
        """
        Disconnect a L{Session}

        param session:    L{Session} to disconnect
        """
        if session in self.sessions:
            Log.debug("Disconnecting.")
            self.removeTask(session)
            self.sessions.remove(session)

    def loadImgDrawing(self, target, name, fileName, textureSize = None):
        """
        Load an SVG drawing synchronously.

        @param target:      An object that will own the drawing
        @param name:        The name of the attribute the drawing will be assigned to
        @param fileName:    The name of the file in the data directory
        @param textureSize  Either None or (x, y), in which case the file will
                            be rendered to an x by y texture
        @return:            L{ImgDrawing} instance
        """
        return self.data.loadImgDrawing(target, name, fileName, textureSize)

    def loading(self):
        """Loading state loop."""
        done = Engine.run(self)
        self.clearScreen()

        if self.data.essentialResourcesLoaded():
            if not self.loadingScreenShown:
                self.loadingScreenShown = True
                Dialogs.showLoadingScreen(self, self.data.resourcesLoaded)
                if self.startupLayer:
                    self.view.pushLayer(self.startupLayer)
                self.mainloop = self.main
            self.view.render()
        self.video.flip()
        return done

    def clearScreen(self):
        self.img.clear(*Theme.backgroundColor)

    def main(self):
        """Main state loop."""

        # Tune the scheduler priority so that transitions are as smooth as possible
        if self.view.isTransitionInProgress():
            self.boostBackgroundThreads(False)
        else:
            self.boostBackgroundThreads(True)

        done = Engine.run(self)
        self.clearScreen()
        self.view.render()
        if self.debugLayer:
            self.debugLayer.render(1.0, True)
        self.video.flip()
        return done

    def run(self):
        try:
            return self.mainloop()
        except KeyboardInterrupt:
            sys.exit(0)
        except SystemExit:
            sys.exit(0)
        except Exception, e:
            def clearMatrixStack(stack):
                try:
                    glMatrixMode(stack)
                    for i in range(16):
                        glPopMatrix()
                except:
                    pass

            if self.handlingException:
                # A recursive exception is fatal as we can't reliably reset the GL state
                sys.exit(1)

            self.handlingException = True
            Log.error("%s: %s" % (e.__class__, e))
            import traceback
            traceback.print_exc()

            clearMatrixStack(GL_PROJECTION)
            clearMatrixStack(GL_MODELVIEW)

            Dialogs.showMessage(self, unicode(e))
            self.handlingException = False
            return True
예제 #54
0
	print "Second run, to check for leaks"
	run()
	for x in gc.get_objects():
		if id(x) not in old:
			print "New", type(x)
			print `x`[:80]
			for y in gc.get_referrers(x):
				if id(y) in old and y is not globals():
					print "\t%s" % `y`[:60]
	print "No. objects after first run:", old_len
	print "No. objects after second run:", len(gc.get_objects())
	
	sys.exit(0)

model = Model(source, dome_data = xml_data)
view = View(model, callback_handlers = (idle_add, idle_remove))

if profiling:
	import profile
	print "Profiling..."
	profile.run('run_nogui()')
else:
	run_nogui()

if view.chroots:
	raise Exception("Processing stopped in a chroot! -- not saving")

view.model.strip_space()

import shutil
예제 #55
0
SPEED = 0.075
BULLET_SPEED = 10
BULLET_DURATION = 60
BULLET_SIZE = 5
ANGULAR_VELOCITY = 4
VELOCITY_CAP = 5
SHOOT_DELAY = 10
SHIELD_SIZE = 20
NUM_BOTS = 10
NUM_WALLS = 20
map_dimensions = (3200, 1800)

camera_bounds = (854, 480)

logic = Logic()
view = View(camera_bounds, logic, map_dimensions)

min_respawn = (320, 240)
max_respawn = (3000, 1600)

respawn = random_respawn(min_respawn, max_respawn)

player_ship = Ship((320, 240), (15, 15), SHOOT_DELAY, SPEED, VELOCITY_CAP, ANGULAR_VELOCITY, respawn)
logic.add_ship(player_ship)

controller = ServerSideController(player_ship, logic, BULLET_SIZE, BULLET_SPEED, BULLET_DURATION, SHOOT_DELAY, SHIELD_SIZE)

def run_bot_func(bot):
    def on_run():
        if not bot.isDead():
            rng = random.randint(0, 30)
예제 #56
0
 def on_move(self, x, y):
     View.set_frame(self._window, Rect(x=x, y=y))
예제 #57
0
class FormCreator(wx.Frame):
    """
    FormCreator GUI class frame
    All design layout code goes into this class
    """
    def __init__(self, parent, title):
        """Initializer"""
        wx.Frame.__init__(self, parent, title=title)
        self.w, self.h = 800, 600

        # Basic frame information
        self.SetTitle("Form Creator " + Preferences.version)
        self.SetClientSize((self.w, self.h))
        self.Center()
        self.Maximize()
        bp = wx.BoxSizer(orient=wx.VERTICAL)
        bp.SetMinSize([self.w, self.h])  # set the min size of the window

        # Add the canvas for rectangular mappi8ng
        self.view = View(self)
        self.idtext = wx.TextCtrl(self, 33)
        self.applybutton = wx.Button(self, -1, " Apply ")
        self.filename = ""
        self.img = ""
        self.rmap_loaded = False
        self.idtext.SetFocus()

        self.listitems = ("text", "radio", "checkbox")
        self.listbox = wx.ListBox(self)
        for i, I in enumerate(self.listitems):
            self.listbox.Insert(I, i)

        # Bottom panel for text entry here with a horizontal sizer
        panelsizer = wx.BoxSizer(wx.HORIZONTAL)

        # Test button creation
        panelsizer.Add(self.applybutton, 0, wx.EXPAND)
        panelsizer.Add(self.idtext, 1, wx.EXPAND)
        panelsizer.Add(self.listbox, 2, wx.EXPAND)

        # Start doing sizers
        bp.Add(self.view, 1, wx.EXPAND)
        bp.Add(panelsizer, 0, wx.BOTTOM | wx.EXPAND)
        self.SetSizer(bp)
        self.SetAutoLayout(1)
        bp.Fit(self)

        # Status bar info and data
        self.CreateStatusBar()
        self.SetStatusText(Preferences.welcomeMessage)

        # File menu operations and buttons
        fmenu = wx.Menu()
        openbutton = fmenu.Append(wx.ID_OPEN, "Open", "Open up an image")
        savebutton = fmenu.Append(wx.ID_SAVE, "Save", "Save your work")
        closebutton = fmenu.Append(wx.ID_CLOSE, "Close", "Close an image mapping")
        exportbutton = fmenu.Append(wx.ID_ADD, "Export", "Export to a print page")
        printbutton = fmenu.Append(wx.ID_BOLD, "Print", "Print all rectangles to text")
        fmenu.AppendSeparator()
        aboutbutton = fmenu.Append(wx.ID_ABOUT, "About", "Info on this program")
        statsbutton = fmenu.Append(wx.ID_STATIC, "Stats", "Statistical data on the view")
        fmenu.AppendSeparator()
        exitbutton = fmenu.Append(wx.ID_EXIT, "E&xit", "Terminate the program")
        emenu = wx.Menu()
        filtbutton = emenu.Append(wx.ID_CUT, "Filter", "Filter any 'bad' rectangles we can't use")
        fmenu.AppendSeparator()
        cleanbutton = emenu.Append(wx.ID_ABORT, "Clean", "Remove any rectangles that don't have ID tags")
        deletebutton = emenu.Append(wx.ID_DELETE, "Delete", "Delete the current selection")
        delallbutton = emenu.Append(wx.ID_EXECUTE, "Delete All", "Delete all rectangles (panic mode!)")

        mb = wx.MenuBar()
        mb.Append(fmenu, "&File")
        mb.Append(emenu, "&Edit")

        # set menubar to be the main menubar of the frame
        self.SetMenuBar(mb)

        # set the frame to be shown on screen (this is important)
        self.Show(True)

        # Bindings
        self.Bind(wx.EVT_MENU, self.on_open, openbutton)
        self.Bind(wx.EVT_MENU, self.on_save, savebutton)
        self.Bind(wx.EVT_MENU, self.on_close, closebutton)
        self.Bind(wx.EVT_MENU, self.on_print, printbutton)
        self.Bind(wx.EVT_MENU, self.export_print_page, exportbutton)
        self.Bind(wx.EVT_MENU, self.on_about, aboutbutton)
        self.Bind(wx.EVT_MENU, self.on_stats, statsbutton)
        self.Bind(wx.EVT_MENU, self.on_exit, exitbutton)
        self.Bind(wx.EVT_MENU, self.filter, filtbutton)
        self.Bind(wx.EVT_MENU, self.cleanup, cleanbutton)
        self.Bind(wx.EVT_MENU, self.on_delete, deletebutton)
        self.Bind(wx.EVT_MENU, self.del_all, delallbutton)
        self.Bind(wx.EVT_LISTBOX, self.on_selection, self.listbox)
        self.Bind(wx.EVT_BUTTON, self.apply_name, self.applybutton)
        self.Bind(wx.EVT_TEXT, self.typing, self.idtext)

    def typing(self, event):
        """
        Set the text being typed to the rectangle's name
        """
        event.Skip()
        if self.view.image is not None:
            self.view.applyname(self.idtext.Value)

    def on_print(self, event):
        """Print button for debugging"""
        event.Skip()
        if self.view is not None:
            for r in self.view.rects:
                print("{0} : {1} - {2}".format(r.idtag, r.typerect, r.data))

    def on_open(self, event):
        """
        Open up an image and load it to the canvas
        """
        event.Skip()
        dirname = ""
        dlg = wx.FileDialog(self, "Choose a file", dirname, "", "*.*", wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            dirname = dlg.GetDirectory()
            self.img = join(dirname, self.filename)
            self.view.image = wx.Bitmap(self.img, type=wx.BITMAP_TYPE_ANY)
            self.view.rects = []
            self.view.Refresh()  # trigger onpaint
            self.SetTitle("Form Creator : " + self.img)

            # Read for an RMAP file
            fname = self.filename.split(".")
            fname.pop()
            rmap_file = join(dirname, ".".join(fname + ["rmap"]))

            if isfile(rmap_file):
                # the file is here!
                with open(rmap_file, "r") as f:
                    rmap_rects = loads(f.read())
                    self.view.read_json(rmap_rects)
                    self.rmap_loaded = True
                self.SetStatusText(Preferences.RmapFound)
            else:
                self.SetStatusText(Preferences.noRmapFound)
                self.rmap_loaded = False
        dlg.Destroy()

    def export_print_page(self, event):
        """Export a print page using a JSON file"""
        event.Skip()
        if self.view.image is not None:
            # We don't require an RMAP file, just rect data that we can generate
            dlg = wx.FileDialog(self, "Choose a JSON file to load", "", "", "", wx.SAVE)
            if dlg.ShowModal() == wx.ID_OK:
                filename = dlg.GetFilename()
                dirname = dlg.GetDirectory()
                dlg.Destroy()
            else:
                self.SetStatusText(Preferences.failedToOpen)
                return False
            rmap_data = self.view.rects
            try:
                with open(join(dirname, filename), "r") as f:
                    json_data = loads(f.read())
            except Exception as e:
                self.SetStatusText(Preferences.failedToExport)
                return False
            fd = self.img.split(".")
            fd.pop()
            fname = ".".join(fd)
            rmap_data = View.filter_list(rmap_data)
            rmap_data = View.clean_list(rmap_data)
            rmap_data = View.generate_data(rmap_data)
            self.write_html_printpage(self.filename, fname, rmap_data, json_data)
        else:
            self.SetStatusText(Preferences.noImageLoaded)

    def on_save(self, event):
        """
        Copy the image from SRC to the destination directory + folder
        Then write the rectangle data to HTML format
        and also a new readable JSON format (called .RMAP)
        """
        event.Skip()
        if self.view.image is not None:
            self.view.update_values()
            rmap_data = self.view.generate_rmap()

            if self.rmap_loaded:  # this means we previously had an RMAP file loaded, so save to that
                # Use self.img as the main determiner
                # remove extension of file
                fpath = self.img.split(".")
                ext = fpath.pop()
                fpath = ".".join(fpath)

                # rewrite the RMAP and HTML
                self.write_html_rmap(fpath, rmap_data,  fpath.split('\\').pop() + "." + ext)
                self.SetStatusText(Preferences.RmapSaved.format(fpath))
            else:
                dlg = wx.FileDialog(self, "Choose a name to save the file", "", "", "rmap", wx.SAVE)
                if dlg.ShowModal() == wx.ID_OK:
                    filename = dlg.GetFilename().replace(".rmap", "")
                    dirname = dlg.GetDirectory()
                    dlg.Destroy()
                else:
                    self.SetStatusText(Preferences.failedToSave)
                    return False
                # make a directory with the filename
                newdir = join(dirname, filename)
                mkdir(newdir)

                # Copy the original image
                copy(self.img, join(newdir, self.filename))
                fname = self.filename.split(".")
                new_fname = ".".join([filename, fname.pop()])
                rename(join(newdir, self.filename), join(newdir, new_fname))

                # export HTML/CSS data to a new HTML file
                self.write_html_rmap(join(newdir, filename), rmap_data, new_fname)
                self.SetStatusText(Preferences.RmapSaved.format(str(join(newdir, new_fname))))
        else:
            self.SetStatusText(Preferences.noImageLoaded)

    @staticmethod
    def write_html_rmap(filepath, rmap_data, new_fname=""):
        """HTML and RMAP export code"""
        with open(filepath+".rmap", "w") as F:  # dump the JSON RMAP
            F.write(FormCreator.export_json(rmap_data))
        with open(join(Preferences.staticFolder, Preferences.SkeletonFile), "r") as f:  # read skeleton file
            skeletal_data = f.read()
        with open(filepath+".html", "w") as f:  # write the HTML/css file
            page_title = new_fname
            css = 3*"\t" + ".sourceImage{ z-index: -1; }\n"
            html = 3*"\t" + "<img src=\"{0}\" class=\"sourceImage\" />\n".format(new_fname)
            text_size_divider = 9  # size to divide rect width by for HTML text
            for key, r in rmap_data.items():
                # append CSS - horiz: off by 10px, vert: off by 10px
                css += 3*"\t" + "."+key+"{position:absolute;top:"+str(r["y"]+10)+"px;left:"+str(r["x"]+10)+"px;}\n"
                # append HTML
                if r["typerect"] == "text" and r["idtag"].strip() != "":
                    i = 3*"\t" + "<input type=\"text\" class=\"{0}\" size=\"{1}\" name=\"{2}\" id=\"{2}\" />\n"
                    html += i.format(key, r["w"]/text_size_divider, r["idtag"])
                elif r["idtag"].strip() != "":  # don't add rects without tags
                    i = 3*"\t" + "<input type=\"{0}\" class=\"{1}\" name=\"{2}\" id=\"{2}\" value=\"{3}\" />\n"
                    html += i.format(r["typerect"], key, r["idtag"], r["value"])
            f.write(skeletal_data.format(page_title, css, html))

    @staticmethod
    def write_html_printpage(iname, filepath, rmap_data, json_data):
        """For future use in writing data to an HTML page (similar code as write_html_rmap)"""
        # TODO: data test writing to an HTML print page
        with open(join(Preferences.staticFolder, Preferences.SkeletonFile), "r") as f:
            skeletal_data = f.read()
        with open(filepath+".print.html", "w") as f:
            css = ".sourceImage{z-index:-1;}\n"
            html = "<img src=\"{0}\" class=\"sourceImage\" />\n".format(iname)
            for key, r in rmap_data.items():
                css += "."+key+"{position:absolute;top:"+str(r["y"]+10)+"px;left:"+str(r["x"]+10)+"px;}\n"
                if r["typerect"] == "text" and r["idtag"].strip() != "":
                    print(r)
                    html += "<p class=\"{0}\">{1}</p>".format(key, json_data[r["idtag"]]["value"])
                else:
                    # <input type"radio" checked> creates a checked radio
                    # we need json info if the field was selected
                    pass
            f.write(skeletal_data.format("", css, html))

    @staticmethod
    def export_json(data):
        """Export JSON etc"""
        return dumps(data, sort_keys=True, indent=4, separators=(',', ': '))

    def on_close(self, event):
        """Close the image and remove excess data from the viewer"""
        event.Skip()
        self.img = ""
        self.view.clear_all()
        self.rmap_loaded = False
        self.SetTitle("FormCreator " + Preferences.version)

    def on_selection(self, event):
        """Apply the selection from listbox to the rectangle selected (if any)"""
        event.Skip()
        n = self.listitems[self.listbox.GetSelection()]
        if self.view.image is not None:
            self.view.applytype(n)

    def filter(self, event):
        """Filter any bad rectangles from the buffer"""
        event.Skip()
        if self.view.image is not None:
            self.view.filter_rects()
            self.SetStatusText(Preferences.filterRects)

    def cleanup(self, event):
        """Cleaning function"""
        event.Skip()
        if self.view.image is not None:
            self.view.cleanup()
            self.SetStatusText(Preferences.cleanRects)

    def on_about(self, event):
        """Instruction dialog for the program"""
        event.Skip()
        dlg = wx.MessageDialog(self, "\n".join(Preferences.aboutAppInstructions), "About FormCreator", wx.OK)
        dlg.ShowModal()
        dlg.Destroy()

    def on_stats(self, event):
        """Statistical count data for the current view"""
        event.Skip()
        if self.view.image is not None:
            s, t, c, r, n = self.view.statistics()
            dlg = wx.MessageDialog(self, Preferences.statisticalData.format(s, t, c, r, n), "Statistics", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
        else:
            self.SetStatusText(Preferences.noImageLoaded)

    def on_exit(self, event):
        """Exit the program"""
        event.Skip()
        self.view.clear_all()
        self.Close(True)  # close program

    def on_delete(self, event):
        """Delete selected rect"""
        event.Skip()
        if self.view.image is not None:
            self.view.deleteselectedrect()
            self.SetStatusText(Preferences.deletingRect)

    def del_all(self, event):
        """Delete all rects"""
        event.Skip()
        if self.view.image is not None:
            self.view.deleteallrects()
            self.SetStatusText(Preferences.deletingAllRects)

    def set_type(self, text):
        """Change the selection in the listbox"""
        self.listbox.SetStringSelection(text)

    def apply_name(self, event):
        """Apply the text to the rectangle"""
        event.Skip()
        if self.view.image is not None:
            self.view.applyname(self.idtext.Value)
#end
예제 #58
0
    def __init__(self, parent, title):
        """Initializer"""
        wx.Frame.__init__(self, parent, title=title)
        self.w, self.h = 800, 600

        # Basic frame information
        self.SetTitle("Form Creator " + Preferences.version)
        self.SetClientSize((self.w, self.h))
        self.Center()
        self.Maximize()
        bp = wx.BoxSizer(orient=wx.VERTICAL)
        bp.SetMinSize([self.w, self.h])  # set the min size of the window

        # Add the canvas for rectangular mappi8ng
        self.view = View(self)
        self.idtext = wx.TextCtrl(self, 33)
        self.applybutton = wx.Button(self, -1, " Apply ")
        self.filename = ""
        self.img = ""
        self.rmap_loaded = False
        self.idtext.SetFocus()

        self.listitems = ("text", "radio", "checkbox")
        self.listbox = wx.ListBox(self)
        for i, I in enumerate(self.listitems):
            self.listbox.Insert(I, i)

        # Bottom panel for text entry here with a horizontal sizer
        panelsizer = wx.BoxSizer(wx.HORIZONTAL)

        # Test button creation
        panelsizer.Add(self.applybutton, 0, wx.EXPAND)
        panelsizer.Add(self.idtext, 1, wx.EXPAND)
        panelsizer.Add(self.listbox, 2, wx.EXPAND)

        # Start doing sizers
        bp.Add(self.view, 1, wx.EXPAND)
        bp.Add(panelsizer, 0, wx.BOTTOM | wx.EXPAND)
        self.SetSizer(bp)
        self.SetAutoLayout(1)
        bp.Fit(self)

        # Status bar info and data
        self.CreateStatusBar()
        self.SetStatusText(Preferences.welcomeMessage)

        # File menu operations and buttons
        fmenu = wx.Menu()
        openbutton = fmenu.Append(wx.ID_OPEN, "Open", "Open up an image")
        savebutton = fmenu.Append(wx.ID_SAVE, "Save", "Save your work")
        closebutton = fmenu.Append(wx.ID_CLOSE, "Close", "Close an image mapping")
        exportbutton = fmenu.Append(wx.ID_ADD, "Export", "Export to a print page")
        printbutton = fmenu.Append(wx.ID_BOLD, "Print", "Print all rectangles to text")
        fmenu.AppendSeparator()
        aboutbutton = fmenu.Append(wx.ID_ABOUT, "About", "Info on this program")
        statsbutton = fmenu.Append(wx.ID_STATIC, "Stats", "Statistical data on the view")
        fmenu.AppendSeparator()
        exitbutton = fmenu.Append(wx.ID_EXIT, "E&xit", "Terminate the program")
        emenu = wx.Menu()
        filtbutton = emenu.Append(wx.ID_CUT, "Filter", "Filter any 'bad' rectangles we can't use")
        fmenu.AppendSeparator()
        cleanbutton = emenu.Append(wx.ID_ABORT, "Clean", "Remove any rectangles that don't have ID tags")
        deletebutton = emenu.Append(wx.ID_DELETE, "Delete", "Delete the current selection")
        delallbutton = emenu.Append(wx.ID_EXECUTE, "Delete All", "Delete all rectangles (panic mode!)")

        mb = wx.MenuBar()
        mb.Append(fmenu, "&File")
        mb.Append(emenu, "&Edit")

        # set menubar to be the main menubar of the frame
        self.SetMenuBar(mb)

        # set the frame to be shown on screen (this is important)
        self.Show(True)

        # Bindings
        self.Bind(wx.EVT_MENU, self.on_open, openbutton)
        self.Bind(wx.EVT_MENU, self.on_save, savebutton)
        self.Bind(wx.EVT_MENU, self.on_close, closebutton)
        self.Bind(wx.EVT_MENU, self.on_print, printbutton)
        self.Bind(wx.EVT_MENU, self.export_print_page, exportbutton)
        self.Bind(wx.EVT_MENU, self.on_about, aboutbutton)
        self.Bind(wx.EVT_MENU, self.on_stats, statsbutton)
        self.Bind(wx.EVT_MENU, self.on_exit, exitbutton)
        self.Bind(wx.EVT_MENU, self.filter, filtbutton)
        self.Bind(wx.EVT_MENU, self.cleanup, cleanbutton)
        self.Bind(wx.EVT_MENU, self.on_delete, deletebutton)
        self.Bind(wx.EVT_MENU, self.del_all, delallbutton)
        self.Bind(wx.EVT_LISTBOX, self.on_selection, self.listbox)
        self.Bind(wx.EVT_BUTTON, self.apply_name, self.applybutton)
        self.Bind(wx.EVT_TEXT, self.typing, self.idtext)
예제 #59
0
 def __init__(self):
     self.board = Board()
     self.evaluation = Evaluation(self.board)
     self.view = View(self.board)
예제 #60
0
class Controller:
    def __init__(self):
        self.model = Model()
        self.view = View()
        self.firstTime = True
        self.result = 0.0
        self.a = 0.0
        self.b = 0.0
        self.usePrev = 0
    
    def run(self):
        while True:
            self.view.printMenu()
            selection = self.view.inputSelection()
            if selection <= 0:
                continue
            elif selection == 5:
                self.view.terminate()
                return
            elif not self.firstTime:
                if self.model.isNumber(self.result):
                    self.usePrev = self.view.usePrevious(self.result)
                else:
                    self.usePrev = 0
            else:
                self.firstTime = False
            if self.usePrev == 0:
                # Enter both operands
                self.a = self.view.oneOp(1)
                self.b = self.view.oneOp(2)
            elif self.usePrev == 1:
                # Enter second operand
                self.a = self.result
                self.view.printOp(1, self.a)
                self.b = self.view.oneOp(2)
            elif self.usePrev == 2:
                # Enter first operand
                self.a = self.view.oneOp(1)
                self.b = self.result
                self.view.printOp(2, self.b)
            else:
                # ERROR: Should never reach this block
                self.view.printInvalidArg()
                continue
            self.view.printCalc(selection, self.a, self.b)
            self.result = self.model.calculate(selection, self.a, self.b)
            self.view.printResult(self.result)
            if self.view.anotherOp():
                continue
            else:
                return