def __init__(self): self.display = (1000, 800) # window'un boyutlari self.mouseX = 0 # mouse hareketinin x koordinati self.mouseY = 0 # mouse hareketinin y koordinati self.flag = False self.flag2 = False self.currentValue = 0 self.antenna = Antenna() self.plane = Plane() self.ground = Ground(100, 100) # ground'un boyutlari self.sidebar = SideBar()
def initModule(self): self.mainpage = MainPage(self) self.sidebar = SideBar(self) self.sidebar.hide() self.tray = TraySet(self) self.tray.show() self.about = AboutMemo() self.about.hide() self.setting = SettingBar(self) self.setting.hide() self.windowIcon = QtGui.QIcon(css.AppIconPath) self.setWindowIcon(self.windowIcon) self.grabKeyboard()
def __init__(self, width, height): global window window = Graphics.window self.width = width self.height = height self.cardWidth = 75 self.cardHeight = 100 self.activePlayer = 0 self.selectedCard = None self.hands = [None] * 2 self.hands[0] = [None] * self.HAND_SIZE self.hands[1] = [None] * self.HAND_SIZE self.powerHandles = [None] * 2 self.menu = Menu(self) self.sideBar = SideBar() self.sideBar.addItem("LClick cards to select them") self.sideBar.addItem("LClick placed tiles to rotate them") self.sideBar.addItem("RClick tile for tile menu") self.sideBar.addItem("RClick card for card menu") self.sideBar.addItem("D to draw") self.sideBar.addItem("T to end turn") self.sideBar.addItem("R to reload json data") self.sideBar.addItem("LClick board to place selected tile") self.sideBar.addItem("") self.cards = [] self.deckSize = 0 self.parseTiles() self.makeDeck() self.sideBar.addItem("") # Draw opening hands for player in xrange(0, 2): for i in xrange(0, 5): self.hands[player][i] = self.deck.pop() self.grid = [[None for y in range(self.height)] for x in range(self.width)] base0 = Tile(self.tileData[0], 0, self.width / 2, self.height - 1, 0) base1 = Tile(self.tileData[0], 0, self.width / 2, 0, 1) base0.active = base1.active = True self.grid[self.width / 2][0] = base1 self.grid[self.width / 2][self.height - 1] = base0 self.calculatePower(0) self.calculatePower(1)
def __init__(self): super(Board, self).__init__() Window.bind(on_key_down=self.on_keyboard_down) self.sidebar = SideBar() self.bindsidebarbutton() self.x1 = self.y1 = 0 self.mode = 0 # 0 for camera and 1 for whiteboard self.draw = False self.erase = False self.canvas = None self.whiteboard = None self.overlaypen = None self.color = (255, 100, 145) self.record = False self.files = list() self.filebox = FileBox() self.popup = Popup(title='Files', title_size=40, title_color=(0, 0, 0, 1), content=self.filebox, background_color=(255, 3, 214, 0.1), background="water.png")
class GtkUI(object): def __init__(self, args): self.daemon_bps = (0, 0, 0) # Setup signals try: import gnome.ui import gnome #Suppress: Warning: Attempt to add property GnomeProgram::*** after class was initialised original_filters = warnings.filters[:] warnings.simplefilter("ignore") try: self.gnome_prog = gnome.init("Deluge", deluge.common.get_version()) finally: warnings.filters = original_filters self.gnome_client = gnome.ui.master_client() def on_die(*args): reactor.stop() self.gnome_client.connect("die", on_die) log.debug("GNOME session 'die' handler registered!") except Exception, e: log.warning( "Unable to register a 'die' handler with the GNOME session manager: %s", e) if deluge.common.windows_check(): from win32api import SetConsoleCtrlHandler from win32con import CTRL_CLOSE_EVENT from win32con import CTRL_SHUTDOWN_EVENT def win_handler(ctrl_type): log.debug("ctrl_type: %s", ctrl_type) if ctrl_type in (CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT): reactor.stop() return 1 SetConsoleCtrlHandler(win_handler) if deluge.common.osx_check() and Gdk.WINDOWING == "quartz": import gtkosx_application self.osxapp = gtkosx_application.gtkosx_application_get() def on_die(*args): reactor.stop() self.osxapp.connect("NSApplicationWillTerminate", on_die) # Set process name again to fix gtk issue setproctitle(getproctitle()) # Attempt to register a magnet URI handler with gconf, but do not overwrite # if already set by another program. common.associate_magnet_links(False) # Make sure gtkui.conf has at least the defaults set self.config = deluge.configmanager.ConfigManager( "gtkui.conf", DEFAULT_PREFS) # We need to check on exit if it was started in classic mode to ensure we # shutdown the daemon. self.started_in_classic = self.config["classic_mode"] # Start the IPC Interface before anything else.. Just in case we are # already running. self.queuedtorrents = QueuedTorrents() self.ipcinterface = IPCInterface(args) # Initialize gdk threading Gdk.threads_init() GObject.threads_init() # We make sure that the UI components start once we get a core URI client.set_disconnect_callback(self.__on_disconnect) self.trackericons = TrackerIcons() self.sessionproxy = SessionProxy() # Initialize various components of the gtkui self.mainwindow = MainWindow() self.menubar = MenuBar() self.toolbar = ToolBar() self.torrentview = TorrentView() self.torrentdetails = TorrentDetails() self.sidebar = SideBar() self.filtertreeview = FilterTreeView() self.preferences = Preferences() self.systemtray = SystemTray() self.statusbar = StatusBar() self.addtorrentdialog = AddTorrentDialog() if deluge.common.osx_check() and Gdk.WINDOWING == "quartz": def nsapp_open_file(osxapp, filename): # Will be raised at app launch (python opening main script) if filename.endswith('Deluge-bin'): return True from deluge.ui.gtkui.ipcinterface import process_args process_args([filename]) self.osxapp.connect("NSApplicationOpenFile", nsapp_open_file) from menubar_osx import menubar_osx menubar_osx(self, self.osxapp) self.osxapp.ready() # Initalize the plugins self.plugins = PluginManager() # Show the connection manager self.connectionmanager = ConnectionManager() from twisted.internet.task import LoopingCall rpc_stats = LoopingCall(self.print_rpc_stats) rpc_stats.start(10) reactor.callWhenRunning(self._on_reactor_start) # Start the gtk main loop Gdk.threads_enter() reactor.run() self.shutdown() Gdk.threads_leave()
class Window(QWidget): showMemo = pyqtSignal(bool) def __init__(self, data=None): super(Window, self).__init__() self.initData(data) self.initUi() self.initModule() self.setModule() self.funcLink() #data self.dataLoad() def initData(self, data): self.autohide = False self.data = read(data) self.memoSettings = readMemoSettings(data) self.uiSettings = readMemoUi(data) date = QDate.currentDate() date = date.toString(Qt.ISODate) if self.data['login_date'] != date: self.data['login_date'] = date write(self.data) def funcLink(self): # button self.mainpage.homeBtn.clicked.connect(self.flexSideBar) self.sidebar.newBtn.clicked.connect(self.addMemo) self.sidebar.setBtn.clicked.connect(self.settingMemo) self.sidebar.dataBtn.clicked.connect(self.dataStatistics) self.sidebar.aboutBtn.clicked.connect(self.aboutMemo) def initUi(self): self.setMinimumWidth(600) self.setMaximumWidth(600) self.layout = QHBoxLayout() self.layoutl = QVBoxLayout() self.layoutr = QVBoxLayout() #self.layout.setMargin(0) self.layout.setSpacing(0) # hide menu bar if self.uiSettings['is_up']: self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool | Qt.WindowStaysOnTopHint) else: self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool) self.setAttribute(Qt.WA_TranslucentBackground) def initModule(self): self.mainpage = MainPage(self) self.sidebar = SideBar(self) self.sidebar.hide() self.tray = TraySet(self) self.tray.show() self.about = AboutMemo() self.about.hide() self.setting = SettingBar(self) self.setting.hide() self.statistics = DataStatistics(self) self.statistics.hide() self.windowIcon = QIcon(css.AppIconPath) self.setWindowIcon(self.windowIcon) self.grabKeyboard() def setModule(self): self.layoutl.addWidget(self.mainpage) self.layoutl.addWidget(self.sidebar) self.layoutl.addStretch(1) #set main layout self.layout.addLayout(self.layoutl) self.layout.addLayout(self.layoutr) self.setLayout(self.layout) def dataLoad(self): content = readMemoContent(self.data) if_done = readMemoPerformance(self.data) if self.data['memo_num'] > 0: for i in range(self.data['memo_num']): info = {} info.update(id=i + 1, content=content[i], if_done=if_done[i]) info.update(self.memoSettings) self.loadMemo(info) def loadMemo(self, data): label = Memo(self, data) allCount = self.layoutr.count() if allCount == 0: self.layoutr.addWidget(label) else: self.layoutr.insertWidget(allCount + 1, label) def addMemo(self): #set dict message about single memo list = self.data['memo_data'] numInfo = len(list) > 0 and list[-1]['id'] or 0 info = {} info.update(id=numInfo + 1) info.update(self.memoSettings) #get the time of creating memo date = QDate.currentDate() date = date.toString(Qt.ISODate) #initialize memo object allCount = self.layoutr.count() label = Memo(self, info) if allCount == 0: self.layoutr.addWidget(label) else: self.layoutr.insertWidget(allCount + 1, label) #save new memo's message memo_data = {} memo_data.update(id=numInfo + 1, content='It is empty!', set_date=date, if_done=[]) self.data['memo_data'].append(memo_data) self.data['memo_num'] = len(list) write(self.data) def aboutMemo(self): self.about.show() def settingMemo(self): self.setting.show() def dataStatistics(self): self.statistics.show() def getTrashPos(self): return self.mainpage.getTrashPos() def flexSideBar(self): if self.sidebar.isHidden(): self.sidebar.show() self.showMemo.emit(True) else: self.sidebar.hide() self.showMemo.emit(False) if self.mainpage.homeLabel.isHidden(): self.mainpage.homeLabel.show() def autoHide(self): x = self.pos().x() y = self.pos().y() desk = QApplication.desktop() if x < -40: self.sidebar.hide() self.showMemo.emit(False) self.move(-65, y) self.autohide = True elif y < -40: self.sidebar.hide() self.showMemo.emit(False) self.move(x, -125) self.autohide = True elif x > desk.width() - 99: self.sidebar.hide() self.showMemo.emit(False) self.move(desk.width() - 65, y) self.autohide = True elif self.autohide: self.sidebar.show() self.showMemo.emit(True) self.autohide = False #move without form def mousePressEvent(self, QMouseEvent): if QMouseEvent.button() == Qt.LeftButton: self.flag = True self.m_Position = QMouseEvent.globalPos() - self.pos() QMouseEvent.accept() self.setCursor(QCursor(Qt.OpenHandCursor)) def mouseMoveEvent(self, QMouseEvent): if Qt.LeftButton and self.flag: self.move(QMouseEvent.globalPos() - self.m_Position) QMouseEvent.accept() def mouseReleaseEvent(self, QMouseEvent): self.flag = False self.setCursor(QCursor(Qt.ArrowCursor)) self.autoHide() #keyboard answer def keyPressEvent(self, QKeyEvent): if QKeyEvent.key() == 0x60: #0x60 means ` if self.isVisible(): self.hide()
from app import app from sidebar import SideBar from table import PersonalTable from barchart import BarChart import dash_bootstrap_components as dbc app.layout = dbc.Row( [ dbc.Col([SideBar()], width=3, className="bg-dark"), # slider dbc.Col([BarChart(), PersonalTable()], width=9), # content ], className="vh-100") if __name__ == "__main__": app.run_server(debug=True)
class GtkUI(object): def __init__(self, args): self.daemon_bps = (0, 0, 0) # Setup signals try: import gnome.ui import gnome self.gnome_prog = gnome.init("Deluge", deluge.common.get_version()) self.gnome_client = gnome.ui.master_client() def on_die(*args): reactor.stop() self.gnome_client.connect("die", on_die) log.debug("GNOME session 'die' handler registered!") except Exception, e: log.warning( "Unable to register a 'die' handler with the GNOME session manager: %s", e) if deluge.common.windows_check(): from win32api import SetConsoleCtrlHandler from win32con import CTRL_CLOSE_EVENT from win32con import CTRL_SHUTDOWN_EVENT def win_handler(ctrl_type): log.debug("ctrl_type: %s", ctrl_type) if ctrl_type in (CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT): reactor.stop() return 1 SetConsoleCtrlHandler(win_handler) # Attempt to register a magnet URI handler with gconf, but do not overwrite # if already set by another program. common.associate_magnet_links(False) # Make sure gtkui.conf has at least the defaults set self.config = deluge.configmanager.ConfigManager( "gtkui.conf", DEFAULT_PREFS) # We need to check on exit if it was started in classic mode to ensure we # shutdown the daemon. self.started_in_classic = self.config["classic_mode"] # Start the IPC Interface before anything else.. Just in case we are # already running. self.queuedtorrents = QueuedTorrents() self.ipcinterface = IPCInterface(args) # Initialize gdk threading gtk.gdk.threads_init() # We make sure that the UI components start once we get a core URI client.set_disconnect_callback(self.__on_disconnect) self.trackericons = TrackerIcons() self.sessionproxy = SessionProxy() # Initialize various components of the gtkui self.mainwindow = MainWindow() self.menubar = MenuBar() self.toolbar = ToolBar() self.torrentview = TorrentView() self.torrentdetails = TorrentDetails() self.sidebar = SideBar() self.filtertreeview = FilterTreeView() self.preferences = Preferences() self.systemtray = SystemTray() self.statusbar = StatusBar() self.addtorrentdialog = AddTorrentDialog() # Initalize the plugins self.plugins = PluginManager() # Late import because of setting up translations from connectionmanager import ConnectionManager # Show the connection manager self.connectionmanager = ConnectionManager() from twisted.internet.task import LoopingCall rpc_stats = LoopingCall(self.print_rpc_stats) rpc_stats.start(10) reactor.callWhenRunning(self._on_reactor_start) # Initialize gdk threading gtk.gdk.threads_enter() reactor.run() self.shutdown() gtk.gdk.threads_leave()
class Application: def __init__(self): self.display = (1000, 800) # window'un boyutlari self.mouseX = 0 # mouse hareketinin x koordinati self.mouseY = 0 # mouse hareketinin y koordinati self.flag = False self.flag2 = False self.currentValue = 0 self.antenna = Antenna() self.plane = Plane() self.ground = Ground(100, 100) # ground'un boyutlari self.sidebar = SideBar() def resetCamera(self): glMatrixMode( GL_PROJECTION ) # characteristics of camera such as clip planes, field of view, projection method glLoadIdentity() # replace the current matrix with the identity matrix width, height = self.display # display'in degerleri width ve height'a atandi gluPerspective(90.0, width / float(height), 1, 200.0) # set up a perspective projection matrix glTranslatef(0.0, 0.0, -5) # multiply the current matrix by a translation matrix glEnable(GL_DEPTH_TEST) # enable server-side GL capabilities glMatrixMode( GL_MODELVIEW ) # model matrix defines the frame’s position of the primitives you are going to draw # ModelView is the matrix that represents your camera(position, pointing and up vector.) # The reason for two separate matrices, instead of one, is that lighting is applied after the modelview view matrix # (i.e. on eye coordinates) and before the projection matrix. Otherwise, the matrices could be combined. def start(self): glutInit(sys.argv) # used to initialize the GLUT library pygame.init() # initialize all imported pygame modules self.screen = pygame.display.set_mode( self.display, OPENGL | DOUBLEBUF | OPENGLBLIT) # initialize a window or screen for display glLightfv(GL_LIGHT0, GL_POSITION, (-40, 200, 100, 0.0)) # set light source parameters glLightfv(GL_LIGHT0, GL_AMBIENT, (0.2, 0.2, 0.2, 1.0)) # set light source parameters glLightfv(GL_LIGHT0, GL_DIFFUSE, (0.5, 0.5, 0.5, 1.0)) # set light source parameters glEnable(GL_LIGHT0) # enable server-side GL capabilities glEnable(GL_LIGHTING) # enable server-side GL capabilities glEnable(GL_COLOR_MATERIAL) # enable server-side GL capabilities glEnable(GL_DEPTH_TEST) # enable server-side GL capabilities glShadeModel(GL_SMOOTH) # most obj files expect to be smooth-shaded self.resetCamera() self.antenna.prepare() # antenna objesi olusturuldu self.plane.prepare() # plane objesi olusturuldu self.loop() def check(self): glMatrixMode(GL_PROJECTION) # kamera ayarlarını sıfırla for event in pygame.event.get( ): # pygame.event.get = (get events from the queue) if event.type == pygame.QUIT: self.plane.stop() # plane objesi icin thread sona erer pygame.quit() # uninitialize all pygame modules quit() if event.type == pygame.MOUSEBUTTONDOWN: # eger mouse'a basili ise if event.button == 4: # forward glScaled(1.05, 1.05, 1.05) # zoom-in elif event.button == 5: # backward glScaled(0.95, 0.95, 0.95) # zoom-out if pygame.key.get_pressed()[K_LCTRL] and pygame.mouse.get_pressed( )[0]: # object rotation (CTRL ve mouse'un sol butonuna basilmis ise) if self.flag == True: # ilk basistaki hareketi engellemek icin self.mouseX, self.mouseY = pygame.mouse.get_rel( ) # get the amount of mouse movement glRotatef(self.mouseX / 5, 0.0, 0.0, 1.0) glRotatef(self.mouseY / 5, cos(radians(self.currentValue)), abs(sin(radians(self.currentValue))), 0.0) self.currentValue += self.mouseX / 5 elif self.flag == False: pygame.mouse.get_rel() # get the amount of mouse movement self.flag = True else: self.flag = False if pygame.key.get_pressed()[K_LCTRL] and pygame.mouse.get_pressed( )[2]: # camera rotation (CTRL ve mouse'un sag kligine basilmis ise) if self.flag2 == True: # ilk basistaki hareketi engellemek icin self.mouseX, self.mouseY = pygame.mouse.get_rel( ) # get the amount of mouse movement glTranslatef(-self.mouseX / 25, self.mouseY / 25, 0.0) elif self.flag2 == False: pygame.mouse.get_rel() # get the amount of mouse movement self.flag2 = True else: self.flag2 = False if event.type == pygame.KEYDOWN and event.key == pygame.K_r: # eger klavyeye basilmissa ve basilan harf r ise self.currentValue = 0 self.resetCamera() glMatrixMode( GL_MODELVIEW ) # model çizmek için matrisi sıfırla. Applies subsequent matrix operations to the modelview matrix stack. def loop(self): self.plane.start() # plane objesi icin thread baslatilir self.sidebar.setFunc(self.antenna, self.plane) while True: glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # clear buffers to preset values self.antenna.rotateToPoint(self.plane.coord[0], self.plane.coord[1], self.plane.coord[2]) self.check() # mouse ve klavye kontrolleri icin self.ground.draw() # ground objesini cizdir self.antenna.draw() # antenna objesini cizdir self.plane.draw() # plane objesini cizdir self.sidebar.draw() #sidebar objesini cizdir pygame.display.flip( ) # update the full display surface to the screen pygame.time.wait(10) # pause the program for an amount of time
class Window(QWidget): def __init__(self, data=None): super(Window, self).__init__() self.initData(data) self.initUi() self.initModule() self.setModule() #hide menu bar self.setWindowFlags(Qt.Qt.FramelessWindowHint) self.setAttribute(Qt.Qt.WA_TranslucentBackground) #button self.mainpage.homeBtn.clicked.connect(self.flexSideBar) self.sidebar.newBtn.clicked.connect(self.addMemo) self.sidebar.setBtn.clicked.connect(self.settingMemo) self.sidebar.aboutBtn.clicked.connect(self.aboutMemo) #data self.dataLoad() def initData(self, data): self.data = read(data) self.memoSettings = readMemoSettings(data) def initUi(self): self.setWindowTitle('Memo') self.setMinimumWidth(600) self.setMaximumWidth(600) self.layout = QHBoxLayout() self.layoutl = QVBoxLayout() self.layoutr = QVBoxLayout() #self.layout.setMargin(0) self.layout.setSpacing(0) def initModule(self): self.mainpage = MainPage(self) self.sidebar = SideBar(self) self.sidebar.hide() self.tray = TraySet(self) self.tray.show() self.about = AboutMemo() self.about.hide() self.setting = SettingBar(self) self.setting.hide() self.windowIcon = QtGui.QIcon(css.AppIconPath) self.setWindowIcon(self.windowIcon) self.grabKeyboard() def setModule(self): self.layoutl.addWidget(self.mainpage) self.layoutl.addWidget(self.sidebar) self.layoutl.addStretch(1) #set main layout self.layout.addLayout(self.layoutl) self.layout.addLayout(self.layoutr) self.setLayout(self.layout) def dataLoad(self): content = readMemoContent(self.data) settings = readMemoSettings(self.data) if self.data['memo_num'] > 0: for i in range(self.data['memo_num']): info = {} info.update(id=i + 1, content=content[i]) info.update(settings) self.loadMemo(info) def loadMemo(self, data): label = Memo(self, data) allCount = self.layoutr.count() if allCount == 0: self.layoutr.addWidget(label) else: self.layoutr.insertWidget(allCount + 1, label) def addMemo(self): list = self.data['memo_data'] numInfo = len(list) > 0 and list[-1]['id'] or 0 info = {} info.update(id=numInfo + 1) info.update(self.memoSettings) allCount = self.layoutr.count() label = Memo(self, info) if allCount == 0: self.layoutr.addWidget(label) else: self.layoutr.insertWidget(allCount + 1, label) memo_data = {} memo_data.update(id=numInfo + 1, content='It is empty!', set_date='', if_done={}) self.data['memo_data'].append(memo_data) self.data['memo_num'] = len(list) write(self.data) def aboutMemo(self): self.about.show() def settingMemo(self): self.setting.show() def getTrashPos(self): return self.mainpage.getTrashPos() def flexSideBar(self): if self.sidebar.isHidden(): self.sidebar.show() else: self.sidebar.hide() #move without form def mousePressEvent(self, QMouseEvent): if QMouseEvent.button() == Qt.Qt.LeftButton: self.flag = True self.m_Position = QMouseEvent.globalPos() - self.pos() QMouseEvent.accept() self.setCursor(Qt.QCursor(Qt.Qt.OpenHandCursor)) def mouseMoveEvent(self, QMouseEvent): if Qt.Qt.LeftButton and self.flag: self.move(QMouseEvent.globalPos() - self.m_Position) QMouseEvent.accept() def mouseReleaseEvent(self, QMouseEvent): self.flag = False self.setCursor(Qt.QCursor(Qt.Qt.ArrowCursor)) #keyboard answer def keyPressEvent(self, QKeyEvent): if QKeyEvent.key() == 0x60: #0x60 means ` if self.isVisible(): self.hide()
import streamlit as st from PIL import Image from vqa.vqa import VQA import torch from vqa.visualisations.vis import show_architecture from vqa.visualisations.vis import hbarplot import pandas as pd from slit.bb import BoundingBox from slit.attmaps import TextSelfAttMaps import numpy as np from sidebar import SideBar st.title('AMA: Visualizing attentions for Visual Question Answering') sb = SideBar() model_name = sb.model_name question = sb.question image_idx = sb.image_idx st.markdown("### Model Architecture") show_architecture(model_name) # Load the VQA model just after UI is loaded if (model_name is not None): vqa_object = VQA(model_name) image = None image_feat = None bboxes = None if (image_idx is not None):
class Game: TILE_SIZE = 50 HAND_SIZE = 7 def __init__(self, width, height): global window window = Graphics.window self.width = width self.height = height self.cardWidth = 75 self.cardHeight = 100 self.activePlayer = 0 self.selectedCard = None self.hands = [None] * 2 self.hands[0] = [None] * self.HAND_SIZE self.hands[1] = [None] * self.HAND_SIZE self.powerHandles = [None] * 2 self.menu = Menu(self) self.sideBar = SideBar() self.sideBar.addItem("LClick cards to select them") self.sideBar.addItem("LClick placed tiles to rotate them") self.sideBar.addItem("RClick tile for tile menu") self.sideBar.addItem("RClick card for card menu") self.sideBar.addItem("D to draw") self.sideBar.addItem("T to end turn") self.sideBar.addItem("R to reload json data") self.sideBar.addItem("LClick board to place selected tile") self.sideBar.addItem("") self.cards = [] self.deckSize = 0 self.parseTiles() self.makeDeck() self.sideBar.addItem("") # Draw opening hands for player in xrange(0, 2): for i in xrange(0, 5): self.hands[player][i] = self.deck.pop() self.grid = [[None for y in range(self.height)] for x in range(self.width)] base0 = Tile(self.tileData[0], 0, self.width / 2, self.height - 1, 0) base1 = Tile(self.tileData[0], 0, self.width / 2, 0, 1) base0.active = base1.active = True self.grid[self.width / 2][0] = base1 self.grid[self.width / 2][self.height - 1] = base0 self.calculatePower(0) self.calculatePower(1) def makeDeck(self, firstRun=True): self.deck = [None] * self.deckSize i = 0 index = 0 for tile in self.tileData: letter = chr(ord('A') + i) if firstRun is True: self.sideBar.addItem(letter + " - " + tile['name']) for j in xrange(0, tile['number']): self.deck[index] = i index += 1 i += 1 shuffle(self.deck) def parseTiles(self): json_data = open('tiles.json') self.tileData = json.load(json_data) json_data.close() self.deckSize = 0 for tile in self.tileData: self.deckSize += tile['number'] def reloadData(self): self.parseTiles() self.makeDeck(False) for col in self.grid: for tile in col: if tile is not None: tile.loadData(self.tileData[tile.mID]) def calculatePower(self, player=None): if player is None: player = self.activePlayer x = self.width / 2 # HACKHACKHACKHACKHACKHACKHACK Hack y = (self.height - 1) * (1 - player) base = self.grid[x][y] for col in self.grid: for tile in col: if tile is not None: tile.checked = False power = self.powerBFS(base, player) output = "Player " + str(player + 1) + " power: " + str(power) if self.powerHandles[player] is None: self.powerHandles[player] = self.sideBar.addItem(output) else: self.sideBar.editItem(output, self.powerHandles[player]) def powerBFS(self, tile, player): tile.checked = True power = 0 if tile.active: power += tile.power con = tile.getConnections() adjacent = [None] * 4 if tile.y != 0: adjacent[0] = self.grid[tile.x][tile.y - 1] if tile.x != self.width - 1: adjacent[1] = self.grid[tile.x + 1][tile.y] if tile.y != self.height - 1: adjacent[2] = self.grid[tile.x][tile.y + 1] if tile.x != 0: adjacent[3] = self.grid[tile.x - 1][tile.y] for i in xrange(0, 4): other = adjacent[i] if other is None or other.owner is not player or other.checked is True: continue if con[i] is True and other.getConnections()[(i + 2) % 4] is True: power += self.powerBFS(other, player) return power ## DRAW FUNCTIONS ## def draw(self): global DRAW_OFFSET, window self.drawBoard() DRAW_OFFSET['y'] += self.height * Tile.SIZE self.drawHand() DRAW_OFFSET['y'] -= self.height * Tile.SIZE DRAW_OFFSET['x'] += self.width * Tile.SIZE self.sideBar.draw(window) DRAW_OFFSET['x'] -= self.width * Tile.SIZE self.menu.draw(window) def drawBoard(self): global DRAW_OFFSET, window box = list((DRAW_OFFSET['x'], DRAW_OFFSET['y'], 0, 0)) box[2] = self.width * Tile.SIZE box[3] = self.height * Tile.SIZE window.fill(pygame.Color('grey'), box, 0) box[2] = Tile.SIZE box[3] = Tile.SIZE for x in xrange(0, len(self.grid)): box[1] = DRAW_OFFSET['y'] for y in xrange(0, len(self.grid[x])): tile = self.grid[x][y] if tile is None: pygame.draw.rect(window, pygame.Color('red'), box, 1) else: tile.draw(window, box[0], box[1]) box[1] += Tile.SIZE box[0] += Tile.SIZE def drawHand(self): global DRAW_OFFSET, window white = pygame.Color('white') black = pygame.Color('black') green = pygame.Color('green') blue = pygame.Color('blue') red = pygame.Color('red') box = list((DRAW_OFFSET['x'], DRAW_OFFSET['y'], 0, 0)) box[2] = self.width * Tile.SIZE box[3] = 100 window.fill(blue if self.activePlayer == 0 else red, box, 0) box = list((DRAW_OFFSET['x'] + 5, DRAW_OFFSET['y'] + 5, 70, 90)) font = pygame.font.Font(None, 42) smallFont = pygame.font.Font(None, 24) for i in xrange(0, self.HAND_SIZE): card = self.getHand()[i] if card is not None: window.fill(white, box, 0) if (self.selectedCard == i): pygame.draw.rect(window, green, box, 5) else: pygame.draw.rect(window, black, box, 2) text = font.render(chr(ord('A') + card), 1, black) text_pos = list(box) text_pos[0] += 5 text_pos[1] += 5 window.blit(text, text_pos) text = smallFont.render(self.tileData[card]["conType"], 1, black) text_pos[1] += 50 window.blit(text, text_pos) box[0] += 75 ## EVENT HANDLERS ## def handleClick(self, x, y, left=True): if (self.menu.handleClick(x, y)): return 1 if x > self.width * Tile.SIZE: return 0 if y > self.height * Tile.SIZE: if (not left and self.selectedCard is not None): self.menu.activate(x, y) else: index = x / self.cardWidth self.cardClicked(index) return 1 else: if (left): self.tileClicked(x / Tile.SIZE, y / Tile.SIZE) else: tile = self.grid[x / Tile.SIZE][y / Tile.SIZE] self.menu.activate(x, y, tile) return 1 def cardClicked(self, index): if (index == self.selectedCard): self.selectedCard = None elif self.getHand()[index] is not None: self.selectedCard = index return 1 def tileClicked(self, x, y): tile = self.grid[x][y] if tile is None: tileID = self.takeCard() if (tileID is not None): tile = Tile(self.tileData[tileID], tileID, x, y, self.activePlayer) self.grid[x][y] = tile else: tile.rotate() self.calculatePower() def flipTile(self, x, y): tile = self.grid[x][y] tile.flip() self.calculatePower(tile.owner) def destroyTile(self, x, y): self.grid[x][y] = None self.calculatePower() def addCard(self): hand = self.getHand() for i in xrange(0, self.HAND_SIZE): if hand[i] is None: hand[i] = self.deck.pop() return def takeCard(self): card = None if (self.selectedCard is not None): card = self.getHand()[self.selectedCard] self.getHand()[self.selectedCard] = None self.selectedCard = None return card def discardSelected(self): if (self.selectedCard is not None): self.getHand()[self.selectedCard] = None self.selectedCard = None def endTurn(self): self.calculatePower() self.activePlayer = 0 if self.activePlayer == 1 else 1 self.selectedCard = None self.calculatePower() def getHand(self): return self.hands[self.activePlayer]
def build_ui(self): """ builds the user interface """ self.root = root = tk.Tk(className=self.settings.name.lower() ) # --> StartupWMClass = pwcode root.protocol("WM_DELETE_WINDOW", self.quit_app) # img = tk.Image('photo', file=self.icon_file) # TODO: Denne virker med tk8.6 men ikke tk8.5 # img = tk.PhotoImage(self.icon_file) root.tk.call('wm', 'iconphoto', root._w, tk.PhotoImage(file=self.icon_file)) # root.tk.call('wm','iconphoto',root._w,img) # root.iconphoto(False, img) w = 1300 # width for the Tk root h = 800 # height for the Tk root ws = root.winfo_screenwidth() hs = root.winfo_screenheight() x = (ws / 2) - (w / 2) y = (hs / 2) - (h / 2) root.geometry('%dx%d+%d+%d' % (w, h, x, y)) # root.option_add( "*font", "gothic" ) # root.option_add("*Font", "Times 20 bold") # def_font = tk.font.nametofont("TkDefaultFont") # def_font.config(size=16) self.font = tk.font.nametofont("TkDefaultFont") self.font.config( size=10 ) # WAIT: Gjør denne konfigurerbar. Også brukes av editor, eller fortsatt separat? style = theme.build_style(self.settings.colors) root.configure(bg=self.settings.colors.bg) # Avoid flashes of gray # TODO: Må endre tilsvarende på et par andre default farger (eks bakgrunn scrollbar når bytter tab) style.theme_use("pwcode") self.commander = Commander(self) # WAIT: Lag funksjon som leser ut dette auto fra commands.py root.bind("<Alt-x>", lambda x: self.run_command('show_commands')) root.bind("<Control-q>", lambda x: self.run_command('quit_app')) root.bind("<Control-o>", lambda x: self.run_command('open_file')) root.bind("<Control-O>", lambda x: self.run_command('open_folder')) root.bind("<Control-n>", lambda x: self.run_command('new_file')) root.bind("<Control-w>", lambda x: self.run_command('close_file')) root.bind("<Control-s>", lambda x: self.run_command('save_file')) root.bind("<Control-S>", lambda x: self.run_command('save_file_as')) root.bind("<Control-Tab>", self.perform_ctrl_tab, True) root.bind("<Control-Right>", lambda x: self.run_command('next_tab_in_index')) # TODO: Linje under gir FM kun på windows: _tkinter.TclError: bad event type or keysym "KP_Right" #root.bind("<Control-KP_Right>", lambda x: self.run_command('next_tab_in_index')) # on keypad root.bind("<Control-KP_6>", lambda x: self.run_command( 'next_tab_in_index')) # on keypad with num lock root.bind("<Control-Left>", lambda x: self.run_command('previous_tab_in_index')) # TODO: Linje under gir FM kun på windows: _tkinter.TclError: bad event type or keysym "KP_Left" #root.bind("<Control-KP_Left>", lambda x: self.run_command('previous_in_index')) # on keypad root.bind("<Control-KP_4>", lambda x: self.run_command( 'previous_tab_in_index')) # on keypad with num lock root.bind("<Control-plus>", lambda x: self.run_command('increase_text_font')) root.bind("<Control-minus>", lambda x: self.run_command('decrease_text_font')) root.bind("<Control-Return>", self.perform_ctrl_return, True) root.bind_class("Text", "<Control-Return>", lambda e: None) root.bind_class("Text", "<Control-k>", lambda e: None) root.bind("<Control-k>", lambda x: self.run_command('kill_process')) root.bind_class("Text", "<Alt-c>", lambda e: None) root.bind_class("Text", "<Alt_L><c>", lambda e: None) root.bind("<Alt-c>", lambda x: self.run_command('toggle_comment')) root.bind("<Alt_L><c>", lambda x: self.run_command('toggle_comment') ) # WAIT: Denne varianten for Alt-x også? # horizontal layout for the sidebar to expand / collapse panels self.paned = paned = tk.ttk.PanedWindow(root, orient=tk.HORIZONTAL) paned.pack(fill=tk.BOTH, expand=1) self.sidebar = SideBar(paned, self) paned.add(self.sidebar) self.editor_frame = EditorFrame(paned, self) paned.add(self.editor_frame) initial_status = '' self.statusbar = StatusBar(root, self, initial_status) self.statusbar.pack(fill=tk.X, side=tk.BOTTOM)