def __init__(self): SimplePanel.__init__(self) vert = VerticalPanel() vert.setSpacing("10px") self.add(vert) panel = ScrollPanel(Size=("300px", "100px")) contents = HTML("<b>Tao Te Ching, Chapter One</b><p>" + "The Way that can be told of is not an unvarying " + "way;<p>The names that can be named are not " + "unvarying names.<p>It was from the Nameless that " + "Heaven and Earth sprang;<p>The named is but the " + "mother that rears the ten thousand creatures, " + "each after its kind.") panel.add(contents) vert.add(panel) container = SimplePanel(Width="400px", Height="200px") contents2 = HTML( 50 * "Dont forget to grab the css for SuperScrollPanel in Showcase.css! " ) panel2 = SuperScrollPanel(contents2) container.add(panel2) vert.add(container)
def __init__(self, c): PopupPanel.__init__(self, True) p = SimplePanel() p.add(c) c.show(10, 10) p.setWidth("100%") self.setWidget(p)
def _gridCancelLink(self): bh4 = Hyperlink(self.cancel) bh4.addClickListener(getattr(self, 'onCancel')) b2 = SimplePanel() b2.add(bh4) b2.addStyleName("calendar-cancel") self.vp.add(b2)
class SuperScrollPanel(ScrollPanel): def __init__(self, panel): ScrollPanel.__init__(self) self.setHeight("100%") self.setStyleName("SuperScrollPanelOuter") self.inner = SimplePanel(Height="100%") self.add(self.inner) self.inner.setStyleName("SuperScrollPanelInner") self.inner.add(panel)
class ReduceOutputIFACE(PanelIFACE): def __init__(self, parent = None): PanelIFACE.__init__(self, parent) self.panel = SimplePanel() rof = Frame("", Size=("100%", parent.getHeight())) self.panel.add(rof) self.roFrame = parent.roFrame = rof return def onWindowResized(self, width, height): self.roFrame.setSize("100%", self.parent.getHeight())
def drawBody(self, container): menu = HorizontalPanel(ID="aur-menu-int") search_cont = SimplePanel(StyleName="aur-content-boundary") search = VerticalPanel(ID="aur-search") footer = VerticalPanel(ID="aur-footer", Width="100%", HorizontalAlignment="center") search_cont.add(search) container.add(menu) container.add(search_cont) container.add(self.content) container.add(footer) container.setCellHeight(menu, "1px") container.setCellHeight(footer, "1px") container.setCellHorizontalAlignment(footer, "center") self.drawInternalMenu(menu) Search.draw(search) self.drawFooter(footer)
def draw(self): parent = self.parent screen = self.screen content = self.content header = HorizontalPanel(ID="aur-header", Width="100%") boundary = SimplePanel(ID="aur-boundary", StyleName="aur-link-stateful") container = VerticalPanel(ID="aur-container", Width="100%", Height="100%") parent.add(screen) screen.add(header) screen.setCellHeight(header, "1px") screen.add(boundary) boundary.add(container) self.drawHeader(header) self.drawBody(container) self.onHistoryChanged()
def __init__(self): SimplePanel.__init__(self) vert = VerticalPanel() vert.setSpacing("10px") self.add(vert) panel = ScrollPanel(Size=("300px", "100px")) contents = HTML("<b>Tao Te Ching, Chapter One</b><p>" + "The Way that can be told of is not an unvarying " + "way;<p>The names that can be named are not " + "unvarying names.<p>It was from the Nameless that " + "Heaven and Earth sprang;<p>The named is but the " + "mother that rears the ten thousand creatures, " + "each after its kind.") panel.add(contents) vert.add(panel) container = SimplePanel(Width="400px", Height="200px") contents2 = HTML(50*"Dont forget to grab the css for SuperScrollPanel in Showcase.css! ") panel2 = SuperScrollPanel(contents2) container.add(panel2) vert.add(container)
def __init__(self, *args, **kwargs): super(NavigationBar, self).__init__(*args, **kwargs) navbar = SimplePanel(StyleName="navbar navbar-fixed") navbar_inner = SimplePanel(StyleName="navbar-inner") self._navbar_container = FlowPanel() navbar_inner.add(self._navbar_container) navbar.add(navbar_inner) SimplePanel.add(self, navbar)
def __init__(self): #set some vars self.title = "last.fm" #this is where we build the ui self.statusPanel = VerticalPanel() self.statusPanel.setID('status_panel') #make a few Labels to hold station, artist, track, album info self.stationLabel = Label() self.artistLabel = Label() self.trackLabel = Label() self.albumLabel = Label() self.timeLabel = Label() self.infoTable = FlexTable() i=0 self.stationLabel = Label() self.infoTable.setWidget(i,0,Label("Station:") ) self.infoTable.setWidget(i,1,self.stationLabel) i+=1 self.infoTable.setWidget(i,0,Label("Artist:") ) self.infoTable.setWidget(i,1,self.artistLabel) i+=1 self.infoTable.setWidget(i,0,Label("Track:") ) self.infoTable.setWidget(i,1,self.trackLabel) i+=1 self.infoTable.setWidget(i,0,Label("Album:") ) self.infoTable.setWidget(i,1,self.albumLabel) self.statusPanel.add(self.infoTable) self.statusPanel.add(self.timeLabel) #make the time bar timebarWrapperPanel = SimplePanel() timebarWrapperPanel.setID("timebar_wrapper") #timebarWrapperPanel.setStyleName('timebar_wrapper') self.timebarPanel = SimplePanel() self.timebarPanel.setID("timebar") #self.timebarPanel.setStyleName('timebar') timebarWrapperPanel.add(self.timebarPanel) self.statusPanel.add(timebarWrapperPanel) #make some shit for buttons self.buttonHPanel = HorizontalPanel() self.skipButton = Button("Skip", self.clicked_skip ) self.buttonHPanel.add(self.skipButton) loveButton = Button("Love", self.clicked_love ) self.buttonHPanel.add(loveButton) pauseButton = Button("Pause", self.clicked_pause ) self.buttonHPanel.add(pauseButton) banButton = Button("Ban", self.clicked_ban ) self.buttonHPanel.add(banButton) #control the volume self.volumePanel = HorizontalPanel() self.volumeLabel = Label("Volume:") self.volumePanel.add(self.volumeLabel) volupButton = Button("+", self.clicked_volume_up, 5) self.volumePanel.add(volupButton) voldownButton = Button("-", self.clicked_volume_down, 5) self.volumePanel.add(voldownButton) #make buttons and shit to create a new station self.setStationHPanel = HorizontalPanel() self.setStationTypeListBox = ListBox() self.setStationTypeListBox.setVisibleItemCount(0) self.setStationTypeListBox.addItem("Similar Artists", "artist/%s/similarartists") self.setStationTypeListBox.addItem("Top Fans", "artist/%s/fans") self.setStationTypeListBox.addItem("Library", "user/%s/library") self.setStationTypeListBox.addItem("Mix", "user/%s/mix") self.setStationTypeListBox.addItem("Recommended", "user/%s/recommended") self.setStationTypeListBox.addItem("Neighbours", "user/%s/neighbours") self.setStationTypeListBox.addItem("Global Tag", "globaltags/%s") self.setStationHPanel.add(self.setStationTypeListBox) self.setStationTextBox = TextBox() self.setStationTextBox.setVisibleLength(10) self.setStationTextBox.setMaxLength(50) self.setStationHPanel.add(self.setStationTextBox) self.setStationButton = Button("Play", self.clicked_set_station) self.setStationHPanel.add(self.setStationButton) #make an error place to display data self.infoHTML = HTML() RootPanel().add(self.statusPanel) RootPanel().add(self.buttonHPanel) RootPanel().add(self.volumePanel) RootPanel().add(self.setStationHPanel) RootPanel().add(self.infoHTML)
class Game(VerticalPanel): def __init__(self, row, column=0): super(Game, self).__init__(StyleName='game') self.sinkEvents(Event.ONCONTEXTMENU) # to disable right click self.row = row self.column = column or row self.level = 1 self.toppers = [[], [], []] # storage for top scorers for 3 levels. self.remote = DataService() self.remote_handler = RemoteHandler(self) self.remote.get_scores(self.remote_handler) # contents of Game menubar = MineMenuBar(self) score_board = HorizontalPanel(StyleName='score-board') self.grid_panel = SimplePanel(StyleName='grid-panel') self.add(menubar) self.add(score_board) self.add(self.grid_panel) # contents of score_board self.counter = Label('000', StyleName='digit counter') self.face = Smiley(self) self.timer = Label('000', StyleName='digit timer') for one in (self.counter, self.face, self.timer): score_board.add(one) score_board.setCellWidth(self.face, '100%') self.create_grid() self.start() def onBrowserEvent(self, event): # prevent right click context menu as well as all the other events. DOM.eventPreventDefault(event) def create_grid(self): # contents of self.grid_panel self.grid = CustomGrid(self, self.row, self.column) self.grid_panel.add(self.grid) def start(self, no_of_bomb=0): self.time = -1 self.started = True self.first_click = True self.bombed_cells = [] self.flagged_cells = [] self.to_be_released = [] # cells to be released after being pressed self.count_opened_cells = 0 self.no_of_click = 0 self.squares = self.row * self.column self.no_of_bomb = no_of_bomb or int((self.squares * 10) / 64) self.no_of_safe_zones = self.squares - self.no_of_bomb self.set_counter() self.timer.setText('000') self.generate_bombs() self.face.setStyleName('facesmile') def get_all_cells(self): for i in xrange(self.row): for j in xrange(self.column): one = self.grid.getCell(i, j) yield one def get_neighbors(self, cell): x = cell.x y = cell.y row, column = self.row, self.column for i in xrange(x-1, x+2): if 0 <= i < row: for j in xrange(y-1, y+2): if 0 <= j < column: if (i,j) != (x, y): one = self.grid.getCell(i, j) yield one def set_counter(self): next_value = self.no_of_bomb - len(self.flagged_cells) if next_value == 0 and self.started: self.counter.setStyleName('digit counter-blue') self.counter.addClickListener(RemainingMineHandler(self)) else: self.counter.setStyleName('digit counter') self.counter._clickListeners = [] if next_value < 0: template = '-00' next_value = abs(next_value) else: template = '000' value = str(next_value) value = template[:-len(value)] + value self.counter.setText(value) def onTimer(self, target): if not self.started or self.first_click: return Timer(1000, self) self.time += 1 if self.time <= 999: str_time = str(self.time) str_time = '000'[:-len(str_time)] + str_time self.timer.setText(str_time) else: self.started = False self.face.setStyleName('faceclock') def sample(self, population, k): # pyjamas doesn't support random.sample but random.choice seq = list(population) s = [] for i in xrange(k): pick = random.choice(seq) seq.remove(pick) s.append(pick) return s def generate_bombs(self): # generate 1 extra mine so that if user's first click is bomb, move that bombs = self.sample(xrange(self.squares), self.no_of_bomb+1) row, column = self.row, self.column for i,bomb in enumerate(bombs): x = bomb // column y = bomb % column mine = self.grid.getCell(x, y) if i == 0: self.extra_mine = mine continue #DOM.setInnerHTML(mine.getElement(),'b');mine.addStyleName('debug') self.bombed_cells.append(mine) mine.count = -1 for one in self.get_neighbors(mine): if one.count != -1: one.count += 1 def move_to_extra_mine(self, to_be_moved): to_be_moved.count = 0 self.bombed_cells.remove(to_be_moved) for one in self.get_neighbors(to_be_moved): if one.count == -1: to_be_moved.count += 1 else: one.count -= 1 self.extra_mine.count = -1 self.bombed_cells.append(self.extra_mine) for one in self.get_neighbors(self.extra_mine): if one.count != -1: one.count += 1 def press_neighbor_cells(self, cell): self.count_flags = 0 self.bomb_explodes_on = [] self.to_be_released = [] for one in self.get_neighbors(cell): if one.state == 3: continue one.addStyleName('pressed') self.to_be_released.append(one) if one.state == 1: self.count_flags += 1 else: if one.count == -1: self.bomb_explodes_on.append(one) def open_if_satisfies(self, cell): if self.count_flags == cell.count: if self.bomb_explodes_on: self.show_all_bombs(self.bomb_explodes_on) else: self.open_neighboring_cells(cell) def open_neighboring_cells(self, cell): if not self.started: return for one in self.get_neighbors(cell): if one.state in (0, 2) and one.count != -1: one.setStyleName('opened') one.state = 3 self.count_opened_cells += 1 if one.count == 0: self.open_neighboring_cells(one) else: setColorfulHTML(one.getElement(), one.count) self.check_win() def check_win(self): if not self.started: return if self.count_opened_cells == self.no_of_safe_zones: for one in self.bombed_cells: if one.state != 1: one.setStyleName('cell bombflagged') self.flagged_cells.append(one) self.started = False self.set_counter() self.face.setStyleName('facewin') name = Window.prompt("You've done it !\n\ Game Time: %s seconds\n\ Number of Clicks: %s\n" "What's ur name ?" % (self.time, self.no_of_click)) if name and self.level in (1, 2, 3): self.remote.add_score(name, self.level, self.time, \ self.no_of_click, self.remote_handler) self.add_player_to_toppers(name) def add_player_to_toppers(self, name): current_level = self.level - 1 toppers_in_this_level = self.toppers[current_level] toppers_in_this_level.append(('<b>%s</b>' % name, self.time)) self.toppers[current_level] = sorted(toppers_in_this_level, \ key=lambda score: score[1]) self.remote_handler.load_top_scores() def show_all_bombs(self, bomb_explodes_on=[]): self.started = False self.face.setStyleName('facedead') for one in self.bombed_cells: if one.state != 1: one.setStyleName('cell bombrevealed') for one in self.flagged_cells: if one.count != -1: one.setStyleName('cell bombmisflagged') for one in bomb_explodes_on: one.setStyleName('cell bombdeath') def next_game(self, level=None, no_of_bomb=0): current_level = (self.row, self.column) if not level or level == (0,0) or level == current_level: self.restart(no_of_bomb) else: self.row, self.column = level if level[0] <= current_level[0] and level[1] <= current_level[1]: self.grid.resize(*level) self.restart(no_of_bomb) else: self.grid_panel.remove(self.grid) self.create_grid() self.start(no_of_bomb) def restart(self, no_of_bomb=0): for one in self.get_all_cells(): one.count = 0 one.state = 0 one.setStyleName('blank') DOM.setInnerHTML(one.getElement(), '') self.start(no_of_bomb)
class Showcase: """ Our main application object. """ def onModuleLoad(self): """ Dynamically build our user interface when the web page is loaded. """ self._root = RootPanel() self._tree = Tree() self._rightPanel = SimplePanel() self._curContents = None intro = HTML('<h3>Welcome to the Pyjamas User Interface Showcase</h3>'+ '<p/>Please click on an item to start.') self._introPanel = VerticalPanel() self._introPanel.add(uiHelpers.indent(intro, left=20)) self._demos = [] # List of all installed demos. Each item in this list # is a dictionary with the following entries: # # 'name' # # The name for this demo. # # 'section' # # The name of the section of the demo tree # this demo should be part of. # # 'doc' # # The documentation for this demo. # # 'src' # # The source code for this demo. # # 'example' # # The Panel which holds the example output for # this demo. self.loadDemos() self.buildTree() self._tree.setSize("0%", "100%") divider = VerticalPanel() divider.setSize("1px", "100%") divider.setBorderWidth(1) scroller = ScrollPanel(self._rightPanel) scroller.setSize("100%", "100%") hPanel = HorizontalPanel() hPanel.setSpacing(4) hPanel.add(self._tree) hPanel.add(divider) hPanel.add(scroller) hPanel.setHeight("100%") self._root.add(hPanel) self._tree.addTreeListener(self) self.showDemo(None) def loadDemos(self): """ Load our various demos, in preparation for showing them. We insert the demos into self._demos. """ self._demos = demoInfo.getDemos() def buildTree(self): """ Build the contents of our tree. Note that, for now, we highlight the demos which haven't been written yet. """ sections = {} # Maps section name to TreeItem object. for demo in self._demos: if demo['section'] not in sections: section = TreeItem('<b>' + demo['section'] + '</b>') DOM.setStyleAttribute(section.getElement(), "cursor", "pointer") DOM.setAttribute(section.itemTable, "cellPadding", "0") DOM.setAttribute(section.itemTable, "cellSpacing", "1") self._tree.addItem(section) sections[demo['section']] = section section = sections[demo['section']] if demo['doc'][:26] == "Documentation goes here...": item = TreeItem('<font style="color:#808080">' + demo['title'] + '</font>') else: item = TreeItem(demo['title']) DOM.setStyleAttribute(item.getElement(), "cursor", "pointer") DOM.setAttribute(item.itemTable, "cellPadding", "0") DOM.setAttribute(item.itemTable, "cellSpacing", "1") item.setUserObject(demo) section.addItem(item) # Open the branches of the tree. for section in sections.keys(): sections[section].setState(True, fireEvents=False) def onTreeItemSelected(self, item): """ Respond to the user selecting an item in our tree. """ demo = item.getUserObject() if demo is None: self.showDemo(None) else: self.showDemo(demo['name']) def onTreeItemStateChanged(self, item): """ Respond to the user opening or closing a branch of the tree. """ pass # Nothing to do. def showDemo(self, name): """ Show the demonstration with the given name. """ if self._curContents is not None: self._rightPanel.remove(self._curContents) self._curContents = None demo = None for d in self._demos: if d['name'] == name: demo = d break if demo is not None: exampleID = HTMLPanel.createUniqueId() html = [] html.append('<div style="padding:20px">') html.append('<b>' + demo['title'] + '</b>') html.append('<p/>') html.append(self.docToHTML(demo['doc'])) html.append('<p/>') html.append('<hr/>') html.append('<b>Working Example</b>') html.append('<p/>') html.append('<div style="padding-left:20px">') html.append('<span id="' + exampleID + '"></span>') html.append('</div>') html.append('<p/>') html.append('<hr/>') html.append('<b>Source Code</b>') html.append('<p/>') html.append(self.srcToHTML(demo['src'])) html.append('</div>') panel = HTMLPanel("\n".join(html)) panel.add(demo['example'], exampleID) self._rightPanel.add(panel) self._curContents = panel else: self._rightPanel.add(self._introPanel) self._curContents = self._introPanel def docToHTML(self, doc): """ Convert the given documentation string to HTML. """ doc = doc.replace('\n\n', '<p/>') isBold = False while True: i = doc.find("``") if i == -1: break if isBold: doc = doc[:i] + '</b></font>' + doc[i+2:] else: doc = doc[:i] + '<font face="monospace"><b>' + doc[i+2:] isBold = not isBold return doc def srcToHTML(self, src): """ Convert the given source code to HTML. The source code is already in HTML format, but has extra tags to make it a complete HTML file. We extract and return just the text between the <body> tags. """ i = src.find('<body') i = src.find('>', i) j = src.find('</body>') return src[i+1:j]
def drawFull(self, month, year): # should be called only once when we draw the calendar for # the first time self.vp = VerticalPanel() self.vp.setSpacing(0) self.vp.setPadding(0) self.vp.addStyleName("calendarbox calendar-module calendar") self.setWidget(self.vp) self.setVisible(False) # mth = int(month) yr = int(year) tp = HorizontalPanel(Width="100%") tp.addStyleName("calendar-top-panel") tp.setSpacing(0) tp.setPadding(0) self.h1 = None self.h2 = None self.h4 = None self.h5 = None if self.backyear: self.h1 = self.bkls(self.backyear, StyleName="calendar-arrows") self.h1.addClickListener(getattr(self, 'onPreviousYear')) tp.add(self.h1) tp.setCellHorizontalAlignment(self.h1, "left") if self.backmonth: self.h2 = self.bkls(self.backmonth, StyleName="calendar-arrows") self.h2.addClickListener(getattr(self, 'onPreviousMonth')) tp.add(self.h2) tp.setCellHorizontalAlignment(self.h2, "left") # titlePanel can be changed, whenever we draw, so keep the reference txt = "<b>" txt += self.getMonthsOfYear()[mth-1] + " " + str(yr) txt += "</b>" self.titlePanel = SimplePanel() self.titlePanel.setWidget(HTML(txt)) self.titlePanel.setStyleName("calendar-center") tp.add(self.titlePanel) tp.setCellHorizontalAlignment(self.titlePanel, "center") tp.setCellWidth(self.titlePanel, "100%") if self.fwdmonth: self.h4 = self.bkls(self.fwdmonth, StyleName="calendar-arrows") self.h4.addClickListener(getattr(self, 'onNextMonth')) tp.add(self.h4) tp.setCellHorizontalAlignment(self.h4, "right") tp.setCellWidth(self.h4, "100%") self.h4.setWidth("100%") if self.fwdyear: self.h5 = self.bkls(self.fwdyear, StyleName="calendar-arrows") self.h5.addClickListener(getattr(self, 'onNextYear')) tp.add(self.h5) tp.setCellHorizontalAlignment(self.h5, "right") tvp = VerticalPanel(Width="100%") tvp.setSpacing(2) tvp.add(tp) self.vp.add(tvp) # done with top panel self.middlePanel = SimplePanel() grid = self.drawGrid(mth, yr) self.middlePanel.setWidget(grid) self.vp.add(self.middlePanel) self.defaultGrid = grid if self.addbuttons: # # some links & handlers # bh1 = Hyperlink(self.yesterday) bh1.addClickListener(getattr(self, 'onYesterday')) bh2 = Hyperlink(self.today) bh2.addClickListener(getattr(self, 'onToday')) bh3 = Hyperlink(self.tomorrow) bh3.addClickListener(getattr(self, 'onTomorrow')) bh4 = Hyperlink(self.cancel) bh4.addClickListener(getattr(self, 'onCancel')) # # add code to test another way of doing the layout # b = HorizontalPanel() b.add(bh1) b.add(bh2) b.add(bh3) b.addStyleName("calendar-shortcuts") self.vp.add(b) b2 = SimplePanel() b2.add(bh4) b2.addStyleName("calendar-cancel") self.vp.add(b2) self.checkLinks(mth, yr) self.setVisible(True)
def drawFull(self, month, year): # should be called only once when we draw the calendar for # the first time self.vp = VerticalPanel() self.vp.setSpacing(2) self.vp.addStyleName("calendarbox calendar-module calendar") self.setWidget(self.vp) self.setVisible(False) # mth = int(month) yr = int(year) tp = HorizontalPanel() tp.addStyleName("calendar-top-panel") tp.setSpacing(5) h1 = Hyperlink('<<') h1.addClickListener(getattr(self, 'onPreviousYear')) h2 = Hyperlink('<') h2.addClickListener(getattr(self, 'onPreviousMonth')) h4 = Hyperlink('>') h4.addClickListener(getattr(self, 'onNextMonth')) h5 = Hyperlink('>>') h5.addClickListener(getattr(self, 'onNextYear')) tp.add(h1) tp.add(h2) # titlePanel can be changed, whenever we draw, so keep the reference txt = "<b>" txt += self.getMonthsOfYear()[mth-1] + " " + str(yr) txt += "</b>" self.titlePanel = SimplePanel() self.titlePanel.setWidget(HTML(txt)) self.titlePanel.setStyleName("calendar-center") tp.add(self.titlePanel) tp.add(h4) tp.add(h5) tvp = VerticalPanel() tvp.setSpacing(10) tvp.add(tp) self.vp.add(tvp) # done with top panel self.middlePanel = SimplePanel() grid = self.drawGrid(mth, yr) self.middlePanel.setWidget(grid) self.vp.add(self.middlePanel) self.defaultGrid = grid # # some links & handlers # bh1 = Hyperlink(self.yesterday) bh1.addClickListener(getattr(self, 'onYesterday')) bh2 = Hyperlink(self.today) bh2.addClickListener(getattr(self, 'onToday')) bh3 = Hyperlink(self.tomorrow) bh3.addClickListener(getattr(self, 'onTomorrow')) bh4 = Hyperlink(self.cancel) bh4.addClickListener(getattr(self, 'onCancel')) # # add code to test another way of doing the layout # b = HorizontalPanel() b.add(bh1) b.add(bh2) b.add(bh3) b.addStyleName("calendar-shortcuts") self.vp.add(b) b2 = SimplePanel() b2.add(bh4) b2.addStyleName("calendar-cancel") self.vp.add(b2) self.setVisible(True) return
class Showcase: """ Our main application object. """ def onModuleLoad(self): """ Dynamically build our user interface when the web page is loaded. """ self._root = RootPanel() self._tree = Tree() self._rightPanel = SimplePanel() self._curContents = None intro = HTML( '<h3>Welcome to the Pyjamas User Interface Showcase</h3>' + '<p/>Please click on an item to start.') self._introPanel = VerticalPanel() self._introPanel.add(uiHelpers.indent(intro, left=20)) self._demos = [ ] # List of all installed demos. Each item in this list # is a dictionary with the following entries: # # 'name' # # The name for this demo. # # 'section' # # The name of the section of the demo tree # this demo should be part of. # # 'doc' # # The documentation for this demo. # # 'src' # # The source code for this demo. # # 'example' # # The Panel which holds the example output for # this demo. self.loadDemos() self.buildTree() self._tree.setSize("0%", "100%") divider = VerticalPanel() divider.setSize("1px", "100%") divider.setBorderWidth(1) scroller = ScrollPanel(self._rightPanel) scroller.setSize("100%", "100%") hPanel = HorizontalPanel() hPanel.setSpacing(4) hPanel.add(self._tree) hPanel.add(divider) hPanel.add(scroller) hPanel.setHeight("100%") self._root.add(hPanel) self._tree.addTreeListener(self) self.showDemo(None) def loadDemos(self): """ Load our various demos, in preparation for showing them. We insert the demos into self._demos. """ self._demos = demoInfo.getDemos() def buildTree(self): """ Build the contents of our tree. Note that, for now, we highlight the demos which haven't been written yet. """ sections = {} # Maps section name to TreeItem object. for demo in self._demos: if demo['section'] not in sections: section = TreeItem('<b>' + demo['section'] + '</b>') DOM.setStyleAttribute(section.getElement(), "cursor", "pointer") DOM.setAttribute(section.itemTable, "cellPadding", "0") DOM.setAttribute(section.itemTable, "cellSpacing", "1") self._tree.addItem(section) sections[demo['section']] = section section = sections[demo['section']] if demo['doc'][:26] == "Documentation goes here...": item = TreeItem('<font style="color:#808080">' + demo['title'] + '</font>') else: item = TreeItem(demo['title']) DOM.setStyleAttribute(item.getElement(), "cursor", "pointer") DOM.setAttribute(item.itemTable, "cellPadding", "0") DOM.setAttribute(item.itemTable, "cellSpacing", "1") item.setUserObject(demo) section.addItem(item) # Open the branches of the tree. for section in sections.keys(): sections[section].setState(True, fireEvents=False) def onTreeItemSelected(self, item): """ Respond to the user selecting an item in our tree. """ demo = item.getUserObject() if demo is None: self.showDemo(None) else: self.showDemo(demo['name']) def onTreeItemStateChanged(self, item): """ Respond to the user opening or closing a branch of the tree. """ pass # Nothing to do. def showDemo(self, name): """ Show the demonstration with the given name. """ if self._curContents is not None: self._rightPanel.remove(self._curContents) self._curContents = None demo = None for d in self._demos: if d['name'] == name: demo = d break if demo is not None: exampleID = HTMLPanel.createUniqueId() html = [] html.append('<div style="padding:20px">') html.append('<b>' + demo['title'] + '</b>') html.append('<p/>') html.append(self.docToHTML(demo['doc'])) html.append('<p/>') html.append('<hr/>') html.append('<b>Working Example</b>') html.append('<p/>') html.append('<div style="padding-left:20px">') html.append('<span id="' + exampleID + '"></span>') html.append('</div>') html.append('<p/>') html.append('<hr/>') html.append('<b>Source Code</b>') html.append('<p/>') html.append(self.srcToHTML(demo['src'])) html.append('</div>') panel = HTMLPanel("\n".join(html)) panel.add(demo['example'], exampleID) self._rightPanel.add(panel) self._curContents = panel else: self._rightPanel.add(self._introPanel) self._curContents = self._introPanel def docToHTML(self, doc): """ Convert the given documentation string to HTML. """ doc = doc.replace('\n\n', '<p/>') isBold = False while True: i = doc.find("``") if i == -1: break if isBold: doc = doc[:i] + '</b></font>' + doc[i + 2:] else: doc = doc[:i] + '<font face="monospace"><b>' + doc[i + 2:] isBold = not isBold return doc def srcToHTML(self, src): """ Convert the given source code to HTML. The source code is already in HTML format, but has extra tags to make it a complete HTML file. We extract and return just the text between the <body> tags. """ i = src.find('<body') i = src.find('>', i) j = src.find('</body>') return src[i + 1:j]
class Game(VerticalPanel): def __init__(self, row, column=0): super(Game, self).__init__(StyleName='game') self.sinkEvents(Event.ONCONTEXTMENU) # to disable right click self.row = row self.column = column or row self.level = 1 self.toppers = [[], [], []] # storage for top scorers for 3 levels. self.remote = DataService() self.remote_handler = RemoteHandler(self) self.remote.get_scores(self.remote_handler) # contents of Game menubar = MineMenuBar(self) score_board = HorizontalPanel(StyleName='score-board') self.grid_panel = SimplePanel(StyleName='grid-panel') self.add(menubar) self.add(score_board) self.add(self.grid_panel) # contents of score_board self.counter = Label('000', StyleName='digit counter') self.face = Smiley(self) self.timer = Label('000', StyleName='digit timer') for one in (self.counter, self.face, self.timer): score_board.add(one) score_board.setCellWidth(self.face, '100%') self.create_grid() self.start() def onBrowserEvent(self, event): # prevent right click context menu as well as all the other events. DOM.eventPreventDefault(event) def create_grid(self): # contents of self.grid_panel self.grid = CustomGrid(self, self.row, self.column) self.grid_panel.add(self.grid) def start(self, no_of_bomb=0): self.time = -1 self.started = True self.first_click = True self.bombed_cells = [] self.flagged_cells = [] self.to_be_released = [] # cells to be released after being pressed self.count_opened_cells = 0 self.no_of_click = 0 self.squares = self.row * self.column self.no_of_bomb = no_of_bomb or int((self.squares * 10) / 64) self.no_of_safe_zones = self.squares - self.no_of_bomb self.set_counter() self.timer.setText('000') self.generate_bombs() self.face.setStyleName('facesmile') def get_all_cells(self): for i in xrange(self.row): for j in xrange(self.column): one = self.grid.getCell(i, j) yield one def get_neighbors(self, cell): x = cell.x y = cell.y row, column = self.row, self.column for i in xrange(x - 1, x + 2): if 0 <= i < row: for j in xrange(y - 1, y + 2): if 0 <= j < column: if (i, j) != (x, y): one = self.grid.getCell(i, j) yield one def set_counter(self): next_value = self.no_of_bomb - len(self.flagged_cells) if next_value == 0 and self.started: self.counter.setStyleName('digit counter-blue') self.counter.addClickListener(RemainingMineHandler(self)) else: self.counter.setStyleName('digit counter') self.counter._clickListeners = [] if next_value < 0: template = '-00' next_value = abs(next_value) else: template = '000' value = str(next_value) value = template[:-len(value)] + value self.counter.setText(value) def onTimer(self, target): if not self.started or self.first_click: return Timer(1000, self) self.time += 1 if self.time <= 999: str_time = str(self.time) str_time = '000'[:-len(str_time)] + str_time self.timer.setText(str_time) else: self.started = False self.face.setStyleName('faceclock') def sample(self, population, k): # pyjamas doesn't support random.sample but random.choice seq = list(population) s = [] for i in xrange(k): pick = random.choice(seq) seq.remove(pick) s.append(pick) return s def generate_bombs(self): # generate 1 extra mine so that if user's first click is bomb, move that bombs = self.sample(xrange(self.squares), self.no_of_bomb + 1) row, column = self.row, self.column for i, bomb in enumerate(bombs): x = bomb // column y = bomb % column mine = self.grid.getCell(x, y) if i == 0: self.extra_mine = mine continue #DOM.setInnerHTML(mine.getElement(),'b');mine.addStyleName('debug') self.bombed_cells.append(mine) mine.count = -1 for one in self.get_neighbors(mine): if one.count != -1: one.count += 1 def move_to_extra_mine(self, to_be_moved): to_be_moved.count = 0 self.bombed_cells.remove(to_be_moved) for one in self.get_neighbors(to_be_moved): if one.count == -1: to_be_moved.count += 1 else: one.count -= 1 self.extra_mine.count = -1 self.bombed_cells.append(self.extra_mine) for one in self.get_neighbors(self.extra_mine): if one.count != -1: one.count += 1 def press_neighbor_cells(self, cell): self.count_flags = 0 self.bomb_explodes_on = [] self.to_be_released = [] for one in self.get_neighbors(cell): if one.state == 3: continue one.addStyleName('pressed') self.to_be_released.append(one) if one.state == 1: self.count_flags += 1 else: if one.count == -1: self.bomb_explodes_on.append(one) def open_if_satisfies(self, cell): if self.count_flags == cell.count: if self.bomb_explodes_on: self.show_all_bombs(self.bomb_explodes_on) else: self.open_neighboring_cells(cell) def open_neighboring_cells(self, cell): if not self.started: return for one in self.get_neighbors(cell): if one.state in (0, 2) and one.count != -1: one.setStyleName('opened') one.state = 3 self.count_opened_cells += 1 if one.count == 0: self.open_neighboring_cells(one) else: setColorfulHTML(one.getElement(), one.count) self.check_win() def check_win(self): if not self.started: return if self.count_opened_cells == self.no_of_safe_zones: for one in self.bombed_cells: if one.state != 1: one.setStyleName('cell bombflagged') self.flagged_cells.append(one) self.started = False self.set_counter() self.face.setStyleName('facewin') name = Window.prompt("You've done it !\n\ Game Time: %s seconds\n\ Number of Clicks: %s\n" "What's ur name ?" % (self.time, self.no_of_click)) if name and self.level in (1, 2, 3): self.remote.add_score(name, self.level, self.time, \ self.no_of_click, self.remote_handler) self.add_player_to_toppers(name) def add_player_to_toppers(self, name): current_level = self.level - 1 toppers_in_this_level = self.toppers[current_level] toppers_in_this_level.append(('<b>%s</b>' % name, self.time)) self.toppers[current_level] = sorted(toppers_in_this_level, \ key=lambda score: score[1]) self.remote_handler.load_top_scores() def show_all_bombs(self, bomb_explodes_on=[]): self.started = False self.face.setStyleName('facedead') for one in self.bombed_cells: if one.state != 1: one.setStyleName('cell bombrevealed') for one in self.flagged_cells: if one.count != -1: one.setStyleName('cell bombmisflagged') for one in bomb_explodes_on: one.setStyleName('cell bombdeath') def next_game(self, level=None, no_of_bomb=0): current_level = (self.row, self.column) if not level or level == (0, 0) or level == current_level: self.restart(no_of_bomb) else: self.row, self.column = level if level[0] <= current_level[0] and level[1] <= current_level[1]: self.grid.resize(*level) self.restart(no_of_bomb) else: self.grid_panel.remove(self.grid) self.create_grid() self.start(no_of_bomb) def restart(self, no_of_bomb=0): for one in self.get_all_cells(): one.count = 0 one.state = 0 one.setStyleName('blank') DOM.setInnerHTML(one.getElement(), '') self.start(no_of_bomb)