示例#1
0
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)
示例#2
0
文件: Showcase.py 项目: Afey/pyjs
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]
示例#3
0
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]
示例#4
0
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)
示例#5
0
文件: DialogBox.py 项目: Afey/pyjs
class DialogBox(PopupPanel):
    _props = [
        ("caption", "Caption", "HTML", None),
    ]

    def __init__(self, autoHide=None, modal=True, centered=False,
                 **kwargs):
        # Init section
        self.dragging = False
        self.dragStartX = 0
        self.dragStartY = 0
        self.child = None
        self.panel = FlexTable(
            Height="100%",
            BorderWidth="0",
            CellPadding="0",
            CellSpacing="0",
        )

        cf = self.panel.getCellFormatter()
        rf = self.panel.getRowFormatter()

        # Arguments section
        self.modal = modal
        self.caption = HTML()
        self.caption.setStyleName("Caption")
        self.caption.addMouseListener(self)

        # Make the DialogBox a 3x3 table, like GWT does, with
        # empty elements with specific style names. These can be
        # used with CSS to, for example, create border around the
        # dialog box.
        self.generate_gwt15 = kwargs.pop('gwt15', False) and True

        if not self.generate_gwt15:
            cf.setHeight(1, 0, "100%")
            cf.setWidth(1, 0, "100%")
            cf.setAlignment(
                1, 0,
                HasHorizontalAlignment.ALIGN_CENTER,
                HasVerticalAlignment.ALIGN_MIDDLE,
            )
            self.panel.setWidget(0, 0, self.caption)
        else:
            row_labels = ['Top', 'Middle', 'Bottom']
            col_labels = ['Left', 'Center', 'Right']

            for r in range(3):
                rf.setStyleName(r, 'dialog%s' % row_labels[r])
                for c in range(3):
                    cf.setStyleName(r, c, 'dialog%s%s' % (row_labels[r],
                                                          col_labels[c]))
                    sp = SimplePanel()
                    sp.setStyleName('dialog%s%sInner' % (row_labels[r],
                                                         col_labels[c]))
                    self.panel.setWidget(r, c, sp)

            cf.setAlignment(
                1, 1,
                HasHorizontalAlignment.ALIGN_CENTER,
                HasVerticalAlignment.ALIGN_MIDDLE,
            )

            self.dialog_content = SimplePanel()
            self.dialog_content.setStyleName('dialogContent')

            self.panel.getWidget(0, 1).add(self.caption)
            self.panel.getWidget(1, 1).add(self.dialog_content)

        # Finalize
        kwargs['StyleName'] = kwargs.get('StyleName', "gwt-DialogBox")
        PopupPanel.__init__(self, autoHide, modal, **kwargs)
        PopupPanel.setWidget(self, self.panel)

        self.centered = centered

    def onWindowResized(self, width, height):
        super(DialogBox, self).onWindowResized(width, height)
        if self.centered:
            self.centerBox()

    def show(self):
        super(DialogBox, self).show()
        if self.centered:
            self.centerBox()

    @classmethod
    def _getProps(self):
        return PopupPanel._getProps() + self._props

    def onEventPreview(self, event):
        # preventDefault on mousedown events, outside of the
        # dialog, to stop text-selection on dragging
        type = DOM.eventGetType(event)
        if type == 'mousedown':
            target = DOM.eventGetTarget(event)
            elem = self.caption.getElement()
            event_targets_popup = target and DOM.isOrHasChild(elem, target)
            if event_targets_popup:
                DOM.eventPreventDefault(event)
        return PopupPanel.onEventPreview(self, event)

    def getHTML(self):
        return self.caption.getHTML()

    def getText(self):
        return self.caption.getText()

    def setHTML(self, html):
        self.caption.setHTML(html)

    def setText(self, text):
        self.caption.setText(text)

    def onMouseDown(self, sender, x, y):
        self.dragging = True
        GlassWidget.show(self.caption)
        self.dragStartX = x
        self.dragStartY = y

    def onMouseEnter(self, sender):
        pass

    def onMouseLeave(self, sender):
        pass

    def onMouseMove(self, sender, x, y):
        if not self.dragging:
            return
        absX = x + self.getAbsoluteLeft()
        absY = y + self.getAbsoluteTop()
        self.setPopupPosition(absX - self.dragStartX,
                              absY - self.dragStartY)

    def onMouseUp(self, sender, x, y):
        self.endDragging()

    def onMouseGlassEnter(self, sender):
        pass

    def onMouseGlassLeave(self, sender):
        self.endDragging()

    def endDragging(self):
        if not self.dragging:
            return
        self.dragging = False
        GlassWidget.hide()

    def remove(self, widget):
        if self.child != widget:
            return False

        self.panel.remove(widget)
        self.child = None
        return True

    def doAttachChildren(self):
        PopupPanel.doAttachChildren(self)
        self.caption.onAttach()

    def doDetachChildren(self):
        PopupPanel.doDetachChildren(self)
        self.caption.onDetach()

    def setWidget(self, widget):
        if self.child is not None:
            if not self.generate_gwt15:
                self.panel.remove(self.child)
            else:
                self.dialog_content.remove(self.child)

        if widget is not None:
            if not self.generate_gwt15:
                self.panel.setWidget(1, 0, widget)
            else:
                self.dialog_content.setWidget(widget)

        self.child = widget